title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Angular 6 - Http Service
Http Service will help us fetch external data, post to it, etc. We need to import the http module to make use of the http service. Let us consider an example to understand how to make use of the http service. To start using the http service, we need to import the module in app.module.ts as shown below − import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { HttpModule } from '@angular/http'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule, HttpModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } If you see the highlighted code, we have imported the HttpModule from @angular/http and the same is also added in the imports array. Let us now use the http service in the app.component.ts. import { Component } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { constructor(private http: Http) { } ngOnInit() { this.http.get("http://jsonplaceholder.typicode.com/users"). map((response) ⇒ response.json()). subscribe((data) ⇒ console.log(data)) } } Let us understand the code highlighted above. We need to import http to make use of the service, which is done as follows − import { Http } from '@angular/http'; In the class AppComponent, a constructor is created and the private variable http of type Http. To fetch the data, we need to use the get API available with http as follows this.http.get(); It takes the url to be fetched as the parameter as shown in the code. We will use the test url − https://jsonplaceholder.typicode.com/users to fetch the json data. Two operations are performed on the fetched url data map and subscribe. The Map method helps to convert the data to json format. To use the map, we need to import the same as shown below − import {map} from 'rxjs/operators'; Once the map is done, the subscribe will log the output in the console as shown in the browser − If you see, the json objects are displayed in the console. The objects can be displayed in the browser too. For the objects to be displayed in the browser, update the codes in app.component.html and app.component.ts as follows − import { Component } from '@angular/core'; import { Http } from '@angular/http'; import { map} from 'rxjs/operators'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { constructor(private http: Http) { } httpdata; ngOnInit() { this.http.get("http://jsonplaceholder.typicode.com/users") .pipe(map((response) => response.json())) .subscribe((data) => this.displaydata(data)); } displaydata(data) {this.httpdata = data;} } In app.component.ts, using the subscribe method we will call the display data method and pass the data fetched as the parameter to it. In the display data method, we will store the data in a variable httpdata. The data is displayed in the browser using for over this httpdata variable, which is done in the app.component.html file. <ul *ngFor = "let data of httpdata"> <li>Name : {{data.name}} Address: {{data.address.city}}</li> </ul> The json object is as follows − { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "[email protected]", "address": { "street": "Kulas Light", "suite": "Apt. 556", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } }, "phone": "1-770-736-8031 x56442", "website": "hildegard.org", "company": { "name": "Romaguera-Crona", "catchPhrase": "Multi-layered client-server neural-net", "bs": "harness real-time e-markets" } } The object has properties such as id, name, username, email, and address that internally has street, city, etc. and other details related to phone, website, and company. Using the for loop, we will display the name and the city details in the browser as shown in the app.component.html file. This is how the display is shown in the browser − Let us now add the search parameter, which will filter based on specific data. We need to fetch the data based on the search param passed. Following are the changes done in app.component.html and app.component.ts files − import { Component } from '@angular/core'; import { Http } from '@angular/http'; import { map} from 'rxjs/operators'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { constructor(private http: Http) { } httpdata; name; searchparam = 2; ngOnInit() { this.http.get("http://jsonplaceholder.typicode.com/users?id="+this.searchparam) .pipe(map((response) => response.json())) .subscribe((data) => this.displaydata(data)); } displaydata(data) {this.httpdata = data;} } For the get api, we will add the search param id = this.searchparam. The searchparam is equal to 2. We need the details of id = 2 from the json file. This is how the browser is displayed − We have consoled the data in the browser, which is received from the http. The same is displayed in the browser console. The name from the json with id = 2 is displayed in the browser. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2204, "s": 1995, "text": "Http Service will help us fetch external data, post to it, etc. We need to import the http module to make use of the http service. Let us consider an example to understand how to make use of the http service." }, { "code": null, "e": 2301, "s": 2204, "text": "To start using the http service, we need to import the module in app.module.ts as shown below −" }, { "code": null, "e": 2796, "s": 2301, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { HttpModule } from '@angular/http';\nimport { AppComponent } from './app.component';\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule,\n BrowserAnimationsModule,\n HttpModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 2929, "s": 2796, "text": "If you see the highlighted code, we have imported the HttpModule from @angular/http and the same is also added in the imports array." }, { "code": null, "e": 2986, "s": 2929, "text": "Let us now use the http service in the app.component.ts." }, { "code": null, "e": 3459, "s": 2986, "text": "import { Component } from '@angular/core';\nimport { Http } from '@angular/http';\nimport 'rxjs/add/operator/map';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n constructor(private http: Http) { }\n ngOnInit() {\n this.http.get(\"http://jsonplaceholder.typicode.com/users\").\n map((response) ⇒ response.json()).\n subscribe((data) ⇒ console.log(data))\n }\n}" }, { "code": null, "e": 3583, "s": 3459, "text": "Let us understand the code highlighted above. We need to import http to make use of the service, which is done as follows −" }, { "code": null, "e": 3622, "s": 3583, "text": "import { Http } from '@angular/http';\n" }, { "code": null, "e": 3795, "s": 3622, "text": "In the class AppComponent, a constructor is created and the private variable http of type Http. To fetch the data, we need to use the get API available with http as follows" }, { "code": null, "e": 3813, "s": 3795, "text": "this.http.get();\n" }, { "code": null, "e": 3883, "s": 3813, "text": "It takes the url to be fetched as the parameter as shown in the code." }, { "code": null, "e": 4166, "s": 3883, "text": "We will use the test url − https://jsonplaceholder.typicode.com/users to fetch the json data. Two operations are performed on the fetched url data map and subscribe. The Map method helps to convert the data to json format. To use the map, we need to import the same as shown below −" }, { "code": null, "e": 4203, "s": 4166, "text": "import {map} from 'rxjs/operators';\n" }, { "code": null, "e": 4300, "s": 4203, "text": "Once the map is done, the subscribe will log the output in the console as shown in the browser −" }, { "code": null, "e": 4408, "s": 4300, "text": "If you see, the json objects are displayed in the console. The objects can be displayed in the browser too." }, { "code": null, "e": 4529, "s": 4408, "text": "For the objects to be displayed in the browser, update the codes in app.component.html and app.component.ts as follows −" }, { "code": null, "e": 5084, "s": 4529, "text": "import { Component } from '@angular/core';\nimport { Http } from '@angular/http';\nimport { map} from 'rxjs/operators';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n constructor(private http: Http) { }\n httpdata;\n ngOnInit() {\n this.http.get(\"http://jsonplaceholder.typicode.com/users\")\n .pipe(map((response) => response.json()))\n .subscribe((data) => this.displaydata(data)); \n }\n displaydata(data) {this.httpdata = data;}\n}" }, { "code": null, "e": 5219, "s": 5084, "text": "In app.component.ts, using the subscribe method we will call the display data method and pass the data fetched as the parameter to it." }, { "code": null, "e": 5416, "s": 5219, "text": "In the display data method, we will store the data in a variable httpdata. The data is displayed in the browser using for over this httpdata variable, which is done in the app.component.html file." }, { "code": null, "e": 5524, "s": 5416, "text": "<ul *ngFor = \"let data of httpdata\">\n <li>Name : {{data.name}} Address: {{data.address.city}}</li>\n</ul>\n" }, { "code": null, "e": 5556, "s": 5524, "text": "The json object is as follows −" }, { "code": null, "e": 6109, "s": 5556, "text": "{\n \"id\": 1,\n \"name\": \"Leanne Graham\",\n \"username\": \"Bret\",\n \"email\": \"[email protected]\",\n \n \"address\": {\n \"street\": \"Kulas Light\",\n \"suite\": \"Apt. 556\",\n \"city\": \"Gwenborough\",\n \"zipcode\": \"92998-3874\",\n \"geo\": {\n \"lat\": \"-37.3159\",\n \"lng\": \"81.1496\"\n }\n },\n \n \"phone\": \"1-770-736-8031 x56442\",\n \"website\": \"hildegard.org\",\n \"company\": {\n \"name\": \"Romaguera-Crona\",\n \"catchPhrase\": \"Multi-layered client-server neural-net\",\n \"bs\": \"harness real-time e-markets\"\n }\n}\n" }, { "code": null, "e": 6401, "s": 6109, "text": "The object has properties such as id, name, username, email, and address that internally has street, city, etc. and other details related to phone, website, and company. Using the for loop, we will display the name and the city details in the browser as shown in the app.component.html file." }, { "code": null, "e": 6451, "s": 6401, "text": "This is how the display is shown in the browser −" }, { "code": null, "e": 6590, "s": 6451, "text": "Let us now add the search parameter, which will filter based on specific data. We need to fetch the data based on the search param passed." }, { "code": null, "e": 6672, "s": 6590, "text": "Following are the changes done in app.component.html and app.component.ts files −" }, { "code": null, "e": 7277, "s": 6672, "text": "import { Component } from '@angular/core';\nimport { Http } from '@angular/http';\nimport { map} from 'rxjs/operators';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n constructor(private http: Http) { }\n httpdata;\n name;\n searchparam = 2;\n ngOnInit() {\n this.http.get(\"http://jsonplaceholder.typicode.com/users?id=\"+this.searchparam)\n .pipe(map((response) => response.json()))\n .subscribe((data) => this.displaydata(data)); \n }\n displaydata(data) {this.httpdata = data;}\n}" }, { "code": null, "e": 7428, "s": 7277, "text": "For the get api, we will add the search param id = this.searchparam. The searchparam is equal to 2. We need the details of id = 2 from the json file. " }, { "code": null, "e": 7467, "s": 7428, "text": "This is how the browser is displayed −" }, { "code": null, "e": 7652, "s": 7467, "text": "We have consoled the data in the browser, which is received from the http. The same is displayed in the browser console. The name from the json with id = 2 is displayed in the browser." }, { "code": null, "e": 7687, "s": 7652, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7701, "s": 7687, "text": " Anadi Sharma" }, { "code": null, "e": 7736, "s": 7701, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7750, "s": 7736, "text": " Anadi Sharma" }, { "code": null, "e": 7785, "s": 7750, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 7805, "s": 7785, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 7840, "s": 7805, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7857, "s": 7840, "text": " Frahaan Hussain" }, { "code": null, "e": 7890, "s": 7857, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 7902, "s": 7890, "text": " Senol Atac" }, { "code": null, "e": 7937, "s": 7902, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7949, "s": 7937, "text": " Senol Atac" }, { "code": null, "e": 7956, "s": 7949, "text": " Print" }, { "code": null, "e": 7967, "s": 7956, "text": " Add Notes" } ]
MySQL - ALTER Command
The MySQL ALTER command is very useful when you want to change a name of your table, any table field or if you want to add or delete an existing column in a table. Let us begin with the creation of a table called testalter_tbl. root@host# mysql -u root -p password; Enter password:******* mysql> use TUTORIALS; Database changed mysql> create table testalter_tbl -> ( -> i INT, -> c CHAR(1) -> ); Query OK, 0 rows affected (0.05 sec) mysql> SHOW COLUMNS FROM testalter_tbl; +-------+---------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+---------+------+-----+---------+-------+ | i | int(11) | YES | | NULL | | | c | char(1) | YES | | NULL | | +-------+---------+------+-----+---------+-------+ 2 rows in set (0.00 sec) If you want to drop an existing column i from the above MySQL table, then you will use the DROP clause along with the ALTER command as shown below − mysql> ALTER TABLE testalter_tbl DROP i; A DROP clause will not work if the column is the only one left in the table. To add a column, use ADD and specify the column definition. The following statement restores the i column to the testalter_tbl − mysql> ALTER TABLE testalter_tbl ADD i INT; After issuing this statement, testalter will contain the same two columns that it had when you first created the table, but will not have the same structure. This is because there are new columns that are added to the end of the table by default. So even though i originally was the first column in mytbl, now it is the last one. mysql> SHOW COLUMNS FROM testalter_tbl; +-------+---------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+---------+------+-----+---------+-------+ | c | char(1) | YES | | NULL | | | i | int(11) | YES | | NULL | | +-------+---------+------+-----+---------+-------+ 2 rows in set (0.00 sec) To indicate that you want a column at a specific position within the table, either use FIRST to make it the first column or AFTER col_name to indicate that the new column should be placed after the col_name. Try the following ALTER TABLE statements, using SHOW COLUMNS after each one to see what effect each one has − ALTER TABLE testalter_tbl DROP i; ALTER TABLE testalter_tbl ADD i INT FIRST; ALTER TABLE testalter_tbl DROP i; ALTER TABLE testalter_tbl ADD i INT AFTER c; The FIRST and AFTER specifiers work only with the ADD clause. This means that if you want to reposition an existing column within a table, you first must DROP it and then ADD it at the new position. To change a column's definition, use MODIFY or CHANGE clause along with the ALTER command. For example, to change column c from CHAR(1) to CHAR(10), you can use the following command − mysql> ALTER TABLE testalter_tbl MODIFY c CHAR(10); With CHANGE, the syntax is a bit different. After the CHANGE keyword, you name the column you want to change, then specify the new definition, which includes the new name. Try out the following example − mysql> ALTER TABLE testalter_tbl CHANGE i j BIGINT; If you now use CHANGE to convert j from BIGINT back to INT without changing the column name, the statement will be as shown below − mysql> ALTER TABLE testalter_tbl CHANGE j j INT; The Effect of ALTER TABLE on Null and Default Value Attributes − When you MODIFY or CHANGE a column, you can also specify whether or not the column can contain NULL values and what its default value is. In fact, if you don't do this, MySQL automatically assigns values for these attributes. The following code block is an example, where the NOT NULL column will have the value as 100 by default. mysql> ALTER TABLE testalter_tbl -> MODIFY j BIGINT NOT NULL DEFAULT 100; If you don't use the above command, then MySQL will fill up NULL values in all the columns. You can change a default value for any column by using the ALTER command. Try out the following example. mysql> ALTER TABLE testalter_tbl ALTER i SET DEFAULT 1000; mysql> SHOW COLUMNS FROM testalter_tbl; +-------+---------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+---------+------+-----+---------+-------+ | c | char(1) | YES | | NULL | | | i | int(11) | YES | | 1000 | | +-------+---------+------+-----+---------+-------+ 2 rows in set (0.00 sec) You can remove the default constraint from any column by using DROP clause along with the ALTER command. mysql> ALTER TABLE testalter_tbl ALTER i DROP DEFAULT; mysql> SHOW COLUMNS FROM testalter_tbl; +-------+---------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+---------+------+-----+---------+-------+ | c | char(1) | YES | | NULL | | | i | int(11) | YES | | NULL | | +-------+---------+------+-----+---------+-------+ 2 rows in set (0.00 sec) You can use a table type by using the TYPE clause along with the ALTER command. Try out the following example to change the testalter_tbl to MYISAM table type. To find out the current type of a table, use the SHOW TABLE STATUS statement. mysql> ALTER TABLE testalter_tbl TYPE = MYISAM; mysql> SHOW TABLE STATUS LIKE 'testalter_tbl'\G *************************** 1. row **************** Name: testalter_tbl Type: MyISAM Row_format: Fixed Rows: 0 Avg_row_length: 0 Data_length: 0 Max_data_length: 25769803775 Index_length: 1024 Data_free: 0 Auto_increment: NULL Create_time: 2007-06-03 08:04:36 Update_time: 2007-06-03 08:04:36 Check_time: NULL Create_options: Comment: 1 row in set (0.00 sec) To rename a table, use the RENAME option of the ALTER TABLE statement. Try out the following example to rename testalter_tbl to alter_tbl. mysql> ALTER TABLE testalter_tbl RENAME TO alter_tbl; You can use the ALTER command to create and drop the INDEX command on a MySQL file. We will discuss in detail about this command in the next chapter. 31 Lectures 6 hours Eduonix Learning Solutions 84 Lectures 5.5 hours Frahaan Hussain 6 Lectures 3.5 hours DATAhill Solutions Srinivas Reddy 60 Lectures 10 hours Vijay Kumar Parvatha Reddy 10 Lectures 1 hours Harshit Srivastava 25 Lectures 4 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2497, "s": 2333, "text": "The MySQL ALTER command is very useful when you want to change a name of your table, any table field or if you want to add or delete an existing column in a table." }, { "code": null, "e": 2561, "s": 2497, "text": "Let us begin with the creation of a table called testalter_tbl." }, { "code": null, "e": 3151, "s": 2561, "text": "root@host# mysql -u root -p password;\nEnter password:*******\n\nmysql> use TUTORIALS;\nDatabase changed\n\nmysql> create table testalter_tbl\n -> (\n -> i INT,\n -> c CHAR(1)\n -> );\nQuery OK, 0 rows affected (0.05 sec)\nmysql> SHOW COLUMNS FROM testalter_tbl;\n+-------+---------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------+---------+------+-----+---------+-------+\n| i | int(11) | YES | | NULL | |\n| c | char(1) | YES | | NULL | |\n+-------+---------+------+-----+---------+-------+\n2 rows in set (0.00 sec)" }, { "code": null, "e": 3300, "s": 3151, "text": "If you want to drop an existing column i from the above MySQL table, then you will use the DROP clause along with the ALTER command as shown below −" }, { "code": null, "e": 3343, "s": 3300, "text": "mysql> ALTER TABLE testalter_tbl DROP i;\n" }, { "code": null, "e": 3420, "s": 3343, "text": "A DROP clause will not work if the column is the only one left in the table." }, { "code": null, "e": 3549, "s": 3420, "text": "To add a column, use ADD and specify the column definition. The following statement restores the i column to the testalter_tbl −" }, { "code": null, "e": 3594, "s": 3549, "text": "mysql> ALTER TABLE testalter_tbl ADD i INT;\n" }, { "code": null, "e": 3924, "s": 3594, "text": "After issuing this statement, testalter will contain the same two columns that it had when you first created the table, but will not have the same structure. This is because there are new columns that are added to the end of the table by default. So even though i originally was the first column in mytbl, now it is the last one." }, { "code": null, "e": 4296, "s": 3924, "text": "mysql> SHOW COLUMNS FROM testalter_tbl;\n+-------+---------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------+---------+------+-----+---------+-------+\n| c | char(1) | YES | | NULL | |\n| i | int(11) | YES | | NULL | |\n+-------+---------+------+-----+---------+-------+\n2 rows in set (0.00 sec)\n" }, { "code": null, "e": 4504, "s": 4296, "text": "To indicate that you want a column at a specific position within the table, either use FIRST to make it the first column or AFTER col_name to indicate that the new column should be placed after the col_name." }, { "code": null, "e": 4614, "s": 4504, "text": "Try the following ALTER TABLE statements, using SHOW COLUMNS after each one to see what effect each one has −" }, { "code": null, "e": 4771, "s": 4614, "text": "ALTER TABLE testalter_tbl DROP i;\nALTER TABLE testalter_tbl ADD i INT FIRST;\nALTER TABLE testalter_tbl DROP i;\nALTER TABLE testalter_tbl ADD i INT AFTER c;\n" }, { "code": null, "e": 4970, "s": 4771, "text": "The FIRST and AFTER specifiers work only with the ADD clause. This means that if you want to reposition an existing column within a table, you first must DROP it and then ADD it at the new position." }, { "code": null, "e": 5061, "s": 4970, "text": "To change a column's definition, use MODIFY or CHANGE clause along with the ALTER command." }, { "code": null, "e": 5155, "s": 5061, "text": "For example, to change column c from CHAR(1) to CHAR(10), you can use the following command −" }, { "code": null, "e": 5208, "s": 5155, "text": "mysql> ALTER TABLE testalter_tbl MODIFY c CHAR(10);\n" }, { "code": null, "e": 5380, "s": 5208, "text": "With CHANGE, the syntax is a bit different. After the CHANGE keyword, you name the column you want to change, then specify the new definition, which includes the new name." }, { "code": null, "e": 5412, "s": 5380, "text": "Try out the following example −" }, { "code": null, "e": 5465, "s": 5412, "text": "mysql> ALTER TABLE testalter_tbl CHANGE i j BIGINT;\n" }, { "code": null, "e": 5597, "s": 5465, "text": "If you now use CHANGE to convert j from BIGINT back to INT without changing the column name, the statement will be as shown below −" }, { "code": null, "e": 5647, "s": 5597, "text": "mysql> ALTER TABLE testalter_tbl CHANGE j j INT;\n" }, { "code": null, "e": 5938, "s": 5647, "text": "The Effect of ALTER TABLE on Null and Default Value Attributes − When you MODIFY or CHANGE a column, you can also specify whether or not the column can contain NULL values and what its default value is. In fact, if you don't do this, MySQL automatically assigns values for these attributes." }, { "code": null, "e": 6043, "s": 5938, "text": "The following code block is an example, where the NOT NULL column will have the value as 100 by default." }, { "code": null, "e": 6122, "s": 6043, "text": "mysql> ALTER TABLE testalter_tbl \n -> MODIFY j BIGINT NOT NULL DEFAULT 100;\n" }, { "code": null, "e": 6214, "s": 6122, "text": "If you don't use the above command, then MySQL will fill up NULL values in all the columns." }, { "code": null, "e": 6288, "s": 6214, "text": "You can change a default value for any column by using the ALTER command." }, { "code": null, "e": 6319, "s": 6288, "text": "Try out the following example." }, { "code": null, "e": 6750, "s": 6319, "text": "mysql> ALTER TABLE testalter_tbl ALTER i SET DEFAULT 1000;\nmysql> SHOW COLUMNS FROM testalter_tbl;\n+-------+---------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------+---------+------+-----+---------+-------+\n| c | char(1) | YES | | NULL | |\n| i | int(11) | YES | | 1000 | |\n+-------+---------+------+-----+---------+-------+\n2 rows in set (0.00 sec)\n" }, { "code": null, "e": 6855, "s": 6750, "text": "You can remove the default constraint from any column by using DROP clause along with the ALTER command." }, { "code": null, "e": 7282, "s": 6855, "text": "mysql> ALTER TABLE testalter_tbl ALTER i DROP DEFAULT;\nmysql> SHOW COLUMNS FROM testalter_tbl;\n+-------+---------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------+---------+------+-----+---------+-------+\n| c | char(1) | YES | | NULL | |\n| i | int(11) | YES | | NULL | |\n+-------+---------+------+-----+---------+-------+\n2 rows in set (0.00 sec)\n" }, { "code": null, "e": 7442, "s": 7282, "text": "You can use a table type by using the TYPE clause along with the ALTER command. Try out the following example to change the testalter_tbl to MYISAM table type." }, { "code": null, "e": 7520, "s": 7442, "text": "To find out the current type of a table, use the SHOW TABLE STATUS statement." }, { "code": null, "e": 8051, "s": 7520, "text": "mysql> ALTER TABLE testalter_tbl TYPE = MYISAM;\nmysql> SHOW TABLE STATUS LIKE 'testalter_tbl'\\G\n*************************** 1. row ****************\n Name: testalter_tbl\n Type: MyISAM\n Row_format: Fixed\n Rows: 0\n Avg_row_length: 0\n Data_length: 0\nMax_data_length: 25769803775\n Index_length: 1024\n Data_free: 0\n Auto_increment: NULL\n Create_time: 2007-06-03 08:04:36\n Update_time: 2007-06-03 08:04:36\n Check_time: NULL\n Create_options:\n Comment:\n1 row in set (0.00 sec)\n" }, { "code": null, "e": 8122, "s": 8051, "text": "To rename a table, use the RENAME option of the ALTER TABLE statement." }, { "code": null, "e": 8190, "s": 8122, "text": "Try out the following example to rename testalter_tbl to alter_tbl." }, { "code": null, "e": 8245, "s": 8190, "text": "mysql> ALTER TABLE testalter_tbl RENAME TO alter_tbl;\n" }, { "code": null, "e": 8395, "s": 8245, "text": "You can use the ALTER command to create and drop the INDEX command on a MySQL file. We will discuss in detail about this command in the next chapter." }, { "code": null, "e": 8428, "s": 8395, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 8456, "s": 8428, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 8491, "s": 8456, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 8508, "s": 8491, "text": " Frahaan Hussain" }, { "code": null, "e": 8542, "s": 8508, "text": "\n 6 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8577, "s": 8542, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 8611, "s": 8577, "text": "\n 60 Lectures \n 10 hours \n" }, { "code": null, "e": 8639, "s": 8611, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 8672, "s": 8639, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 8692, "s": 8672, "text": " Harshit Srivastava" }, { "code": null, "e": 8725, "s": 8692, "text": "\n 25 Lectures \n 4 hours \n" }, { "code": null, "e": 8743, "s": 8725, "text": " Trevoir Williams" }, { "code": null, "e": 8750, "s": 8743, "text": " Print" }, { "code": null, "e": 8761, "s": 8750, "text": " Add Notes" } ]
Set style to current link in a Navigation Bar with CSS
To set a style to current link in a navigation bar, add style to .active. You can try to run the following code to style current link: Live Demo <!DOCTYPE html> <html> <head> <style> ul { list-style-type: none; margin: 5; padding: 5; } li a { display: block; width: 70px; background-color: #F0E7E7; } .active { background-color: #4CAF50; color: white; } </style> </head> <body> <ul> <li><a href="#home">Home</a></li> <li><a href="#company" class="active">Company</a></li> <li><a href="#product">Product</a></li> <li><a href="#services">Services</a></li> <li><a href="#contact">Contact</a></li> </ul> </body> </html>
[ { "code": null, "e": 1197, "s": 1062, "text": "To set a style to current link in a navigation bar, add style to .active. You can try to run the following code to style current link:" }, { "code": null, "e": 1207, "s": 1197, "text": "Live Demo" }, { "code": null, "e": 1909, "s": 1207, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n ul {\n list-style-type: none;\n margin: 5;\n padding: 5;\n }\n li a {\n display: block;\n width: 70px;\n background-color: #F0E7E7;\n }\n .active {\n background-color: #4CAF50;\n color: white;\n }\n </style>\n </head>\n <body>\n <ul>\n <li><a href=\"#home\">Home</a></li>\n <li><a href=\"#company\" class=\"active\">Company</a></li>\n <li><a href=\"#product\">Product</a></li>\n <li><a href=\"#services\">Services</a></li>\n <li><a href=\"#contact\">Contact</a></li>\n </ul>\n </body>\n</html>" } ]
Delete items from dictionary while iterating in Python
A python dictionary is a collection which is unordered, changeable and indexed. They have keys and values and each item is referred using the key. In this article we will explore the ways to delete the items form a dictionary. In this approach we capture the key values that are needed to be deleted. Once we apply the del function, the key value pairs for those keys get deleted. Live Demo # Given dictionary ADict = {1: 'Mon', 2: 'Tue', 3: 'Wed',4:'Thu',5:'Fri'} # Get keys with value in 2,3. to_del = [key for key in ADict if key in(2,3)] # Delete keys for key in to_del: del ADict[key] # New Dictionary print(ADict) Running the above code gives us the following result − {1: 'Mon', 4: 'Thu', 5: 'Fri'} We can create a list containing the keys from the dictionary and also use a conditional expression to select the keys to be used for deletion. In the below example we have only considered the keys with even values by comparing the remainder from division with two equal to zero. Live Demo # Given dictionary ADict = {1: 'Mon', 2: 'Tue', 3: 'Wed',4:'Thu',5:'Fri'} # Get keys with even value for key in list(ADict): if (key%2) == 0: del ADict[key] # New Dictionary print(ADict) Running the above code gives us the following result − {1: 'Mon', 3: 'Wed', 5: 'Fri'} Instead of keys we can also use the items of the dictionary to delete the values. But after choosing the item we have to indirectly use the keys to select the items to be deleted. Live Demo # Given dictionary ADict = {1: 'Mon', 2: 'Tue', 3: 'Wed',4:'Thu',5:'Fri'} NewDict = [] # Get keys with even value for key,val in ADict.items(): if val in('Tue','Fri'): NewDict.append(key) for i in NewDict: del ADict[i] # New Dictionary print(ADict) Running the above code gives us the following result − {1: 'Mon', 3: 'Wed', 4: 'Thu'}
[ { "code": null, "e": 1289, "s": 1062, "text": "A python dictionary is a collection which is unordered, changeable and indexed. They have keys and values and each item is referred using the key. In this article we will explore the ways to delete the items form a dictionary." }, { "code": null, "e": 1443, "s": 1289, "text": "In this approach we capture the key values that are needed to be deleted. Once we apply the del function, the key value pairs for those keys get deleted." }, { "code": null, "e": 1454, "s": 1443, "text": " Live Demo" }, { "code": null, "e": 1686, "s": 1454, "text": "# Given dictionary\nADict = {1: 'Mon', 2: 'Tue', 3: 'Wed',4:'Thu',5:'Fri'}\n\n# Get keys with value in 2,3.\nto_del = [key for key in ADict if key in(2,3)]\n\n# Delete keys\nfor key in to_del: del ADict[key]\n\n# New Dictionary\nprint(ADict)" }, { "code": null, "e": 1741, "s": 1686, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1772, "s": 1741, "text": "{1: 'Mon', 4: 'Thu', 5: 'Fri'}" }, { "code": null, "e": 2051, "s": 1772, "text": "We can create a list containing the keys from the dictionary and also use a conditional expression to select the keys to be used for deletion. In the below example we have only considered the keys with even values by comparing the remainder from division with two equal to zero." }, { "code": null, "e": 2062, "s": 2051, "text": " Live Demo" }, { "code": null, "e": 2251, "s": 2062, "text": "# Given dictionary\nADict = {1: 'Mon', 2: 'Tue', 3: 'Wed',4:'Thu',5:'Fri'}\n\n# Get keys with even value\nfor key in list(ADict):\nif (key%2) == 0:\ndel ADict[key]\n\n# New Dictionary\nprint(ADict)" }, { "code": null, "e": 2306, "s": 2251, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2337, "s": 2306, "text": "{1: 'Mon', 3: 'Wed', 5: 'Fri'}" }, { "code": null, "e": 2517, "s": 2337, "text": "Instead of keys we can also use the items of the dictionary to delete the values. But after choosing the item we have to indirectly use the keys to select the items to be deleted." }, { "code": null, "e": 2528, "s": 2517, "text": " Live Demo" }, { "code": null, "e": 2780, "s": 2528, "text": "# Given dictionary\nADict = {1: 'Mon', 2: 'Tue', 3: 'Wed',4:'Thu',5:'Fri'}\n\nNewDict = []\n# Get keys with even value\nfor key,val in ADict.items():\nif val in('Tue','Fri'):\nNewDict.append(key)\n\nfor i in NewDict:\ndel ADict[i]\n\n# New Dictionary\nprint(ADict)" }, { "code": null, "e": 2835, "s": 2780, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2866, "s": 2835, "text": "{1: 'Mon', 3: 'Wed', 4: 'Thu'}" } ]
Java - Regular Expressions
Java provides the java.util.regex package for pattern matching with regular expressions. Java regular expressions are very similar to the Perl programming language and very easy to learn. A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. They can be used to search, edit, or manipulate text and data. The java.util.regex package primarily consists of the following three classes − Pattern Class − A Pattern object is a compiled representation of a regular expression. The Pattern class provides no public constructors. To create a pattern, you must first invoke one of its public static compile() methods, which will then return a Pattern object. These methods accept a regular expression as the first argument. Pattern Class − A Pattern object is a compiled representation of a regular expression. The Pattern class provides no public constructors. To create a pattern, you must first invoke one of its public static compile() methods, which will then return a Pattern object. These methods accept a regular expression as the first argument. Matcher Class − A Matcher object is the engine that interprets the pattern and performs match operations against an input string. Like the Pattern class, Matcher defines no public constructors. You obtain a Matcher object by invoking the matcher() method on a Pattern object. Matcher Class − A Matcher object is the engine that interprets the pattern and performs match operations against an input string. Like the Pattern class, Matcher defines no public constructors. You obtain a Matcher object by invoking the matcher() method on a Pattern object. PatternSyntaxException − A PatternSyntaxException object is an unchecked exception that indicates a syntax error in a regular expression pattern. PatternSyntaxException − A PatternSyntaxException object is an unchecked exception that indicates a syntax error in a regular expression pattern. Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d", "o", and "g". Capturing groups are numbered by counting their opening parentheses from the left to the right. In the expression ((A)(B(C))), for example, there are four such groups − ((A)(B(C))) (A) (B(C)) (C) To find out how many groups are present in the expression, call the groupCount method on a matcher object. The groupCount method returns an int showing the number of capturing groups present in the matcher's pattern. There is also a special group, group 0, which always represents the entire expression. This group is not included in the total reported by groupCount. Example Following example illustrates how to find a digit string from the given alphanumeric string − import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexMatches { public static void main( String args[] ) { // String to be scanned to find the pattern. String line = "This order was placed for QT3000! OK?"; String pattern = "(.*)(\\d+)(.*)"; // Create a Pattern object Pattern r = Pattern.compile(pattern); // Now create matcher object. Matcher m = r.matcher(line); if (m.find( )) { System.out.println("Found value: " + m.group(0) ); System.out.println("Found value: " + m.group(1) ); System.out.println("Found value: " + m.group(2) ); }else { System.out.println("NO MATCH"); } } } This will produce the following result − Output Found value: This order was placed for QT3000! OK? Found value: This order was placed for QT300 Found value: 0 Here is the table listing down all the regular expression metacharacter syntax available in Java − Here is a list of useful instance methods − Index methods provide useful index values that show precisely where the match was found in the input string − public int start() Returns the start index of the previous match. public int start(int group) Returns the start index of the subsequence captured by the given group during the previous match operation. public int end() Returns the offset after the last character matched. public int end(int group) Returns the offset after the last character of the subsequence captured by the given group during the previous match operation. Study methods review the input string and return a Boolean indicating whether or not the pattern is found − public boolean lookingAt() Attempts to match the input sequence, starting at the beginning of the region, against the pattern. public boolean find() Attempts to find the next subsequence of the input sequence that matches the pattern. public boolean find(int start) Resets this matcher and then attempts to find the next subsequence of the input sequence that matches the pattern, starting at the specified index. public boolean matches() Attempts to match the entire region against the pattern. Replacement methods are useful methods for replacing text in an input string − public Matcher appendReplacement(StringBuffer sb, String replacement) Implements a non-terminal append-and-replace step. public StringBuffer appendTail(StringBuffer sb) Implements a terminal append-and-replace step. public String replaceAll(String replacement) Replaces every subsequence of the input sequence that matches the pattern with the given replacement string. public String replaceFirst(String replacement) Replaces the first subsequence of the input sequence that matches the pattern with the given replacement string. public static String quoteReplacement(String s) Returns a literal replacement String for the specified String. This method produces a String that will work as a literal replacement s in the appendReplacement method of the Matcher class. Following is the example that counts the number of times the word "cat" appears in the input string − Example import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexMatches { private static final String REGEX = "\\bcat\\b"; private static final String INPUT = "cat cat cat cattie cat"; public static void main( String args[] ) { Pattern p = Pattern.compile(REGEX); Matcher m = p.matcher(INPUT); // get a matcher object int count = 0; while(m.find()) { count++; System.out.println("Match number "+count); System.out.println("start(): "+m.start()); System.out.println("end(): "+m.end()); } } } This will produce the following result − Output Match number 1 start(): 0 end(): 3 Match number 2 start(): 4 end(): 7 Match number 3 start(): 8 end(): 11 Match number 4 start(): 19 end(): 22 You can see that this example uses word boundaries to ensure that the letters "c" "a" "t" are not merely a substring in a longer word. It also gives some useful information about where in the input string the match has occurred. The start method returns the start index of the subsequence captured by the given group during the previous match operation, and the end returns the index of the last character matched, plus one. The matches and lookingAt methods both attempt to match an input sequence against a pattern. The difference, however, is that matches requires the entire input sequence to be matched, while lookingAt does not. Both methods always start at the beginning of the input string. Here is the example explaining the functionality − Example import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexMatches { private static final String REGEX = "foo"; private static final String INPUT = "fooooooooooooooooo"; private static Pattern pattern; private static Matcher matcher; public static void main( String args[] ) { pattern = Pattern.compile(REGEX); matcher = pattern.matcher(INPUT); System.out.println("Current REGEX is: "+REGEX); System.out.println("Current INPUT is: "+INPUT); System.out.println("lookingAt(): "+matcher.lookingAt()); System.out.println("matches(): "+matcher.matches()); } } This will produce the following result − Output Current REGEX is: foo Current INPUT is: fooooooooooooooooo lookingAt(): true matches(): false The replaceFirst and replaceAll methods replace the text that matches a given regular expression. As their names indicate, replaceFirst replaces the first occurrence, and replaceAll replaces all occurrences. Here is the example explaining the functionality − Example import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexMatches { private static String REGEX = "dog"; private static String INPUT = "The dog says meow. " + "All dogs say meow."; private static String REPLACE = "cat"; public static void main(String[] args) { Pattern p = Pattern.compile(REGEX); // get a matcher object Matcher m = p.matcher(INPUT); INPUT = m.replaceAll(REPLACE); System.out.println(INPUT); } } This will produce the following result − Output The cat says meow. All cats say meow. The Matcher class also provides appendReplacement and appendTail methods for text replacement. Here is the example explaining the functionality − Example import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexMatches { private static String REGEX = "a*b"; private static String INPUT = "aabfooaabfooabfoob"; private static String REPLACE = "-"; public static void main(String[] args) { Pattern p = Pattern.compile(REGEX); // get a matcher object Matcher m = p.matcher(INPUT); StringBuffer sb = new StringBuffer(); while(m.find()) { m.appendReplacement(sb, REPLACE); } m.appendTail(sb); System.out.println(sb.toString()); } } This will produce the following result − Output -foo-foo-foo- A PatternSyntaxException is an unchecked exception that indicates a syntax error in a regular expression pattern. The PatternSyntaxException class provides the following methods to help you determine what went wrong − public String getDescription() Retrieves the description of the error. public int getIndex() Retrieves the error index. public String getPattern() Retrieves the erroneous regular expression pattern. public String getMessage() Returns a multi-line string containing the description of the syntax error and its index, the erroneous regular expression pattern, and a visual indication of the error index within the pattern. 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2565, "s": 2377, "text": "Java provides the java.util.regex package for pattern matching with regular expressions. Java regular expressions are very similar to the Perl programming language and very easy to learn." }, { "code": null, "e": 2794, "s": 2565, "text": "A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. They can be used to search, edit, or manipulate text and data." }, { "code": null, "e": 2874, "s": 2794, "text": "The java.util.regex package primarily consists of the following three classes −" }, { "code": null, "e": 3205, "s": 2874, "text": "Pattern Class − A Pattern object is a compiled representation of a regular expression. The Pattern class provides no public constructors. To create a pattern, you must first invoke one of its public static compile() methods, which will then return a Pattern object. These methods accept a regular expression as the first argument." }, { "code": null, "e": 3536, "s": 3205, "text": "Pattern Class − A Pattern object is a compiled representation of a regular expression. The Pattern class provides no public constructors. To create a pattern, you must first invoke one of its public static compile() methods, which will then return a Pattern object. These methods accept a regular expression as the first argument." }, { "code": null, "e": 3812, "s": 3536, "text": "Matcher Class − A Matcher object is the engine that interprets the pattern and performs match operations against an input string. Like the Pattern class, Matcher defines no public constructors. You obtain a Matcher object by invoking the matcher() method on a Pattern object." }, { "code": null, "e": 4088, "s": 3812, "text": "Matcher Class − A Matcher object is the engine that interprets the pattern and performs match operations against an input string. Like the Pattern class, Matcher defines no public constructors. You obtain a Matcher object by invoking the matcher() method on a Pattern object." }, { "code": null, "e": 4234, "s": 4088, "text": "PatternSyntaxException − A PatternSyntaxException object is an unchecked exception that indicates a syntax error in a regular expression pattern." }, { "code": null, "e": 4380, "s": 4234, "text": "PatternSyntaxException − A PatternSyntaxException object is an unchecked exception that indicates a syntax error in a regular expression pattern." }, { "code": null, "e": 4647, "s": 4380, "text": "Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters \"d\", \"o\", and \"g\"." }, { "code": null, "e": 4816, "s": 4647, "text": "Capturing groups are numbered by counting their opening parentheses from the left to the right. In the expression ((A)(B(C))), for example, there are four such groups −" }, { "code": null, "e": 4828, "s": 4816, "text": "((A)(B(C)))" }, { "code": null, "e": 4832, "s": 4828, "text": "(A)" }, { "code": null, "e": 4839, "s": 4832, "text": "(B(C))" }, { "code": null, "e": 4843, "s": 4839, "text": "(C)" }, { "code": null, "e": 5060, "s": 4843, "text": "To find out how many groups are present in the expression, call the groupCount method on a matcher object. The groupCount method returns an int showing the number of capturing groups present in the matcher's pattern." }, { "code": null, "e": 5211, "s": 5060, "text": "There is also a special group, group 0, which always represents the entire expression. This group is not included in the total reported by groupCount." }, { "code": null, "e": 5219, "s": 5211, "text": "Example" }, { "code": null, "e": 5313, "s": 5219, "text": "Following example illustrates how to find a digit string from the given alphanumeric string −" }, { "code": null, "e": 6029, "s": 5313, "text": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class RegexMatches {\n\n public static void main( String args[] ) {\n // String to be scanned to find the pattern.\n String line = \"This order was placed for QT3000! OK?\";\n String pattern = \"(.*)(\\\\d+)(.*)\";\n\n // Create a Pattern object\n Pattern r = Pattern.compile(pattern);\n\n // Now create matcher object.\n Matcher m = r.matcher(line);\n if (m.find( )) {\n System.out.println(\"Found value: \" + m.group(0) );\n System.out.println(\"Found value: \" + m.group(1) );\n System.out.println(\"Found value: \" + m.group(2) );\n }else {\n System.out.println(\"NO MATCH\");\n }\n }\n}" }, { "code": null, "e": 6070, "s": 6029, "text": "This will produce the following result −" }, { "code": null, "e": 6077, "s": 6070, "text": "Output" }, { "code": null, "e": 6189, "s": 6077, "text": "Found value: This order was placed for QT3000! OK?\nFound value: This order was placed for QT300\nFound value: 0\n" }, { "code": null, "e": 6288, "s": 6189, "text": "Here is the table listing down all the regular expression metacharacter syntax available in Java −" }, { "code": null, "e": 6332, "s": 6288, "text": "Here is a list of useful instance methods −" }, { "code": null, "e": 6442, "s": 6332, "text": "Index methods provide useful index values that show precisely where the match was found in the input string −" }, { "code": null, "e": 6461, "s": 6442, "text": "public int start()" }, { "code": null, "e": 6508, "s": 6461, "text": "Returns the start index of the previous match." }, { "code": null, "e": 6536, "s": 6508, "text": "public int start(int group)" }, { "code": null, "e": 6644, "s": 6536, "text": "Returns the start index of the subsequence captured by the given group during the previous match operation." }, { "code": null, "e": 6661, "s": 6644, "text": "public int end()" }, { "code": null, "e": 6714, "s": 6661, "text": "Returns the offset after the last character matched." }, { "code": null, "e": 6740, "s": 6714, "text": "public int end(int group)" }, { "code": null, "e": 6868, "s": 6740, "text": "Returns the offset after the last character of the subsequence captured by the given group during the previous match operation." }, { "code": null, "e": 6976, "s": 6868, "text": "Study methods review the input string and return a Boolean indicating whether or not the pattern is found −" }, { "code": null, "e": 7003, "s": 6976, "text": "public boolean lookingAt()" }, { "code": null, "e": 7103, "s": 7003, "text": "Attempts to match the input sequence, starting at the beginning of the region, against the pattern." }, { "code": null, "e": 7125, "s": 7103, "text": "public boolean find()" }, { "code": null, "e": 7211, "s": 7125, "text": "Attempts to find the next subsequence of the input sequence that matches the pattern." }, { "code": null, "e": 7242, "s": 7211, "text": "public boolean find(int start)" }, { "code": null, "e": 7390, "s": 7242, "text": "Resets this matcher and then attempts to find the next subsequence of the input sequence that matches the pattern, starting at the specified index." }, { "code": null, "e": 7415, "s": 7390, "text": "public boolean matches()" }, { "code": null, "e": 7472, "s": 7415, "text": "Attempts to match the entire region against the pattern." }, { "code": null, "e": 7551, "s": 7472, "text": "Replacement methods are useful methods for replacing text in an input string −" }, { "code": null, "e": 7621, "s": 7551, "text": "public Matcher appendReplacement(StringBuffer sb, String replacement)" }, { "code": null, "e": 7672, "s": 7621, "text": "Implements a non-terminal append-and-replace step." }, { "code": null, "e": 7720, "s": 7672, "text": "public StringBuffer appendTail(StringBuffer sb)" }, { "code": null, "e": 7767, "s": 7720, "text": "Implements a terminal append-and-replace step." }, { "code": null, "e": 7812, "s": 7767, "text": "public String replaceAll(String replacement)" }, { "code": null, "e": 7921, "s": 7812, "text": "Replaces every subsequence of the input sequence that matches the pattern with the given replacement string." }, { "code": null, "e": 7968, "s": 7921, "text": "public String replaceFirst(String replacement)" }, { "code": null, "e": 8081, "s": 7968, "text": "Replaces the first subsequence of the input sequence that matches the pattern with the given replacement string." }, { "code": null, "e": 8129, "s": 8081, "text": "public static String quoteReplacement(String s)" }, { "code": null, "e": 8318, "s": 8129, "text": "Returns a literal replacement String for the specified String. This method produces a String that will work as a literal replacement s in the appendReplacement method of the Matcher class." }, { "code": null, "e": 8420, "s": 8318, "text": "Following is the example that counts the number of times the word \"cat\" appears in the input string −" }, { "code": null, "e": 8428, "s": 8420, "text": "Example" }, { "code": null, "e": 9021, "s": 8428, "text": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class RegexMatches {\n\n private static final String REGEX = \"\\\\bcat\\\\b\";\n private static final String INPUT = \"cat cat cat cattie cat\";\n\n public static void main( String args[] ) {\n Pattern p = Pattern.compile(REGEX);\n Matcher m = p.matcher(INPUT); // get a matcher object\n int count = 0;\n\n while(m.find()) {\n count++;\n System.out.println(\"Match number \"+count);\n System.out.println(\"start(): \"+m.start());\n System.out.println(\"end(): \"+m.end());\n }\n }\n}" }, { "code": null, "e": 9062, "s": 9021, "text": "This will produce the following result −" }, { "code": null, "e": 9069, "s": 9062, "text": "Output" }, { "code": null, "e": 9213, "s": 9069, "text": "Match number 1\nstart(): 0\nend(): 3\nMatch number 2\nstart(): 4\nend(): 7\nMatch number 3\nstart(): 8\nend(): 11\nMatch number 4\nstart(): 19\nend(): 22\n" }, { "code": null, "e": 9442, "s": 9213, "text": "You can see that this example uses word boundaries to ensure that the letters \"c\" \"a\" \"t\" are not merely a substring in a longer word. It also gives some useful information about where in the input string the match has occurred." }, { "code": null, "e": 9638, "s": 9442, "text": "The start method returns the start index of the subsequence captured by the given group during the previous match operation, and the end returns the index of the last character matched, plus one." }, { "code": null, "e": 9848, "s": 9638, "text": "The matches and lookingAt methods both attempt to match an input sequence against a pattern. The difference, however, is that matches requires the entire input sequence to be matched, while lookingAt does not." }, { "code": null, "e": 9963, "s": 9848, "text": "Both methods always start at the beginning of the input string. Here is the example explaining the functionality −" }, { "code": null, "e": 9971, "s": 9963, "text": "Example" }, { "code": null, "e": 10608, "s": 9971, "text": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class RegexMatches {\n\n private static final String REGEX = \"foo\";\n private static final String INPUT = \"fooooooooooooooooo\";\n private static Pattern pattern;\n private static Matcher matcher;\n\n public static void main( String args[] ) {\n pattern = Pattern.compile(REGEX);\n matcher = pattern.matcher(INPUT);\n\n System.out.println(\"Current REGEX is: \"+REGEX);\n System.out.println(\"Current INPUT is: \"+INPUT);\n\n System.out.println(\"lookingAt(): \"+matcher.lookingAt());\n System.out.println(\"matches(): \"+matcher.matches());\n }\n}" }, { "code": null, "e": 10649, "s": 10608, "text": "This will produce the following result −" }, { "code": null, "e": 10656, "s": 10649, "text": "Output" }, { "code": null, "e": 10751, "s": 10656, "text": "Current REGEX is: foo\nCurrent INPUT is: fooooooooooooooooo\nlookingAt(): true\nmatches(): false\n" }, { "code": null, "e": 10959, "s": 10751, "text": "The replaceFirst and replaceAll methods replace the text that matches a given regular expression. As their names indicate, replaceFirst replaces the first occurrence, and replaceAll replaces all occurrences." }, { "code": null, "e": 11010, "s": 10959, "text": "Here is the example explaining the functionality −" }, { "code": null, "e": 11018, "s": 11010, "text": "Example" }, { "code": null, "e": 11511, "s": 11018, "text": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class RegexMatches {\n\n private static String REGEX = \"dog\";\n private static String INPUT = \"The dog says meow. \" + \"All dogs say meow.\";\n private static String REPLACE = \"cat\";\n\n public static void main(String[] args) {\n Pattern p = Pattern.compile(REGEX);\n \n // get a matcher object\n Matcher m = p.matcher(INPUT); \n INPUT = m.replaceAll(REPLACE);\n System.out.println(INPUT);\n }\n}" }, { "code": null, "e": 11552, "s": 11511, "text": "This will produce the following result −" }, { "code": null, "e": 11559, "s": 11552, "text": "Output" }, { "code": null, "e": 11598, "s": 11559, "text": "The cat says meow. All cats say meow.\n" }, { "code": null, "e": 11693, "s": 11598, "text": "The Matcher class also provides appendReplacement and appendTail methods for text replacement." }, { "code": null, "e": 11744, "s": 11693, "text": "Here is the example explaining the functionality −" }, { "code": null, "e": 11752, "s": 11744, "text": "Example" }, { "code": null, "e": 12332, "s": 11752, "text": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class RegexMatches {\n\n private static String REGEX = \"a*b\";\n private static String INPUT = \"aabfooaabfooabfoob\";\n private static String REPLACE = \"-\";\n public static void main(String[] args) {\n\n Pattern p = Pattern.compile(REGEX);\n \n // get a matcher object\n Matcher m = p.matcher(INPUT);\n StringBuffer sb = new StringBuffer();\n while(m.find()) {\n m.appendReplacement(sb, REPLACE);\n }\n m.appendTail(sb);\n System.out.println(sb.toString());\n }\n}" }, { "code": null, "e": 12373, "s": 12332, "text": "This will produce the following result −" }, { "code": null, "e": 12380, "s": 12373, "text": "Output" }, { "code": null, "e": 12395, "s": 12380, "text": "-foo-foo-foo-\n" }, { "code": null, "e": 12613, "s": 12395, "text": "A PatternSyntaxException is an unchecked exception that indicates a syntax error in a regular expression pattern. The PatternSyntaxException class provides the following methods to help you determine what went wrong −" }, { "code": null, "e": 12644, "s": 12613, "text": "public String getDescription()" }, { "code": null, "e": 12684, "s": 12644, "text": "Retrieves the description of the error." }, { "code": null, "e": 12706, "s": 12684, "text": "public int getIndex()" }, { "code": null, "e": 12733, "s": 12706, "text": "Retrieves the error index." }, { "code": null, "e": 12760, "s": 12733, "text": "public String getPattern()" }, { "code": null, "e": 12812, "s": 12760, "text": "Retrieves the erroneous regular expression pattern." }, { "code": null, "e": 12839, "s": 12812, "text": "public String getMessage()" }, { "code": null, "e": 13034, "s": 12839, "text": "Returns a multi-line string containing the description of the syntax error and its index, the erroneous regular expression pattern, and a visual indication of the error index within the pattern." }, { "code": null, "e": 13067, "s": 13034, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 13083, "s": 13067, "text": " Malhar Lathkar" }, { "code": null, "e": 13116, "s": 13083, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 13132, "s": 13116, "text": " Malhar Lathkar" }, { "code": null, "e": 13167, "s": 13132, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 13181, "s": 13167, "text": " Anadi Sharma" }, { "code": null, "e": 13215, "s": 13181, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 13229, "s": 13215, "text": " Tushar Kale" }, { "code": null, "e": 13266, "s": 13229, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 13281, "s": 13266, "text": " Monica Mittal" }, { "code": null, "e": 13314, "s": 13281, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 13333, "s": 13314, "text": " Arnab Chakraborty" }, { "code": null, "e": 13340, "s": 13333, "text": " Print" }, { "code": null, "e": 13351, "s": 13340, "text": " Add Notes" } ]
Python - Remove Top level from Dictionary - GeeksforGeeks
22 Apr, 2020 Sometimes, while working with Python Dictionaries, we can have nesting of dictionaries, with each key being single values dictionary. In this we need to remove the top level of dictionary. This can have application in data preprocessing. Lets discuss certain ways in which this task can be performed. Method #1 : Using values() + dictionary comprehensionThe combination of above functions can be used to solve this problem. In this, we perform the task of dictionary reconstruction using dictionary comprehension and nested lists are extracted using values(). # Python3 code to demonstrate working of # Remove Top level from Dictionary# Using dictionary comprehension + values() # initializing dictionarytest_dict = {'gfg' : {'data1' : [4, 5, 6, 7]}, 'is' : {'data2' : [1, 3, 8]}, 'best' : {'data3' : [9, 10, 13]}} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Remove Top level from Dictionary# Using dictionary comprehension + values()res = dict(ele for sub in test_dict.values() for ele in sub.items()) # printing result print("The top level removed dictionary is : " + str(res)) The original dictionary is : {‘is’: {‘data2’: [1, 3, 8]}, ‘gfg’: {‘data1’: [4, 5, 6, 7]}, ‘best’: {‘data3’: [9, 10, 13]}}The top level removed dictionary is : {‘data1’: [4, 5, 6, 7], ‘data2’: [1, 3, 8], ‘data3’: [9, 10, 13]} Method #2 : Using ChainMap() + dict()The combination of above functionalities can also be used to solve this problem. In this, we employ ChainMap() to perform mapping of nested values. # Python3 code to demonstrate working of # Remove Top level from Dictionary# Using ChainMap() + dict()from collections import ChainMap # initializing dictionarytest_dict = {'gfg' : {'data1' : [4, 5, 6, 7]}, 'is' : {'data2' : [1, 3, 8]}, 'best' : {'data3' : [9, 10, 13]}} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Remove Top level from Dictionary# Using ChainMap() + dict()res = dict(ChainMap(*test_dict.values())) # printing result print("The top level removed dictionary is : " + str(res)) The original dictionary is : {‘is’: {‘data2’: [1, 3, 8]}, ‘gfg’: {‘data1’: [4, 5, 6, 7]}, ‘best’: {‘data3’: [9, 10, 13]}}The top level removed dictionary is : {‘data1’: [4, 5, 6, 7], ‘data2’: [1, 3, 8], ‘data3’: [9, 10, 13]} Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n22 Apr, 2020" }, { "code": null, "e": 25838, "s": 25537, "text": "Sometimes, while working with Python Dictionaries, we can have nesting of dictionaries, with each key being single values dictionary. In this we need to remove the top level of dictionary. This can have application in data preprocessing. Lets discuss certain ways in which this task can be performed." }, { "code": null, "e": 26097, "s": 25838, "text": "Method #1 : Using values() + dictionary comprehensionThe combination of above functions can be used to solve this problem. In this, we perform the task of dictionary reconstruction using dictionary comprehension and nested lists are extracted using values()." }, { "code": "# Python3 code to demonstrate working of # Remove Top level from Dictionary# Using dictionary comprehension + values() # initializing dictionarytest_dict = {'gfg' : {'data1' : [4, 5, 6, 7]}, 'is' : {'data2' : [1, 3, 8]}, 'best' : {'data3' : [9, 10, 13]}} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Remove Top level from Dictionary# Using dictionary comprehension + values()res = dict(ele for sub in test_dict.values() for ele in sub.items()) # printing result print(\"The top level removed dictionary is : \" + str(res)) ", "e": 26694, "s": 26097, "text": null }, { "code": null, "e": 26919, "s": 26694, "text": "The original dictionary is : {‘is’: {‘data2’: [1, 3, 8]}, ‘gfg’: {‘data1’: [4, 5, 6, 7]}, ‘best’: {‘data3’: [9, 10, 13]}}The top level removed dictionary is : {‘data1’: [4, 5, 6, 7], ‘data2’: [1, 3, 8], ‘data3’: [9, 10, 13]}" }, { "code": null, "e": 27106, "s": 26921, "text": "Method #2 : Using ChainMap() + dict()The combination of above functionalities can also be used to solve this problem. In this, we employ ChainMap() to perform mapping of nested values." }, { "code": "# Python3 code to demonstrate working of # Remove Top level from Dictionary# Using ChainMap() + dict()from collections import ChainMap # initializing dictionarytest_dict = {'gfg' : {'data1' : [4, 5, 6, 7]}, 'is' : {'data2' : [1, 3, 8]}, 'best' : {'data3' : [9, 10, 13]}} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Remove Top level from Dictionary# Using ChainMap() + dict()res = dict(ChainMap(*test_dict.values())) # printing result print(\"The top level removed dictionary is : \" + str(res)) ", "e": 27676, "s": 27106, "text": null }, { "code": null, "e": 27901, "s": 27676, "text": "The original dictionary is : {‘is’: {‘data2’: [1, 3, 8]}, ‘gfg’: {‘data1’: [4, 5, 6, 7]}, ‘best’: {‘data3’: [9, 10, 13]}}The top level removed dictionary is : {‘data1’: [4, 5, 6, 7], ‘data2’: [1, 3, 8], ‘data3’: [9, 10, 13]}" }, { "code": null, "e": 27928, "s": 27901, "text": "Python dictionary-programs" }, { "code": null, "e": 27935, "s": 27928, "text": "Python" }, { "code": null, "e": 27951, "s": 27935, "text": "Python Programs" }, { "code": null, "e": 28049, "s": 27951, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28081, "s": 28049, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28123, "s": 28081, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28165, "s": 28123, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28192, "s": 28165, "text": "Python Classes and Objects" }, { "code": null, "e": 28248, "s": 28192, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28270, "s": 28248, "text": "Defaultdict in Python" }, { "code": null, "e": 28309, "s": 28270, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28355, "s": 28309, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28393, "s": 28355, "text": "Python | Convert a list to dictionary" } ]
Assign Mice to Holes - GeeksforGeeks
31 Mar, 2021 There are N Mice and N holes are placed in a straight line. Each hole can accommodate only 1 mouse. A mouse can stay at his position, move one step right from x to x + 1, or move one step left from x to x -1. Any of these moves consumes 1 minute. Assign mice to holes so that the time when the last mouse gets inside a hole is minimized. Examples: Input : positions of mice are: 4 -4 2 positions of holes are: 4 0 5 Output : 4 Assign mouse at position x = 4 to hole at position x = 4 : Time taken is 0 minutes Assign mouse at position x=-4 to hole at position x = 0 : Time taken is 4 minutes Assign mouse at position x=2 to hole at position x = 5 : Time taken is 3 minutes After 4 minutes all of the mice are in the holes. Since, there is no combination possible where the last mouse's time is less than 4, answer = 4. Input : positions of mice are: -10, -79, -79, 67, 93, -85, -28, -94 positions of holes are: -2, 9, 69, 25, -31, 23, 50, 78 Output : 102 This problem can be solved using greedy strategy. We can put every mouse to its nearest hole to minimize the time. This can be done by sorting the positions of mice and holes. This allows us to put the ith mice to the corresponding hole in the holes list. We can then find the maximum difference between the mice and corresponding hole position. In example 2, on sorting both the lists, we find that the mouse at position -79 is the last to travel to hole 23 taking time 102. sort mice positions (in any order) sort hole positions Loop i = 1 to N: update ans according to the value of |mice(i) - hole(i)|. It should be maximum of all differences. Proof of correctness: Let i1 < i2 be the positions of two mice and let j1 < j2 be the positions of two holes. It suffices to show via case analysis that max(|i1-j1|, |i2-j2|) <= max(|i1-j2|, |i2-j1|), where '|a - b|' represent absolute value of (a - b) Since it follows by induction that every assignment can be transformed by a series of swaps into the sorted assignment, where none of these swaps increases the span. C++ Java Python3 C# Javascript // C++ program to find the minimum// time to place all mice in all holes.#include <bits/stdc++.h>using namespace std; // Returns minimum time required// to place mice in holes.int assignHole(int mices[], int holes[], int n, int m){ // Base Condition // No. of mouse and holes should be same if (n != m) return -1; // Sort the arrays sort(mices, mices + n); sort(holes, holes + m); // Finding max difference between // ith mice and hole int max = 0; for(int i = 0; i < n; ++i) { if (max < abs(mices[i] - holes[i])) max = abs(mices[i] - holes[i]); } return max;} // Driver Codeint main(){ // Position of mouses int mices[] = { 4, -4, 2 }; // Position of holes int holes[] = { 4, 0, 5 }; // Number of mouses int n = sizeof(mices) / sizeof(mices[0]); // Number of holes int m = sizeof(holes) / sizeof(holes[0]); // The required answer is returned // from the function int minTime = assignHole(mices, holes, n, m); cout << "The last mouse gets into the hole in time:" << minTime << endl; return 0;} // This code is contributed by Aayush Garg // Java program to find the minimum time to place// all mice in all holes.import java.util.* ; public class GFG{ // Returns minimum time required to place mice // in holes. public int assignHole(ArrayList<Integer> mice, ArrayList<Integer> holes) { if (mice.size() != holes.size()) return -1; /* Sort the lists */ Collections.sort(mice); Collections.sort(holes); int size = mice.size(); /* finding max difference between ith mice and hole */ int max = 0; for (int i=0; i<size; i++) if (max < Math.abs(mice.get(i)-holes.get(i))) max = Math.abs(mice.get(i)-holes.get(i)); return Math.abs(max); } /* Driver Function to test other functions */ public static void main(String[] args) { GFG gfg = new GFG(); ArrayList<Integer> mice = new ArrayList<Integer>(); mice.add(4); mice.add(-4); mice.add(2); ArrayList<Integer> holes= new ArrayList<Integer>(); holes.add(4); holes.add(0); holes.add(5); System.out.println("The last mouse gets into "+ "the hole in time: "+gfg.assignHole(mice, holes)); }} # Python3 program to find the minimum# time to place all mice in all holes. # Returns minimum time required# to place mice in holes.def assignHole(mices, holes, n, m): # Base Condition # No. of mouse and holes should be same if (n != m): return -1 # Sort the arrays mices.sort() holes.sort() # Finding max difference between # ith mice and hole Max = 0 for i in range(n): if (Max < abs(mices[i] - holes[i])): Max = abs(mices[i] - holes[i]) return Max # Driver code # Position of mousesmices = [ 4, -4, 2 ] # Position of holesholes = [ 4, 0, 5 ] # Number of mousesn = len(mices) # Number of holesm = len(holes) # The required answer is returned# from the functionminTime = assignHole(mices, holes, n, m) print("The last mouse gets into the hole in time:", minTime) # This code is contributed by divyeshrabadiya07 // C# program to find the minimum// time to place all mice in all holes.using System;class GFG{ // Returns minimum time required // to place mice in holes. static int assignHole(int[] mices, int[] holes, int n, int m) { // Base Condition // No. of mouse and holes should be same if (n != m) return -1; // Sort the arrays Array.Sort(mices); Array.Sort(holes); // Finding max difference between // ith mice and hole int max = 0; for(int i = 0; i < n; ++i) { if (max < Math.Abs(mices[i] - holes[i])) max = Math.Abs(mices[i] - holes[i]); } return max; } // Driver code static void Main() { // Position of mouses int[] mices = { 4, -4, 2 }; // Position of holes int[] holes = { 4, 0, 5 }; // Number of mouses int n = mices.Length; // Number of holes int m = holes.Length; // The required answer is returned // from the function int minTime = assignHole(mices, holes, n, m); Console.WriteLine("The last mouse gets into the hole in time: " + minTime); }} // This code is contributed by divyesh072019 <script> // Javascript program to find the minimum // time to place all mice in all holes. // Returns minimum time required // to place mice in holes. function assignHole(mices, holes, n, m) { // Base Condition // No. of mouse and holes should be same if (n != m) return -1; // Sort the arrays mices.sort(); holes.sort(); // Finding max difference between // ith mice and hole let max = 0; for(let i = 0; i < n; ++i) { if (max < Math.abs(mices[i] - holes[i])) max = Math.abs(mices[i] - holes[i]); } return max; } // Position of mouses let mices = [ 4, -4, 2 ]; // Position of holes let holes = [ 4, 0, 5 ]; // Number of mouses let n = mices.length; // Number of holes let m = holes.length; // The required answer is returned // from the function let minTime = assignHole(mices, holes, n, m); document.write("The last mouse gets into the hole in time:" + minTime); // This code is contributed by mukesh07.</script> The last mouse gets into the hole in time: 4 This article is contributed by Saloni Baweja. 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. aayushgarg06 divyeshrabadiya07 divyesh072019 mukesh07 Greedy Mathematical Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Huffman Coding | Greedy Algo-3 Activity Selection Problem | Greedy Algo-1 Fractional Knapsack Problem Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Job Sequencing Problem C++ Data Types Set in C++ Standard Template Library (STL) Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples
[ { "code": null, "e": 26097, "s": 26069, "text": "\n31 Mar, 2021" }, { "code": null, "e": 26435, "s": 26097, "text": "There are N Mice and N holes are placed in a straight line. Each hole can accommodate only 1 mouse. A mouse can stay at his position, move one step right from x to x + 1, or move one step left from x to x -1. Any of these moves consumes 1 minute. Assign mice to holes so that the time when the last mouse gets inside a hole is minimized." }, { "code": null, "e": 26446, "s": 26435, "text": "Examples: " }, { "code": null, "e": 27120, "s": 26446, "text": "Input : positions of mice are:\n 4 -4 2\n positions of holes are:\n 4 0 5\nOutput : 4\nAssign mouse at position x = 4 to hole at \nposition x = 4 : Time taken is 0 minutes \nAssign mouse at position x=-4 to hole at \nposition x = 0 : Time taken is 4 minutes \nAssign mouse at position x=2 to hole at \nposition x = 5 : Time taken is 3 minutes \nAfter 4 minutes all of the mice are in the holes.\nSince, there is no combination possible where\nthe last mouse's time is less than 4, \nanswer = 4.\n\nInput : positions of mice are:\n -10, -79, -79, 67, 93, -85, -28, -94 \n positions of holes are:\n -2, 9, 69, 25, -31, 23, 50, 78 \nOutput : 102" }, { "code": null, "e": 27467, "s": 27120, "text": "This problem can be solved using greedy strategy. We can put every mouse to its nearest hole to minimize the time. This can be done by sorting the positions of mice and holes. This allows us to put the ith mice to the corresponding hole in the holes list. We can then find the maximum difference between the mice and corresponding hole position. " }, { "code": null, "e": 27597, "s": 27467, "text": "In example 2, on sorting both the lists, we find that the mouse at position -79 is the last to travel to hole 23 taking time 102." }, { "code": null, "e": 27783, "s": 27597, "text": "sort mice positions (in any order)\nsort hole positions \n\nLoop i = 1 to N:\n update ans according to the value \n of |mice(i) - hole(i)|. It should\n be maximum of all differences." }, { "code": null, "e": 27937, "s": 27783, "text": "Proof of correctness: Let i1 < i2 be the positions of two mice and let j1 < j2 be the positions of two holes. It suffices to show via case analysis that " }, { "code": null, "e": 28041, "s": 27937, "text": "max(|i1-j1|, |i2-j2|) <= max(|i1-j2|, |i2-j1|), \n where '|a - b|' represent absolute value of (a - b)" }, { "code": null, "e": 28208, "s": 28041, "text": "Since it follows by induction that every assignment can be transformed by a series of swaps into the sorted assignment, where none of these swaps increases the span. " }, { "code": null, "e": 28212, "s": 28208, "text": "C++" }, { "code": null, "e": 28217, "s": 28212, "text": "Java" }, { "code": null, "e": 28225, "s": 28217, "text": "Python3" }, { "code": null, "e": 28228, "s": 28225, "text": "C#" }, { "code": null, "e": 28239, "s": 28228, "text": "Javascript" }, { "code": "// C++ program to find the minimum// time to place all mice in all holes.#include <bits/stdc++.h>using namespace std; // Returns minimum time required// to place mice in holes.int assignHole(int mices[], int holes[], int n, int m){ // Base Condition // No. of mouse and holes should be same if (n != m) return -1; // Sort the arrays sort(mices, mices + n); sort(holes, holes + m); // Finding max difference between // ith mice and hole int max = 0; for(int i = 0; i < n; ++i) { if (max < abs(mices[i] - holes[i])) max = abs(mices[i] - holes[i]); } return max;} // Driver Codeint main(){ // Position of mouses int mices[] = { 4, -4, 2 }; // Position of holes int holes[] = { 4, 0, 5 }; // Number of mouses int n = sizeof(mices) / sizeof(mices[0]); // Number of holes int m = sizeof(holes) / sizeof(holes[0]); // The required answer is returned // from the function int minTime = assignHole(mices, holes, n, m); cout << \"The last mouse gets into the hole in time:\" << minTime << endl; return 0;} // This code is contributed by Aayush Garg", "e": 29440, "s": 28239, "text": null }, { "code": "// Java program to find the minimum time to place// all mice in all holes.import java.util.* ; public class GFG{ // Returns minimum time required to place mice // in holes. public int assignHole(ArrayList<Integer> mice, ArrayList<Integer> holes) { if (mice.size() != holes.size()) return -1; /* Sort the lists */ Collections.sort(mice); Collections.sort(holes); int size = mice.size(); /* finding max difference between ith mice and hole */ int max = 0; for (int i=0; i<size; i++) if (max < Math.abs(mice.get(i)-holes.get(i))) max = Math.abs(mice.get(i)-holes.get(i)); return Math.abs(max); } /* Driver Function to test other functions */ public static void main(String[] args) { GFG gfg = new GFG(); ArrayList<Integer> mice = new ArrayList<Integer>(); mice.add(4); mice.add(-4); mice.add(2); ArrayList<Integer> holes= new ArrayList<Integer>(); holes.add(4); holes.add(0); holes.add(5); System.out.println(\"The last mouse gets into \"+ \"the hole in time: \"+gfg.assignHole(mice, holes)); }}", "e": 30662, "s": 29440, "text": null }, { "code": "# Python3 program to find the minimum# time to place all mice in all holes. # Returns minimum time required# to place mice in holes.def assignHole(mices, holes, n, m): # Base Condition # No. of mouse and holes should be same if (n != m): return -1 # Sort the arrays mices.sort() holes.sort() # Finding max difference between # ith mice and hole Max = 0 for i in range(n): if (Max < abs(mices[i] - holes[i])): Max = abs(mices[i] - holes[i]) return Max # Driver code # Position of mousesmices = [ 4, -4, 2 ] # Position of holesholes = [ 4, 0, 5 ] # Number of mousesn = len(mices) # Number of holesm = len(holes) # The required answer is returned# from the functionminTime = assignHole(mices, holes, n, m) print(\"The last mouse gets into the hole in time:\", minTime) # This code is contributed by divyeshrabadiya07", "e": 31564, "s": 30662, "text": null }, { "code": "// C# program to find the minimum// time to place all mice in all holes.using System;class GFG{ // Returns minimum time required // to place mice in holes. static int assignHole(int[] mices, int[] holes, int n, int m) { // Base Condition // No. of mouse and holes should be same if (n != m) return -1; // Sort the arrays Array.Sort(mices); Array.Sort(holes); // Finding max difference between // ith mice and hole int max = 0; for(int i = 0; i < n; ++i) { if (max < Math.Abs(mices[i] - holes[i])) max = Math.Abs(mices[i] - holes[i]); } return max; } // Driver code static void Main() { // Position of mouses int[] mices = { 4, -4, 2 }; // Position of holes int[] holes = { 4, 0, 5 }; // Number of mouses int n = mices.Length; // Number of holes int m = holes.Length; // The required answer is returned // from the function int minTime = assignHole(mices, holes, n, m); Console.WriteLine(\"The last mouse gets into the hole in time: \" + minTime); }} // This code is contributed by divyesh072019", "e": 32826, "s": 31564, "text": null }, { "code": "<script> // Javascript program to find the minimum // time to place all mice in all holes. // Returns minimum time required // to place mice in holes. function assignHole(mices, holes, n, m) { // Base Condition // No. of mouse and holes should be same if (n != m) return -1; // Sort the arrays mices.sort(); holes.sort(); // Finding max difference between // ith mice and hole let max = 0; for(let i = 0; i < n; ++i) { if (max < Math.abs(mices[i] - holes[i])) max = Math.abs(mices[i] - holes[i]); } return max; } // Position of mouses let mices = [ 4, -4, 2 ]; // Position of holes let holes = [ 4, 0, 5 ]; // Number of mouses let n = mices.length; // Number of holes let m = holes.length; // The required answer is returned // from the function let minTime = assignHole(mices, holes, n, m); document.write(\"The last mouse gets into the hole in time:\" + minTime); // This code is contributed by mukesh07.</script>", "e": 33967, "s": 32826, "text": null }, { "code": null, "e": 34012, "s": 33967, "text": "The last mouse gets into the hole in time: 4" }, { "code": null, "e": 34435, "s": 34012, "text": " This article is contributed by Saloni Baweja. 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": 34448, "s": 34435, "text": "aayushgarg06" }, { "code": null, "e": 34466, "s": 34448, "text": "divyeshrabadiya07" }, { "code": null, "e": 34480, "s": 34466, "text": "divyesh072019" }, { "code": null, "e": 34489, "s": 34480, "text": "mukesh07" }, { "code": null, "e": 34496, "s": 34489, "text": "Greedy" }, { "code": null, "e": 34509, "s": 34496, "text": "Mathematical" }, { "code": null, "e": 34516, "s": 34509, "text": "Greedy" }, { "code": null, "e": 34529, "s": 34516, "text": "Mathematical" }, { "code": null, "e": 34627, "s": 34529, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34658, "s": 34627, "text": "Huffman Coding | Greedy Algo-3" }, { "code": null, "e": 34701, "s": 34658, "text": "Activity Selection Problem | Greedy Algo-1" }, { "code": null, "e": 34729, "s": 34701, "text": "Fractional Knapsack Problem" }, { "code": null, "e": 34810, "s": 34729, "text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)" }, { "code": null, "e": 34833, "s": 34810, "text": "Job Sequencing Problem" }, { "code": null, "e": 34848, "s": 34833, "text": "C++ Data Types" }, { "code": null, "e": 34891, "s": 34848, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 34915, "s": 34891, "text": "Merge two sorted arrays" } ]
Check if any two intervals intersects among a given set of intervals - GeeksforGeeks
24 Nov, 2021 An interval is represented as a combination of start time and end time. Given a set of intervals, check if any two intervals intersect. Examples: Input: arr[] = {{1, 3}, {5, 7}, {2, 4}, {6, 8}} Output: true The intervals {1, 3} and {2, 4} overlap Input: arr[] = {{1, 3}, {7, 9}, {4, 6}, {10, 13}} Output: false No pair of intervals overlap. Expected time complexity is O(nLogn) where n is number of intervals.We strongly recommend to minimize your browser and try this yourself first.A Simple Solution is to consider every pair of intervals and check if the pair intersects or not. The time complexity of this solution is O(n2) Method 1 A better solution is to Use Sorting. Following is complete algorithm. 1) Sort all intervals in increasing order of start time. This step takes O(nLogn) time. 2) In the sorted array, if start time of an interval is less than end of previous interval, then there is an overlap. This step takes O(n) time.So overall time complexity of the algorithm is O(nLogn) + O(n) which is O(nLogn). Below is the implementation of above idea. C++ Java Javascript // A C++ program to check if any two intervals overlap#include <algorithm>#include <iostream>using namespace std; // An interval has start time and end timestruct Interval { int start; int end;}; // Compares two intervals according to their starting time.// This is needed for sorting the intervals using library// function std::sort(). See http:// goo.gl/iGspVbool compareInterval(Interval i1, Interval i2){ return (i1.start < i2.start) ? true : false;} // Function to check if any two intervals overlapbool isIntersect(Interval arr[], int n){ // Sort intervals in increasing order of start time sort(arr, arr + n , compareInterval); // In the sorted array, if start time of an interval // is less than end of previous interval, then there // is an overlap for (int i = 1; i < n; i++) if (arr[i - 1].end > arr[i].start) return true; // If we reach here, then no overlap return false;} // Driver programint main(){ Interval arr1[] = { { 1, 3 }, { 7, 9 }, { 4, 6 }, { 10, 13 } }; int n1 = sizeof(arr1) / sizeof(arr1[0]); isIntersect(arr1, n1) ? cout << "Yes\n" : cout << "No\n"; Interval arr2[] = { { 6, 8 }, { 1, 3 }, { 2, 4 }, { 4, 7 } }; int n2 = sizeof(arr2) / sizeof(arr2[0]); isIntersect(arr2, n2) ? cout << "Yes\n" : cout << "No\n"; return 0;} // A Java program to check if any two intervals overlapimport java.io.*;import java.lang.*;import java.util.*; class GFG{ // An interval has start time and end timestatic class Interval{ int start; int end; public Interval(int start, int end) { super(); this.start = start; this.end = end; }}; // Function to check if any two intervals overlapstatic boolean isIntersect(Interval arr[], int n){ // Sort intervals in increasing order of start time Arrays.sort(arr, (i1, i2) -> { return i1.start - i2.start; }); // In the sorted array, if start time of an interval // is less than end of previous interval, then there // is an overlap for(int i = 1; i < n; i++) if (arr[i - 1].end > arr[i].start) return true; // If we reach here, then no overlap return false;} // Driver codepublic static void main(String[] args){ Interval arr1[] = { new Interval(1, 3), new Interval(7, 9), new Interval(4, 6), new Interval(10, 13) }; int n1 = arr1.length; if (isIntersect(arr1, n1)) System.out.print("Yes\n"); else System.out.print("No\n"); Interval arr2[] = { new Interval(6, 8), new Interval(1, 3), new Interval(2, 4), new Interval(4, 7) }; int n2 = arr2.length; if (isIntersect(arr2, n2)) System.out.print("Yes\n"); else System.out.print("No\n");}} // This code is contributed by Kingash <script>// A Javascript program to check if any two intervals overlap // An interval has start time and end timeclass Interval{ constructor(start,end) { this.start = start; this.end = end; }} // Function to check if any two intervals overlapfunction isIntersect(arr,n){ // Sort intervals in increasing order of start time arr.sort(function(i1, i2){ return i1.start - i2.start; }); // In the sorted array, if start time of an interval // is less than end of previous interval, then there // is an overlap for(let i = 1; i < n; i++) if (arr[i - 1].end > arr[i].start) return true; // If we reach here, then no overlap return false;} // Driver codelet arr1=[new Interval(1, 3), new Interval(7, 9), new Interval(4, 6), new Interval(10, 13) ];let n1 = arr1.length;if (isIntersect(arr1, n1)) document.write("Yes<br>");else document.write("No<br>"); let arr2 = [ new Interval(6, 8),new Interval(1, 3),new Interval(2, 4),new Interval(4, 7) ];let n2 = arr2.length; if (isIntersect(arr2, n2)) document.write("Yes<br>");else document.write("No<br>"); // This code is contributed by rag2127</script> Output: No Yes Method 2: This approach is suggested by Anjali Agarwal. Following are the steps: 1. Find the overall maximum element. Let it be max_ele 2. Initialize an array of size max_ele with 0. 3. For every interval [start, end], increment the value at index start, i.e. arr[start]++ and decrement the value at index (end + 1), i.e. arr[end + 1]- -. 4. Compute the prefix sum of this array (arr[]). 5. Every index, i of this prefix sum array will tell how many times i has occurred in all the intervals taken together. If this value is greater than 1, then it occurs in 2 or more intervals. 6. So, simply initialize the result variable as false and while traversing the prefix sum array, change the result variable to true whenever the value at that index is greater than 1. Below is the implementation of this (Method 2) approach. C++ Java C# Javascript // A C++ program to check if any two intervals overlap#include <algorithm>#include <iostream>using namespace std; // An interval has start time and end timestruct Interval { int start; int end;}; // Function to check if any two intervals overlapbool isIntersect(Interval arr[], int n){ int max_ele = 0; // Find the overall maximum element for (int i = 0; i < n; i++) { if (max_ele < arr[i].end) max_ele = arr[i].end; } // Initialize an array of size max_ele int aux[max_ele + 1] = { 0 }; for (int i = 0; i < n; i++) { // starting point of the interval int x = arr[i].start; // end point of the interval int y = arr[i].end; aux[x]++, aux[y + 1]--; } for (int i = 1; i <= max_ele; i++) { // Calculating the prefix Sum aux[i] += aux[i - 1]; // Overlap if (aux[i] > 1) return true; } // If we reach here, then no Overlap return false;} // Driver programint main(){ Interval arr1[] = { { 1, 3 }, { 7, 9 }, { 4, 6 }, { 10, 13 } }; int n1 = sizeof(arr1) / sizeof(arr1[0]); isIntersect(arr1, n1) ? cout << "Yes\n" : cout << "No\n"; Interval arr2[] = { { 6, 8 }, { 1, 3 }, { 2, 4 }, { 4, 7 } }; int n2 = sizeof(arr2) / sizeof(arr2[0]); isIntersect(arr2, n2) ? cout << "Yes\n" : cout << "No\n"; return 0;}// This Code is written by Anjali Agarwal // A Java program to check if any two intervals overlapclass GFG{ // An interval has start time and end timestatic class Interval{ int start; int end; public Interval(int start, int end) { super(); this.start = start; this.end = end; }}; // Function to check if any two intervals overlapstatic boolean isIntersect(Interval arr[], int n){ int max_ele = 0; // Find the overall maximum element for (int i = 0; i < n; i++) { if (max_ele < arr[i].end) max_ele = arr[i].end; } // Initialize an array of size max_ele int []aux = new int[max_ele + 1]; for (int i = 0; i < n; i++) { // starting point of the interval int x = arr[i].start; // end point of the interval int y = arr[i].end; aux[x]++; aux[y ]--; } for (int i = 1; i <= max_ele; i++) { // Calculating the prefix Sum aux[i] += aux[i - 1]; // Overlap if (aux[i] > 1) return true; } // If we reach here, then no Overlap return false;} // Driver programpublic static void main(String[] args){ Interval arr1[] = { new Interval(1, 3), new Interval(7, 9), new Interval(4, 6), new Interval(10, 13) }; int n1 = arr1.length; if(isIntersect(arr1, n1)) System.out.print("Yes\n"); else System.out.print("No\n"); Interval arr2[] = { new Interval(6, 8), new Interval(1, 3), new Interval(2, 4), new Interval(4, 7) }; int n2 = arr2.length; if(isIntersect(arr2, n2)) System.out.print("Yes\n"); else System.out.print("No\n");}} // This code is contributed by 29AjayKumar // C# program to check if// any two intervals overlapusing System; class GFG{ // An interval has start time and end timeclass Interval{ public int start; public int end; public Interval(int start, int end) { this.start = start; this.end = end; }}; // Function to check if// any two intervals overlapstatic bool isIntersect(Interval []arr, int n){ int max_ele = 0; // Find the overall maximum element for (int i = 0; i < n; i++) { if (max_ele < arr[i].end) max_ele = arr[i].end; } // Initialize an array of size max_ele int []aux = new int[max_ele + 1]; for (int i = 0; i < n; i++) { // starting point of the interval int x = arr[i].start; // end point of the interval int y = arr[i].end; aux[x]++; aux[y ]--; } for (int i = 1; i <= max_ele; i++) { // Calculating the prefix Sum aux[i] += aux[i - 1]; // Overlap if (aux[i] > 1) return true; } // If we reach here, then no Overlap return false;} // Driver Codepublic static void Main(String[] args){ Interval []arr1 = { new Interval(1, 3), new Interval(7, 9), new Interval(4, 6), new Interval(10, 13) }; int n1 = arr1.Length; if(isIntersect(arr1, n1)) Console.Write("Yes\n"); else Console.Write("No\n"); Interval []arr2 = { new Interval(6, 8), new Interval(1, 3), new Interval(2, 4), new Interval(4, 7) }; int n2 = arr2.Length; if(isIntersect(arr2, n2)) Console.Write("Yes\n"); else Console.Write("No\n");}} // This code is contributed by Rajput-Ji <script>// A Javascript program to check if any two intervals overlap // An interval has start time and end timeclass Interval{ constructor(start, end) { this.start = start; this.end = end; }} // Function to check if any two intervals overlapfunction isIntersect(arr, n){ let max_ele = 0; // Find the overall maximum element for (let i = 0; i < n; i++) { if (max_ele < arr[i].end) max_ele = arr[i].end; } // Initialize an array of size max_ele let aux = new Array(max_ele + 1); for(let i=0;i<(max_ele + 1);i++) { aux[i]=0; } for (let i = 0; i < n; i++) { // starting point of the interval let x = arr[i].start; // end point of the interval let y = arr[i].end; aux[x]++; aux[y ]--; } for (let i = 1; i <= max_ele; i++) { // Calculating the prefix Sum aux[i] += aux[i - 1]; // Overlap if (aux[i] > 1) return true; } // If we reach here, then no Overlap return false;} // Driver programlet arr1 = [new Interval(1, 3), new Interval(7, 9), new Interval(4, 6), new Interval(10, 13)];let n1 = arr1.length;if(isIntersect(arr1, n1)) document.write("Yes<br>"); else document.write("No<br>"); let arr2 = [ new Interval(6, 8), new Interval(1, 3), new Interval(2, 4), new Interval(4, 7) ]; let n2 = arr2.length; if(isIntersect(arr2, n2)) document.write("Yes<br>"); else document.write("No<br>"); // This code is contributed by avanitrachhadiya2155</script> Output: No Yes Time Complexity : O(max_ele + n) Note: This method is more efficient than Method 1 if there are more number of intervals and at the same time maximum value among all intervals should be low, since time complexity is directly proportional to O(max_ele). Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above smitm1 Akanksha_Rai 29AjayKumar Rajput-Ji deepak_2431 Kingash rag2127 avanitrachhadiya2155 rs1686740 Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. HeapSort std::sort() in C++ STL Time Complexities of all Sorting Algorithms Radix Sort Merge two sorted arrays Chocolate Distribution Problem Count Inversions in an array | Set 1 (Using Merge Sort) Sort an array of 0s, 1s and 2s k largest(or smallest) elements in an array Python Program for Bubble Sort
[ { "code": null, "e": 25835, "s": 25807, "text": "\n24 Nov, 2021" }, { "code": null, "e": 25972, "s": 25835, "text": "An interval is represented as a combination of start time and end time. Given a set of intervals, check if any two intervals intersect. " }, { "code": null, "e": 25983, "s": 25972, "text": "Examples: " }, { "code": null, "e": 26183, "s": 25983, "text": "Input: arr[] = {{1, 3}, {5, 7}, {2, 4}, {6, 8}}\nOutput: true\nThe intervals {1, 3} and {2, 4} overlap\n\n\nInput: arr[] = {{1, 3}, {7, 9}, {4, 6}, {10, 13}}\nOutput: false\nNo pair of intervals overlap. " }, { "code": null, "e": 26470, "s": 26183, "text": "Expected time complexity is O(nLogn) where n is number of intervals.We strongly recommend to minimize your browser and try this yourself first.A Simple Solution is to consider every pair of intervals and check if the pair intersects or not. The time complexity of this solution is O(n2)" }, { "code": null, "e": 26863, "s": 26470, "text": "Method 1 A better solution is to Use Sorting. Following is complete algorithm. 1) Sort all intervals in increasing order of start time. This step takes O(nLogn) time. 2) In the sorted array, if start time of an interval is less than end of previous interval, then there is an overlap. This step takes O(n) time.So overall time complexity of the algorithm is O(nLogn) + O(n) which is O(nLogn)." }, { "code": null, "e": 26906, "s": 26863, "text": "Below is the implementation of above idea." }, { "code": null, "e": 26910, "s": 26906, "text": "C++" }, { "code": null, "e": 26915, "s": 26910, "text": "Java" }, { "code": null, "e": 26926, "s": 26915, "text": "Javascript" }, { "code": "// A C++ program to check if any two intervals overlap#include <algorithm>#include <iostream>using namespace std; // An interval has start time and end timestruct Interval { int start; int end;}; // Compares two intervals according to their starting time.// This is needed for sorting the intervals using library// function std::sort(). See http:// goo.gl/iGspVbool compareInterval(Interval i1, Interval i2){ return (i1.start < i2.start) ? true : false;} // Function to check if any two intervals overlapbool isIntersect(Interval arr[], int n){ // Sort intervals in increasing order of start time sort(arr, arr + n , compareInterval); // In the sorted array, if start time of an interval // is less than end of previous interval, then there // is an overlap for (int i = 1; i < n; i++) if (arr[i - 1].end > arr[i].start) return true; // If we reach here, then no overlap return false;} // Driver programint main(){ Interval arr1[] = { { 1, 3 }, { 7, 9 }, { 4, 6 }, { 10, 13 } }; int n1 = sizeof(arr1) / sizeof(arr1[0]); isIntersect(arr1, n1) ? cout << \"Yes\\n\" : cout << \"No\\n\"; Interval arr2[] = { { 6, 8 }, { 1, 3 }, { 2, 4 }, { 4, 7 } }; int n2 = sizeof(arr2) / sizeof(arr2[0]); isIntersect(arr2, n2) ? cout << \"Yes\\n\" : cout << \"No\\n\"; return 0;}", "e": 28252, "s": 26926, "text": null }, { "code": "// A Java program to check if any two intervals overlapimport java.io.*;import java.lang.*;import java.util.*; class GFG{ // An interval has start time and end timestatic class Interval{ int start; int end; public Interval(int start, int end) { super(); this.start = start; this.end = end; }}; // Function to check if any two intervals overlapstatic boolean isIntersect(Interval arr[], int n){ // Sort intervals in increasing order of start time Arrays.sort(arr, (i1, i2) -> { return i1.start - i2.start; }); // In the sorted array, if start time of an interval // is less than end of previous interval, then there // is an overlap for(int i = 1; i < n; i++) if (arr[i - 1].end > arr[i].start) return true; // If we reach here, then no overlap return false;} // Driver codepublic static void main(String[] args){ Interval arr1[] = { new Interval(1, 3), new Interval(7, 9), new Interval(4, 6), new Interval(10, 13) }; int n1 = arr1.length; if (isIntersect(arr1, n1)) System.out.print(\"Yes\\n\"); else System.out.print(\"No\\n\"); Interval arr2[] = { new Interval(6, 8), new Interval(1, 3), new Interval(2, 4), new Interval(4, 7) }; int n2 = arr2.length; if (isIntersect(arr2, n2)) System.out.print(\"Yes\\n\"); else System.out.print(\"No\\n\");}} // This code is contributed by Kingash", "e": 29819, "s": 28252, "text": null }, { "code": "<script>// A Javascript program to check if any two intervals overlap // An interval has start time and end timeclass Interval{ constructor(start,end) { this.start = start; this.end = end; }} // Function to check if any two intervals overlapfunction isIntersect(arr,n){ // Sort intervals in increasing order of start time arr.sort(function(i1, i2){ return i1.start - i2.start; }); // In the sorted array, if start time of an interval // is less than end of previous interval, then there // is an overlap for(let i = 1; i < n; i++) if (arr[i - 1].end > arr[i].start) return true; // If we reach here, then no overlap return false;} // Driver codelet arr1=[new Interval(1, 3), new Interval(7, 9), new Interval(4, 6), new Interval(10, 13) ];let n1 = arr1.length;if (isIntersect(arr1, n1)) document.write(\"Yes<br>\");else document.write(\"No<br>\"); let arr2 = [ new Interval(6, 8),new Interval(1, 3),new Interval(2, 4),new Interval(4, 7) ];let n2 = arr2.length; if (isIntersect(arr2, n2)) document.write(\"Yes<br>\");else document.write(\"No<br>\"); // This code is contributed by rag2127</script>", "e": 31067, "s": 29819, "text": null }, { "code": null, "e": 31076, "s": 31067, "text": "Output: " }, { "code": null, "e": 31083, "s": 31076, "text": "No\nYes" }, { "code": null, "e": 31166, "s": 31083, "text": "Method 2: This approach is suggested by Anjali Agarwal. Following are the steps: " }, { "code": null, "e": 31851, "s": 31166, "text": "1. Find the overall maximum element. Let it be max_ele 2. Initialize an array of size max_ele with 0. 3. For every interval [start, end], increment the value at index start, i.e. arr[start]++ and decrement the value at index (end + 1), i.e. arr[end + 1]- -. 4. Compute the prefix sum of this array (arr[]). 5. Every index, i of this prefix sum array will tell how many times i has occurred in all the intervals taken together. If this value is greater than 1, then it occurs in 2 or more intervals. 6. So, simply initialize the result variable as false and while traversing the prefix sum array, change the result variable to true whenever the value at that index is greater than 1. " }, { "code": null, "e": 31909, "s": 31851, "text": "Below is the implementation of this (Method 2) approach. " }, { "code": null, "e": 31913, "s": 31909, "text": "C++" }, { "code": null, "e": 31918, "s": 31913, "text": "Java" }, { "code": null, "e": 31921, "s": 31918, "text": "C#" }, { "code": null, "e": 31932, "s": 31921, "text": "Javascript" }, { "code": "// A C++ program to check if any two intervals overlap#include <algorithm>#include <iostream>using namespace std; // An interval has start time and end timestruct Interval { int start; int end;}; // Function to check if any two intervals overlapbool isIntersect(Interval arr[], int n){ int max_ele = 0; // Find the overall maximum element for (int i = 0; i < n; i++) { if (max_ele < arr[i].end) max_ele = arr[i].end; } // Initialize an array of size max_ele int aux[max_ele + 1] = { 0 }; for (int i = 0; i < n; i++) { // starting point of the interval int x = arr[i].start; // end point of the interval int y = arr[i].end; aux[x]++, aux[y + 1]--; } for (int i = 1; i <= max_ele; i++) { // Calculating the prefix Sum aux[i] += aux[i - 1]; // Overlap if (aux[i] > 1) return true; } // If we reach here, then no Overlap return false;} // Driver programint main(){ Interval arr1[] = { { 1, 3 }, { 7, 9 }, { 4, 6 }, { 10, 13 } }; int n1 = sizeof(arr1) / sizeof(arr1[0]); isIntersect(arr1, n1) ? cout << \"Yes\\n\" : cout << \"No\\n\"; Interval arr2[] = { { 6, 8 }, { 1, 3 }, { 2, 4 }, { 4, 7 } }; int n2 = sizeof(arr2) / sizeof(arr2[0]); isIntersect(arr2, n2) ? cout << \"Yes\\n\" : cout << \"No\\n\"; return 0;}// This Code is written by Anjali Agarwal", "e": 33334, "s": 31932, "text": null }, { "code": "// A Java program to check if any two intervals overlapclass GFG{ // An interval has start time and end timestatic class Interval{ int start; int end; public Interval(int start, int end) { super(); this.start = start; this.end = end; }}; // Function to check if any two intervals overlapstatic boolean isIntersect(Interval arr[], int n){ int max_ele = 0; // Find the overall maximum element for (int i = 0; i < n; i++) { if (max_ele < arr[i].end) max_ele = arr[i].end; } // Initialize an array of size max_ele int []aux = new int[max_ele + 1]; for (int i = 0; i < n; i++) { // starting point of the interval int x = arr[i].start; // end point of the interval int y = arr[i].end; aux[x]++; aux[y ]--; } for (int i = 1; i <= max_ele; i++) { // Calculating the prefix Sum aux[i] += aux[i - 1]; // Overlap if (aux[i] > 1) return true; } // If we reach here, then no Overlap return false;} // Driver programpublic static void main(String[] args){ Interval arr1[] = { new Interval(1, 3), new Interval(7, 9), new Interval(4, 6), new Interval(10, 13) }; int n1 = arr1.length; if(isIntersect(arr1, n1)) System.out.print(\"Yes\\n\"); else System.out.print(\"No\\n\"); Interval arr2[] = { new Interval(6, 8), new Interval(1, 3), new Interval(2, 4), new Interval(4, 7) }; int n2 = arr2.length; if(isIntersect(arr2, n2)) System.out.print(\"Yes\\n\"); else System.out.print(\"No\\n\");}} // This code is contributed by 29AjayKumar", "e": 35025, "s": 33334, "text": null }, { "code": "// C# program to check if// any two intervals overlapusing System; class GFG{ // An interval has start time and end timeclass Interval{ public int start; public int end; public Interval(int start, int end) { this.start = start; this.end = end; }}; // Function to check if// any two intervals overlapstatic bool isIntersect(Interval []arr, int n){ int max_ele = 0; // Find the overall maximum element for (int i = 0; i < n; i++) { if (max_ele < arr[i].end) max_ele = arr[i].end; } // Initialize an array of size max_ele int []aux = new int[max_ele + 1]; for (int i = 0; i < n; i++) { // starting point of the interval int x = arr[i].start; // end point of the interval int y = arr[i].end; aux[x]++; aux[y ]--; } for (int i = 1; i <= max_ele; i++) { // Calculating the prefix Sum aux[i] += aux[i - 1]; // Overlap if (aux[i] > 1) return true; } // If we reach here, then no Overlap return false;} // Driver Codepublic static void Main(String[] args){ Interval []arr1 = { new Interval(1, 3), new Interval(7, 9), new Interval(4, 6), new Interval(10, 13) }; int n1 = arr1.Length; if(isIntersect(arr1, n1)) Console.Write(\"Yes\\n\"); else Console.Write(\"No\\n\"); Interval []arr2 = { new Interval(6, 8), new Interval(1, 3), new Interval(2, 4), new Interval(4, 7) }; int n2 = arr2.Length; if(isIntersect(arr2, n2)) Console.Write(\"Yes\\n\"); else Console.Write(\"No\\n\");}} // This code is contributed by Rajput-Ji", "e": 36798, "s": 35025, "text": null }, { "code": "<script>// A Javascript program to check if any two intervals overlap // An interval has start time and end timeclass Interval{ constructor(start, end) { this.start = start; this.end = end; }} // Function to check if any two intervals overlapfunction isIntersect(arr, n){ let max_ele = 0; // Find the overall maximum element for (let i = 0; i < n; i++) { if (max_ele < arr[i].end) max_ele = arr[i].end; } // Initialize an array of size max_ele let aux = new Array(max_ele + 1); for(let i=0;i<(max_ele + 1);i++) { aux[i]=0; } for (let i = 0; i < n; i++) { // starting point of the interval let x = arr[i].start; // end point of the interval let y = arr[i].end; aux[x]++; aux[y ]--; } for (let i = 1; i <= max_ele; i++) { // Calculating the prefix Sum aux[i] += aux[i - 1]; // Overlap if (aux[i] > 1) return true; } // If we reach here, then no Overlap return false;} // Driver programlet arr1 = [new Interval(1, 3), new Interval(7, 9), new Interval(4, 6), new Interval(10, 13)];let n1 = arr1.length;if(isIntersect(arr1, n1)) document.write(\"Yes<br>\"); else document.write(\"No<br>\"); let arr2 = [ new Interval(6, 8), new Interval(1, 3), new Interval(2, 4), new Interval(4, 7) ]; let n2 = arr2.length; if(isIntersect(arr2, n2)) document.write(\"Yes<br>\"); else document.write(\"No<br>\"); // This code is contributed by avanitrachhadiya2155</script>", "e": 38427, "s": 36798, "text": null }, { "code": null, "e": 38436, "s": 38427, "text": "Output: " }, { "code": null, "e": 38443, "s": 38436, "text": "No\nYes" }, { "code": null, "e": 38477, "s": 38443, "text": "Time Complexity : O(max_ele + n) " }, { "code": null, "e": 38822, "s": 38477, "text": "Note: This method is more efficient than Method 1 if there are more number of intervals and at the same time maximum value among all intervals should be low, since time complexity is directly proportional to O(max_ele). Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 38829, "s": 38822, "text": "smitm1" }, { "code": null, "e": 38842, "s": 38829, "text": "Akanksha_Rai" }, { "code": null, "e": 38854, "s": 38842, "text": "29AjayKumar" }, { "code": null, "e": 38864, "s": 38854, "text": "Rajput-Ji" }, { "code": null, "e": 38876, "s": 38864, "text": "deepak_2431" }, { "code": null, "e": 38884, "s": 38876, "text": "Kingash" }, { "code": null, "e": 38892, "s": 38884, "text": "rag2127" }, { "code": null, "e": 38913, "s": 38892, "text": "avanitrachhadiya2155" }, { "code": null, "e": 38923, "s": 38913, "text": "rs1686740" }, { "code": null, "e": 38931, "s": 38923, "text": "Sorting" }, { "code": null, "e": 38939, "s": 38931, "text": "Sorting" }, { "code": null, "e": 39037, "s": 38939, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39046, "s": 39037, "text": "HeapSort" }, { "code": null, "e": 39069, "s": 39046, "text": "std::sort() in C++ STL" }, { "code": null, "e": 39113, "s": 39069, "text": "Time Complexities of all Sorting Algorithms" }, { "code": null, "e": 39124, "s": 39113, "text": "Radix Sort" }, { "code": null, "e": 39148, "s": 39124, "text": "Merge two sorted arrays" }, { "code": null, "e": 39179, "s": 39148, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 39235, "s": 39179, "text": "Count Inversions in an array | Set 1 (Using Merge Sort)" }, { "code": null, "e": 39266, "s": 39235, "text": "Sort an array of 0s, 1s and 2s" }, { "code": null, "e": 39310, "s": 39266, "text": "k largest(or smallest) elements in an array" } ]
Check whether an Array is Subarray of another Array - GeeksforGeeks
11 May, 2021 Given two arrays A[] and B[] consisting of and integers. The task is to check whether the array B[] is a subarray of the array A[] or not.Examples: Input : A[] = {2, 3, 0, 5, 1, 1, 2}, B[] = {3, 0, 5, 1} Output : YesInput : A[] = {1, 2, 3, 4, 5}, B[] = {2, 5, 6} Output : No Source : Visa Interview ExperienceSimple Approach: A simple approach is to run two nested loops and generate all subarrays of the array A[] and use one more loop to check if any of the subarray of A[] is equal to the array B[].Efficient Approach : An efficient approach is to use two pointers to traverse both the array simultaneously. Keep the pointer of array B[] still and if any element of A[] matches with the first element of B[] then increase the pointer of both the array else set the pointer of A to the next element of the previous starting point and reset the pointer of B to 0. If all the elements of B are matched then print YES otherwise print NO.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to check if an array is// subarray of another array #include <bits/stdc++.h>using namespace std; // Function to check if an array is// subarray of another arraybool isSubArray(int A[], int B[], int n, int m){ // Two pointers to traverse the arrays int i = 0, j = 0; // Traverse both arrays simultaneously while (i < n && j < m) { // If element matches // increment both pointers if (A[i] == B[j]) { i++; j++; // If array B is completely // traversed if (j == m) return true; } // If not, // increment i and reset j else { i = i - j + 1; j = 0; } } return false;} // Driver Codeint main(){ int A[] = { 2, 3, 0, 5, 1, 1, 2 }; int n = sizeof(A) / sizeof(int); int B[] = { 3, 0, 5, 1 }; int m = sizeof(B) / sizeof(int); if (isSubArray(A, B, n, m)) cout << "YES\n"; else cout << "NO\n"; return 0;} // Java program to check if an array is// subarray of another arrayclass gfg{ // Function to check if an array is // subarray of another array static boolean isSubArray(int A[], int B[], int n, int m) { // Two pointers to traverse the arrays int i = 0, j = 0; // Traverse both arrays simultaneously while (i < n && j < m) { // If element matches // increment both pointers if (A[i] == B[j]) { i++; j++; // If array B is completely // traversed if (j == m) return true; } // If not, // increment i and reset j else { i = i - j + 1; j = 0; } } return false; } // Driver Code public static void main(String arr[]) { int A[] = { 2, 3, 0, 5, 1, 1, 2 }; int n = A.length; int B[] = { 3, 0, 5, 1 }; int m = B.length; if (isSubArray(A, B, n, m)) System.out.println("YES"); else System.out.println("NO"); }} // This code is contributed by gp6 # Python3 program to check if an array is# subarray of another array # Function to check if an array is# subarray of another arraydef isSubArray(A, B, n, m): # Two pointers to traverse the arrays i = 0; j = 0; # Traverse both arrays simultaneously while (i < n and j < m): # If element matches # increment both pointers if (A[i] == B[j]): i += 1; j += 1; # If array B is completely # traversed if (j == m): return True; # If not, # increment i and reset j else: i = i - j + 1; j = 0; return False; # Driver Codeif __name__ == '__main__': A = [ 2, 3, 0, 5, 1, 1, 2 ]; n = len(A); B = [ 3, 0, 5, 1 ]; m = len(B); if (isSubArray(A, B, n, m)): print("YES"); else: print("NO"); # This code is contributed by Rajput-Ji // C# program to check if an array is// subarray of another arrayusing System; public class GFG{ // Function to check if an array is // subarray of another array static bool isSubArray(int []A, int []B, int n, int m) { // Two pointers to traverse the arrays int i = 0, j = 0; // Traverse both arrays simultaneously while (i < n && j < m) { // If element matches // increment both pointers if (A[i] == B[j]) { i++; j++; // If array B is completely // traversed if (j == m) return true; } // If not, // increment i and reset j else { i = i - j + 1; j = 0; } } return false; } // Driver Code public static void Main(String []arr) { int []A = { 2, 3, 0, 5, 1, 1, 2 }; int n = A.Length; int []B = { 3, 0, 5, 1 }; int m = B.Length; if (isSubArray(A, B, n, m)) Console.WriteLine("YES"); else Console.WriteLine("NO"); }} // This code is contributed by PrinciRaj1992 <script>// Javascript program to check if an array is// subarray of another array // Function to check if an array is// subarray of another arrayfunction isSubArray(A, B, n,m){ // Two pointers to traverse the arrays var i = 0, j = 0; // Traverse both arrays simultaneously while (i < n && j < m) { // If element matches // increment both pointers if (A[i] == B[j]) { i++; j++; // If array B is completely // traversed if (j == m) return true; } // If not, // increment i and reset j else { i = i - j + 1; j = 0; } } return false;} var A = [ 2, 3, 0, 5, 1, 1, 2 ];var n = A.length;var B = [ 3, 0, 5, 1 ];var m =B.length;if (isSubArray(A, B, n, m)) document.write( "YES<br>"); else document.write( "NO<br>"); // This code is contributed by SoumikMondal</script> YES Shashank12 Abhi Reddy ankthon Sanjit_Prasad amyjais35 Mithun Kumar gp6 princiraj1992 Rajput-Ji SoumikMondal Arrays subarray Visa Arrays Visa Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Arrays Linked List vs Array Search an element in a sorted and rotated array Queue | Set 1 (Introduction and Array Implementation) Find the Missing Number Find Second largest element in an array Merge two sorted arrays Chocolate Distribution Problem Count Inversions in an array | Set 1 (Using Merge Sort) Program to find largest element in an array
[ { "code": null, "e": 26179, "s": 26151, "text": "\n11 May, 2021" }, { "code": null, "e": 26329, "s": 26179, "text": "Given two arrays A[] and B[] consisting of and integers. The task is to check whether the array B[] is a subarray of the array A[] or not.Examples: " }, { "code": null, "e": 26458, "s": 26329, "text": "Input : A[] = {2, 3, 0, 5, 1, 1, 2}, B[] = {3, 0, 5, 1} Output : YesInput : A[] = {1, 2, 3, 4, 5}, B[] = {2, 5, 6} Output : No " }, { "code": null, "e": 27174, "s": 26460, "text": "Source : Visa Interview ExperienceSimple Approach: A simple approach is to run two nested loops and generate all subarrays of the array A[] and use one more loop to check if any of the subarray of A[] is equal to the array B[].Efficient Approach : An efficient approach is to use two pointers to traverse both the array simultaneously. Keep the pointer of array B[] still and if any element of A[] matches with the first element of B[] then increase the pointer of both the array else set the pointer of A to the next element of the previous starting point and reset the pointer of B to 0. If all the elements of B are matched then print YES otherwise print NO.Below is the implementation of the above approach: " }, { "code": null, "e": 27178, "s": 27174, "text": "C++" }, { "code": null, "e": 27183, "s": 27178, "text": "Java" }, { "code": null, "e": 27191, "s": 27183, "text": "Python3" }, { "code": null, "e": 27194, "s": 27191, "text": "C#" }, { "code": null, "e": 27205, "s": 27194, "text": "Javascript" }, { "code": "// C++ program to check if an array is// subarray of another array #include <bits/stdc++.h>using namespace std; // Function to check if an array is// subarray of another arraybool isSubArray(int A[], int B[], int n, int m){ // Two pointers to traverse the arrays int i = 0, j = 0; // Traverse both arrays simultaneously while (i < n && j < m) { // If element matches // increment both pointers if (A[i] == B[j]) { i++; j++; // If array B is completely // traversed if (j == m) return true; } // If not, // increment i and reset j else { i = i - j + 1; j = 0; } } return false;} // Driver Codeint main(){ int A[] = { 2, 3, 0, 5, 1, 1, 2 }; int n = sizeof(A) / sizeof(int); int B[] = { 3, 0, 5, 1 }; int m = sizeof(B) / sizeof(int); if (isSubArray(A, B, n, m)) cout << \"YES\\n\"; else cout << \"NO\\n\"; return 0;}", "e": 28221, "s": 27205, "text": null }, { "code": "// Java program to check if an array is// subarray of another arrayclass gfg{ // Function to check if an array is // subarray of another array static boolean isSubArray(int A[], int B[], int n, int m) { // Two pointers to traverse the arrays int i = 0, j = 0; // Traverse both arrays simultaneously while (i < n && j < m) { // If element matches // increment both pointers if (A[i] == B[j]) { i++; j++; // If array B is completely // traversed if (j == m) return true; } // If not, // increment i and reset j else { i = i - j + 1; j = 0; } } return false; } // Driver Code public static void main(String arr[]) { int A[] = { 2, 3, 0, 5, 1, 1, 2 }; int n = A.length; int B[] = { 3, 0, 5, 1 }; int m = B.length; if (isSubArray(A, B, n, m)) System.out.println(\"YES\"); else System.out.println(\"NO\"); }} // This code is contributed by gp6", "e": 29511, "s": 28221, "text": null }, { "code": "# Python3 program to check if an array is# subarray of another array # Function to check if an array is# subarray of another arraydef isSubArray(A, B, n, m): # Two pointers to traverse the arrays i = 0; j = 0; # Traverse both arrays simultaneously while (i < n and j < m): # If element matches # increment both pointers if (A[i] == B[j]): i += 1; j += 1; # If array B is completely # traversed if (j == m): return True; # If not, # increment i and reset j else: i = i - j + 1; j = 0; return False; # Driver Codeif __name__ == '__main__': A = [ 2, 3, 0, 5, 1, 1, 2 ]; n = len(A); B = [ 3, 0, 5, 1 ]; m = len(B); if (isSubArray(A, B, n, m)): print(\"YES\"); else: print(\"NO\"); # This code is contributed by Rajput-Ji", "e": 30433, "s": 29511, "text": null }, { "code": "// C# program to check if an array is// subarray of another arrayusing System; public class GFG{ // Function to check if an array is // subarray of another array static bool isSubArray(int []A, int []B, int n, int m) { // Two pointers to traverse the arrays int i = 0, j = 0; // Traverse both arrays simultaneously while (i < n && j < m) { // If element matches // increment both pointers if (A[i] == B[j]) { i++; j++; // If array B is completely // traversed if (j == m) return true; } // If not, // increment i and reset j else { i = i - j + 1; j = 0; } } return false; } // Driver Code public static void Main(String []arr) { int []A = { 2, 3, 0, 5, 1, 1, 2 }; int n = A.Length; int []B = { 3, 0, 5, 1 }; int m = B.Length; if (isSubArray(A, B, n, m)) Console.WriteLine(\"YES\"); else Console.WriteLine(\"NO\"); }} // This code is contributed by PrinciRaj1992", "e": 31755, "s": 30433, "text": null }, { "code": "<script>// Javascript program to check if an array is// subarray of another array // Function to check if an array is// subarray of another arrayfunction isSubArray(A, B, n,m){ // Two pointers to traverse the arrays var i = 0, j = 0; // Traverse both arrays simultaneously while (i < n && j < m) { // If element matches // increment both pointers if (A[i] == B[j]) { i++; j++; // If array B is completely // traversed if (j == m) return true; } // If not, // increment i and reset j else { i = i - j + 1; j = 0; } } return false;} var A = [ 2, 3, 0, 5, 1, 1, 2 ];var n = A.length;var B = [ 3, 0, 5, 1 ];var m =B.length;if (isSubArray(A, B, n, m)) document.write( \"YES<br>\"); else document.write( \"NO<br>\"); // This code is contributed by SoumikMondal</script>", "e": 32712, "s": 31755, "text": null }, { "code": null, "e": 32716, "s": 32712, "text": "YES" }, { "code": null, "e": 32729, "s": 32718, "text": "Shashank12" }, { "code": null, "e": 32740, "s": 32729, "text": "Abhi Reddy" }, { "code": null, "e": 32748, "s": 32740, "text": "ankthon" }, { "code": null, "e": 32762, "s": 32748, "text": "Sanjit_Prasad" }, { "code": null, "e": 32772, "s": 32762, "text": "amyjais35" }, { "code": null, "e": 32785, "s": 32772, "text": "Mithun Kumar" }, { "code": null, "e": 32789, "s": 32785, "text": "gp6" }, { "code": null, "e": 32803, "s": 32789, "text": "princiraj1992" }, { "code": null, "e": 32813, "s": 32803, "text": "Rajput-Ji" }, { "code": null, "e": 32826, "s": 32813, "text": "SoumikMondal" }, { "code": null, "e": 32833, "s": 32826, "text": "Arrays" }, { "code": null, "e": 32842, "s": 32833, "text": "subarray" }, { "code": null, "e": 32847, "s": 32842, "text": "Visa" }, { "code": null, "e": 32854, "s": 32847, "text": "Arrays" }, { "code": null, "e": 32859, "s": 32854, "text": "Visa" }, { "code": null, "e": 32866, "s": 32859, "text": "Arrays" }, { "code": null, "e": 32964, "s": 32866, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32987, "s": 32964, "text": "Introduction to Arrays" }, { "code": null, "e": 33008, "s": 32987, "text": "Linked List vs Array" }, { "code": null, "e": 33056, "s": 33008, "text": "Search an element in a sorted and rotated array" }, { "code": null, "e": 33110, "s": 33056, "text": "Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 33134, "s": 33110, "text": "Find the Missing Number" }, { "code": null, "e": 33174, "s": 33134, "text": "Find Second largest element in an array" }, { "code": null, "e": 33198, "s": 33174, "text": "Merge two sorted arrays" }, { "code": null, "e": 33229, "s": 33198, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 33285, "s": 33229, "text": "Count Inversions in an array | Set 1 (Using Merge Sort)" } ]
Explain the differences between for(..in) and for(..of) statement in JavaScript. - GeeksforGeeks
31 Jan, 2020 Often in a JavaScript script, we iterate over some objects of few built-in classes like Arrays, Dictionaries, Strings, Maps, etc. We iterate the objects using loops. JavaScript supports different kinds of loops: for loop for (..in) loop for (..of) loop while loop do-while loop In this article, we will be learning about the difference between for (..in) and for (..of) Loops. for (..in) loop: The JavaScript for (..in) statement loops through the enumerable properties of an object. The loop will iterate over all enumerable properties of the object itself and those the object inherits from its constructor’s prototype. Syntaxfor (variable in object) statement for (variable in object) statement Example<!DOCTYPE html><html> <body> <p id="demo"></p> <script> var person = { firstName: "GeeksforGeeks", lastName: "<br>A Computer Science Portal for Geeks ", rank: 43 }; var userId = ""; var i; for (i in person) { userId += person[i]; } document.getElementById("demo").innerHTML = userId; </script></body> </html> <!DOCTYPE html><html> <body> <p id="demo"></p> <script> var person = { firstName: "GeeksforGeeks", lastName: "<br>A Computer Science Portal for Geeks ", rank: 43 }; var userId = ""; var i; for (i in person) { userId += person[i]; } document.getElementById("demo").innerHTML = userId; </script></body> </html> Output: As you can see the for (..in) loop iterate over only the properties or the values of the dictionary object.GeeksforGeeks A Computer Science Portal for Geeks 43for (..of) loop: This for (..of) statement lets you loop over the data structures that are iterable such as Arrays, Strings, Maps, Node Lists, and more. It calls a custom iteration hook with instructions to execute on the value of each property of the object.Syntaxfor (variable of iterable) { statement } Example<!DOCTYPE html><html> <body> <p id ="demo"></p> <script> var text = [ "GeeksforGeeks", " A Computer Science Portal for Geeks ", "43" ]; var userId = ""; var i; for (i of text) { userId+=i; } document.getElementById("demo").innerHTML = userId; </script> </body></html> Output: As you can see the for (..of) loop iterate over only the content of the Array object.GeeksforGeeks A Computer Science Portal for Geeks 43My Personal Notes arrow_drop_upSave GeeksforGeeks A Computer Science Portal for Geeks 43 for (..of) loop: This for (..of) statement lets you loop over the data structures that are iterable such as Arrays, Strings, Maps, Node Lists, and more. It calls a custom iteration hook with instructions to execute on the value of each property of the object. Syntaxfor (variable of iterable) { statement } for (variable of iterable) { statement } Example<!DOCTYPE html><html> <body> <p id ="demo"></p> <script> var text = [ "GeeksforGeeks", " A Computer Science Portal for Geeks ", "43" ]; var userId = ""; var i; for (i of text) { userId+=i; } document.getElementById("demo").innerHTML = userId; </script> </body></html> <!DOCTYPE html><html> <body> <p id ="demo"></p> <script> var text = [ "GeeksforGeeks", " A Computer Science Portal for Geeks ", "43" ]; var userId = ""; var i; for (i of text) { userId+=i; } document.getElementById("demo").innerHTML = userId; </script> </body></html> Output: As you can see the for (..of) loop iterate over only the content of the Array object.GeeksforGeeks A Computer Science Portal for Geeks 43 GeeksforGeeks A Computer Science Portal for Geeks 43 CSS-Misc HTML-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 31329, "s": 31301, "text": "\n31 Jan, 2020" }, { "code": null, "e": 31541, "s": 31329, "text": "Often in a JavaScript script, we iterate over some objects of few built-in classes like Arrays, Dictionaries, Strings, Maps, etc. We iterate the objects using loops. JavaScript supports different kinds of loops:" }, { "code": null, "e": 31550, "s": 31541, "text": "for loop" }, { "code": null, "e": 31566, "s": 31550, "text": "for (..in) loop" }, { "code": null, "e": 31582, "s": 31566, "text": "for (..of) loop" }, { "code": null, "e": 31593, "s": 31582, "text": "while loop" }, { "code": null, "e": 31607, "s": 31593, "text": "do-while loop" }, { "code": null, "e": 31706, "s": 31607, "text": "In this article, we will be learning about the difference between for (..in) and for (..of) Loops." }, { "code": null, "e": 31951, "s": 31706, "text": "for (..in) loop: The JavaScript for (..in) statement loops through the enumerable properties of an object. The loop will iterate over all enumerable properties of the object itself and those the object inherits from its constructor’s prototype." }, { "code": null, "e": 31994, "s": 31951, "text": "Syntaxfor (variable in object)\n statement" }, { "code": null, "e": 32031, "s": 31994, "text": "for (variable in object)\n statement" }, { "code": null, "e": 32451, "s": 32031, "text": "Example<!DOCTYPE html><html> <body> <p id=\"demo\"></p> <script> var person = { firstName: \"GeeksforGeeks\", lastName: \"<br>A Computer Science Portal for Geeks \", rank: 43 }; var userId = \"\"; var i; for (i in person) { userId += person[i]; } document.getElementById(\"demo\").innerHTML = userId; </script></body> </html>" }, { "code": "<!DOCTYPE html><html> <body> <p id=\"demo\"></p> <script> var person = { firstName: \"GeeksforGeeks\", lastName: \"<br>A Computer Science Portal for Geeks \", rank: 43 }; var userId = \"\"; var i; for (i in person) { userId += person[i]; } document.getElementById(\"demo\").innerHTML = userId; </script></body> </html>", "e": 32864, "s": 32451, "text": null }, { "code": null, "e": 33935, "s": 32864, "text": "Output: As you can see the for (..in) loop iterate over only the properties or the values of the dictionary object.GeeksforGeeks\nA Computer Science Portal for Geeks 43for (..of) loop: This for (..of) statement lets you loop over the data structures that are iterable such as Arrays, Strings, Maps, Node Lists, and more. It calls a custom iteration hook with instructions to execute on the value of each property of the object.Syntaxfor (variable of iterable) {\n statement\n}\nExample<!DOCTYPE html><html> <body> <p id =\"demo\"></p> <script> var text = [ \"GeeksforGeeks\", \" A Computer Science Portal for Geeks \", \"43\" ]; var userId = \"\"; var i; for (i of text) { userId+=i; } document.getElementById(\"demo\").innerHTML = userId; </script> </body></html> Output: As you can see the for (..of) loop iterate over only the content of the Array object.GeeksforGeeks A Computer Science Portal for Geeks 43My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 33988, "s": 33935, "text": "GeeksforGeeks\nA Computer Science Portal for Geeks 43" }, { "code": null, "e": 34248, "s": 33988, "text": "for (..of) loop: This for (..of) statement lets you loop over the data structures that are iterable such as Arrays, Strings, Maps, Node Lists, and more. It calls a custom iteration hook with instructions to execute on the value of each property of the object." }, { "code": null, "e": 34298, "s": 34248, "text": "Syntaxfor (variable of iterable) {\n statement\n}\n" }, { "code": null, "e": 34342, "s": 34298, "text": "for (variable of iterable) {\n statement\n}\n" }, { "code": null, "e": 34758, "s": 34342, "text": "Example<!DOCTYPE html><html> <body> <p id =\"demo\"></p> <script> var text = [ \"GeeksforGeeks\", \" A Computer Science Portal for Geeks \", \"43\" ]; var userId = \"\"; var i; for (i of text) { userId+=i; } document.getElementById(\"demo\").innerHTML = userId; </script> </body></html> " }, { "code": "<!DOCTYPE html><html> <body> <p id =\"demo\"></p> <script> var text = [ \"GeeksforGeeks\", \" A Computer Science Portal for Geeks \", \"43\" ]; var userId = \"\"; var i; for (i of text) { userId+=i; } document.getElementById(\"demo\").innerHTML = userId; </script> </body></html> ", "e": 35167, "s": 34758, "text": null }, { "code": null, "e": 35313, "s": 35167, "text": "Output: As you can see the for (..of) loop iterate over only the content of the Array object.GeeksforGeeks A Computer Science Portal for Geeks 43" }, { "code": null, "e": 35366, "s": 35313, "text": "GeeksforGeeks A Computer Science Portal for Geeks 43" }, { "code": null, "e": 35375, "s": 35366, "text": "CSS-Misc" }, { "code": null, "e": 35385, "s": 35375, "text": "HTML-Misc" }, { "code": null, "e": 35392, "s": 35385, "text": "Picked" }, { "code": null, "e": 35403, "s": 35392, "text": "JavaScript" }, { "code": null, "e": 35420, "s": 35403, "text": "Web Technologies" }, { "code": null, "e": 35447, "s": 35420, "text": "Web technologies Questions" }, { "code": null, "e": 35545, "s": 35447, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35585, "s": 35545, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 35630, "s": 35585, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 35691, "s": 35630, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 35763, "s": 35691, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 35832, "s": 35763, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 35872, "s": 35832, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 35905, "s": 35872, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 35950, "s": 35905, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 35993, "s": 35950, "text": "How to fetch data from an API in ReactJS ?" } ]
Print all ways to break a string in bracket form - GeeksforGeeks
25 Jan, 2022 Given a string, find all ways to break the given string in bracket form. Enclose each substring within a parenthesis. Examples: Input : abc Output: (a)(b)(c) (a)(bc) (ab)(c) (abc) Input : abcd Output : (a)(b)(c)(d) (a)(b)(cd) (a)(bc)(d) (a)(bcd) (ab)(c)(d) (ab)(cd) (abc)(d) (abcd) We strongly recommend you to minimize your browser and try this yourself first.The idea is to use recursion. We maintain two parameters – index of the next character to be processed and the output string so far. We start from index of next character to be processed, append substring formed by unprocessed string to the output string and recurse on remaining string until we process the whole string. We use std::substr to form the output string. substr(pos, n) returns a substring of length n that starts at position pos of current string. Below diagram shows recursion tree for input string “abc”. Each node on the diagram shows processed string (marked by green) and unprocessed string (marked by red). Below is the implementation of the above idea- C++ Java Python3 C# // C++ Program to find all combinations of Non-// overlapping substrings formed from given// string#include <iostream>using namespace std; // find all combinations of non-overlapping// substrings formed by input string str// index – index of the next character to// be processed// out - output string so farvoid findCombinations(string str, int index, string out){ if (index == str.length()) cout << out << endl; for (int i = index; i < str.length(); i++) { // append substring formed by str[index, // i] to output string findCombinations( str, i + 1, out + "(" + str.substr(index, i + 1 - index) + ")"); }} // Driver Codeint main(){ // input string string str = "abcd"; findCombinations(str, 0, ""); return 0;} // Java program to find all combinations of Non-// overlapping substrings formed from given// string class GFG{ // find all combinations of non-overlapping // substrings formed by input string str static void findCombinations(String str, int index, String out) { if (index == str.length()) System.out.println(out); for (int i = index; i < str.length(); i++) // append substring formed by str[index, // i] to output string findCombinations(str, i + 1, out + "(" + str.substring(index, i+1) + ")" ); } // Driver Code public static void main (String[] args) { // input string String str = "abcd"; findCombinations(str, 0, ""); }} // Contributed by Pramod Kumar # Python3 Program to find all combinations of Non-# overlapping substrings formed from given# string # find all combinations of non-overlapping# substrings formed by input string str# index – index of the next character to# be processed# out - output string so fardef findCombinations(string, index, out): if index == len(string): print(out) for i in range(index, len(string), 1): # append substring formed by str[index, # i] to output string findCombinations(string, i + 1, out + "(" + string[index:i + 1] + ")") # Driver Codeif __name__ == "__main__": # input string string = "abcd" findCombinations(string, 0, "") # This code is contributed by# sanjeev2552 // C# program to find all combinations// of Non-overlapping substrings formed// from given stringusing System; class GFG { // find all combinations of non-overlapping // substrings formed by input string str public static void findCombinations(string str, int index, string @out) { if (index == str.Length) { Console.WriteLine(@out); } for (int i = index; i < str.Length; i++) { // append substring formed by // str[index, i] to output string findCombinations( str, i + 1, @out + "(" + str.Substring(index, (i + 1) - index) + ")"); } } // Driver Code public static void Main(string[] args) { // input string string str = "abcd"; findCombinations(str, 0, ""); }} // This code is contributed by Shrikant13 (a)(b)(c)(d) (a)(b)(cd) (a)(bc)(d) (a)(bcd) (ab)(c)(d) (ab)(cd) (abc)(d) (abcd) Time Complexity: O(N2)Auxiliary Space: O(N2) This article is contributed by Aditya Goel. 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 shrikanth13 sanjeev2552 Akanksha_Rai ujjwalgoel1103 amartyaniel20 Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 String Coding Problems for Interviews Print all the duplicates in the input string Vigenère Cipher String class in Java | Set 1 sprintf() in C Print all subsequences of a string Convert character array to string in C++ How to Append a Character to a String in C Program to count occurrence of a given character in a string Naive algorithm for Pattern Searching
[ { "code": null, "e": 26097, "s": 26069, "text": "\n25 Jan, 2022" }, { "code": null, "e": 26215, "s": 26097, "text": "Given a string, find all ways to break the given string in bracket form. Enclose each substring within a parenthesis." }, { "code": null, "e": 26226, "s": 26215, "text": "Examples: " }, { "code": null, "e": 26469, "s": 26226, "text": "Input : abc\nOutput: (a)(b)(c)\n (a)(bc)\n (ab)(c)\n (abc)\n\n\nInput : abcd\nOutput : (a)(b)(c)(d)\n (a)(b)(cd)\n (a)(bc)(d)\n (a)(bcd)\n (ab)(c)(d)\n (ab)(cd)\n (abc)(d)\n (abcd)" }, { "code": null, "e": 27010, "s": 26469, "text": "We strongly recommend you to minimize your browser and try this yourself first.The idea is to use recursion. We maintain two parameters – index of the next character to be processed and the output string so far. We start from index of next character to be processed, append substring formed by unprocessed string to the output string and recurse on remaining string until we process the whole string. We use std::substr to form the output string. substr(pos, n) returns a substring of length n that starts at position pos of current string." }, { "code": null, "e": 27176, "s": 27010, "text": "Below diagram shows recursion tree for input string “abc”. Each node on the diagram shows processed string (marked by green) and unprocessed string (marked by red). " }, { "code": null, "e": 27223, "s": 27176, "text": "Below is the implementation of the above idea-" }, { "code": null, "e": 27227, "s": 27223, "text": "C++" }, { "code": null, "e": 27232, "s": 27227, "text": "Java" }, { "code": null, "e": 27240, "s": 27232, "text": "Python3" }, { "code": null, "e": 27243, "s": 27240, "text": "C#" }, { "code": "// C++ Program to find all combinations of Non-// overlapping substrings formed from given// string#include <iostream>using namespace std; // find all combinations of non-overlapping// substrings formed by input string str// index – index of the next character to// be processed// out - output string so farvoid findCombinations(string str, int index, string out){ if (index == str.length()) cout << out << endl; for (int i = index; i < str.length(); i++) { // append substring formed by str[index, // i] to output string findCombinations( str, i + 1, out + \"(\" + str.substr(index, i + 1 - index) + \")\"); }} // Driver Codeint main(){ // input string string str = \"abcd\"; findCombinations(str, 0, \"\"); return 0;}", "e": 28067, "s": 27243, "text": null }, { "code": "// Java program to find all combinations of Non-// overlapping substrings formed from given// string class GFG{ // find all combinations of non-overlapping // substrings formed by input string str static void findCombinations(String str, int index, String out) { if (index == str.length()) System.out.println(out); for (int i = index; i < str.length(); i++) // append substring formed by str[index, // i] to output string findCombinations(str, i + 1, out + \"(\" + str.substring(index, i+1) + \")\" ); } // Driver Code public static void main (String[] args) { // input string String str = \"abcd\"; findCombinations(str, 0, \"\"); }} // Contributed by Pramod Kumar", "e": 28887, "s": 28067, "text": null }, { "code": "# Python3 Program to find all combinations of Non-# overlapping substrings formed from given# string # find all combinations of non-overlapping# substrings formed by input string str# index – index of the next character to# be processed# out - output string so fardef findCombinations(string, index, out): if index == len(string): print(out) for i in range(index, len(string), 1): # append substring formed by str[index, # i] to output string findCombinations(string, i + 1, out + \"(\" + string[index:i + 1] + \")\") # Driver Codeif __name__ == \"__main__\": # input string string = \"abcd\" findCombinations(string, 0, \"\") # This code is contributed by# sanjeev2552", "e": 29626, "s": 28887, "text": null }, { "code": "// C# program to find all combinations// of Non-overlapping substrings formed// from given stringusing System; class GFG { // find all combinations of non-overlapping // substrings formed by input string str public static void findCombinations(string str, int index, string @out) { if (index == str.Length) { Console.WriteLine(@out); } for (int i = index; i < str.Length; i++) { // append substring formed by // str[index, i] to output string findCombinations( str, i + 1, @out + \"(\" + str.Substring(index, (i + 1) - index) + \")\"); } } // Driver Code public static void Main(string[] args) { // input string string str = \"abcd\"; findCombinations(str, 0, \"\"); }} // This code is contributed by Shrikant13", "e": 30524, "s": 29626, "text": null }, { "code": null, "e": 30604, "s": 30524, "text": "(a)(b)(c)(d)\n(a)(b)(cd)\n(a)(bc)(d)\n(a)(bcd)\n(ab)(c)(d)\n(ab)(cd)\n(abc)(d)\n(abcd)" }, { "code": null, "e": 30649, "s": 30604, "text": "Time Complexity: O(N2)Auxiliary Space: O(N2)" }, { "code": null, "e": 31038, "s": 30649, "text": "This article is contributed by Aditya Goel. 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" }, { "code": null, "e": 31050, "s": 31038, "text": "shrikanth13" }, { "code": null, "e": 31062, "s": 31050, "text": "sanjeev2552" }, { "code": null, "e": 31075, "s": 31062, "text": "Akanksha_Rai" }, { "code": null, "e": 31090, "s": 31075, "text": "ujjwalgoel1103" }, { "code": null, "e": 31104, "s": 31090, "text": "amartyaniel20" }, { "code": null, "e": 31112, "s": 31104, "text": "Strings" }, { "code": null, "e": 31120, "s": 31112, "text": "Strings" }, { "code": null, "e": 31218, "s": 31120, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31263, "s": 31218, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 31308, "s": 31263, "text": "Print all the duplicates in the input string" }, { "code": null, "e": 31325, "s": 31308, "text": "Vigenère Cipher" }, { "code": null, "e": 31354, "s": 31325, "text": "String class in Java | Set 1" }, { "code": null, "e": 31369, "s": 31354, "text": "sprintf() in C" }, { "code": null, "e": 31404, "s": 31369, "text": "Print all subsequences of a string" }, { "code": null, "e": 31445, "s": 31404, "text": "Convert character array to string in C++" }, { "code": null, "e": 31488, "s": 31445, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 31549, "s": 31488, "text": "Program to count occurrence of a given character in a string" } ]
Program to find the XOR of ASCII values of characters in a string - GeeksforGeeks
28 Jan, 2022 Given a string str, the task is to find the XOR of ASCII values of characters in the string.Examples: Input: str = “Geeks” Output: 95 ASCII value of G = 71 ASCII value of e = 101 ASCII value of e = 101 ASCII value of k = 107 ASCII value of s = 115 XOR of ASCII values = 71 ^ 101 ^ 101 ^ 107 ^ 115 = 95Input: str = “GfG” Output: 102 Approach: The idea is to find out the ASCII value of each character one by one and find the XOR value of these values.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find XOR of ASCII// value of characters in string #include <bits/stdc++.h>using namespace std; // Function to find the XOR of ASCII// value of characters in stringint XorAscii(string str, int len){ // store value of first character int ans = int(str[0]); for (int i = 1; i < len; i++) { // Traverse string to find the XOR ans = (ans ^ (int(str[i]))); } // Return the XOR return ans;} // Driver codeint main(){ string str = "geeksforgeeks"; int len = str.length(); cout << XorAscii(str, len) << endl; str = "GfG"; len = str.length(); cout << XorAscii(str, len); return 0;} // Java program to find XOR of ASCII// value of characters in Stringclass GFG{ // Function to find the XOR of ASCII// value of characters in Stringstatic int XorAscii(String str, int len){ // store value of first character int ans = (str.charAt(0)); for (int i = 1; i < len; i++) { // Traverse String to find the XOR ans = (ans ^ ((str.charAt(i)))); } // Return the XOR return ans;} // Driver codepublic static void main(String[] args){ String str = "geeksforgeeks"; int len = str.length(); System.out.print(XorAscii(str, len) +"\n"); str = "GfG"; len = str.length(); System.out.print(XorAscii(str, len));}} // This code is contributed by PrinciRaj1992 # Python3 program to find XOR of ASCII# value of characters in string # Function to find the XOR of ASCII# value of characters in stringdef XorAscii(str1, len1): # store value of first character ans = ord(str1[0]) for i in range(1,len1): # Traverse string to find the XOR ans = (ans ^ (ord(str1[i]))) # Return the XOR return ans # Driver codestr1 = "geeksforgeeks"len1 = len(str1)print(XorAscii(str1, len1)) str1 = "GfG"len1 = len(str1)print(XorAscii(str1, len1)) # This code is contributed by mohit kumar 29 // C# program to find XOR of ASCII// value of characters in Stringusing System; class GFG{ // Function to find the XOR of ASCII// value of characters in Stringstatic int XorAscii(String str, int len){ // store value of first character int ans = (str[0]); for (int i = 1; i < len; i++) { // Traverse String to find the XOR ans = (ans ^ ((str[i]))); } // Return the XOR return ans;} // Driver codepublic static void Main(String[] args){ String str = "geeksforgeeks"; int len = str.Length; Console.Write(XorAscii(str, len) +"\n"); str = "GfG"; len = str.Length; Console.Write(XorAscii(str, len));}} // This code is contributed by PrinciRaj1992 <script> // Javascript program to find XOR of ASCII// value of characters in string // Function to find the XOR of ASCII// value of characters in stringfunction XorAscii(str, len){ // store value of first character let ans = str.codePointAt(0); for (let i = 1; i < len; i++) { // Traverse string to find the XOR ans = (ans ^ (str.codePointAt(i))); } // Return the XOR return ans;} // Driver code let str = "geeksforgeeks"; let len = str.length; document.write(XorAscii(str, len) + "<br>"); str = "GfG"; len = str.length; document.write(XorAscii(str, len)); </script> 123 102 Time Complexity: O(N), where N is the length of string. mohit kumar 29 princiraj1992 souravmahato348 simmytarika5 Bitwise-XOR C-String-Question Mathematical Strings Strings Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Print all possible combinations of r elements in a given array of size n Program for factorial of a number Write a program to reverse an array or string Reverse a string in Java Longest Common Subsequence | DP-4 Check for Balanced Brackets in an expression (well-formedness) using Stack Python program to check if a string is palindrome or not
[ { "code": null, "e": 25891, "s": 25863, "text": "\n28 Jan, 2022" }, { "code": null, "e": 25995, "s": 25891, "text": "Given a string str, the task is to find the XOR of ASCII values of characters in the string.Examples: " }, { "code": null, "e": 26227, "s": 25995, "text": "Input: str = “Geeks” Output: 95 ASCII value of G = 71 ASCII value of e = 101 ASCII value of e = 101 ASCII value of k = 107 ASCII value of s = 115 XOR of ASCII values = 71 ^ 101 ^ 101 ^ 107 ^ 115 = 95Input: str = “GfG” Output: 102 " }, { "code": null, "e": 26400, "s": 26229, "text": "Approach: The idea is to find out the ASCII value of each character one by one and find the XOR value of these values.Below is the implementation of the above approach: " }, { "code": null, "e": 26404, "s": 26400, "text": "C++" }, { "code": null, "e": 26409, "s": 26404, "text": "Java" }, { "code": null, "e": 26417, "s": 26409, "text": "Python3" }, { "code": null, "e": 26420, "s": 26417, "text": "C#" }, { "code": null, "e": 26431, "s": 26420, "text": "Javascript" }, { "code": "// C++ program to find XOR of ASCII// value of characters in string #include <bits/stdc++.h>using namespace std; // Function to find the XOR of ASCII// value of characters in stringint XorAscii(string str, int len){ // store value of first character int ans = int(str[0]); for (int i = 1; i < len; i++) { // Traverse string to find the XOR ans = (ans ^ (int(str[i]))); } // Return the XOR return ans;} // Driver codeint main(){ string str = \"geeksforgeeks\"; int len = str.length(); cout << XorAscii(str, len) << endl; str = \"GfG\"; len = str.length(); cout << XorAscii(str, len); return 0;}", "e": 27081, "s": 26431, "text": null }, { "code": "// Java program to find XOR of ASCII// value of characters in Stringclass GFG{ // Function to find the XOR of ASCII// value of characters in Stringstatic int XorAscii(String str, int len){ // store value of first character int ans = (str.charAt(0)); for (int i = 1; i < len; i++) { // Traverse String to find the XOR ans = (ans ^ ((str.charAt(i)))); } // Return the XOR return ans;} // Driver codepublic static void main(String[] args){ String str = \"geeksforgeeks\"; int len = str.length(); System.out.print(XorAscii(str, len) +\"\\n\"); str = \"GfG\"; len = str.length(); System.out.print(XorAscii(str, len));}} // This code is contributed by PrinciRaj1992", "e": 27798, "s": 27081, "text": null }, { "code": "# Python3 program to find XOR of ASCII# value of characters in string # Function to find the XOR of ASCII# value of characters in stringdef XorAscii(str1, len1): # store value of first character ans = ord(str1[0]) for i in range(1,len1): # Traverse string to find the XOR ans = (ans ^ (ord(str1[i]))) # Return the XOR return ans # Driver codestr1 = \"geeksforgeeks\"len1 = len(str1)print(XorAscii(str1, len1)) str1 = \"GfG\"len1 = len(str1)print(XorAscii(str1, len1)) # This code is contributed by mohit kumar 29", "e": 28340, "s": 27798, "text": null }, { "code": "// C# program to find XOR of ASCII// value of characters in Stringusing System; class GFG{ // Function to find the XOR of ASCII// value of characters in Stringstatic int XorAscii(String str, int len){ // store value of first character int ans = (str[0]); for (int i = 1; i < len; i++) { // Traverse String to find the XOR ans = (ans ^ ((str[i]))); } // Return the XOR return ans;} // Driver codepublic static void Main(String[] args){ String str = \"geeksforgeeks\"; int len = str.Length; Console.Write(XorAscii(str, len) +\"\\n\"); str = \"GfG\"; len = str.Length; Console.Write(XorAscii(str, len));}} // This code is contributed by PrinciRaj1992", "e": 29053, "s": 28340, "text": null }, { "code": "<script> // Javascript program to find XOR of ASCII// value of characters in string // Function to find the XOR of ASCII// value of characters in stringfunction XorAscii(str, len){ // store value of first character let ans = str.codePointAt(0); for (let i = 1; i < len; i++) { // Traverse string to find the XOR ans = (ans ^ (str.codePointAt(i))); } // Return the XOR return ans;} // Driver code let str = \"geeksforgeeks\"; let len = str.length; document.write(XorAscii(str, len) + \"<br>\"); str = \"GfG\"; len = str.length; document.write(XorAscii(str, len)); </script>", "e": 29676, "s": 29053, "text": null }, { "code": null, "e": 29684, "s": 29676, "text": "123\n102" }, { "code": null, "e": 29743, "s": 29686, "text": "Time Complexity: O(N), where N is the length of string. " }, { "code": null, "e": 29758, "s": 29743, "text": "mohit kumar 29" }, { "code": null, "e": 29772, "s": 29758, "text": "princiraj1992" }, { "code": null, "e": 29788, "s": 29772, "text": "souravmahato348" }, { "code": null, "e": 29801, "s": 29788, "text": "simmytarika5" }, { "code": null, "e": 29813, "s": 29801, "text": "Bitwise-XOR" }, { "code": null, "e": 29831, "s": 29813, "text": "C-String-Question" }, { "code": null, "e": 29844, "s": 29831, "text": "Mathematical" }, { "code": null, "e": 29852, "s": 29844, "text": "Strings" }, { "code": null, "e": 29860, "s": 29852, "text": "Strings" }, { "code": null, "e": 29873, "s": 29860, "text": "Mathematical" }, { "code": null, "e": 29971, "s": 29873, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29995, "s": 29971, "text": "Merge two sorted arrays" }, { "code": null, "e": 30038, "s": 29995, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 30052, "s": 30038, "text": "Prime Numbers" }, { "code": null, "e": 30125, "s": 30052, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 30159, "s": 30125, "text": "Program for factorial of a number" }, { "code": null, "e": 30205, "s": 30159, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 30230, "s": 30205, "text": "Reverse a string in Java" }, { "code": null, "e": 30264, "s": 30230, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 30339, "s": 30264, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" } ]
PHP | SimpleXMLElement addChild() Function - GeeksforGeeks
29 May, 2019 Pre-requisite: Read XML Basics The SimpleXMLElement::addChild() function is an inbuilt function in PHP which is used to add a child in a SimpleXML object. Syntax: SimpleXMLElement SimpleXMLElement::addChild($name, $value, $namespace); Parameter: This function accepts three parameters as mentioned above and described below: $name: It is required parameter. It specifies the name of the child element to be added. $value: It is optional parameter. It specifies the value of the child element to be added. $namespace: It is optional parameter. It specifies namespace for the child element. Return Value: It returns SimpleXMLElement object on successful child addition. Note: This function is available for PHP 5.1.3 and newer version. Example: <?php// Loading XML document to $user $user = <<<XML<user><username>user123</username><name>firstname lastname</name><phone>+91-9876543210</phone><detail>I am John Doe. Live in Kolkata, India.</detail></user>XML; // creating new SimpleXMLElement// object from $user$xml = new SimpleXMLElement($user); // Adding child named "institution"// and valued "geeksforgeeks"$xml -> addChild("institution", "geeksforgeeks"); // Printing as XMLecho $xml->asXML(); echo $xml->asXML('savexmltofile.xml'); ?> Output: user123 firstname lastname +91-9876543210 I am John Doe. Live in Kolkata, India. geeksforgeeks 1 Saved XML file: Reference: https://www.php.net/manual/en/simplexmlelement.addchild.php PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from localserver database and display on HTML table using PHP ? How to create admin login page using PHP? PHP str_replace() Function How to pass form variables from one page to other page in PHP ? Create a drop-down list that options fetched from a MySQL database in PHP Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 26217, "s": 26189, "text": "\n29 May, 2019" }, { "code": null, "e": 26248, "s": 26217, "text": "Pre-requisite: Read XML Basics" }, { "code": null, "e": 26372, "s": 26248, "text": "The SimpleXMLElement::addChild() function is an inbuilt function in PHP which is used to add a child in a SimpleXML object." }, { "code": null, "e": 26380, "s": 26372, "text": "Syntax:" }, { "code": null, "e": 26452, "s": 26380, "text": "SimpleXMLElement SimpleXMLElement::addChild($name, $value, $namespace);" }, { "code": null, "e": 26542, "s": 26452, "text": "Parameter: This function accepts three parameters as mentioned above and described below:" }, { "code": null, "e": 26631, "s": 26542, "text": "$name: It is required parameter. It specifies the name of the child element to be added." }, { "code": null, "e": 26722, "s": 26631, "text": "$value: It is optional parameter. It specifies the value of the child element to be added." }, { "code": null, "e": 26806, "s": 26722, "text": "$namespace: It is optional parameter. It specifies namespace for the child element." }, { "code": null, "e": 26885, "s": 26806, "text": "Return Value: It returns SimpleXMLElement object on successful child addition." }, { "code": null, "e": 26951, "s": 26885, "text": "Note: This function is available for PHP 5.1.3 and newer version." }, { "code": null, "e": 26960, "s": 26951, "text": "Example:" }, { "code": "<?php// Loading XML document to $user $user = <<<XML<user><username>user123</username><name>firstname lastname</name><phone>+91-9876543210</phone><detail>I am John Doe. Live in Kolkata, India.</detail></user>XML; // creating new SimpleXMLElement// object from $user$xml = new SimpleXMLElement($user); // Adding child named \"institution\"// and valued \"geeksforgeeks\"$xml -> addChild(\"institution\", \"geeksforgeeks\"); // Printing as XMLecho $xml->asXML(); echo $xml->asXML('savexmltofile.xml'); ?>", "e": 27461, "s": 26960, "text": null }, { "code": null, "e": 27469, "s": 27461, "text": "Output:" }, { "code": null, "e": 27567, "s": 27469, "text": "user123 firstname lastname +91-9876543210 I am John Doe.\nLive in Kolkata, India. geeksforgeeks 1\n" }, { "code": null, "e": 27583, "s": 27567, "text": "Saved XML file:" }, { "code": null, "e": 27654, "s": 27583, "text": "Reference: https://www.php.net/manual/en/simplexmlelement.addchild.php" }, { "code": null, "e": 27667, "s": 27654, "text": "PHP-function" }, { "code": null, "e": 27671, "s": 27667, "text": "PHP" }, { "code": null, "e": 27688, "s": 27671, "text": "Web Technologies" }, { "code": null, "e": 27692, "s": 27688, "text": "PHP" }, { "code": null, "e": 27790, "s": 27692, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27872, "s": 27790, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 27914, "s": 27872, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 27941, "s": 27914, "text": "PHP str_replace() Function" }, { "code": null, "e": 28005, "s": 27941, "text": "How to pass form variables from one page to other page in PHP ?" }, { "code": null, "e": 28079, "s": 28005, "text": "Create a drop-down list that options fetched from a MySQL database in PHP" }, { "code": null, "e": 28119, "s": 28079, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28152, "s": 28119, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28197, "s": 28152, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28240, "s": 28197, "text": "How to fetch data from an API in ReactJS ?" } ]
Euler Circuit in a Directed Graph
The Euler path is a path, by which we can visit every edge exactly once. We can use the same vertices for multiple times. The Euler Circuit is a special type of Euler path. When the starting vertex of the Euler path is also connected with the ending vertex of that path, then it is called the Euler Circuit. To check whether a graph is Eulerian or not, we have to check two conditions − The graph must be connected. The in-degree and out-degree of each vertex must be the same. Input: Adjacency matrix of the graph. 0 1 0 0 0 0 0 1 0 0 0 0 0 1 1 1 0 0 0 0 0 0 1 0 0 Output: Euler Circuit Found. traverse(u, visited) Input: The start node u and the visited node to mark which node is visited. Output: Traverse all connected vertices. Begin mark u as visited for all vertex v, if it is adjacent with u, do if v is not visited, then traverse(v, visited) done End isConnected(graph) Input − The graph. Output − True if the graph is connected. Begin define visited array for all vertices u in the graph, do make all nodes unvisited traverse(u, visited) if any unvisited node is still remaining, then return false done return true End isEulerCircuit(Graph) Input: The given Graph. Output: True when one Euler circuit is found. Begin if isConnected() is false, then return false define list for inward and outward edge count for each node for all vertex i in the graph, do sum := 0 for all vertex j which are connected with i, do inward edges for vertex i increased increase sum done number of outward of vertex i is sum done if inward list and outward list are same, then return true otherwise return false End #include<iostream> #include<vector> #define NODE 5 using namespace std; int graph[NODE][NODE] = { {0, 1, 0, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 1, 1}, {1, 0, 0, 0, 0}, {0, 0, 1, 0, 0} }; void traverse(int u, bool visited[]) { visited[u] = true; //mark v as visited for(int v = 0; v<NODE; v++) { if(graph[u][v]) { if(!visited[v]) traverse(v, visited); } } } bool isConnected() { bool *vis = new bool[NODE]; //for all vertex u as start point, check whether all nodes are visible or not for(int u; u < NODE; u++) { for(int i = 0; i<NODE; i++) vis[i] = false; //initialize as no node is visited traverse(u, vis); for(int i = 0; i<NODE; i++) { if(!vis[i]) //if there is a node, not visited by traversal, graph is not connected return false; } } return true; } bool isEulerCircuit() { if(isConnected() == false) { //when graph is not connected return false; } vector<int> inward(NODE, 0), outward(NODE, 0); for(int i = 0; i<NODE; i++) { int sum = 0; for(int j = 0; j<NODE; j++) { if(graph[i][j]) { inward[j]++; //increase inward edge for destination vertex sum++; //how many outward edge } } outward[i] = sum; } if(inward == outward) //when number inward edges and outward edges for each node is same return true; return false; } int main() { if(isEulerCircuit()) cout << "Euler Circuit Found."; else cout << "There is no Euler Circuit."; } Euler Circuit Found.
[ { "code": null, "e": 1370, "s": 1062, "text": "The Euler path is a path, by which we can visit every edge exactly once. We can use the same vertices for multiple times. The Euler Circuit is a special type of Euler path. When the starting vertex of the Euler path is also connected with the ending vertex of that path, then it is called the Euler Circuit." }, { "code": null, "e": 1449, "s": 1370, "text": "To check whether a graph is Eulerian or not, we have to check two conditions −" }, { "code": null, "e": 1478, "s": 1449, "text": "The graph must be connected." }, { "code": null, "e": 1540, "s": 1478, "text": "The in-degree and out-degree of each vertex must be the same." }, { "code": null, "e": 1658, "s": 1540, "text": "Input:\nAdjacency matrix of the graph.\n0 1 0 0 0\n0 0 1 0 0\n0 0 0 1 1\n1 0 0 0 0\n0 0 1 0 0\n\nOutput:\nEuler Circuit Found." }, { "code": null, "e": 1679, "s": 1658, "text": "traverse(u, visited)" }, { "code": null, "e": 1755, "s": 1679, "text": "Input: The start node u and the visited node to mark which node is visited." }, { "code": null, "e": 1796, "s": 1755, "text": "Output: Traverse all connected vertices." }, { "code": null, "e": 1947, "s": 1796, "text": "Begin\n mark u as visited\n for all vertex v, if it is adjacent with u, do\n if v is not visited, then\n traverse(v, visited)\n done\nEnd" }, { "code": null, "e": 1966, "s": 1947, "text": "isConnected(graph)" }, { "code": null, "e": 1985, "s": 1966, "text": "Input − The graph." }, { "code": null, "e": 2026, "s": 1985, "text": "Output − True if the graph is connected." }, { "code": null, "e": 2255, "s": 2026, "text": "Begin\n define visited array\n for all vertices u in the graph, do\n make all nodes unvisited\n traverse(u, visited)\n if any unvisited node is still remaining, then\n return false\n done\n return true\nEnd" }, { "code": null, "e": 2277, "s": 2255, "text": "isEulerCircuit(Graph)" }, { "code": null, "e": 2301, "s": 2277, "text": "Input: The given Graph." }, { "code": null, "e": 2347, "s": 2301, "text": "Output: True when one Euler circuit is found." }, { "code": null, "e": 2805, "s": 2347, "text": "Begin\n if isConnected() is false, then\n return false\n define list for inward and outward edge count for each node\n\n for all vertex i in the graph, do\n sum := 0\n for all vertex j which are connected with i, do\n inward edges for vertex i increased\n increase sum\n done\n number of outward of vertex i is sum\n done\n\n if inward list and outward list are same, then\n return true\n otherwise return false\nEnd" }, { "code": null, "e": 4462, "s": 2805, "text": "#include<iostream>\n#include<vector>\n#define NODE 5\nusing namespace std;\n\nint graph[NODE][NODE] = {\n {0, 1, 0, 0, 0},\n {0, 0, 1, 0, 0},\n {0, 0, 0, 1, 1},\n {1, 0, 0, 0, 0},\n {0, 0, 1, 0, 0}\n};\n \nvoid traverse(int u, bool visited[]) {\n visited[u] = true; //mark v as visited\n\n for(int v = 0; v<NODE; v++) {\n if(graph[u][v]) {\n if(!visited[v])\n traverse(v, visited);\n }\n }\n}\n\nbool isConnected() {\n bool *vis = new bool[NODE];\n //for all vertex u as start point, check whether all nodes are visible or not\n\n for(int u; u < NODE; u++) {\n for(int i = 0; i<NODE; i++)\n vis[i] = false; //initialize as no node is visited\n \n traverse(u, vis);\n \n for(int i = 0; i<NODE; i++) {\n if(!vis[i]) //if there is a node, not visited by traversal, graph is not connected\n return false;\n }\n }\n return true;\n}\n\nbool isEulerCircuit() {\n if(isConnected() == false) { //when graph is not connected\n return false;\n }\n\n vector<int> inward(NODE, 0), outward(NODE, 0);\n \n for(int i = 0; i<NODE; i++) {\n int sum = 0;\n for(int j = 0; j<NODE; j++) {\n if(graph[i][j]) {\n inward[j]++; //increase inward edge for destination vertex\n sum++; //how many outward edge\n }\n }\n outward[i] = sum;\n }\n\n if(inward == outward) //when number inward edges and outward edges for each node is same\n return true;\n return false;\n}\n\nint main() {\n if(isEulerCircuit())\n cout << \"Euler Circuit Found.\";\n else\n cout << \"There is no Euler Circuit.\";\n}" }, { "code": null, "e": 4483, "s": 4462, "text": "Euler Circuit Found." } ]
C# User Input
You have already learned that Console.WriteLine() is used to output (print) values. Now we will use Console.ReadLine() to get user input. In the following example, the user can input his or hers username, which is stored in the variable userName. Then we print the value of userName: // Type your username and press enter Console.WriteLine("Enter username:"); // Create a string variable and get user input from the keyboard and store it in the variable string userName = Console.ReadLine(); // Print the value of the variable (userName), which will display the input value Console.WriteLine("Username is: " + userName); Run example » The Console.ReadLine() method returns a string. Therefore, you cannot get information from another data type, such as int. The following program will cause an error: Console.WriteLine("Enter your age:"); int age = Console.ReadLine(); Console.WriteLine("Your age is: " + age); The error message will be something like this: Like the error message says, you cannot implicitly convert type 'string' to 'int'. Luckily, for you, you just learned from the previous chapter (Type Casting), that you can convert any type explicitly, by using one of the Convert.To methods: Console.WriteLine("Enter your age:"); int age = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Your age is: " + age); Run example » Note: If you enter wrong input (e.g. text in a numerical input), you will get an exception/error message (like System.FormatException: 'Input string was not in a correct format.'). You will learn more about Exceptions and how to handle errors in a later chapter. Fill in the missing parts to get user input, stored in the variable userName: Console.WriteLine("Enter username:"); userName = Console.; Console.WriteLine("Username is: " + userName); 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": 139, "s": 0, "text": "You have already learned that Console.WriteLine() is used to output (print) values. Now we will use \nConsole.ReadLine() to get user input." }, { "code": null, "e": 288, "s": 139, "text": "In the following example, the user can input his or hers username, which is stored in the \nvariable userName. Then we print the value of \n\nuserName:" }, { "code": null, "e": 627, "s": 288, "text": "// Type your username and press enter\nConsole.WriteLine(\"Enter username:\");\n\n// Create a string variable and get user input from the keyboard and store it in the variable\nstring userName = Console.ReadLine();\n\n// Print the value of the variable (userName), which will display the input value\nConsole.WriteLine(\"Username is: \" + userName);" }, { "code": null, "e": 643, "s": 627, "text": "\nRun example »\n" }, { "code": null, "e": 809, "s": 643, "text": "The Console.ReadLine() method returns a string. Therefore, you cannot get information from another data type, such as int. The following program will cause an error:" }, { "code": null, "e": 919, "s": 809, "text": "Console.WriteLine(\"Enter your age:\");\nint age = Console.ReadLine();\nConsole.WriteLine(\"Your age is: \" + age);" }, { "code": null, "e": 966, "s": 919, "text": "The error message will be something like this:" }, { "code": null, "e": 1051, "s": 966, "text": "Like the error message says, you cannot implicitly convert type 'string' to \n'int'. " }, { "code": null, "e": 1212, "s": 1051, "text": "Luckily, for you, you just learned from the previous chapter (Type Casting), that you can convert \nany type explicitly, by using one of the \nConvert.To methods:" }, { "code": null, "e": 1339, "s": 1212, "text": "Console.WriteLine(\"Enter your age:\");\nint age = Convert.ToInt32(Console.ReadLine());\nConsole.WriteLine(\"Your age is: \" + age);" }, { "code": null, "e": 1355, "s": 1339, "text": "\nRun example »\n" }, { "code": null, "e": 1536, "s": 1355, "text": "Note: If you enter wrong input (e.g. text in a numerical input), you will get an exception/error message (like System.FormatException: 'Input string was not in a correct format.')." }, { "code": null, "e": 1618, "s": 1536, "text": "You will learn more about Exceptions and how to handle errors in a later chapter." }, { "code": null, "e": 1696, "s": 1618, "text": "Fill in the missing parts to get user input, stored in the variable userName:" }, { "code": null, "e": 1803, "s": 1696, "text": "Console.WriteLine(\"Enter username:\");\n userName = Console.;\nConsole.WriteLine(\"Username is: \" + userName);" }, { "code": null, "e": 1822, "s": 1803, "text": "Start the Exercise" }, { "code": null, "e": 1855, "s": 1822, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1897, "s": 1855, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2004, "s": 1897, "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": 2023, "s": 2004, "text": "[email protected]" } ]
Understanding Dimensionality Reduction for Machine Learning | by Rajat S | Towards Data Science
Recently, I was asked to work on a dataset that was a bit on the heavy side. It was so large that my Excel program would stop responding for a few minutes while loading, and manually exploring the data started to become a real pain. I am still a newbie in the Machine Learning world. So, I had to go back the Excel multiple times to decide which features should be used in the Machine Learning model. But after an excruciatingly long and mind wrecking time, I was able to build a model that would give me some decent results! I started to feel really good about myself and started to believe that I could make it as a Machine Learning Engineer! But then I came across my next obstacle: How do I show my results to ordinary people? I could make two columns where one would show the real-world results and the other column would show the results given to me by the ML model. But this is not the most visually appealing way to go. While machines are better than us at understanding large sets of numeric data, the human mind finds it easier to understand visual data like graphs and plots. So a plot is the best way to go forward. But our screen is two dimensional and our data can have more than two features where each feature can be considered as a dimension. One of the two dimensions of the plot is going to be the output. So the question we should ask ourselves is: How do we represent all of our features, which could be anywhere from hundreds to thousands, in a single dimension? This is where dimensionality reduction comes into play! Dimensionality Reduction is a technique in Machine Learning that reduces the number of features in your dataset. The great thing about dimensionality reduction is that it does not negatively affect your machine learning model’s performance. In some cases, this technique has even increased the accuracy of the model. By reducing the number of features in our dataset, we are also reducing the storage space required to store the data, our python compiler will need less time to go through the dataset. In this post, we will take a look at two of the most popular types of Dimensionality Reduction techniques, Principle Component Analysis (PCA) and Linear Discriminant Analysis (LDA). Before we move further, let’s make sure that your system is ready to work with some python code. There two major versions of Python: 2.x and 3.x. I would suggest that you make sure that you have the 3.x version installed on your system. If that is not the case, then you can get it from here. Next, we need a good code editor that will help make your coding experience easier and enjoyable. My personal choice is the amazing VSCode, but you can also try out Spyder or Jupyter Notebook. There are also a couple of online code editors like Repl and Google Colab that you can try. Using online editor would let you skip the time and storage wasting task of installing Python Libraries. We will be working on the Wine Dataset. This dataset is completely numeric and it does not contain any missing values, making it perfect for this article as I won’t have to waste time on Data-Preprocessing techniques such as converting categorical data to numeric data and imputing data into empty cells. Let’s start by importing some Python Libraries that we will need in our script: import pandas as pdfrom sklearn.preprocessing import StandardScaler We also need to load the wine dataset into our python script. Let’s do that using the read_csv() function from the pandas library: dataset_url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv'dataset = pd.read_csv(dataset_url, sep=';') The dataset looks something like this: The quality column will be the dependent variable of our Machine Learning Model, and the rest of the columns will be the independent variables. So let’s split the dataset into two parts accordingly: X = dataset.iloc[:, 0:-1].valuesy = dataset.iloc[:, -1].values X contains 11 columns, and y the 12th column. We also need to perform some feature scaling on the data. We are using the StandardScalar function to do this for us. This function will transform our data in such a way that the data’s distribution will have a mean of 0 and a standard deviation of 1. We will perform the feature scaling on the independent variables since we want our dependent variable to stay as pristine as possible. sc = StandardScaler()X = sc.fit_transform(X) We are now ready to perform dimensionality reduction! Let’s start with PCA first, and then perform LDA. I would suggest to make a new python script file and copy your code into it, and use it later with the LDA part. Principal Component Analysis (PCA) is one of the most popular dimensionality reduction algorithms out there and can also be used for noise filtering, stock market predictions, data visualization, and much more. PCA reduces the number of features in the dataset by detecting the correlation between them. When the correlation between the features is strong enough, they will get merged together and form a single feature. We could take a look at the Math behind the algorithm and try to understand how it works, but I found it easier to get into the code and see what outputs we get. Picking up from where we left our code in the previous section, let’s start by import the PCA class from sklearn: from sklearn.decomposition import PCA Next, we need to create a local instance of the PCA class. pca = PCA(n_components=None) We are passing a parameter called n_components which we will intially pass a value of None. Next, we will call the fit_transform method on pca and pass it the X_train dataset as input. We will also call the transform method and pass the X_test dataset as input X = pca.fit_transform(X) Once this is done, we need to get the explained variance of different principal components of the dataset. Our pca object has a property called explained_variance_ratio_ that contains an array of percentages. variances = pca.explained_variance_ratio_ If you print this variable, you will get an array similar to this: [0.28173931 0.1750827 0.1409585 0.11029387 0.08720837 0.05996439 0.05307193 0.03845061 0.0313311 0.01648483 0.00541439] We can see that the elements of this array are in descending order. But what do these values mean? Each of the values explains the amount of variance given by each of the 11 principal components in our dataset. So if only take the first principal component, we will have 28.17% variance. If we take two principal components, we will have the sum of the first two elements of the array, which is around 45.68% variance, and so on. Now we can our Python compiler, and replace the None value passed to n_components inside PCA with the desired number of dimensions. Let’s see what we get by selecting 1 as the desired number of dimensions pca = PCA(n_components=2)X = pca.fit_transform(X)// Output[[-1.61952988] [-0.79916993] [-0.74847909] ... [-1.45612897] [-2.27051793] [-0.42697475]] Voila! We have successfully reduced the number of dimensions of our input dataset from 11 to just 1! Similar to PCA, LDA is also a dimensionality reduction algorithm. But unlike PCA, LDA will also find the features that maximize the separation between multiple classes. You might ask yourself: why should I bother with this new algorithm that basically does the same thing as the previous algorithm? Both PCA and LDA are dimensionality reduction algorithms. But where PCA is considered to be an unsupervised algorithm, LDA, on the other hand, is considered to be supervised. Supervised and Unsupervised? These are common machine learning terms that define whether an algorithm uses the dependent variable or not, respectively. So LDA uses the dependent variable, and PCA, as we have seen before, does not. Let’s get to some code and understand how to implement the LDA algorithm in our python code. If you have not already done so, then take the code from the getting started section and paste it in a new python script file. Then, import the LinearDiscriminantAnalysis class from sklearn. from sklearn.discriminant_analysis import LinearDiscriminantAnalysis Next, we create a local object called lda from the LinearDiscriminantAnalysis. We will also pass it a parameter called n_components. Now we could do the whole thing where we find the percentage of variance introduced by each principal component. But I am just going to skip that part and set the n_components parameter to the value of 1. lda = LinearDiscriminantAnalysis(n_component=1) One last thing to do! Call the fit method on lda and pass it the X and y datasets as input, and then chain a transform method with X as its input. X = lda.fit(X,y).transform(X)// Output[[-1.51304437] [-1.28152255] [-1.11875163] ... [ 0.71637389] [-0.32030997] [ 0.8645305 ]] Tada! 🎉 We have now successfully reduced the dimensions of X to 1! Thank you for reading this post on dimensionality reduction. I hope that it helped you even a little bit on your journey in the machine learning. Dimensionality Reduction Algorithms are truly amazing and really helpful not just for visualizing your results, but also to help reduce processing time and the strain on your system by preventing it from reading large datasets.
[ { "code": null, "e": 405, "s": 172, "text": "Recently, I was asked to work on a dataset that was a bit on the heavy side. It was so large that my Excel program would stop responding for a few minutes while loading, and manually exploring the data started to become a real pain." }, { "code": null, "e": 573, "s": 405, "text": "I am still a newbie in the Machine Learning world. So, I had to go back the Excel multiple times to decide which features should be used in the Machine Learning model." }, { "code": null, "e": 817, "s": 573, "text": "But after an excruciatingly long and mind wrecking time, I was able to build a model that would give me some decent results! I started to feel really good about myself and started to believe that I could make it as a Machine Learning Engineer!" }, { "code": null, "e": 903, "s": 817, "text": "But then I came across my next obstacle: How do I show my results to ordinary people?" }, { "code": null, "e": 1259, "s": 903, "text": "I could make two columns where one would show the real-world results and the other column would show the results given to me by the ML model. But this is not the most visually appealing way to go. While machines are better than us at understanding large sets of numeric data, the human mind finds it easier to understand visual data like graphs and plots." }, { "code": null, "e": 1657, "s": 1259, "text": "So a plot is the best way to go forward. But our screen is two dimensional and our data can have more than two features where each feature can be considered as a dimension. One of the two dimensions of the plot is going to be the output. So the question we should ask ourselves is: How do we represent all of our features, which could be anywhere from hundreds to thousands, in a single dimension?" }, { "code": null, "e": 1713, "s": 1657, "text": "This is where dimensionality reduction comes into play!" }, { "code": null, "e": 2030, "s": 1713, "text": "Dimensionality Reduction is a technique in Machine Learning that reduces the number of features in your dataset. The great thing about dimensionality reduction is that it does not negatively affect your machine learning model’s performance. In some cases, this technique has even increased the accuracy of the model." }, { "code": null, "e": 2215, "s": 2030, "text": "By reducing the number of features in our dataset, we are also reducing the storage space required to store the data, our python compiler will need less time to go through the dataset." }, { "code": null, "e": 2397, "s": 2215, "text": "In this post, we will take a look at two of the most popular types of Dimensionality Reduction techniques, Principle Component Analysis (PCA) and Linear Discriminant Analysis (LDA)." }, { "code": null, "e": 2494, "s": 2397, "text": "Before we move further, let’s make sure that your system is ready to work with some python code." }, { "code": null, "e": 2690, "s": 2494, "text": "There two major versions of Python: 2.x and 3.x. I would suggest that you make sure that you have the 3.x version installed on your system. If that is not the case, then you can get it from here." }, { "code": null, "e": 3080, "s": 2690, "text": "Next, we need a good code editor that will help make your coding experience easier and enjoyable. My personal choice is the amazing VSCode, but you can also try out Spyder or Jupyter Notebook. There are also a couple of online code editors like Repl and Google Colab that you can try. Using online editor would let you skip the time and storage wasting task of installing Python Libraries." }, { "code": null, "e": 3385, "s": 3080, "text": "We will be working on the Wine Dataset. This dataset is completely numeric and it does not contain any missing values, making it perfect for this article as I won’t have to waste time on Data-Preprocessing techniques such as converting categorical data to numeric data and imputing data into empty cells." }, { "code": null, "e": 3465, "s": 3385, "text": "Let’s start by importing some Python Libraries that we will need in our script:" }, { "code": null, "e": 3533, "s": 3465, "text": "import pandas as pdfrom sklearn.preprocessing import StandardScaler" }, { "code": null, "e": 3664, "s": 3533, "text": "We also need to load the wine dataset into our python script. Let’s do that using the read_csv() function from the pandas library:" }, { "code": null, "e": 3814, "s": 3664, "text": "dataset_url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv'dataset = pd.read_csv(dataset_url, sep=';')" }, { "code": null, "e": 3853, "s": 3814, "text": "The dataset looks something like this:" }, { "code": null, "e": 4052, "s": 3853, "text": "The quality column will be the dependent variable of our Machine Learning Model, and the rest of the columns will be the independent variables. So let’s split the dataset into two parts accordingly:" }, { "code": null, "e": 4115, "s": 4052, "text": "X = dataset.iloc[:, 0:-1].valuesy = dataset.iloc[:, -1].values" }, { "code": null, "e": 4161, "s": 4115, "text": "X contains 11 columns, and y the 12th column." }, { "code": null, "e": 4548, "s": 4161, "text": "We also need to perform some feature scaling on the data. We are using the StandardScalar function to do this for us. This function will transform our data in such a way that the data’s distribution will have a mean of 0 and a standard deviation of 1. We will perform the feature scaling on the independent variables since we want our dependent variable to stay as pristine as possible." }, { "code": null, "e": 4593, "s": 4548, "text": "sc = StandardScaler()X = sc.fit_transform(X)" }, { "code": null, "e": 4810, "s": 4593, "text": "We are now ready to perform dimensionality reduction! Let’s start with PCA first, and then perform LDA. I would suggest to make a new python script file and copy your code into it, and use it later with the LDA part." }, { "code": null, "e": 5021, "s": 4810, "text": "Principal Component Analysis (PCA) is one of the most popular dimensionality reduction algorithms out there and can also be used for noise filtering, stock market predictions, data visualization, and much more." }, { "code": null, "e": 5231, "s": 5021, "text": "PCA reduces the number of features in the dataset by detecting the correlation between them. When the correlation between the features is strong enough, they will get merged together and form a single feature." }, { "code": null, "e": 5393, "s": 5231, "text": "We could take a look at the Math behind the algorithm and try to understand how it works, but I found it easier to get into the code and see what outputs we get." }, { "code": null, "e": 5507, "s": 5393, "text": "Picking up from where we left our code in the previous section, let’s start by import the PCA class from sklearn:" }, { "code": null, "e": 5545, "s": 5507, "text": "from sklearn.decomposition import PCA" }, { "code": null, "e": 5604, "s": 5545, "text": "Next, we need to create a local instance of the PCA class." }, { "code": null, "e": 5633, "s": 5604, "text": "pca = PCA(n_components=None)" }, { "code": null, "e": 5725, "s": 5633, "text": "We are passing a parameter called n_components which we will intially pass a value of None." }, { "code": null, "e": 5894, "s": 5725, "text": "Next, we will call the fit_transform method on pca and pass it the X_train dataset as input. We will also call the transform method and pass the X_test dataset as input" }, { "code": null, "e": 5919, "s": 5894, "text": "X = pca.fit_transform(X)" }, { "code": null, "e": 6128, "s": 5919, "text": "Once this is done, we need to get the explained variance of different principal components of the dataset. Our pca object has a property called explained_variance_ratio_ that contains an array of percentages." }, { "code": null, "e": 6170, "s": 6128, "text": "variances = pca.explained_variance_ratio_" }, { "code": null, "e": 6237, "s": 6170, "text": "If you print this variable, you will get an array similar to this:" }, { "code": null, "e": 6361, "s": 6237, "text": "[0.28173931 0.1750827 0.1409585 0.11029387 0.08720837 0.05996439 0.05307193 0.03845061 0.0313311 0.01648483 0.00541439]" }, { "code": null, "e": 6572, "s": 6361, "text": "We can see that the elements of this array are in descending order. But what do these values mean? Each of the values explains the amount of variance given by each of the 11 principal components in our dataset." }, { "code": null, "e": 6791, "s": 6572, "text": "So if only take the first principal component, we will have 28.17% variance. If we take two principal components, we will have the sum of the first two elements of the array, which is around 45.68% variance, and so on." }, { "code": null, "e": 6996, "s": 6791, "text": "Now we can our Python compiler, and replace the None value passed to n_components inside PCA with the desired number of dimensions. Let’s see what we get by selecting 1 as the desired number of dimensions" }, { "code": null, "e": 7156, "s": 6996, "text": "pca = PCA(n_components=2)X = pca.fit_transform(X)// Output[[-1.61952988] [-0.79916993] [-0.74847909] ... [-1.45612897] [-2.27051793] [-0.42697475]]" }, { "code": null, "e": 7257, "s": 7156, "text": "Voila! We have successfully reduced the number of dimensions of our input dataset from 11 to just 1!" }, { "code": null, "e": 7426, "s": 7257, "text": "Similar to PCA, LDA is also a dimensionality reduction algorithm. But unlike PCA, LDA will also find the features that maximize the separation between multiple classes." }, { "code": null, "e": 7556, "s": 7426, "text": "You might ask yourself: why should I bother with this new algorithm that basically does the same thing as the previous algorithm?" }, { "code": null, "e": 7731, "s": 7556, "text": "Both PCA and LDA are dimensionality reduction algorithms. But where PCA is considered to be an unsupervised algorithm, LDA, on the other hand, is considered to be supervised." }, { "code": null, "e": 7962, "s": 7731, "text": "Supervised and Unsupervised? These are common machine learning terms that define whether an algorithm uses the dependent variable or not, respectively. So LDA uses the dependent variable, and PCA, as we have seen before, does not." }, { "code": null, "e": 8055, "s": 7962, "text": "Let’s get to some code and understand how to implement the LDA algorithm in our python code." }, { "code": null, "e": 8246, "s": 8055, "text": "If you have not already done so, then take the code from the getting started section and paste it in a new python script file. Then, import the LinearDiscriminantAnalysis class from sklearn." }, { "code": null, "e": 8315, "s": 8246, "text": "from sklearn.discriminant_analysis import LinearDiscriminantAnalysis" }, { "code": null, "e": 8653, "s": 8315, "text": "Next, we create a local object called lda from the LinearDiscriminantAnalysis. We will also pass it a parameter called n_components. Now we could do the whole thing where we find the percentage of variance introduced by each principal component. But I am just going to skip that part and set the n_components parameter to the value of 1." }, { "code": null, "e": 8701, "s": 8653, "text": "lda = LinearDiscriminantAnalysis(n_component=1)" }, { "code": null, "e": 8848, "s": 8701, "text": "One last thing to do! Call the fit method on lda and pass it the X and y datasets as input, and then chain a transform method with X as its input." }, { "code": null, "e": 8988, "s": 8848, "text": "X = lda.fit(X,y).transform(X)// Output[[-1.51304437] [-1.28152255] [-1.11875163] ... [ 0.71637389] [-0.32030997] [ 0.8645305 ]]" }, { "code": null, "e": 9055, "s": 8988, "text": "Tada! 🎉 We have now successfully reduced the dimensions of X to 1!" } ]
600X t-SNE speedup with RAPIDS. RAPIDS GPU-accelerated t-SNE achieves a... | by Connor Shorten | Towards Data Science
GPU accelerations are commonly associated with Deep Learning. GPUs power Convolutional Neural Networks for Computer Vision and Transformers for Natural Language Processing. They do this through parallel computation, making them much faster for certain tasks compared to CPUs. RAPIDS is expanding the utilization of GPUs by bringing traditional Machine Learning and Data Science algorithms, such as t-SNE or XGBoost, to GPUs. Hardware: This experiment was run on the Data Science PC by Digital Storm t-SNE is an algorithm for visualizing high-dimensional data. Shown above is an example of transforming the 512-dimensional vectors from intermediate CNN activations into 2-dimensional vectors. Each image in the CIFAR-10 dataset is passed through the image classifier. The activations right before the final classification layer are added to an array for visualization. This is done with the following line of code: from tensorflow.keras.models import Modelintermediate_layer_model = Model(inputs = model.input, outputs = model.get_layer('VisualizationLayer').output) The final Dense layer is given the name ‘VisualizationLayer’ to index it in this way t-SNE visualization is great for gaining intuition about the decision space. Another approach to this might be to use a confusion matrix. The t-SNE visualization shows errors such as the overlap between cars and airplanes. Whereas a confusion matrix would simply tell us something like ‘8’ cars have been misclassified as airplanes, the t-SNE visualization gives more information about what is happening here. We see that at least the misclassified cars are on the fringe of the airplane boundary, we might be able to solve this problem with some label smoothing / data augmentation. Gaining intuition about our models is very useful for this kind of EDA (exploratory data analysis). This can help inform data-level decisions such as identifying the impact of class imbalance, data augmentation, or utility of gathering more data. This can also help compare loss functions with another. In “GAN-based Synthetic Medical Image Augmentation for increased CNN Performance in Liver Lesion Classification”, Frid-adar et al. use t-SNE visualizations to show how adding GAN-generated data improves the decision boundaries for Medical Image classification (notice the improved disentanglement of the blue class in figure b compared to a). In “Improving Adversarial Robustness via Guided Complement Entropy” by Chen et al. They show how their improvement on the cross-entropy loss function results in a smoother decision boundary with less overlap (compare the figure on the right to the figure on the left). They use this visualization to illustrate how their improved decision boundaries provide adversarial attack defense. This example demonstrates > 600X speedup on t-SNE using RAPIDS vs. Sklearn This example is running the Barnes-Hut (n log n) version of t-SNE on 50,000 CIFAR-10 images that have been processed through an image classifier (trained to 79% accuracy) to 512-dimensional vectors. The t-SNE algorithm converts these 512-d vectors to 2-d for visualization. 1918 seconds (~30 minutes) (Sklearn) from sklearn.manifold import TSNEsklearn_embedded = TSNE(n_components=2).fit_transform(embeddings) 3 seconds (RAPIDS cuml) from cuml.manifold import TSNE as cumlTSNEtsne = cumlTSNE(n_components=2, method='barnes_hut')tsne_embedding = tsne.fit_transform(embeddings) Hardware: This experiment was run on the Data Science PC by Digital Storm The t-SNE speedup enabled by RAPIDS makes high-dimensional data visualization much more practical. Embedding the 50K CIFAR-10 vectors took 30 minutes on the CPU implementation, trying to embed the 1.2 million ImageNet dataset would take at least 12 hours by extension if the t-SNE algorithm had O(n) time complexity (although the latter log n of the barnes-hut algorithm would be largely negligible at this scale). Powered by RAPIDS, t-SNE visualization can enable visualization of the entire ImageNet dataset (explored in t-SNE-CUDA by Chan et al.). GPU speedups on these kinds of vector representations are also enormously useful for Image similarity / retrieval applications. One of the best approaches for finding the most semantically similar image from a large image database is to compare the intermediate activations of an image classifier. This results in comparing a large set of k-dimensional vector embeddings from the classifier. RAPIDS can dramatically speed up this kind of operation for clustering algorithms such as K-Means. t-SNE is a great technique to gain insight about datasets and the intermediate representations constructed by neural networks. RAPIDS is helping power t-SNE to new heights through GPU-acceleration, enabling a much larger volume of data to be visualized with this algorithm. Thanks for reading! If you found this article interesting, you may also enjoy this video walking through the experiment step-by-step from the NGC docker container to setup the RAPIDS libraries to the final t-SNE visualization!
[ { "code": null, "e": 447, "s": 171, "text": "GPU accelerations are commonly associated with Deep Learning. GPUs power Convolutional Neural Networks for Computer Vision and Transformers for Natural Language Processing. They do this through parallel computation, making them much faster for certain tasks compared to CPUs." }, { "code": null, "e": 596, "s": 447, "text": "RAPIDS is expanding the utilization of GPUs by bringing traditional Machine Learning and Data Science algorithms, such as t-SNE or XGBoost, to GPUs." }, { "code": null, "e": 670, "s": 596, "text": "Hardware: This experiment was run on the Data Science PC by Digital Storm" }, { "code": null, "e": 1085, "s": 670, "text": "t-SNE is an algorithm for visualizing high-dimensional data. Shown above is an example of transforming the 512-dimensional vectors from intermediate CNN activations into 2-dimensional vectors. Each image in the CIFAR-10 dataset is passed through the image classifier. The activations right before the final classification layer are added to an array for visualization. This is done with the following line of code:" }, { "code": null, "e": 1248, "s": 1085, "text": "from tensorflow.keras.models import Modelintermediate_layer_model = Model(inputs = model.input, outputs = model.get_layer('VisualizationLayer').output)" }, { "code": null, "e": 1333, "s": 1248, "text": "The final Dense layer is given the name ‘VisualizationLayer’ to index it in this way" }, { "code": null, "e": 1917, "s": 1333, "text": "t-SNE visualization is great for gaining intuition about the decision space. Another approach to this might be to use a confusion matrix. The t-SNE visualization shows errors such as the overlap between cars and airplanes. Whereas a confusion matrix would simply tell us something like ‘8’ cars have been misclassified as airplanes, the t-SNE visualization gives more information about what is happening here. We see that at least the misclassified cars are on the fringe of the airplane boundary, we might be able to solve this problem with some label smoothing / data augmentation." }, { "code": null, "e": 2220, "s": 1917, "text": "Gaining intuition about our models is very useful for this kind of EDA (exploratory data analysis). This can help inform data-level decisions such as identifying the impact of class imbalance, data augmentation, or utility of gathering more data. This can also help compare loss functions with another." }, { "code": null, "e": 2563, "s": 2220, "text": "In “GAN-based Synthetic Medical Image Augmentation for increased CNN Performance in Liver Lesion Classification”, Frid-adar et al. use t-SNE visualizations to show how adding GAN-generated data improves the decision boundaries for Medical Image classification (notice the improved disentanglement of the blue class in figure b compared to a)." }, { "code": null, "e": 2949, "s": 2563, "text": "In “Improving Adversarial Robustness via Guided Complement Entropy” by Chen et al. They show how their improvement on the cross-entropy loss function results in a smoother decision boundary with less overlap (compare the figure on the right to the figure on the left). They use this visualization to illustrate how their improved decision boundaries provide adversarial attack defense." }, { "code": null, "e": 3024, "s": 2949, "text": "This example demonstrates > 600X speedup on t-SNE using RAPIDS vs. Sklearn" }, { "code": null, "e": 3298, "s": 3024, "text": "This example is running the Barnes-Hut (n log n) version of t-SNE on 50,000 CIFAR-10 images that have been processed through an image classifier (trained to 79% accuracy) to 512-dimensional vectors. The t-SNE algorithm converts these 512-d vectors to 2-d for visualization." }, { "code": null, "e": 3335, "s": 3298, "text": "1918 seconds (~30 minutes) (Sklearn)" }, { "code": null, "e": 3434, "s": 3335, "text": "from sklearn.manifold import TSNEsklearn_embedded = TSNE(n_components=2).fit_transform(embeddings)" }, { "code": null, "e": 3458, "s": 3434, "text": "3 seconds (RAPIDS cuml)" }, { "code": null, "e": 3600, "s": 3458, "text": "from cuml.manifold import TSNE as cumlTSNEtsne = cumlTSNE(n_components=2, method='barnes_hut')tsne_embedding = tsne.fit_transform(embeddings)" }, { "code": null, "e": 3674, "s": 3600, "text": "Hardware: This experiment was run on the Data Science PC by Digital Storm" }, { "code": null, "e": 4089, "s": 3674, "text": "The t-SNE speedup enabled by RAPIDS makes high-dimensional data visualization much more practical. Embedding the 50K CIFAR-10 vectors took 30 minutes on the CPU implementation, trying to embed the 1.2 million ImageNet dataset would take at least 12 hours by extension if the t-SNE algorithm had O(n) time complexity (although the latter log n of the barnes-hut algorithm would be largely negligible at this scale)." }, { "code": null, "e": 4225, "s": 4089, "text": "Powered by RAPIDS, t-SNE visualization can enable visualization of the entire ImageNet dataset (explored in t-SNE-CUDA by Chan et al.)." }, { "code": null, "e": 4716, "s": 4225, "text": "GPU speedups on these kinds of vector representations are also enormously useful for Image similarity / retrieval applications. One of the best approaches for finding the most semantically similar image from a large image database is to compare the intermediate activations of an image classifier. This results in comparing a large set of k-dimensional vector embeddings from the classifier. RAPIDS can dramatically speed up this kind of operation for clustering algorithms such as K-Means." }, { "code": null, "e": 4990, "s": 4716, "text": "t-SNE is a great technique to gain insight about datasets and the intermediate representations constructed by neural networks. RAPIDS is helping power t-SNE to new heights through GPU-acceleration, enabling a much larger volume of data to be visualized with this algorithm." } ]
list::swap() in C++ STL - GeeksforGeeks
12 Jan, 2018 Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. This function is used to swap the contents of one list with another list of same type and size. Syntax : listname1.swap(listname2) Parameters : The name of the lists with which the contents have to be swapped. Result : All the elements of the 2 list are swapped. Examples: Input : mylist1 = {1, 2, 3, 4} mylist2 = {3, 5, 7, 9} mylist1.swap(mylist2); Output : mylist1 = {3, 5, 7, 9} mylist2 = {1, 2, 3, 4} Input : mylist1 = {1, 3, 5, 7} mylist2 = {2, 4, 6, 8} mylist1.swap(mylist2); Output : mylist1 = {2, 4, 6, 8} mylist2 = {1, 3, 5, 7} Errors and Exceptions 1. It throws an error if the lists are not of the same type.2. It throws an error if the lists are not of the same size.2. It has a basic no exception throw guarantee otherwise. // CPP program to illustrate// Implementation of swap() function#include <iostream>#include <list>using namespace std; int main(){ // list container declaration list<int> mylist1{ 1, 2, 3, 4 }; list<int> mylist2{ 3, 5, 7, 9 }; // using swap() function to //swap elements of lists mylist1.swap(mylist2); // printing the first list cout << "mylist1 = "; for (auto it = mylist1.begin(); it != mylist1.end(); ++it) cout << ' ' << *it; // printing the second list cout << endl << "mylist2 = "; for (auto it = mylist2.begin(); it != mylist2.end(); ++it) cout << ' ' << *it; return 0;} Output: mylist1 = 3 5 7 9 mylist2 = 1 2 3 4 cpp-list STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ C++ Classes and Objects Bitwise Operators in C/C++ Virtual Function in C++ Templates in C++ with Examples Constructors in C++ Operator Overloading in C++ Socket Programming in C/C++ vector erase() and clear() in C++ Object Oriented Programming in C++
[ { "code": null, "e": 25649, "s": 25621, "text": "\n12 Jan, 2018" }, { "code": null, "e": 25900, "s": 25649, "text": "Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists." }, { "code": null, "e": 25996, "s": 25900, "text": "This function is used to swap the contents of one list with another list of same type and size." }, { "code": null, "e": 26005, "s": 25996, "text": "Syntax :" }, { "code": null, "e": 26164, "s": 26005, "text": "listname1.swap(listname2)\nParameters :\nThe name of the lists with which\nthe contents have to be swapped.\nResult :\nAll the elements of the 2 list are swapped.\n" }, { "code": null, "e": 26174, "s": 26164, "text": "Examples:" }, { "code": null, "e": 26496, "s": 26174, "text": "Input : mylist1 = {1, 2, 3, 4}\n mylist2 = {3, 5, 7, 9}\n mylist1.swap(mylist2);\nOutput : mylist1 = {3, 5, 7, 9}\n mylist2 = {1, 2, 3, 4}\n\nInput : mylist1 = {1, 3, 5, 7}\n mylist2 = {2, 4, 6, 8}\n mylist1.swap(mylist2);\nOutput : mylist1 = {2, 4, 6, 8}\n mylist2 = {1, 3, 5, 7}\n" }, { "code": null, "e": 26518, "s": 26496, "text": "Errors and Exceptions" }, { "code": null, "e": 26696, "s": 26518, "text": "1. It throws an error if the lists are not of the same type.2. It throws an error if the lists are not of the same size.2. It has a basic no exception throw guarantee otherwise." }, { "code": "// CPP program to illustrate// Implementation of swap() function#include <iostream>#include <list>using namespace std; int main(){ // list container declaration list<int> mylist1{ 1, 2, 3, 4 }; list<int> mylist2{ 3, 5, 7, 9 }; // using swap() function to //swap elements of lists mylist1.swap(mylist2); // printing the first list cout << \"mylist1 = \"; for (auto it = mylist1.begin(); it != mylist1.end(); ++it) cout << ' ' << *it; // printing the second list cout << endl << \"mylist2 = \"; for (auto it = mylist2.begin(); it != mylist2.end(); ++it) cout << ' ' << *it; return 0;}", "e": 27369, "s": 26696, "text": null }, { "code": null, "e": 27377, "s": 27369, "text": "Output:" }, { "code": null, "e": 27416, "s": 27377, "text": "mylist1 = 3 5 7 9 \nmylist2 = 1 2 3 4 \n" }, { "code": null, "e": 27425, "s": 27416, "text": "cpp-list" }, { "code": null, "e": 27429, "s": 27425, "text": "STL" }, { "code": null, "e": 27433, "s": 27429, "text": "C++" }, { "code": null, "e": 27437, "s": 27433, "text": "STL" }, { "code": null, "e": 27441, "s": 27437, "text": "CPP" }, { "code": null, "e": 27539, "s": 27441, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27558, "s": 27539, "text": "Inheritance in C++" }, { "code": null, "e": 27582, "s": 27558, "text": "C++ Classes and Objects" }, { "code": null, "e": 27609, "s": 27582, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 27633, "s": 27609, "text": "Virtual Function in C++" }, { "code": null, "e": 27664, "s": 27633, "text": "Templates in C++ with Examples" }, { "code": null, "e": 27684, "s": 27664, "text": "Constructors in C++" }, { "code": null, "e": 27712, "s": 27684, "text": "Operator Overloading in C++" }, { "code": null, "e": 27740, "s": 27712, "text": "Socket Programming in C/C++" }, { "code": null, "e": 27774, "s": 27740, "text": "vector erase() and clear() in C++" } ]
Logger getName() Method in Java with Examples - GeeksforGeeks
26 Mar, 2019 getName() method of a Logger class used to get the name of logger. Many times you have to check the logger name so we can use this method to get the logger name. Syntax: public String getName() Parameters: This method accepts nothing. Return value: This method return logger name and it will be null for anonymous Loggers. Below programs illustrate the getName() method:Program 1: // Java program to demonstrate// Logger.getName() method import java.util.logging.*; public class GFG { // Create a logger using getGLobal() static Logger logger1 = Logger.getGlobal(); // Create a logger using getLogger() static Logger logger2 = Logger.getLogger("com.gfg"); public static void main(String[] args) { System.out.println("logger1 name = " + logger1.getName()); System.out.println("logger2 name = " + logger2.getName()); }} logger1 name = global logger2 name = com.gfg Program 2: // Java program to demonstrate// Logger.getName() method import java.util.logging.*; public class GFG { // Create a logger using getLogger() static Logger logger = Logger.getLogger("com.gfg.logger."); public static void main(String[] args) { System.out.println("logger name = " + logger.getName()); }} logger name = com.gfg.logger. Reference: https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#getName() Java - util package Java-Functions Java-Logger Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n26 Mar, 2019" }, { "code": null, "e": 25387, "s": 25225, "text": "getName() method of a Logger class used to get the name of logger. Many times you have to check the logger name so we can use this method to get the logger name." }, { "code": null, "e": 25395, "s": 25387, "text": "Syntax:" }, { "code": null, "e": 25420, "s": 25395, "text": "public String getName()\n" }, { "code": null, "e": 25461, "s": 25420, "text": "Parameters: This method accepts nothing." }, { "code": null, "e": 25549, "s": 25461, "text": "Return value: This method return logger name and it will be null for anonymous Loggers." }, { "code": null, "e": 25607, "s": 25549, "text": "Below programs illustrate the getName() method:Program 1:" }, { "code": "// Java program to demonstrate// Logger.getName() method import java.util.logging.*; public class GFG { // Create a logger using getGLobal() static Logger logger1 = Logger.getGlobal(); // Create a logger using getLogger() static Logger logger2 = Logger.getLogger(\"com.gfg\"); public static void main(String[] args) { System.out.println(\"logger1 name = \" + logger1.getName()); System.out.println(\"logger2 name = \" + logger2.getName()); }}", "e": 26155, "s": 25607, "text": null }, { "code": null, "e": 26201, "s": 26155, "text": "logger1 name = global\nlogger2 name = com.gfg\n" }, { "code": null, "e": 26212, "s": 26201, "text": "Program 2:" }, { "code": "// Java program to demonstrate// Logger.getName() method import java.util.logging.*; public class GFG { // Create a logger using getLogger() static Logger logger = Logger.getLogger(\"com.gfg.logger.\"); public static void main(String[] args) { System.out.println(\"logger name = \" + logger.getName()); }}", "e": 26577, "s": 26212, "text": null }, { "code": null, "e": 26608, "s": 26577, "text": "logger name = com.gfg.logger.\n" }, { "code": null, "e": 26702, "s": 26608, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#getName()" }, { "code": null, "e": 26722, "s": 26702, "text": "Java - util package" }, { "code": null, "e": 26737, "s": 26722, "text": "Java-Functions" }, { "code": null, "e": 26749, "s": 26737, "text": "Java-Logger" }, { "code": null, "e": 26754, "s": 26749, "text": "Java" }, { "code": null, "e": 26759, "s": 26754, "text": "Java" }, { "code": null, "e": 26857, "s": 26759, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26872, "s": 26857, "text": "Stream In Java" }, { "code": null, "e": 26893, "s": 26872, "text": "Constructors in Java" }, { "code": null, "e": 26912, "s": 26893, "text": "Exceptions in Java" }, { "code": null, "e": 26942, "s": 26912, "text": "Functional Interfaces in Java" }, { "code": null, "e": 26988, "s": 26942, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27005, "s": 26988, "text": "Generics in Java" }, { "code": null, "e": 27026, "s": 27005, "text": "Introduction to Java" }, { "code": null, "e": 27069, "s": 27026, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27105, "s": 27069, "text": "Internal Working of HashMap in Java" } ]
Inorder Tree Traversal without recursion and without stack! - GeeksforGeeks
26 Oct, 2021 Using Morris Traversal, we can traverse the tree without using stack and recursion. The idea of Morris Traversal is based on Threaded Binary Tree. In this traversal, we first create links to Inorder successor and print the data using these links, and finally revert the changes to restore original tree. 1. Initialize current as root 2. While current is not NULL If the current does not have left child a) Print current’s data b) Go to the right, i.e., current = current->right Else a) Find rightmost node in current left subtree OR node whose right child == current. If we found right child == current a) Update the right child as NULL of that node whose right child is current b) Print current’s data c) Go to the right, i.e. current = current->right Else a) Make current as the right child of that rightmost node we found; and b) Go to this left child, i.e., current = current->left Although the tree is modified through the traversal, it is reverted back to its original shape after the completion. Unlike Stack based traversal, no extra space is required for this traversal. C++ Java Python 3 C# Javascript #include <stdio.h>#include <stdlib.h> /* A binary tree tNode has data, a pointer to left child and a pointer to right child */struct tNode { int data; struct tNode* left; struct tNode* right;}; /* Function to traverse the binary tree without recursion and without stack */void MorrisTraversal(struct tNode* root){ struct tNode *current, *pre; if (root == NULL) return; current = root; while (current != NULL) { if (current->left == NULL) { printf("%d ", current->data); current = current->right; } else { /* Find the inorder predecessor of current */ pre = current->left; while (pre->right != NULL && pre->right != current) pre = pre->right; /* Make current as the right child of its inorder predecessor */ if (pre->right == NULL) { pre->right = current; current = current->left; } /* Revert the changes made in the 'if' part to restore the original tree i.e., fix the right child of predecessor */ else { pre->right = NULL; printf("%d ", current->data); current = current->right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */} /* UTILITY FUNCTIONS *//* Helper function that allocates a new tNode with the given data and NULL left and right pointers. */struct tNode* newtNode(int data){ struct tNode* node = new tNode; node->data = data; node->left = NULL; node->right = NULL; return (node);} /* Driver program to test above functions*/int main(){ /* Constructed binary tree is 1 / \ 2 3 / \ 4 5 */ struct tNode* root = newtNode(1); root->left = newtNode(2); root->right = newtNode(3); root->left->left = newtNode(4); root->left->right = newtNode(5); MorrisTraversal(root); return 0;} // Java program to print inorder // traversal without recursion// and stack /* A binary tree tNode has data, a pointer to left child and a pointer to right child */class tNode { int data; tNode left, right; tNode(int item) { data = item; left = right = null; }} class BinaryTree { tNode root; /* Function to traverse a binary tree without recursion and without stack */ void MorrisTraversal(tNode root) { tNode current, pre; if (root == null) return; current = root; while (current != null) { if (current.left == null) { System.out.print(current.data + " "); current = current.right; } else { /* Find the inorder predecessor of current */ pre = current.left; while (pre.right != null && pre.right != current) pre = pre.right; /* Make current as right child of its * inorder predecessor */ if (pre.right == null) { pre.right = current; current = current.left; } /* Revert the changes made in the 'if' part to restore the original tree i.e., fix the right child of predecessor*/ else { pre.right = null; System.out.print(current.data + " "); current = current.right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */ } // Driver Code public static void main(String args[]) { /* Constructed binary tree is 1 / \ 2 3 / \ 4 5 */ BinaryTree tree = new BinaryTree(); tree.root = new tNode(1); tree.root.left = new tNode(2); tree.root.right = new tNode(3); tree.root.left.left = new tNode(4); tree.root.left.right = new tNode(5); tree.MorrisTraversal(tree.root); }} // This code has been contributed by Mayank// Jaiswal(mayank_24) # Python program to do Morris inOrder Traversal:# inorder traversal without recursion and without stack class Node: """A binary tree node""" def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def morris_traversal(root): """Generator function for iterative inorder tree traversal""" current = root while current is not None: if current.left is None: yield current.data current = current.right else: # Find the inorder # predecessor of current pre = current.left while pre.right is not None and pre.right is not current: pre = pre.right if pre.right is None: # Make current as right # child of its inorder predecessor pre.right = current current = current.left else: # Revert the changes made # in the 'if' part to restore the # original tree. i.e., fix # the right child of predecessor pre.right = None yield current.data current = current.right # Driver code""" Constructed binary tree is 1 / \ 2 3 / \ 4 5"""root = Node(1, right=Node(3), left=Node(2, left=Node(4), right=Node(5) ) ) for v in morris_traversal(root): print(v, end=' ') # This code is contributed by Naveen Aili# updated by Elazar Gershuni // C# program to print inorder traversal// without recursion and stackusing System; /* A binary tree tNode has data, pointer to left child and a pointer to right child */ class BinaryTree { tNode root; public class tNode { public int data; public tNode left, right; public tNode(int item) { data = item; left = right = null; } } /* Function to traverse binary tree without recursion and without stack */ void MorrisTraversal(tNode root) { tNode current, pre; if (root == null) return; current = root; while (current != null) { if (current.left == null) { Console.Write(current.data + " "); current = current.right; } else { /* Find the inorder predecessor of current */ pre = current.left; while (pre.right != null && pre.right != current) pre = pre.right; /* Make current as right child of its inorder predecessor */ if (pre.right == null) { pre.right = current; current = current.left; } /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecessor*/ else { pre.right = null; Console.Write(current.data + " "); current = current.right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */ } // Driver code public static void Main(String[] args) { /* Constructed binary tree is 1 / \ 2 3 / \ 4 5 */ BinaryTree tree = new BinaryTree(); tree.root = new tNode(1); tree.root.left = new tNode(2); tree.root.right = new tNode(3); tree.root.left.left = new tNode(4); tree.root.left.right = new tNode(5); tree.MorrisTraversal(tree.root); }} // This code has been contributed// by Arnab Kundu <script> // JavaScript program to print inorder// traversal without recursion// and stack /* A binary tree tNode has data, a pointer to left child and a pointer to right child */class tNode{ constructor(item) { this.data = item; this.left = this.right = null; }} let root; /* Function to traverse a binary tree without recursion and without stack */function MorrisTraversal(root){ let current, pre; if (root == null) return; current = root; while (current != null) { if (current.left == null) { document.write(current.data + " "); current = current.right; } else { /* Find the inorder predecessor of current */ pre = current.left; while (pre.right != null && pre.right != current) pre = pre.right; /* Make current as right child of its * inorder predecessor */ if (pre.right == null) { pre.right = current; current = current.left; } /* Revert the changes made in the 'if' part to restore the original tree i.e., fix the right child of predecessor*/ else { pre.right = null; document.write(current.data + " "); current = current.right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */} // Driver Code/* Constructed binary tree is 1 / \ 2 3 / \ 4 5 */ root = new tNode(1);root.left = new tNode(2);root.right = new tNode(3);root.left.left = new tNode(4);root.left.right = new tNode(5); MorrisTraversal(root); // This code is contributed by avanitrachhadiya2155 </script> 4 2 5 1 3 Time Complexity : O(n) If we take a closer look, we can notice that every edge of the tree is traversed at most three times. And in the worst case, the same number of extra edges (as input tree) are created and removed. References: www.liacs.nl/~deutz/DS/september28.pdf www.scss.tcd.ie/disciplines/software_systems/.../HughGibbonsSlides.pdfPlease write comments if you find any bug in above code/algorithm, or want to share more information about stack Morris Inorder Tree Traversal. andrew1234 Akanksha_Rai elazarg bronzenose upadhyayronak9313 sweetyty abhishek20aeccse avanitrachhadiya2155 arorakashish0911 threaded-binary-tree tree-traversal Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. AVL Tree | Set 1 (Insertion) Level Order Binary Tree Traversal Write a Program to Find the Maximum Depth or Height of a Tree Decision Tree A program to check if a binary tree is BST or not Introduction to Tree Data Structure Lowest Common Ancestor in a Binary Tree | Set 1 Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Expression Tree Deletion in a Binary Tree
[ { "code": null, "e": 39003, "s": 38975, "text": "\n26 Oct, 2021" }, { "code": null, "e": 39308, "s": 39003, "text": "Using Morris Traversal, we can traverse the tree without using stack and recursion. The idea of Morris Traversal is based on Threaded Binary Tree. In this traversal, we first create links to Inorder successor and print the data using these links, and finally revert the changes to restore original tree. " }, { "code": null, "e": 40030, "s": 39308, "text": "1. Initialize current as root \n2. While current is not NULL\n If the current does not have left child\n a) Print current’s data\n b) Go to the right, i.e., current = current->right\n Else\n a) Find rightmost node in current left subtree OR\n node whose right child == current.\n If we found right child == current\n a) Update the right child as NULL of that node whose right child is current\n b) Print current’s data\n c) Go to the right, i.e. current = current->right\n Else\n a) Make current as the right child of that rightmost \n node we found; and \n b) Go to this left child, i.e., current = current->left" }, { "code": null, "e": 40224, "s": 40030, "text": "Although the tree is modified through the traversal, it is reverted back to its original shape after the completion. Unlike Stack based traversal, no extra space is required for this traversal." }, { "code": null, "e": 40228, "s": 40224, "text": "C++" }, { "code": null, "e": 40233, "s": 40228, "text": "Java" }, { "code": null, "e": 40242, "s": 40233, "text": "Python 3" }, { "code": null, "e": 40245, "s": 40242, "text": "C#" }, { "code": null, "e": 40256, "s": 40245, "text": "Javascript" }, { "code": "#include <stdio.h>#include <stdlib.h> /* A binary tree tNode has data, a pointer to left child and a pointer to right child */struct tNode { int data; struct tNode* left; struct tNode* right;}; /* Function to traverse the binary tree without recursion and without stack */void MorrisTraversal(struct tNode* root){ struct tNode *current, *pre; if (root == NULL) return; current = root; while (current != NULL) { if (current->left == NULL) { printf(\"%d \", current->data); current = current->right; } else { /* Find the inorder predecessor of current */ pre = current->left; while (pre->right != NULL && pre->right != current) pre = pre->right; /* Make current as the right child of its inorder predecessor */ if (pre->right == NULL) { pre->right = current; current = current->left; } /* Revert the changes made in the 'if' part to restore the original tree i.e., fix the right child of predecessor */ else { pre->right = NULL; printf(\"%d \", current->data); current = current->right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */} /* UTILITY FUNCTIONS *//* Helper function that allocates a new tNode with the given data and NULL left and right pointers. */struct tNode* newtNode(int data){ struct tNode* node = new tNode; node->data = data; node->left = NULL; node->right = NULL; return (node);} /* Driver program to test above functions*/int main(){ /* Constructed binary tree is 1 / \\ 2 3 / \\ 4 5 */ struct tNode* root = newtNode(1); root->left = newtNode(2); root->right = newtNode(3); root->left->left = newtNode(4); root->left->right = newtNode(5); MorrisTraversal(root); return 0;}", "e": 42363, "s": 40256, "text": null }, { "code": "// Java program to print inorder // traversal without recursion// and stack /* A binary tree tNode has data, a pointer to left child and a pointer to right child */class tNode { int data; tNode left, right; tNode(int item) { data = item; left = right = null; }} class BinaryTree { tNode root; /* Function to traverse a binary tree without recursion and without stack */ void MorrisTraversal(tNode root) { tNode current, pre; if (root == null) return; current = root; while (current != null) { if (current.left == null) { System.out.print(current.data + \" \"); current = current.right; } else { /* Find the inorder predecessor of current */ pre = current.left; while (pre.right != null && pre.right != current) pre = pre.right; /* Make current as right child of its * inorder predecessor */ if (pre.right == null) { pre.right = current; current = current.left; } /* Revert the changes made in the 'if' part to restore the original tree i.e., fix the right child of predecessor*/ else { pre.right = null; System.out.print(current.data + \" \"); current = current.right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */ } // Driver Code public static void main(String args[]) { /* Constructed binary tree is 1 / \\ 2 3 / \\ 4 5 */ BinaryTree tree = new BinaryTree(); tree.root = new tNode(1); tree.root.left = new tNode(2); tree.root.right = new tNode(3); tree.root.left.left = new tNode(4); tree.root.left.right = new tNode(5); tree.MorrisTraversal(tree.root); }} // This code has been contributed by Mayank// Jaiswal(mayank_24)", "e": 44767, "s": 42363, "text": null }, { "code": "# Python program to do Morris inOrder Traversal:# inorder traversal without recursion and without stack class Node: \"\"\"A binary tree node\"\"\" def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def morris_traversal(root): \"\"\"Generator function for iterative inorder tree traversal\"\"\" current = root while current is not None: if current.left is None: yield current.data current = current.right else: # Find the inorder # predecessor of current pre = current.left while pre.right is not None and pre.right is not current: pre = pre.right if pre.right is None: # Make current as right # child of its inorder predecessor pre.right = current current = current.left else: # Revert the changes made # in the 'if' part to restore the # original tree. i.e., fix # the right child of predecessor pre.right = None yield current.data current = current.right # Driver code\"\"\" Constructed binary tree is 1 / \\ 2 3 / \\ 4 5\"\"\"root = Node(1, right=Node(3), left=Node(2, left=Node(4), right=Node(5) ) ) for v in morris_traversal(root): print(v, end=' ') # This code is contributed by Naveen Aili# updated by Elazar Gershuni", "e": 46445, "s": 44767, "text": null }, { "code": "// C# program to print inorder traversal// without recursion and stackusing System; /* A binary tree tNode has data, pointer to left child and a pointer to right child */ class BinaryTree { tNode root; public class tNode { public int data; public tNode left, right; public tNode(int item) { data = item; left = right = null; } } /* Function to traverse binary tree without recursion and without stack */ void MorrisTraversal(tNode root) { tNode current, pre; if (root == null) return; current = root; while (current != null) { if (current.left == null) { Console.Write(current.data + \" \"); current = current.right; } else { /* Find the inorder predecessor of current */ pre = current.left; while (pre.right != null && pre.right != current) pre = pre.right; /* Make current as right child of its inorder predecessor */ if (pre.right == null) { pre.right = current; current = current.left; } /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecessor*/ else { pre.right = null; Console.Write(current.data + \" \"); current = current.right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */ } // Driver code public static void Main(String[] args) { /* Constructed binary tree is 1 / \\ 2 3 / \\ 4 5 */ BinaryTree tree = new BinaryTree(); tree.root = new tNode(1); tree.root.left = new tNode(2); tree.root.right = new tNode(3); tree.root.left.left = new tNode(4); tree.root.left.right = new tNode(5); tree.MorrisTraversal(tree.root); }} // This code has been contributed// by Arnab Kundu", "e": 48839, "s": 46445, "text": null }, { "code": "<script> // JavaScript program to print inorder// traversal without recursion// and stack /* A binary tree tNode has data, a pointer to left child and a pointer to right child */class tNode{ constructor(item) { this.data = item; this.left = this.right = null; }} let root; /* Function to traverse a binary tree without recursion and without stack */function MorrisTraversal(root){ let current, pre; if (root == null) return; current = root; while (current != null) { if (current.left == null) { document.write(current.data + \" \"); current = current.right; } else { /* Find the inorder predecessor of current */ pre = current.left; while (pre.right != null && pre.right != current) pre = pre.right; /* Make current as right child of its * inorder predecessor */ if (pre.right == null) { pre.right = current; current = current.left; } /* Revert the changes made in the 'if' part to restore the original tree i.e., fix the right child of predecessor*/ else { pre.right = null; document.write(current.data + \" \"); current = current.right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */} // Driver Code/* Constructed binary tree is 1 / \\ 2 3 / \\ 4 5 */ root = new tNode(1);root.left = new tNode(2);root.right = new tNode(3);root.left.left = new tNode(4);root.left.right = new tNode(5); MorrisTraversal(root); // This code is contributed by avanitrachhadiya2155 </script>", "e": 50995, "s": 48839, "text": null }, { "code": null, "e": 51006, "s": 50995, "text": "4 2 5 1 3 " }, { "code": null, "e": 51226, "s": 51006, "text": "Time Complexity : O(n) If we take a closer look, we can notice that every edge of the tree is traversed at most three times. And in the worst case, the same number of extra edges (as input tree) are created and removed." }, { "code": null, "e": 51492, "s": 51226, "text": "References: www.liacs.nl/~deutz/DS/september28.pdf www.scss.tcd.ie/disciplines/software_systems/.../HughGibbonsSlides.pdfPlease write comments if you find any bug in above code/algorithm, or want to share more information about stack Morris Inorder Tree Traversal. " }, { "code": null, "e": 51503, "s": 51492, "text": "andrew1234" }, { "code": null, "e": 51516, "s": 51503, "text": "Akanksha_Rai" }, { "code": null, "e": 51524, "s": 51516, "text": "elazarg" }, { "code": null, "e": 51535, "s": 51524, "text": "bronzenose" }, { "code": null, "e": 51553, "s": 51535, "text": "upadhyayronak9313" }, { "code": null, "e": 51562, "s": 51553, "text": "sweetyty" }, { "code": null, "e": 51579, "s": 51562, "text": "abhishek20aeccse" }, { "code": null, "e": 51600, "s": 51579, "text": "avanitrachhadiya2155" }, { "code": null, "e": 51617, "s": 51600, "text": "arorakashish0911" }, { "code": null, "e": 51638, "s": 51617, "text": "threaded-binary-tree" }, { "code": null, "e": 51653, "s": 51638, "text": "tree-traversal" }, { "code": null, "e": 51658, "s": 51653, "text": "Tree" }, { "code": null, "e": 51663, "s": 51658, "text": "Tree" }, { "code": null, "e": 51761, "s": 51663, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 51790, "s": 51761, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 51824, "s": 51790, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 51886, "s": 51824, "text": "Write a Program to Find the Maximum Depth or Height of a Tree" }, { "code": null, "e": 51900, "s": 51886, "text": "Decision Tree" }, { "code": null, "e": 51950, "s": 51900, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 51986, "s": 51950, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 52034, "s": 51986, "text": "Lowest Common Ancestor in a Binary Tree | Set 1" }, { "code": null, "e": 52117, "s": 52034, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 52133, "s": 52117, "text": "Expression Tree" } ]
Mid-Square hashing - GeeksforGeeks
18 Jul, 2018 Mid-Square hashing is a hashing technique in which unique keys are generated. In this technique, a seed value is taken and it is squared. Then, some digits from the middle are extracted. These extracted digits form a number which is taken as the new seed. This technique can generate keys with high randomness if a big enough seed value is taken. However, it has a limitation. As the seed is squared, if a 6-digit number is taken, then the square will have 12-digits. This exceeds the range of int data type. So, overflow must be taken care of. In case of overflow, use long long int data type or use string as multiplication if overflow still occurs. The chances of a collision in mid-square hashing are low, not obsolete. So, in the chances, if a collision occurs, it is handled using some hash map. Example: Suppose a 4-digit seed is taken. seed = 4765Hence, square of seed is = 4765 * 4765 = 22705225Now, from this 8-digit number, any four digits are extracted (Say, the middle four).So, the new seed value becomes seed = 7052Now, square of this new seed is = 7052 * 7052 = 49730704Again, the same set of 4-digits is extracted.So, the new seed value becomes seed = 7307....This process is repeated as many times as a key is required. Mid square technique takes a certain number of digits from the square of a number. This number extracted is a pseudo-random number, which can be used as a key for hashing. Algorithm: Choose a seed value. This is an important step as for same seed value, the same sequence of random numbers is generated.Take the square of the seed value and update seed by a certain number of digits that occur in the square. Note: The larger is the number of digits, larger will be the randomness.Return the key. Choose a seed value. This is an important step as for same seed value, the same sequence of random numbers is generated. Take the square of the seed value and update seed by a certain number of digits that occur in the square. Note: The larger is the number of digits, larger will be the randomness. Return the key. Below is the implementation of above algorithm: // C++ program to illustrate the// mid-square hashing technique#include <ctime>#include <iostream> using namespace std; // Returns a seed value based on current system time.long long int newTime(){ // Acquiring number of seconds // passed from Jan 1, 1970. time_t t = time(NULL); // Converting the time to year, month, // day, hour, minute, and second. struct tm* tm = localtime(&t); long long int x; // Applying a certain logic to get // required number of digits. It may vary. x = (tm->tm_hour) * 10000000 + (tm->tm_min) * 100000 + (tm->tm_sec) * 1000 + (tm->tm_mday) * 10 + (tm->tm_year); // Return the calculated number. return x;} // Returns a random 8-digit key.long int getKey(){ // Taking the key from system time. // returns a 8-digit seed value. static long long int key = newTime(); // Squaring the key. key = key * key; // Extracting required number of digits ( here, 8 ). if (key < 1000000000000000) { key = key / 10000; key = key % 100000000; } else { key = key / 10000; key = key % 100000000; } // Returning the key value. return key;} // Driver Codeint main(){ // get the first key std::cout << getKey() << endl; // get the second key std::cout << getKey() << endl; return 0;} 56002270 25424515 Note: The output will change according to the date and time. Hash Random Algorithms Randomized Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Classification of Algorithms with Examples Randomized Algorithms | Set 0 (Mathematical Background) Generate a random Binary String of length N Select a Random Node from a tree with equal probability Randomized Algorithms | Set 3 (1/2 Approximate Median) Random Acyclic Maze Generator with given Entry and Exit point Strong Password Suggester Program Write a function that generates one of 3 numbers according to given probabilities Maximum length sub-array which satisfies the given conditions Estimating the value of Pi using Monte Carlo | Parallel Computing Method
[ { "code": null, "e": 26093, "s": 26065, "text": "\n18 Jul, 2018" }, { "code": null, "e": 26895, "s": 26093, "text": "Mid-Square hashing is a hashing technique in which unique keys are generated. In this technique, a seed value is taken and it is squared. Then, some digits from the middle are extracted. These extracted digits form a number which is taken as the new seed. This technique can generate keys with high randomness if a big enough seed value is taken. However, it has a limitation. As the seed is squared, if a 6-digit number is taken, then the square will have 12-digits. This exceeds the range of int data type. So, overflow must be taken care of. In case of overflow, use long long int data type or use string as multiplication if overflow still occurs. The chances of a collision in mid-square hashing are low, not obsolete. So, in the chances, if a collision occurs, it is handled using some hash map." }, { "code": null, "e": 26904, "s": 26895, "text": "Example:" }, { "code": null, "e": 27331, "s": 26904, "text": "Suppose a 4-digit seed is taken. seed = 4765Hence, square of seed is = 4765 * 4765 = 22705225Now, from this 8-digit number, any four digits are extracted (Say, the middle four).So, the new seed value becomes seed = 7052Now, square of this new seed is = 7052 * 7052 = 49730704Again, the same set of 4-digits is extracted.So, the new seed value becomes seed = 7307....This process is repeated as many times as a key is required." }, { "code": null, "e": 27503, "s": 27331, "text": "Mid square technique takes a certain number of digits from the square of a number. This number extracted is a pseudo-random number, which can be used as a key for hashing." }, { "code": null, "e": 27514, "s": 27503, "text": "Algorithm:" }, { "code": null, "e": 27828, "s": 27514, "text": "Choose a seed value. This is an important step as for same seed value, the same sequence of random numbers is generated.Take the square of the seed value and update seed by a certain number of digits that occur in the square. Note: The larger is the number of digits, larger will be the randomness.Return the key." }, { "code": null, "e": 27949, "s": 27828, "text": "Choose a seed value. This is an important step as for same seed value, the same sequence of random numbers is generated." }, { "code": null, "e": 28128, "s": 27949, "text": "Take the square of the seed value and update seed by a certain number of digits that occur in the square. Note: The larger is the number of digits, larger will be the randomness." }, { "code": null, "e": 28144, "s": 28128, "text": "Return the key." }, { "code": null, "e": 28192, "s": 28144, "text": "Below is the implementation of above algorithm:" }, { "code": "// C++ program to illustrate the// mid-square hashing technique#include <ctime>#include <iostream> using namespace std; // Returns a seed value based on current system time.long long int newTime(){ // Acquiring number of seconds // passed from Jan 1, 1970. time_t t = time(NULL); // Converting the time to year, month, // day, hour, minute, and second. struct tm* tm = localtime(&t); long long int x; // Applying a certain logic to get // required number of digits. It may vary. x = (tm->tm_hour) * 10000000 + (tm->tm_min) * 100000 + (tm->tm_sec) * 1000 + (tm->tm_mday) * 10 + (tm->tm_year); // Return the calculated number. return x;} // Returns a random 8-digit key.long int getKey(){ // Taking the key from system time. // returns a 8-digit seed value. static long long int key = newTime(); // Squaring the key. key = key * key; // Extracting required number of digits ( here, 8 ). if (key < 1000000000000000) { key = key / 10000; key = key % 100000000; } else { key = key / 10000; key = key % 100000000; } // Returning the key value. return key;} // Driver Codeint main(){ // get the first key std::cout << getKey() << endl; // get the second key std::cout << getKey() << endl; return 0;}", "e": 29531, "s": 28192, "text": null }, { "code": null, "e": 29550, "s": 29531, "text": "56002270\n25424515\n" }, { "code": null, "e": 29611, "s": 29550, "text": "Note: The output will change according to the date and time." }, { "code": null, "e": 29616, "s": 29611, "text": "Hash" }, { "code": null, "e": 29634, "s": 29616, "text": "Random Algorithms" }, { "code": null, "e": 29645, "s": 29634, "text": "Randomized" }, { "code": null, "e": 29650, "s": 29645, "text": "Hash" }, { "code": null, "e": 29748, "s": 29650, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29791, "s": 29748, "text": "Classification of Algorithms with Examples" }, { "code": null, "e": 29847, "s": 29791, "text": "Randomized Algorithms | Set 0 (Mathematical Background)" }, { "code": null, "e": 29891, "s": 29847, "text": "Generate a random Binary String of length N" }, { "code": null, "e": 29947, "s": 29891, "text": "Select a Random Node from a tree with equal probability" }, { "code": null, "e": 30002, "s": 29947, "text": "Randomized Algorithms | Set 3 (1/2 Approximate Median)" }, { "code": null, "e": 30064, "s": 30002, "text": "Random Acyclic Maze Generator with given Entry and Exit point" }, { "code": null, "e": 30098, "s": 30064, "text": "Strong Password Suggester Program" }, { "code": null, "e": 30180, "s": 30098, "text": "Write a function that generates one of 3 numbers according to given probabilities" }, { "code": null, "e": 30242, "s": 30180, "text": "Maximum length sub-array which satisfies the given conditions" } ]
PostgreSQL - GROUP BY clause - GeeksforGeeks
28 Aug, 2020 The PostgreSQL GROUP BY clause is used to divide rows returned by SELECT statement into different groups. The speciality of GROUP BY clause is that one can use Functions like SUM() to calculate the sum of items or COUNT() to get the total number of items in the groups. Syntax: SELECT column_1, column_2, computing_function(column_3) FROM table_name GROUP BY column_1, column_2; It is important to note that The GROUP BY clause must exactly appear after the FROM or WHERE clause. For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link in our examples.Example 1:Here we will query for data from the payment table and group the result by customer id from the “payment” table of our sample database. SELECT customer_id FROM payment GROUP BY customer_id; Output: Example 2:Here we will query to get the amount that each customer has paid till date and use an aggregate function (ie SUM()), to do so and group them by customer_id from the “payment” table of the sample database. SELECT customer_id, SUM (amount) FROM payment GROUP BY customer_id; Output: Example 3:here we will make a query to count the number of payment transactions that each staff has been processing, you group the rows in the payment table based on staff_id and use the COUNT() function to get the number of transactions. SELECT staff_id, COUNT (payment_id) FROM payment GROUP BY staff_id; Output: postgreSQL-clauses PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. PostgreSQL - Psql commands PostgreSQL - Change Column Type PostgreSQL - For Loops PostgreSQL - Function Returning A Table PostgreSQL - Create Auto-increment Column using SERIAL PostgreSQL - CREATE PROCEDURE PostgreSQL - ARRAY_AGG() Function PostgreSQL - DROP INDEX PostgreSQL - Copy Table PostgreSQL - Identity Column
[ { "code": null, "e": 29269, "s": 29241, "text": "\n28 Aug, 2020" }, { "code": null, "e": 29539, "s": 29269, "text": "The PostgreSQL GROUP BY clause is used to divide rows returned by SELECT statement into different groups. The speciality of GROUP BY clause is that one can use Functions like SUM() to calculate the sum of items or COUNT() to get the total number of items in the groups." }, { "code": null, "e": 29670, "s": 29539, "text": "Syntax:\nSELECT \n column_1, \n column_2,\n computing_function(column_3)\nFROM \n table_name\nGROUP BY \n column_1,\n column_2;" }, { "code": null, "e": 29771, "s": 29670, "text": "It is important to note that The GROUP BY clause must exactly appear after the FROM or WHERE clause." }, { "code": null, "e": 30082, "s": 29771, "text": "For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link in our examples.Example 1:Here we will query for data from the payment table and group the result by customer id from the “payment” table of our sample database." }, { "code": null, "e": 30145, "s": 30082, "text": "SELECT\n customer_id\nFROM\n payment\nGROUP BY\n customer_id;" }, { "code": null, "e": 30153, "s": 30145, "text": "Output:" }, { "code": null, "e": 30368, "s": 30153, "text": "Example 2:Here we will query to get the amount that each customer has paid till date and use an aggregate function (ie SUM()), to do so and group them by customer_id from the “payment” table of the sample database." }, { "code": null, "e": 30452, "s": 30368, "text": "SELECT\n customer_id,\n SUM (amount)\nFROM\n payment\nGROUP BY\n customer_id;" }, { "code": null, "e": 30460, "s": 30452, "text": "Output:" }, { "code": null, "e": 30699, "s": 30460, "text": "Example 3:here we will make a query to count the number of payment transactions that each staff has been processing, you group the rows in the payment table based on staff_id and use the COUNT() function to get the number of transactions." }, { "code": null, "e": 30783, "s": 30699, "text": "SELECT\n staff_id,\n COUNT (payment_id)\nFROM\n payment\nGROUP BY\n staff_id;" }, { "code": null, "e": 30791, "s": 30783, "text": "Output:" }, { "code": null, "e": 30810, "s": 30791, "text": "postgreSQL-clauses" }, { "code": null, "e": 30821, "s": 30810, "text": "PostgreSQL" }, { "code": null, "e": 30919, "s": 30821, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30946, "s": 30919, "text": "PostgreSQL - Psql commands" }, { "code": null, "e": 30978, "s": 30946, "text": "PostgreSQL - Change Column Type" }, { "code": null, "e": 31001, "s": 30978, "text": "PostgreSQL - For Loops" }, { "code": null, "e": 31041, "s": 31001, "text": "PostgreSQL - Function Returning A Table" }, { "code": null, "e": 31096, "s": 31041, "text": "PostgreSQL - Create Auto-increment Column using SERIAL" }, { "code": null, "e": 31126, "s": 31096, "text": "PostgreSQL - CREATE PROCEDURE" }, { "code": null, "e": 31160, "s": 31126, "text": "PostgreSQL - ARRAY_AGG() Function" }, { "code": null, "e": 31184, "s": 31160, "text": "PostgreSQL - DROP INDEX" }, { "code": null, "e": 31208, "s": 31184, "text": "PostgreSQL - Copy Table" } ]
Decimal Equivalent of Gray Code and its Inverse - GeeksforGeeks
08 Jul, 2021 Given a decimal number n. Find the gray code of this number in decimal form. Examples: Input : 7 Output : 4 Explanation: 7 is represented as 111 in binary form. The equivalent gray code of 111 is 100 in binary form, whose decimal equivalent is 4. Input : 10 Output : 15 Explanation: 10 is represented as 1010 in binary form. The equivalent gray code of 1010 is 1111 in binary form, whose decimal equivalent is 15. The following table shows the conversion of binary code values to gray code values: Below is the approach for the conversion of decimal code values to gray code values. Let G(n) be the Gray code equivalent of binary representation n. Consider bits of a number n and a number bit G(n). Note that the leftmost set bits of both n and G(n) are in the same position. Let this position be i and positions on the right of it be (i+1), (i+2), etc. The (i + 1)th bit in G(n) is 0 if (i+1)th bit in n is 1 and vice versa is also true. The same is true for (i+2)-th bits, etc. Thus we have G (n) = n xor (n >> 1): C++ Java Python3 C# PHP Javascript // CPP Program to convert given// decimal number into decimal// equivalent of its gray code form#include <bits/stdc++.h>using namespace std; int grayCode(int n){ /* Right Shift the number by 1 taking xor with original number */ return n ^ (n >> 1);} // Driver Codeint main(){ int n = 10; cout << grayCode(n) << endl; return 0;} // Java Program to convert given// decimal number into decimal// equivalent of its gray code formclass GFG { static int grayCode(int n) { // Right Shift the number // by 1 taking xor with // original number return n ^ (n >> 1); } // Driver Code public static void main(String[] args) { int n = 10; System.out.println(grayCode(n)); }} // This code is contributed by// Smitha Dinesh Semwal # Python 3 Program to convert# given decimal number into# decimal equivalent of its# gray code form def grayCode(n): # Right Shift the number # by 1 taking xor with # original number return n ^ (n >> 1) # Driver Coden = 10print(grayCode(n)) # This code is contributed# by Smitha Dinesh Semwal // C# Program to convert given// decimal number into decimal// equivalent of its gray code formusing System; public class GFG { // Function for conversion public static int grayCode(int n) { // Right Shift the number // by 1 taking xor with // original number return n ^ (n >> 1); } // Driver Code static public void Main () { int n = 10; Console.WriteLine(grayCode(n)); }} // This code is contributed by Ajit. <?php// PHP Program to convert given// decimal number into decimal// equivalent of its gray code form function grayCode($n){ /* Right Shift the number by 1 taking xor with original number */ return $n ^ ($n >> 1);} // Driver Code $n = 10; echo grayCode($n) ; // This code is contributed by nitin mittal.?> <script> // Javascript Program to convert given// decimal number into decimal// equivalent of its gray code form function grayCode(n){ /* Right Shift the number by 1 taking xor with original number */ return n ^ (n >> 1);} // Driver Codevar n = 10;document.write( grayCode(n) ); </script> 15 Finding the Inverse Gray Code Given a decimal equivalent number n of a gray code. Find its original number in decimal form. Examples: Input : 4 Output : 7 Input : 15 Output : 10 Below is the approach for the conversion of gray code values to decimal code values. We will go from the older bits to the younger ones (even the smallest bit has number 1, and the oldest bit is numbered k). We obtain such relations between the bits of the ni number n and the bits of the gi number g: nk = gk, nk-1 = gk-1 xor nk = gk xor gk-1 nk-2 = gk-2 xor nk-1 = gk xor gk-1 xor gk-2 nk-3 = gk-3 xor nk-2 = gk xor gk-1 xor gk-2 xor gk-3 ... C++ Java Python3 C# PHP Javascript // CPP Program to convert given// decimal number of gray code// into its inverse in decimal form#include <bits/stdc++.h>using namespace std; int inversegrayCode(int n){ int inv = 0; // Taking xor until n becomes zero for (; n; n = n >> 1) inv ^= n; return inv;} // Driver Codeint main(){ int n = 15; cout << inversegrayCode(n) << endl; return 0;} // Java Program to convert given// decimal number of gray code// into its inverse in decimal formimport java.io.*; class GFG { // Function to convert given // decimal number of gray code // into its inverse in decimal form static int inversegrayCode(int n) { int inv = 0; // Taking xor until n becomes zero for ( ; n != 0 ; n = n >> 1) inv ^= n; return inv; } // Driver code public static void main (String[] args) { int n = 15; System.out.println(inversegrayCode(n)); }} // This code is contributed by Ajit. # Python3 Program to convert# given decimal number of# gray code into its inverse# in decimal form def inversegrayCode(n): inv = 0; # Taking xor until # n becomes zero while(n): inv = inv ^ n; n = n >> 1; return inv; # Driver Coden = 15;print(inversegrayCode(n)); # This code is contributed# by mits // C# Program to convert given// decimal number of gray code// into its inverse in decimal formusing System; class GFG { // Function to convert given // decimal number of gray code // into its inverse in decimal form static int inversegrayCode(int n) { int inv = 0; // Taking xor until n becomes zero for ( ; n != 0 ; n = n >> 1) inv ^= n; return inv; } // Driver code public static void Main () { int n = 15; Console.Write(inversegrayCode(n)); }} // This code is contributed by nitin mittal. <?php// PHP Program to convert given// decimal number of gray code// into its inverse in decimal form function inversegrayCode( $n){ $inv = 0; // Taking xor until // n becomes zero for (; $n; $n = $n >> 1) $inv ^= $n; return $inv;} // Driver Code $n = 15; echo inversegrayCode($n); // This code is contributed by anuj_67.?> <script> // JavaScript Program to convert given// decimal number of gray code// into its inverse in decimal form function inversegrayCode(n){ let inv = 0; // Taking xor until n becomes zero for (; n; n = n >> 1) inv ^= n; return inv;} // Driver Code let n = 15; document.write(inversegrayCode(n)); </script> 10 Smitha Dinesh Semwal jit_t nitin mittal vt_m Mithun Kumar javademon rutvik_56 rishavmahato348 nityavedanta3 base-conversion binary-representation gray-code Bit Magic Mathematical Technical Scripter Mathematical Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Set, Clear and Toggle a given bit of a number in C Write an Efficient Method to Check if a Number is Multiple of 3 Highest power of 2 less than or equal to given number Swap bits in a given number Check for Integer Overflow Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26277, "s": 26249, "text": "\n08 Jul, 2021" }, { "code": null, "e": 26354, "s": 26277, "text": "Given a decimal number n. Find the gray code of this number in decimal form." }, { "code": null, "e": 26365, "s": 26354, "text": "Examples: " }, { "code": null, "e": 26525, "s": 26365, "text": "Input : 7 Output : 4 Explanation: 7 is represented as 111 in binary form. The equivalent gray code of 111 is 100 in binary form, whose decimal equivalent is 4." }, { "code": null, "e": 26693, "s": 26525, "text": "Input : 10 Output : 15 Explanation: 10 is represented as 1010 in binary form. The equivalent gray code of 1010 is 1111 in binary form, whose decimal equivalent is 15. " }, { "code": null, "e": 26778, "s": 26693, "text": "The following table shows the conversion of binary code values to gray code values: " }, { "code": null, "e": 27298, "s": 26778, "text": "Below is the approach for the conversion of decimal code values to gray code values. Let G(n) be the Gray code equivalent of binary representation n. Consider bits of a number n and a number bit G(n). Note that the leftmost set bits of both n and G(n) are in the same position. Let this position be i and positions on the right of it be (i+1), (i+2), etc. The (i + 1)th bit in G(n) is 0 if (i+1)th bit in n is 1 and vice versa is also true. The same is true for (i+2)-th bits, etc. Thus we have G (n) = n xor (n >> 1): " }, { "code": null, "e": 27302, "s": 27298, "text": "C++" }, { "code": null, "e": 27307, "s": 27302, "text": "Java" }, { "code": null, "e": 27315, "s": 27307, "text": "Python3" }, { "code": null, "e": 27318, "s": 27315, "text": "C#" }, { "code": null, "e": 27322, "s": 27318, "text": "PHP" }, { "code": null, "e": 27333, "s": 27322, "text": "Javascript" }, { "code": "// CPP Program to convert given// decimal number into decimal// equivalent of its gray code form#include <bits/stdc++.h>using namespace std; int grayCode(int n){ /* Right Shift the number by 1 taking xor with original number */ return n ^ (n >> 1);} // Driver Codeint main(){ int n = 10; cout << grayCode(n) << endl; return 0;}", "e": 27682, "s": 27333, "text": null }, { "code": "// Java Program to convert given// decimal number into decimal// equivalent of its gray code formclass GFG { static int grayCode(int n) { // Right Shift the number // by 1 taking xor with // original number return n ^ (n >> 1); } // Driver Code public static void main(String[] args) { int n = 10; System.out.println(grayCode(n)); }} // This code is contributed by// Smitha Dinesh Semwal", "e": 28166, "s": 27682, "text": null }, { "code": "# Python 3 Program to convert# given decimal number into# decimal equivalent of its# gray code form def grayCode(n): # Right Shift the number # by 1 taking xor with # original number return n ^ (n >> 1) # Driver Coden = 10print(grayCode(n)) # This code is contributed# by Smitha Dinesh Semwal", "e": 28473, "s": 28166, "text": null }, { "code": "// C# Program to convert given// decimal number into decimal// equivalent of its gray code formusing System; public class GFG { // Function for conversion public static int grayCode(int n) { // Right Shift the number // by 1 taking xor with // original number return n ^ (n >> 1); } // Driver Code static public void Main () { int n = 10; Console.WriteLine(grayCode(n)); }} // This code is contributed by Ajit.", "e": 28978, "s": 28473, "text": null }, { "code": "<?php// PHP Program to convert given// decimal number into decimal// equivalent of its gray code form function grayCode($n){ /* Right Shift the number by 1 taking xor with original number */ return $n ^ ($n >> 1);} // Driver Code $n = 10; echo grayCode($n) ; // This code is contributed by nitin mittal.?>", "e": 29312, "s": 28978, "text": null }, { "code": "<script> // Javascript Program to convert given// decimal number into decimal// equivalent of its gray code form function grayCode(n){ /* Right Shift the number by 1 taking xor with original number */ return n ^ (n >> 1);} // Driver Codevar n = 10;document.write( grayCode(n) ); </script>", "e": 29615, "s": 29312, "text": null }, { "code": null, "e": 29618, "s": 29615, "text": "15" }, { "code": null, "e": 29744, "s": 29620, "text": "Finding the Inverse Gray Code Given a decimal equivalent number n of a gray code. Find its original number in decimal form." }, { "code": null, "e": 29755, "s": 29744, "text": "Examples: " }, { "code": null, "e": 29776, "s": 29755, "text": "Input : 4 Output : 7" }, { "code": null, "e": 29799, "s": 29776, "text": "Input : 15 Output : 10" }, { "code": null, "e": 30103, "s": 29799, "text": "Below is the approach for the conversion of gray code values to decimal code values. We will go from the older bits to the younger ones (even the smallest bit has number 1, and the oldest bit is numbered k). We obtain such relations between the bits of the ni number n and the bits of the gi number g: " }, { "code": null, "e": 30254, "s": 30103, "text": " nk = gk, \n nk-1 = gk-1 xor nk = gk xor gk-1\n nk-2 = gk-2 xor nk-1 = gk xor gk-1 xor gk-2 \n nk-3 = gk-3 xor nk-2 = gk xor gk-1 xor gk-2 xor gk-3\n ... " }, { "code": null, "e": 30258, "s": 30254, "text": "C++" }, { "code": null, "e": 30263, "s": 30258, "text": "Java" }, { "code": null, "e": 30271, "s": 30263, "text": "Python3" }, { "code": null, "e": 30274, "s": 30271, "text": "C#" }, { "code": null, "e": 30278, "s": 30274, "text": "PHP" }, { "code": null, "e": 30289, "s": 30278, "text": "Javascript" }, { "code": "// CPP Program to convert given// decimal number of gray code// into its inverse in decimal form#include <bits/stdc++.h>using namespace std; int inversegrayCode(int n){ int inv = 0; // Taking xor until n becomes zero for (; n; n = n >> 1) inv ^= n; return inv;} // Driver Codeint main(){ int n = 15; cout << inversegrayCode(n) << endl; return 0;}", "e": 30666, "s": 30289, "text": null }, { "code": "// Java Program to convert given// decimal number of gray code// into its inverse in decimal formimport java.io.*; class GFG { // Function to convert given // decimal number of gray code // into its inverse in decimal form static int inversegrayCode(int n) { int inv = 0; // Taking xor until n becomes zero for ( ; n != 0 ; n = n >> 1) inv ^= n; return inv; } // Driver code public static void main (String[] args) { int n = 15; System.out.println(inversegrayCode(n)); }} // This code is contributed by Ajit.", "e": 31278, "s": 30666, "text": null }, { "code": "# Python3 Program to convert# given decimal number of# gray code into its inverse# in decimal form def inversegrayCode(n): inv = 0; # Taking xor until # n becomes zero while(n): inv = inv ^ n; n = n >> 1; return inv; # Driver Coden = 15;print(inversegrayCode(n)); # This code is contributed# by mits", "e": 31612, "s": 31278, "text": null }, { "code": "// C# Program to convert given// decimal number of gray code// into its inverse in decimal formusing System; class GFG { // Function to convert given // decimal number of gray code // into its inverse in decimal form static int inversegrayCode(int n) { int inv = 0; // Taking xor until n becomes zero for ( ; n != 0 ; n = n >> 1) inv ^= n; return inv; } // Driver code public static void Main () { int n = 15; Console.Write(inversegrayCode(n)); }} // This code is contributed by nitin mittal.", "e": 32208, "s": 31612, "text": null }, { "code": "<?php// PHP Program to convert given// decimal number of gray code// into its inverse in decimal form function inversegrayCode( $n){ $inv = 0; // Taking xor until // n becomes zero for (; $n; $n = $n >> 1) $inv ^= $n; return $inv;} // Driver Code $n = 15; echo inversegrayCode($n); // This code is contributed by anuj_67.?>", "e": 32566, "s": 32208, "text": null }, { "code": "<script> // JavaScript Program to convert given// decimal number of gray code// into its inverse in decimal form function inversegrayCode(n){ let inv = 0; // Taking xor until n becomes zero for (; n; n = n >> 1) inv ^= n; return inv;} // Driver Code let n = 15; document.write(inversegrayCode(n)); </script>", "e": 32905, "s": 32566, "text": null }, { "code": null, "e": 32908, "s": 32905, "text": "10" }, { "code": null, "e": 32931, "s": 32910, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 32937, "s": 32931, "text": "jit_t" }, { "code": null, "e": 32950, "s": 32937, "text": "nitin mittal" }, { "code": null, "e": 32955, "s": 32950, "text": "vt_m" }, { "code": null, "e": 32968, "s": 32955, "text": "Mithun Kumar" }, { "code": null, "e": 32978, "s": 32968, "text": "javademon" }, { "code": null, "e": 32988, "s": 32978, "text": "rutvik_56" }, { "code": null, "e": 33004, "s": 32988, "text": "rishavmahato348" }, { "code": null, "e": 33018, "s": 33004, "text": "nityavedanta3" }, { "code": null, "e": 33034, "s": 33018, "text": "base-conversion" }, { "code": null, "e": 33056, "s": 33034, "text": "binary-representation" }, { "code": null, "e": 33066, "s": 33056, "text": "gray-code" }, { "code": null, "e": 33076, "s": 33066, "text": "Bit Magic" }, { "code": null, "e": 33089, "s": 33076, "text": "Mathematical" }, { "code": null, "e": 33108, "s": 33089, "text": "Technical Scripter" }, { "code": null, "e": 33121, "s": 33108, "text": "Mathematical" }, { "code": null, "e": 33131, "s": 33121, "text": "Bit Magic" }, { "code": null, "e": 33229, "s": 33131, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33280, "s": 33229, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 33344, "s": 33280, "text": "Write an Efficient Method to Check if a Number is Multiple of 3" }, { "code": null, "e": 33398, "s": 33344, "text": "Highest power of 2 less than or equal to given number" }, { "code": null, "e": 33426, "s": 33398, "text": "Swap bits in a given number" }, { "code": null, "e": 33453, "s": 33426, "text": "Check for Integer Overflow" }, { "code": null, "e": 33483, "s": 33453, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 33543, "s": 33483, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 33558, "s": 33543, "text": "C++ Data Types" }, { "code": null, "e": 33601, "s": 33558, "text": "Set in C++ Standard Template Library (STL)" } ]
Data Structures and Algorithms | Set 21 - GeeksforGeeks
27 Mar, 2017 Following questions have been asked in GATE CS 2008 exam. 1. The subset-sum problem is defined as follows. Given a set of n positive integers, S = {a1 ,a2 ,a3 ,...,an} and positive integer W, is there a subset of S whose elements sum to W? A dynamic program for solving this problem uses a 2-dimensional Boolean array X, with n rows and W+1 columns. X[i, j],1 <= i <= n, 0 <= j <= W, is TRUE if and only if there is a subset of {a1 ,a2 ,...,ai} whose elements sum to j. Which of the following is valid for 2 <= i <= n and ai <= j <= W?(A) X[i, j] = X[i – 1, j] V X[i, j -ai](B) X[i, j] = X[i – 1, j] V X[i – 1, j – ai](C) X[i, j] = X[i – 1, j] V X[i, j – ai](D) X[i, j] = X[i – 1, j] V X[i -1, j – ai] Answer (B) X[I, j] (2 <= i <= n and ai <= j <= W), is true if any of the following is true 1) Sum of weights excluding ai is equal to j, i.e., if X[i-1, j] is true. 2) Sum of weights including ai is equal to j, i.e., if X[i-1, j-ai] is true so that we get (j – ai) + ai as j. 2. In question 1, which entry of the array X, if TRUE, implies that there is a subset whose elements sum to W?(A) X[1, W](B) X[n ,0](C) X[n, W](D) X[n -1, n] Answer (C)If we get the entry X[n, W] as true then there is a subset of {a1, a2, .. an} that has sum as W. Reference: http://en.wikipedia.org/wiki/Subset_sum_problem 3. Consider the following C program that attempts to locate an element x in an array Y[] using binary search. The program is erroneous. 1. f(int Y[10], int x) {2. int i, j, k;3. i = 0; j = 9;4. do {5. k = (i + j) /2;6. if( Y[k] < x) i = k; else j = k;7. } while(Y[k] != x && i < j);8. if(Y[k] == x) printf ("x is in the array ") ;9. else printf (" x is not in the array ") ;10. } On which of the following contents of Y and x does the program fail?(A) Y is [1 2 3 4 5 6 7 8 9 10] and x < 10 (B) Y is [1 3 5 7 9 11 13 15 17 19] and x < 1 (C) Y is [2 2 2 2 2 2 2 2 2 2] and x > 2(D) Y is [2 4 6 8 10 12 14 16 18 20] and 2 < x < 20 and x is even Answer (C) The above program doesn’t work for the cases where element to be searched is the last element of Y[] or greater than the last element (or maximum element) in Y[]. For such cases, program goes in an infinite loop because i is assigned value as k in all iterations, and i never becomes equal to or greater than j. So while condition never becomes false. 4. In question 3, the correction needed in the program to make it work properly is(A) Change line 6 to: if (Y[k] < x) i = k + 1; else j = k-1; (B) Change line 6 to: if (Y[k] < x) i = k - 1; else j = k+1; (C) Change line 6 to: if (Y[k] <= x) i = k; else j = k; (D) Change line 7 to: } while ((Y[k] == x) && (i < j)); Answer (A) Below is the corrected function f(int Y[10], int x) { int i, j, k; i = 0; j = 9; do { k = (i + j) /2; if( Y[k] < x) i = k + 1; else j = k - 1; } while(Y[k] != x && i < j); if(Y[k] == x) printf ("x is in the array ") ; else printf (" x is not in the array ") ;} Reference: http://en.wikipedia.org/wiki/Binary_search_algorithm#Implementations Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc. Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above. GATE-CS-2008 GATE-CS-DS-&-Algo GATE CS MCQ Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Page Replacement Algorithms in Operating Systems Differences between TCP and UDP Cache Memory in Computer Organization Introduction of Operating System - Set 1 Semaphores in Process Synchronization Data Structures and Algorithms | Set 25 Operating Systems | Set 1 Practice questions on Height balanced/AVL Tree Computer Networks | Set 2 Computer Networks | Set 1
[ { "code": null, "e": 25573, "s": 25545, "text": "\n27 Mar, 2017" }, { "code": null, "e": 25631, "s": 25573, "text": "Following questions have been asked in GATE CS 2008 exam." }, { "code": null, "e": 26275, "s": 25631, "text": "1. The subset-sum problem is defined as follows. Given a set of n positive integers, S = {a1 ,a2 ,a3 ,...,an} and positive integer W, is there a subset of S whose elements sum to W? A dynamic program for solving this problem uses a 2-dimensional Boolean array X, with n rows and W+1 columns. X[i, j],1 <= i <= n, 0 <= j <= W, is TRUE if and only if there is a subset of {a1 ,a2 ,...,ai} whose elements sum to j. Which of the following is valid for 2 <= i <= n and ai <= j <= W?(A) X[i, j] = X[i – 1, j] V X[i, j -ai](B) X[i, j] = X[i – 1, j] V X[i – 1, j – ai](C) X[i, j] = X[i – 1, j] V X[i, j – ai](D) X[i, j] = X[i – 1, j] V X[i -1, j – ai]" }, { "code": null, "e": 26286, "s": 26275, "text": "Answer (B)" }, { "code": null, "e": 26709, "s": 26286, "text": "X[I, j] (2 <= i <= n and ai <= j <= W), is true if any of the following is true\n1) Sum of weights excluding ai is equal to j, i.e., if X[i-1, j] is true.\n2) Sum of weights including ai is equal to j, i.e., if X[i-1, j-ai] is true so that we get (j – ai) + ai as j.\n2. In question 1, which entry of the array X, if TRUE, implies that there is a subset whose elements sum to W?(A) X[1, W](B) X[n ,0](C) X[n, W](D) X[n -1, n]" }, { "code": null, "e": 26816, "s": 26709, "text": "Answer (C)If we get the entry X[n, W] as true then there is a subset of {a1, a2, .. an} that has sum as W." }, { "code": null, "e": 26875, "s": 26816, "text": "Reference: http://en.wikipedia.org/wiki/Subset_sum_problem" }, { "code": null, "e": 27011, "s": 26875, "text": "3. Consider the following C program that attempts to locate an element x in an array Y[] using binary search. The program is erroneous." }, { "code": "1. f(int Y[10], int x) {2. int i, j, k;3. i = 0; j = 9;4. do {5. k = (i + j) /2;6. if( Y[k] < x) i = k; else j = k;7. } while(Y[k] != x && i < j);8. if(Y[k] == x) printf (\"x is in the array \") ;9. else printf (\" x is not in the array \") ;10. }", "e": 27311, "s": 27011, "text": null }, { "code": null, "e": 28296, "s": 27311, "text": "On which of the following contents of Y and x does the program fail?(A) Y is [1 2 3 4 5 6 7 8 9 10] and x < 10\n(B) Y is [1 3 5 7 9 11 13 15 17 19] and x < 1\n(C) Y is [2 2 2 2 2 2 2 2 2 2] and x > 2(D) Y is [2 4 6 8 10 12 14 16 18 20] and 2 < x < 20 and x is even\nAnswer (C)\nThe above program doesn’t work for the cases where element to be searched is the last element of Y[] or greater than the last element (or maximum element) in Y[]. For such cases, program goes in an infinite loop because i is assigned value as k in all iterations, and i never becomes equal to or greater than j. So while condition never becomes false.\n4. In question 3, the correction needed in the program to make it work properly is(A) Change line 6 to: if (Y[k] < x) i = k + 1; else j = k-1;\n(B) Change line 6 to: if (Y[k] < x) i = k - 1; else j = k+1;\n(C) Change line 6 to: if (Y[k] <= x) i = k; else j = k;\n(D) Change line 7 to: } while ((Y[k] == x) && (i < j));\nAnswer (A)\nBelow is the corrected function" }, { "code": "f(int Y[10], int x) { int i, j, k; i = 0; j = 9; do { k = (i + j) /2; if( Y[k] < x) i = k + 1; else j = k - 1; } while(Y[k] != x && i < j); if(Y[k] == x) printf (\"x is in the array \") ; else printf (\" x is not in the array \") ;}", "e": 28563, "s": 28296, "text": null }, { "code": null, "e": 28643, "s": 28563, "text": "Reference: http://en.wikipedia.org/wiki/Binary_search_algorithm#Implementations" }, { "code": null, "e": 28757, "s": 28643, "text": "Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc." }, { "code": null, "e": 28906, "s": 28757, "text": "Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above." }, { "code": null, "e": 28919, "s": 28906, "text": "GATE-CS-2008" }, { "code": null, "e": 28937, "s": 28919, "text": "GATE-CS-DS-&-Algo" }, { "code": null, "e": 28945, "s": 28937, "text": "GATE CS" }, { "code": null, "e": 28949, "s": 28945, "text": "MCQ" }, { "code": null, "e": 29047, "s": 28949, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29096, "s": 29047, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 29128, "s": 29096, "text": "Differences between TCP and UDP" }, { "code": null, "e": 29166, "s": 29128, "text": "Cache Memory in Computer Organization" }, { "code": null, "e": 29207, "s": 29166, "text": "Introduction of Operating System - Set 1" }, { "code": null, "e": 29245, "s": 29207, "text": "Semaphores in Process Synchronization" }, { "code": null, "e": 29285, "s": 29245, "text": "Data Structures and Algorithms | Set 25" }, { "code": null, "e": 29311, "s": 29285, "text": "Operating Systems | Set 1" }, { "code": null, "e": 29358, "s": 29311, "text": "Practice questions on Height balanced/AVL Tree" }, { "code": null, "e": 29384, "s": 29358, "text": "Computer Networks | Set 2" } ]
Compress the array into Ranges - GeeksforGeeks
18 Nov, 2021 Given an array of integers of size N, The task is to print the consecutive integers as a range.Examples: Input : N = 7, arr=[7, 8, 9, 15, 16, 20, 25] Output : 7-9 15-16 20 25 Consecutive elements present are[ {7, 8, 9}, {15, 16}, {20}, {25} ] Hence output the result as 7-9 15-16 20 25Input : N = 6, arr=[1, 2, 3, 4, 5, 6] Output : 1-6 Approach: The problem can be easily visualised as a variation of run length encoding problem. First sort the array. Then, start a while loop for traversing the array to check the consecutive elements. The ending of the consecutive numbers will be denoted by j-1 and start by i at any particular instance. Increment i by 1 if it do not falls in while loop otherwise increment it by j+1 so that it jumps to the next ith element which is out of current range. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to compress the array ranges#include <bits/stdc++.h>using namespace std; // Function to compress the array rangesvoid compressArr(int arr[], int n){ int i = 0, j = 0; sort(arr, arr + n); while (i < n) { // start iteration from the // ith array element j = i; // loop until arr[i+1] == arr[i] // and increment j while ((j + 1 < n) && (arr[j + 1] == arr[j] + 1)) { j++; } // if the program do not enter into // the above while loop this means that // (i+1)th element is not consecutive // to i th element if (i == j) { cout << arr[i] << " "; // increment i for next iteration i++; } else { // print the consecutive range found cout << arr[i] << "-" << arr[j] << " "; // move i jump directly to j+1 i = j + 1; } }} // Driver codeint main(){ int n = 7; int arr[n] = { 1, 3, 4, 5, 6, 9, 10 }; compressArr(arr, n);} // Java program to compress the array rangesimport java.util.Arrays; class GFG{ // Function to compress the array rangesstatic void compressArr(int arr[], int n){ int i = 0, j = 0; Arrays.sort(arr); while (i < n) { // start iteration from the // ith array element j = i; // loop until arr[i+1] == arr[i] // and increment j while ((j + 1 < n) && (arr[j + 1] == arr[j] + 1)) { j++; } // if the program do not enter into // the above while loop this means that // (i+1)th element is not consecutive // to i th element if (i == j) { System.out.print( arr[i] + " "); // increment i for next iteration i++; } else { // print the consecutive range found System.out.print( arr[i] + "-" + arr[j] + " "); // move i jump directly to j+1 i = j + 1; } }} // Driver code public static void main (String[] args) { int n = 7; int arr[] = { 1, 3, 4, 5, 6, 9, 10 }; compressArr(arr, n); }} // This code is contributed by anuj_67.. # Python program to compress the array ranges # Function to compress the array rangesdef compressArr(arr, n): i = 0; j = 0; arr.sort(); while (i < n): # start iteration from the # ith array element j = i; # loop until arr[i+1] == arr[i] # and increment j while ((j + 1 < n) and (arr[j + 1] == arr[j] + 1)): j += 1; # if the program do not enter into # the above while loop this means that # (i+1)th element is not consecutive # to i th element if (i == j): print(arr[i], end=" "); # increment i for next iteration i+=1; else: # print the consecutive range found print(arr[i], "-", arr[j], end=" "); # move i jump directly to j+1 i = j + 1; # Driver coden = 7;arr = [ 1, 3, 4, 5, 6, 9, 10 ];compressArr(arr, n); # This code is contributed by PrinciRaj1992 // C# program to compress the array rangesusing System; class GFG{ // Function to compress the array rangesstatic void compressArr(int []arr, int n){ int i = 0, j = 0; Array.Sort(arr); while (i < n) { // start iteration from the // ith array element j = i; // loop until arr[i+1] == arr[i] // and increment j while ((j + 1 < n) && (arr[j + 1] == arr[j] + 1)) { j++; } // if the program do not enter into // the above while loop this means that // (i+1)th element is not consecutive // to i th element if (i == j) { Console.Write( arr[i] + " "); // increment i for next iteration i++; } else { // print the consecutive range found Console.Write( arr[i] + "-" + arr[j] + " "); // move i jump directly to j+1 i = j + 1; } }} // Driver codepublic static void Main (){ int n = 7; int []arr = { 1, 3, 4, 5, 6, 9, 10 }; compressArr(arr, n);}} // This code is contributed by anuj_67.. <script> // Javascript program to compress the array ranges // Function to compress the array ranges function compressArr(arr, n) { let i = 0, j = 0; arr.sort(function(a, b){return a - b}); while (i < n) { // start iteration from the // ith array element j = i; // loop until arr[i+1] == arr[i] // and increment j while ((j + 1 < n) && (arr[j + 1] == arr[j] + 1)) { j++; } // if the program do not enter into // the above while loop this means that // (i+1)th element is not consecutive // to i th element if (i == j) { document.write( arr[i] + " "); // increment i for next iteration i++; } else { // print the consecutive range found document.write( arr[i] + "-" + arr[j] + " "); // move i jump directly to j+1 i = j + 1; } } } let n = 7; let arr = [ 1, 3, 4, 5, 6, 9, 10 ]; compressArr(arr, n); </script> 1 3-6 9-10 Time complexity: O(nlogn) vt_m princiraj1992 nidhi_biet divyesh072019 sagar0719kumar yash_zz String-Run Length Encoding Arrays Sorting Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element
[ { "code": null, "e": 26067, "s": 26039, "text": "\n18 Nov, 2021" }, { "code": null, "e": 26173, "s": 26067, "text": "Given an array of integers of size N, The task is to print the consecutive integers as a range.Examples: " }, { "code": null, "e": 26406, "s": 26173, "text": "Input : N = 7, arr=[7, 8, 9, 15, 16, 20, 25] Output : 7-9 15-16 20 25 Consecutive elements present are[ {7, 8, 9}, {15, 16}, {20}, {25} ] Hence output the result as 7-9 15-16 20 25Input : N = 6, arr=[1, 2, 3, 4, 5, 6] Output : 1-6 " }, { "code": null, "e": 26504, "s": 26408, "text": "Approach: The problem can be easily visualised as a variation of run length encoding problem. " }, { "code": null, "e": 26526, "s": 26504, "text": "First sort the array." }, { "code": null, "e": 26715, "s": 26526, "text": "Then, start a while loop for traversing the array to check the consecutive elements. The ending of the consecutive numbers will be denoted by j-1 and start by i at any particular instance." }, { "code": null, "e": 26867, "s": 26715, "text": "Increment i by 1 if it do not falls in while loop otherwise increment it by j+1 so that it jumps to the next ith element which is out of current range." }, { "code": null, "e": 26920, "s": 26867, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26924, "s": 26920, "text": "C++" }, { "code": null, "e": 26929, "s": 26924, "text": "Java" }, { "code": null, "e": 26937, "s": 26929, "text": "Python3" }, { "code": null, "e": 26940, "s": 26937, "text": "C#" }, { "code": null, "e": 26951, "s": 26940, "text": "Javascript" }, { "code": "// C++ program to compress the array ranges#include <bits/stdc++.h>using namespace std; // Function to compress the array rangesvoid compressArr(int arr[], int n){ int i = 0, j = 0; sort(arr, arr + n); while (i < n) { // start iteration from the // ith array element j = i; // loop until arr[i+1] == arr[i] // and increment j while ((j + 1 < n) && (arr[j + 1] == arr[j] + 1)) { j++; } // if the program do not enter into // the above while loop this means that // (i+1)th element is not consecutive // to i th element if (i == j) { cout << arr[i] << \" \"; // increment i for next iteration i++; } else { // print the consecutive range found cout << arr[i] << \"-\" << arr[j] << \" \"; // move i jump directly to j+1 i = j + 1; } }} // Driver codeint main(){ int n = 7; int arr[n] = { 1, 3, 4, 5, 6, 9, 10 }; compressArr(arr, n);}", "e": 28013, "s": 26951, "text": null }, { "code": "// Java program to compress the array rangesimport java.util.Arrays; class GFG{ // Function to compress the array rangesstatic void compressArr(int arr[], int n){ int i = 0, j = 0; Arrays.sort(arr); while (i < n) { // start iteration from the // ith array element j = i; // loop until arr[i+1] == arr[i] // and increment j while ((j + 1 < n) && (arr[j + 1] == arr[j] + 1)) { j++; } // if the program do not enter into // the above while loop this means that // (i+1)th element is not consecutive // to i th element if (i == j) { System.out.print( arr[i] + \" \"); // increment i for next iteration i++; } else { // print the consecutive range found System.out.print( arr[i] + \"-\" + arr[j] + \" \"); // move i jump directly to j+1 i = j + 1; } }} // Driver code public static void main (String[] args) { int n = 7; int arr[] = { 1, 3, 4, 5, 6, 9, 10 }; compressArr(arr, n); }} // This code is contributed by anuj_67..", "e": 29210, "s": 28013, "text": null }, { "code": "# Python program to compress the array ranges # Function to compress the array rangesdef compressArr(arr, n): i = 0; j = 0; arr.sort(); while (i < n): # start iteration from the # ith array element j = i; # loop until arr[i+1] == arr[i] # and increment j while ((j + 1 < n) and (arr[j + 1] == arr[j] + 1)): j += 1; # if the program do not enter into # the above while loop this means that # (i+1)th element is not consecutive # to i th element if (i == j): print(arr[i], end=\" \"); # increment i for next iteration i+=1; else: # print the consecutive range found print(arr[i], \"-\", arr[j], end=\" \"); # move i jump directly to j+1 i = j + 1; # Driver coden = 7;arr = [ 1, 3, 4, 5, 6, 9, 10 ];compressArr(arr, n); # This code is contributed by PrinciRaj1992", "e": 30169, "s": 29210, "text": null }, { "code": "// C# program to compress the array rangesusing System; class GFG{ // Function to compress the array rangesstatic void compressArr(int []arr, int n){ int i = 0, j = 0; Array.Sort(arr); while (i < n) { // start iteration from the // ith array element j = i; // loop until arr[i+1] == arr[i] // and increment j while ((j + 1 < n) && (arr[j + 1] == arr[j] + 1)) { j++; } // if the program do not enter into // the above while loop this means that // (i+1)th element is not consecutive // to i th element if (i == j) { Console.Write( arr[i] + \" \"); // increment i for next iteration i++; } else { // print the consecutive range found Console.Write( arr[i] + \"-\" + arr[j] + \" \"); // move i jump directly to j+1 i = j + 1; } }} // Driver codepublic static void Main (){ int n = 7; int []arr = { 1, 3, 4, 5, 6, 9, 10 }; compressArr(arr, n);}} // This code is contributed by anuj_67..", "e": 31305, "s": 30169, "text": null }, { "code": "<script> // Javascript program to compress the array ranges // Function to compress the array ranges function compressArr(arr, n) { let i = 0, j = 0; arr.sort(function(a, b){return a - b}); while (i < n) { // start iteration from the // ith array element j = i; // loop until arr[i+1] == arr[i] // and increment j while ((j + 1 < n) && (arr[j + 1] == arr[j] + 1)) { j++; } // if the program do not enter into // the above while loop this means that // (i+1)th element is not consecutive // to i th element if (i == j) { document.write( arr[i] + \" \"); // increment i for next iteration i++; } else { // print the consecutive range found document.write( arr[i] + \"-\" + arr[j] + \" \"); // move i jump directly to j+1 i = j + 1; } } } let n = 7; let arr = [ 1, 3, 4, 5, 6, 9, 10 ]; compressArr(arr, n); </script>", "e": 32508, "s": 31305, "text": null }, { "code": null, "e": 32519, "s": 32508, "text": "1 3-6 9-10" }, { "code": null, "e": 32548, "s": 32521, "text": "Time complexity: O(nlogn) " }, { "code": null, "e": 32553, "s": 32548, "text": "vt_m" }, { "code": null, "e": 32567, "s": 32553, "text": "princiraj1992" }, { "code": null, "e": 32578, "s": 32567, "text": "nidhi_biet" }, { "code": null, "e": 32592, "s": 32578, "text": "divyesh072019" }, { "code": null, "e": 32607, "s": 32592, "text": "sagar0719kumar" }, { "code": null, "e": 32615, "s": 32607, "text": "yash_zz" }, { "code": null, "e": 32642, "s": 32615, "text": "String-Run Length Encoding" }, { "code": null, "e": 32649, "s": 32642, "text": "Arrays" }, { "code": null, "e": 32657, "s": 32649, "text": "Sorting" }, { "code": null, "e": 32664, "s": 32657, "text": "Arrays" }, { "code": null, "e": 32672, "s": 32664, "text": "Sorting" }, { "code": null, "e": 32770, "s": 32672, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32797, "s": 32770, "text": "Count pairs with given sum" }, { "code": null, "e": 32828, "s": 32797, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 32853, "s": 32828, "text": "Window Sliding Technique" }, { "code": null, "e": 32891, "s": 32853, "text": "Reversal algorithm for array rotation" } ]
HTML - <table> Tag
The HTML <table> tag is used for defining a table. The table tag contains other tags that define the structure of the table. <!DOCTYPE html> <html> <head> <title>HTML table Tag</title> </head> <body> <table border = "1"> <tr> <th>Team</th> <th>Ranking</th> </tr> <tr> <td>India</td> <td>1</td> </tr> <tr> <td>South Africa</td> <td>2</td> </tr> <tr> <td>Australia</td> <td>3</td> </tr> </table> </body> </html> This will produce the following result − This tag supports all the global attributes described in − HTML Attribute Reference The HTML <table> tag also supports the following additional attributes − This tag supports all the event attributes described in − HTML Events Reference 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2499, "s": 2374, "text": "The HTML <table> tag is used for defining a table. The table tag contains other tags that define the structure of the table." }, { "code": null, "e": 3015, "s": 2499, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML table Tag</title>\n </head>\n\n <body>\n <table border = \"1\">\n <tr>\n <th>Team</th>\n <th>Ranking</th>\n </tr>\n \n <tr>\n <td>India</td>\n <td>1</td>\n </tr>\n \n <tr>\n <td>South Africa</td>\n <td>2</td>\n </tr>\n \n <tr>\n <td>Australia</td>\n <td>3</td>\n </tr>\n </table>\n </body>\n\n</html>" }, { "code": null, "e": 3056, "s": 3015, "text": "This will produce the following result −" }, { "code": null, "e": 3140, "s": 3056, "text": "This tag supports all the global attributes described in − HTML Attribute Reference" }, { "code": null, "e": 3213, "s": 3140, "text": "The HTML <table> tag also supports the following additional attributes −" }, { "code": null, "e": 3293, "s": 3213, "text": "This tag supports all the event attributes described in − HTML Events Reference" }, { "code": null, "e": 3326, "s": 3293, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 3340, "s": 3326, "text": " Anadi Sharma" }, { "code": null, "e": 3375, "s": 3340, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3389, "s": 3375, "text": " Anadi Sharma" }, { "code": null, "e": 3424, "s": 3389, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3441, "s": 3424, "text": " Frahaan Hussain" }, { "code": null, "e": 3476, "s": 3441, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3507, "s": 3476, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3540, "s": 3507, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 3571, "s": 3540, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3606, "s": 3571, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3637, "s": 3606, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3644, "s": 3637, "text": " Print" }, { "code": null, "e": 3655, "s": 3644, "text": " Add Notes" } ]
Largest Rectangle in a Matrix. How to combine programming techniques | by Shuo Wang | Towards Data Science
As I accumulate more experience in coding and life in general, one of the things among my observations that stood out to me is that, whenever there is a problem to be solved, there usually exists a very intuitive solution to it. Sometimes this solution happens to be efficient, sometimes grossly suboptimal. This is especially noticeable in algorithms, because an algorithm is often times a conceptualization of a real life problem, and through the algorithm the essential elements of the problem is kept, allowing us to tackle the problem directly. The largest rectangle in a matrix is one such problem, in my opinion. Here is a brief description of the problem. I have a board of red and blue dots, would like to find a biggest rectangle formed by the blue dots: In this example, it’s easy to tell that the largest rectangle formed by the blue dots has a size of 8. But let’s figure out a way to do this algorithmically. How to do this simply The first time I tried out this problem, I thought to myself: Well, it looks like I probably need to iterate through every point in the matrix, and at each point, I need to find the largest rectangle containing that point. I’ll compare that rectangle to the size of the rectangles I have already found. If the new one is bigger, I’ll keep it, otherwise I move on to the next point. This sounds great, but there is a problem with it. How do I find the largest rectangle containing a particular point. Nothing comes to mind that would help me solve this problem. What if I just want to find the largest rectangle that has the current point as its top left corner? I think this is a more manageable problem. In order for me to figure that out, I’ll loop through each point to the right of my current point, at each point I find the maximum height of blue dots, if it’s smaller than the height at the current point, I’ll update the current point height to the new height and find the size of the new rectangle, if it’s a bigger rectangle I’ll update the max size. Let’s apply this procedure to our example. Suppose I have looped to point (1, 0): I find the height of my current point, which is 2, the largest rectangle with (1, 0) as top right corner given this information is also 2. (1, 0): height = 2, max_rectangle = 2. I iterate through every point to the right: Point (2, 0) has a height of 3, but it’s larger than the starting point, so the height is still 2. But now we know that we can have a rectangle of size 2 * 2 = 4: (2, 0): height = 2, max_rectangle = 4 Point (3, 0) has a height of 1, it’s smaller than current height, so we update current height to 1, the rectangle that can be created is: 1 * 3 = 3, but the current max is 4, so we ignore it: (3, 0): height = 1, max_rectangle = 4 Going through the same process for the rest of points: (4, 0): height = 1, max_rectangle = 4 (5, 0): height = 1, max_rectangle = 5 we find the largest rectangle with top right corner of (1, 0) to be of size 5. Let’s put this into code: def find_max001(matrix): width = len(matrix[0]) height = len(matrix) # max width and max height at the a point # uses memorization and dynamic programming max_matrix = [[None for v in row] for row in matrix] def get_max(i, j): if i >= width: return 0, 0 elif j >= height: return 0, 0 elif max_matrix[j][i] is not None: return max_matrix[j][i] elif matrix[j][i] == 0: max_matrix[j][i] = (0, 0) return max_matrix[j][i] max_down = get_max(i, j + 1) max_right = get_max(i + 1, j) max_matrix[j][i] = (max_right[0] + 1, max_down[1] + 1) return max_matrix[j][i] max_rect = 0 for i in range(width): for j in range(height): rect = get_max(i, j) cur_max = rect[1] for k in range(1, rect[0]): cur_max = min(cur_max, get_max(i+k, j)[1]) max_rect = max(max_rect, cur_max * rect[0]) return max_rectdef problem003(solver): m001 = [ [1, 1, 1, 1, 1, 1], [0, 1, 1, 0, 1, 1], [0, 0, 1, 0, 1, 1], [0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0] ] res1 = solver(m001) print(f'res1: {res1}')def test003(): solver = find_max001 problem003(solver)test003()# res1: 8 What is the complexity of the algorithm? Since we are looping through each point, the complexity is at least w * h. Luckily we are able to use memoization and dynamic programming technique to find the height at each point, so they don’t add to the complexity. At each point we are looping through the width of the matrix to find the largest rectangle at that point, this slows the complexity to w*h*w. So the complexity is: O(w2*h) Since we are also using a map to store width and height at each point: memory usage is: O(w*h). How to improve the algorithm? Is there a way to reduce the w2 term in complexity? It turns out, there is. Let’s go back to our example: Suppose now we are looping through the first row. From (0, 0), (1, 0), (2, 0) the height keeps increasing 1, 2, 3. We keep a list: [(0, 0: 1), (1, 0: 2), (2, 0: 3)] At position (3, 0), height drops to 1. What does this new information tell us? Quite a bit, actually. Given this information, we can say for certain that a rectangle with top left corner at position (2, 0) with height 3 can only have a maximum size of 3. We can also say for certain that a rectangle with top left corner at position (1, 0) with height 2 can only have a maximum size of 4. After process the two points, we can remove them permanently, but we need to add a new point, at (1, 0) (note, not at (3, 0)), with height 1: [(0, 0: 1), (1, 0: 1)] Essentially what we are doing is trimming the height of (2, 0) and (1, 0) to equal to the height of (3, 0). Moving on this way till the end of the row, we do not encounter any more drop in height. [(0, 0: 1), (1, 0: 1), (5, 0: 4), (4, 0: 4)] We can then process the rest of the rows: (5, 0) max_rectangle = 4 (4, 0) max_rectangle = 4 * 2 = 8 (1, 0) max_rectangle = 1 * 5= 5 (0, 0) max_rectangle = 1 * 6 = 6 So the max_rectangle after processing the first row is 8, and we have only looped 6 points! This means the complexity of the algorithm is now w*h! Below is the algorithm in code: from collections import dequedef find_max002(matrix): width = len(matrix[0]) height = len(matrix) # max depths max_matrix = [[None for v in row] for row in matrix] def get_max(i, j): if i >= width: return 0, 0 elif j >= height: return 0, 0 elif max_matrix[j][i] is not None: return max_matrix[j][i] elif matrix[j][i] == 0: max_matrix[j][i] = (0, 0) return max_matrix[j][i] max_down = get_max(i, j + 1) max_right = get_max(i + 1, j) max_matrix[j][i] = (max_right[0] + 1, max_down[1] + 1) return max_matrix[j][i] def get_rect(stack, j): cur_idx = stack.pop() cur_max = cur_idx[1] * (j - cur_idx[0]) print(f"cur_max at {cur_idx[0]}: {cur_max}") return cur_max max_rect = 0 for i in range(width): # implement the algorithm with stack stack = deque() stack.append((-1, 0)) for j in range(height): rect = get_max(i, j) cur_width = rect[0] cur_idx = j while stack[-1][1] > cur_width: cur_idx = stack[-1][0] max_rect = max(max_rect, get_rect(stack, j)) stack.append((cur_idx, cur_width)) while len(stack) > 1: max_rect = max(max_rect, get_rect(stack, height)) return max_rectdef test004(): solver = find_max002 problem003(solver)test004()# res1: 8 Notice in order to implement the removal of points (2, 0) and (1, 0) after we reach (3, 0), we use a stack data structure to push and pop points efficiently. As mentioned earlier, we have improved upon solution #1 so that at each point, we don’t have to loop through the rest of the points to its right anymore. The complexity improves to: O(w*h)! The memory usage remains the same: O(w*h). besides the algorithm and coding techniques An algorithm can have many variations, the first one you come up with is usually not the most efficient. An understanding of complexity analysis and programming techniques can make a big difference. The importance of this realization extends not only to programming, but to doing almost everything in life, because everything in life is an algorithm.
[ { "code": null, "e": 722, "s": 172, "text": "As I accumulate more experience in coding and life in general, one of the things among my observations that stood out to me is that, whenever there is a problem to be solved, there usually exists a very intuitive solution to it. Sometimes this solution happens to be efficient, sometimes grossly suboptimal. This is especially noticeable in algorithms, because an algorithm is often times a conceptualization of a real life problem, and through the algorithm the essential elements of the problem is kept, allowing us to tackle the problem directly." }, { "code": null, "e": 836, "s": 722, "text": "The largest rectangle in a matrix is one such problem, in my opinion. Here is a brief description of the problem." }, { "code": null, "e": 937, "s": 836, "text": "I have a board of red and blue dots, would like to find a biggest rectangle formed by the blue dots:" }, { "code": null, "e": 1040, "s": 937, "text": "In this example, it’s easy to tell that the largest rectangle formed by the blue dots has a size of 8." }, { "code": null, "e": 1095, "s": 1040, "text": "But let’s figure out a way to do this algorithmically." }, { "code": null, "e": 1117, "s": 1095, "text": "How to do this simply" }, { "code": null, "e": 1179, "s": 1117, "text": "The first time I tried out this problem, I thought to myself:" }, { "code": null, "e": 1499, "s": 1179, "text": "Well, it looks like I probably need to iterate through every point in the matrix, and at each point, I need to find the largest rectangle containing that point. I’ll compare that rectangle to the size of the rectangles I have already found. If the new one is bigger, I’ll keep it, otherwise I move on to the next point." }, { "code": null, "e": 1678, "s": 1499, "text": "This sounds great, but there is a problem with it. How do I find the largest rectangle containing a particular point. Nothing comes to mind that would help me solve this problem." }, { "code": null, "e": 1822, "s": 1678, "text": "What if I just want to find the largest rectangle that has the current point as its top left corner? I think this is a more manageable problem." }, { "code": null, "e": 2177, "s": 1822, "text": "In order for me to figure that out, I’ll loop through each point to the right of my current point, at each point I find the maximum height of blue dots, if it’s smaller than the height at the current point, I’ll update the current point height to the new height and find the size of the new rectangle, if it’s a bigger rectangle I’ll update the max size." }, { "code": null, "e": 2220, "s": 2177, "text": "Let’s apply this procedure to our example." }, { "code": null, "e": 2259, "s": 2220, "text": "Suppose I have looped to point (1, 0):" }, { "code": null, "e": 2398, "s": 2259, "text": "I find the height of my current point, which is 2, the largest rectangle with (1, 0) as top right corner given this information is also 2." }, { "code": null, "e": 2437, "s": 2398, "text": "(1, 0): height = 2, max_rectangle = 2." }, { "code": null, "e": 2481, "s": 2437, "text": "I iterate through every point to the right:" }, { "code": null, "e": 2644, "s": 2481, "text": "Point (2, 0) has a height of 3, but it’s larger than the starting point, so the height is still 2. But now we know that we can have a rectangle of size 2 * 2 = 4:" }, { "code": null, "e": 2682, "s": 2644, "text": "(2, 0): height = 2, max_rectangle = 4" }, { "code": null, "e": 2874, "s": 2682, "text": "Point (3, 0) has a height of 1, it’s smaller than current height, so we update current height to 1, the rectangle that can be created is: 1 * 3 = 3, but the current max is 4, so we ignore it:" }, { "code": null, "e": 2912, "s": 2874, "text": "(3, 0): height = 1, max_rectangle = 4" }, { "code": null, "e": 2967, "s": 2912, "text": "Going through the same process for the rest of points:" }, { "code": null, "e": 3005, "s": 2967, "text": "(4, 0): height = 1, max_rectangle = 4" }, { "code": null, "e": 3043, "s": 3005, "text": "(5, 0): height = 1, max_rectangle = 5" }, { "code": null, "e": 3122, "s": 3043, "text": "we find the largest rectangle with top right corner of (1, 0) to be of size 5." }, { "code": null, "e": 3148, "s": 3122, "text": "Let’s put this into code:" }, { "code": null, "e": 4465, "s": 3148, "text": "def find_max001(matrix): width = len(matrix[0]) height = len(matrix) # max width and max height at the a point # uses memorization and dynamic programming max_matrix = [[None for v in row] for row in matrix] def get_max(i, j): if i >= width: return 0, 0 elif j >= height: return 0, 0 elif max_matrix[j][i] is not None: return max_matrix[j][i] elif matrix[j][i] == 0: max_matrix[j][i] = (0, 0) return max_matrix[j][i] max_down = get_max(i, j + 1) max_right = get_max(i + 1, j) max_matrix[j][i] = (max_right[0] + 1, max_down[1] + 1) return max_matrix[j][i] max_rect = 0 for i in range(width): for j in range(height): rect = get_max(i, j) cur_max = rect[1] for k in range(1, rect[0]): cur_max = min(cur_max, get_max(i+k, j)[1]) max_rect = max(max_rect, cur_max * rect[0]) return max_rectdef problem003(solver): m001 = [ [1, 1, 1, 1, 1, 1], [0, 1, 1, 0, 1, 1], [0, 0, 1, 0, 1, 1], [0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0] ] res1 = solver(m001) print(f'res1: {res1}')def test003(): solver = find_max001 problem003(solver)test003()# res1: 8" }, { "code": null, "e": 4506, "s": 4465, "text": "What is the complexity of the algorithm?" }, { "code": null, "e": 4725, "s": 4506, "text": "Since we are looping through each point, the complexity is at least w * h. Luckily we are able to use memoization and dynamic programming technique to find the height at each point, so they don’t add to the complexity." }, { "code": null, "e": 4867, "s": 4725, "text": "At each point we are looping through the width of the matrix to find the largest rectangle at that point, this slows the complexity to w*h*w." }, { "code": null, "e": 4897, "s": 4867, "text": "So the complexity is: O(w2*h)" }, { "code": null, "e": 4968, "s": 4897, "text": "Since we are also using a map to store width and height at each point:" }, { "code": null, "e": 4993, "s": 4968, "text": "memory usage is: O(w*h)." }, { "code": null, "e": 5023, "s": 4993, "text": "How to improve the algorithm?" }, { "code": null, "e": 5075, "s": 5023, "text": "Is there a way to reduce the w2 term in complexity?" }, { "code": null, "e": 5099, "s": 5075, "text": "It turns out, there is." }, { "code": null, "e": 5129, "s": 5099, "text": "Let’s go back to our example:" }, { "code": null, "e": 5179, "s": 5129, "text": "Suppose now we are looping through the first row." }, { "code": null, "e": 5260, "s": 5179, "text": "From (0, 0), (1, 0), (2, 0) the height keeps increasing 1, 2, 3. We keep a list:" }, { "code": null, "e": 5294, "s": 5260, "text": "[(0, 0: 1), (1, 0: 2), (2, 0: 3)]" }, { "code": null, "e": 5373, "s": 5294, "text": "At position (3, 0), height drops to 1. What does this new information tell us?" }, { "code": null, "e": 5549, "s": 5373, "text": "Quite a bit, actually. Given this information, we can say for certain that a rectangle with top left corner at position (2, 0) with height 3 can only have a maximum size of 3." }, { "code": null, "e": 5683, "s": 5549, "text": "We can also say for certain that a rectangle with top left corner at position (1, 0) with height 2 can only have a maximum size of 4." }, { "code": null, "e": 5825, "s": 5683, "text": "After process the two points, we can remove them permanently, but we need to add a new point, at (1, 0) (note, not at (3, 0)), with height 1:" }, { "code": null, "e": 5848, "s": 5825, "text": "[(0, 0: 1), (1, 0: 1)]" }, { "code": null, "e": 5956, "s": 5848, "text": "Essentially what we are doing is trimming the height of (2, 0) and (1, 0) to equal to the height of (3, 0)." }, { "code": null, "e": 6045, "s": 5956, "text": "Moving on this way till the end of the row, we do not encounter any more drop in height." }, { "code": null, "e": 6090, "s": 6045, "text": "[(0, 0: 1), (1, 0: 1), (5, 0: 4), (4, 0: 4)]" }, { "code": null, "e": 6132, "s": 6090, "text": "We can then process the rest of the rows:" }, { "code": null, "e": 6157, "s": 6132, "text": "(5, 0) max_rectangle = 4" }, { "code": null, "e": 6190, "s": 6157, "text": "(4, 0) max_rectangle = 4 * 2 = 8" }, { "code": null, "e": 6222, "s": 6190, "text": "(1, 0) max_rectangle = 1 * 5= 5" }, { "code": null, "e": 6255, "s": 6222, "text": "(0, 0) max_rectangle = 1 * 6 = 6" }, { "code": null, "e": 6402, "s": 6255, "text": "So the max_rectangle after processing the first row is 8, and we have only looped 6 points! This means the complexity of the algorithm is now w*h!" }, { "code": null, "e": 6434, "s": 6402, "text": "Below is the algorithm in code:" }, { "code": null, "e": 7907, "s": 6434, "text": "from collections import dequedef find_max002(matrix): width = len(matrix[0]) height = len(matrix) # max depths max_matrix = [[None for v in row] for row in matrix] def get_max(i, j): if i >= width: return 0, 0 elif j >= height: return 0, 0 elif max_matrix[j][i] is not None: return max_matrix[j][i] elif matrix[j][i] == 0: max_matrix[j][i] = (0, 0) return max_matrix[j][i] max_down = get_max(i, j + 1) max_right = get_max(i + 1, j) max_matrix[j][i] = (max_right[0] + 1, max_down[1] + 1) return max_matrix[j][i] def get_rect(stack, j): cur_idx = stack.pop() cur_max = cur_idx[1] * (j - cur_idx[0]) print(f\"cur_max at {cur_idx[0]}: {cur_max}\") return cur_max max_rect = 0 for i in range(width): # implement the algorithm with stack stack = deque() stack.append((-1, 0)) for j in range(height): rect = get_max(i, j) cur_width = rect[0] cur_idx = j while stack[-1][1] > cur_width: cur_idx = stack[-1][0] max_rect = max(max_rect, get_rect(stack, j)) stack.append((cur_idx, cur_width)) while len(stack) > 1: max_rect = max(max_rect, get_rect(stack, height)) return max_rectdef test004(): solver = find_max002 problem003(solver)test004()# res1: 8" }, { "code": null, "e": 8065, "s": 7907, "text": "Notice in order to implement the removal of points (2, 0) and (1, 0) after we reach (3, 0), we use a stack data structure to push and pop points efficiently." }, { "code": null, "e": 8255, "s": 8065, "text": "As mentioned earlier, we have improved upon solution #1 so that at each point, we don’t have to loop through the rest of the points to its right anymore. The complexity improves to: O(w*h)!" }, { "code": null, "e": 8298, "s": 8255, "text": "The memory usage remains the same: O(w*h)." }, { "code": null, "e": 8342, "s": 8298, "text": "besides the algorithm and coding techniques" } ]
Docker - Containers and Shells
By default, when you launch a container, you will also use a shell command while launching the container as shown below. This is what we have seen in the earlier chapters when we were working with containers. In the above screenshot, you can observe that we have issued the following command − sudo docker run –it centos /bin/bash We used this command to create a new container and then used the Ctrl+P+Q command to exit out of the container. It ensures that the container still exists even after we exit from the container. We can verify that the container still exists with the Docker ps command. If we had to exit out of the container directly, then the container itself would be destroyed. Now there is an easier way to attach to containers and exit them cleanly without the need of destroying them. One way of achieving this is by using the nsenter command. Before we run the nsenter command, you need to first install the nsenter image. It can be done by using the following command − docker run --rm -v /usr/local/bin:/target jpetazzo/nsenter Before we use the nsenter command, we need to get the Process ID of the container, because this is required by the nsenter command. We can get the Process ID via the Docker inspect command and filtering it via the Pid. As seen in the above screenshot, we have first used the docker ps command to see the running containers. We can see that there is one running container with the ID of ef42a4c5e663. We then use the Docker inspect command to inspect the configuration of this container and then use the grep command to just filter the Process ID. And from the output, we can see that the Process ID is 2978. Now that we have the process ID, we can proceed forward and use the nsenter command to attach to the Docker container. This method allows one to attach to a container without exiting the container. nsenter –m –u –n –p –i –t containerID command -u is used to mention the Uts namespace -u is used to mention the Uts namespace -m is used to mention the mount namespace -m is used to mention the mount namespace -n is used to mention the network namespace -n is used to mention the network namespace -p is used to mention the process namespace -p is used to mention the process namespace -i s to make the container run in interactive mode. -i s to make the container run in interactive mode. -t is used to connect the I/O streams of the container to the host OS. -t is used to connect the I/O streams of the container to the host OS. containerID − This is the ID of the container. containerID − This is the ID of the container. Command − This is the command to run within the container. Command − This is the command to run within the container. None sudo nsenter –m –u –n –p –i –t 2978 /bin/bash From the output, we can observe the following points − The prompt changes to the bash shell directly when we issue the nsenter command. The prompt changes to the bash shell directly when we issue the nsenter command. We then issue the exit command. Now normally if you did not use the nsenter command, the container would be destroyed. But you would notice that when we run the nsenter command, the container is still up and running. We then issue the exit command. Now normally if you did not use the nsenter command, the container would be destroyed. But you would notice that when we run the nsenter command, the container is still up and running. 70 Lectures 12 hours Anshul Chauhan 41 Lectures 5 hours AR Shankar 31 Lectures 3 hours Abhilash Nelson 15 Lectures 2 hours Harshit Srivastava, Pranjal Srivastava 33 Lectures 4 hours Mumshad Mannambeth 13 Lectures 53 mins Musab Zayadneh Print Add Notes Bookmark this page
[ { "code": null, "e": 2549, "s": 2340, "text": "By default, when you launch a container, you will also use a shell command while launching the container as shown below. This is what we have seen in the earlier chapters when we were working with containers." }, { "code": null, "e": 2634, "s": 2549, "text": "In the above screenshot, you can observe that we have issued the following command −" }, { "code": null, "e": 2673, "s": 2634, "text": "sudo docker run –it centos /bin/bash \n" }, { "code": null, "e": 2867, "s": 2673, "text": "We used this command to create a new container and then used the Ctrl+P+Q command to exit out of the container. It ensures that the container still exists even after we exit from the container." }, { "code": null, "e": 3036, "s": 2867, "text": "We can verify that the container still exists with the Docker ps command. If we had to exit out of the container directly, then the container itself would be destroyed." }, { "code": null, "e": 3205, "s": 3036, "text": "Now there is an easier way to attach to containers and exit them cleanly without the need of destroying them. One way of achieving this is by using the nsenter command." }, { "code": null, "e": 3333, "s": 3205, "text": "Before we run the nsenter command, you need to first install the nsenter image. It can be done by using the following command −" }, { "code": null, "e": 3393, "s": 3333, "text": "docker run --rm -v /usr/local/bin:/target jpetazzo/nsenter\n" }, { "code": null, "e": 3612, "s": 3393, "text": "Before we use the nsenter command, we need to get the Process ID of the container, because this is required by the nsenter command. We can get the Process ID via the Docker inspect command and filtering it via the Pid." }, { "code": null, "e": 3793, "s": 3612, "text": "As seen in the above screenshot, we have first used the docker ps command to see the running containers. We can see that there is one running container with the ID of ef42a4c5e663." }, { "code": null, "e": 4001, "s": 3793, "text": "We then use the Docker inspect command to inspect the configuration of this container and then use the grep command to just filter the Process ID. And from the output, we can see that the Process ID is 2978." }, { "code": null, "e": 4120, "s": 4001, "text": "Now that we have the process ID, we can proceed forward and use the nsenter command to attach to the Docker container." }, { "code": null, "e": 4199, "s": 4120, "text": "This method allows one to attach to a container without exiting the container." }, { "code": null, "e": 4245, "s": 4199, "text": "nsenter –m –u –n –p –i –t containerID command" }, { "code": null, "e": 4285, "s": 4245, "text": "-u is used to mention the Uts namespace" }, { "code": null, "e": 4325, "s": 4285, "text": "-u is used to mention the Uts namespace" }, { "code": null, "e": 4367, "s": 4325, "text": "-m is used to mention the mount namespace" }, { "code": null, "e": 4409, "s": 4367, "text": "-m is used to mention the mount namespace" }, { "code": null, "e": 4454, "s": 4409, "text": "-n is used to mention the network namespace" }, { "code": null, "e": 4499, "s": 4454, "text": "-n is used to mention the network namespace" }, { "code": null, "e": 4543, "s": 4499, "text": "-p is used to mention the process namespace" }, { "code": null, "e": 4587, "s": 4543, "text": "-p is used to mention the process namespace" }, { "code": null, "e": 4639, "s": 4587, "text": "-i s to make the container run in interactive mode." }, { "code": null, "e": 4691, "s": 4639, "text": "-i s to make the container run in interactive mode." }, { "code": null, "e": 4762, "s": 4691, "text": "-t is used to connect the I/O streams of the container to the host OS." }, { "code": null, "e": 4833, "s": 4762, "text": "-t is used to connect the I/O streams of the container to the host OS." }, { "code": null, "e": 4880, "s": 4833, "text": "containerID − This is the ID of the container." }, { "code": null, "e": 4927, "s": 4880, "text": "containerID − This is the ID of the container." }, { "code": null, "e": 4986, "s": 4927, "text": "Command − This is the command to run within the container." }, { "code": null, "e": 5045, "s": 4986, "text": "Command − This is the command to run within the container." }, { "code": null, "e": 5050, "s": 5045, "text": "None" }, { "code": null, "e": 5096, "s": 5050, "text": "sudo nsenter –m –u –n –p –i –t 2978 /bin/bash" }, { "code": null, "e": 5151, "s": 5096, "text": "From the output, we can observe the following points −" }, { "code": null, "e": 5232, "s": 5151, "text": "The prompt changes to the bash shell directly when we issue the nsenter command." }, { "code": null, "e": 5313, "s": 5232, "text": "The prompt changes to the bash shell directly when we issue the nsenter command." }, { "code": null, "e": 5530, "s": 5313, "text": "We then issue the exit command. Now normally if you did not use the nsenter command, the container would be destroyed. But you would notice that when we run the nsenter command, the container is still up and running." }, { "code": null, "e": 5747, "s": 5530, "text": "We then issue the exit command. Now normally if you did not use the nsenter command, the container would be destroyed. But you would notice that when we run the nsenter command, the container is still up and running." }, { "code": null, "e": 5781, "s": 5747, "text": "\n 70 Lectures \n 12 hours \n" }, { "code": null, "e": 5797, "s": 5781, "text": " Anshul Chauhan" }, { "code": null, "e": 5830, "s": 5797, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 5842, "s": 5830, "text": " AR Shankar" }, { "code": null, "e": 5875, "s": 5842, "text": "\n 31 Lectures \n 3 hours \n" }, { "code": null, "e": 5892, "s": 5875, "text": " Abhilash Nelson" }, { "code": null, "e": 5925, "s": 5892, "text": "\n 15 Lectures \n 2 hours \n" }, { "code": null, "e": 5965, "s": 5925, "text": " Harshit Srivastava, Pranjal Srivastava" }, { "code": null, "e": 5998, "s": 5965, "text": "\n 33 Lectures \n 4 hours \n" }, { "code": null, "e": 6018, "s": 5998, "text": " Mumshad Mannambeth" }, { "code": null, "e": 6050, "s": 6018, "text": "\n 13 Lectures \n 53 mins\n" }, { "code": null, "e": 6066, "s": 6050, "text": " Musab Zayadneh" }, { "code": null, "e": 6073, "s": 6066, "text": " Print" }, { "code": null, "e": 6084, "s": 6073, "text": " Add Notes" } ]
Overload unary minus operator in C++?
The operator keyword declares a function specifying what operator-symbol means when applied to instances of a class. This gives the operator more than one meaning, or "overloads" it. The compiler distinguishes between the different meanings of an operator by examining the types of its operands. The unary operators operate on a single operand and following are the examples of Unary operators − The increment (++) and decrement (--) operators. The unary minus (-) operator. The logical not (!) operator. The unary operators operate on the object for which they were called and normally, this operator appears on the left side of the object, as in !obj, -obj, and ++obj but sometimes they can be used as postfix as well like obj++ or obj--. Following example explain how minus(-) operator can be overloaded for prefix usage − #include <iostream> using namespace std; class Distance { private: int feet; int inches; public: // Constructor Distance(int f, int i) { feet = f; inches = i; } // method to display distance void display() { cout << "F: " << feet << " I:" << inches <<endl; } // overloaded minus(-) operator Distance operator-() { feet = -feet; inches = -inches; return Distance(feet, inches); } }; int main() { Distance D1(3, 4), D2(-1, 10); !D1; D1.display(); !D2; D2.display(); return 0; } This will give the output − F: -3 I:-4 F: 1 I:-10
[ { "code": null, "e": 1358, "s": 1062, "text": "The operator keyword declares a function specifying what operator-symbol means when applied to instances of a class. This gives the operator more than one meaning, or \"overloads\" it. The compiler distinguishes between the different meanings of an operator by examining the types of its operands." }, { "code": null, "e": 1458, "s": 1358, "text": "The unary operators operate on a single operand and following are the examples of Unary operators −" }, { "code": null, "e": 1507, "s": 1458, "text": "The increment (++) and decrement (--) operators." }, { "code": null, "e": 1537, "s": 1507, "text": "The unary minus (-) operator." }, { "code": null, "e": 1567, "s": 1537, "text": "The logical not (!) operator." }, { "code": null, "e": 1803, "s": 1567, "text": "The unary operators operate on the object for which they were called and normally, this operator appears on the left side of the object, as in !obj, -obj, and ++obj but sometimes they can be used as postfix as well like obj++ or obj--." }, { "code": null, "e": 1888, "s": 1803, "text": "Following example explain how minus(-) operator can be overloaded for prefix usage −" }, { "code": null, "e": 2457, "s": 1888, "text": "#include <iostream>\nusing namespace std;\nclass Distance {\n private:\n int feet;\n int inches;\n public:\n // Constructor\n Distance(int f, int i) {\n feet = f;\n inches = i;\n }\n // method to display distance\n void display() {\n cout << \"F: \" << feet << \" I:\" << inches <<endl;\n }\n // overloaded minus(-) operator\n Distance operator-() {\n feet = -feet;\n inches = -inches;\n return Distance(feet, inches);\n }\n};\nint main() {\n Distance D1(3, 4), D2(-1, 10);\n !D1;\n D1.display();\n !D2;\n D2.display();\n return 0;\n}" }, { "code": null, "e": 2485, "s": 2457, "text": "This will give the output −" }, { "code": null, "e": 2507, "s": 2485, "text": "F: -3 I:-4\nF: 1 I:-10" } ]
How to add Google reCAPTCHA to Django forms ? - GeeksforGeeks
30 May, 2021 This tutorial explains to integrate Google’s reCaptcha system to your Django site. To create a form in Django you can check out – How to create a form using Django Forms ? Adding reCaptcha to any HTML form involves the following steps: Register your site domain to reCaptcha Admin Console.Add recaptcha keys to project settings.Add reCaptcha scripts and input element to HTML template.On form submission, make a post request to google reCaptcha API in the backend with the form’s reCaptcha field value and recaptcha keys as the POST data.Process the response from Google. Register your site domain to reCaptcha Admin Console. Add recaptcha keys to project settings. Add reCaptcha scripts and input element to HTML template. On form submission, make a post request to google reCaptcha API in the backend with the form’s reCaptcha field value and recaptcha keys as the POST data. Process the response from Google. While this can be done manually, we will be using a third-party library as it makes the process much faster and simpler. Now let’s make a sample contact form where we will integrate the reCaptcha Make sure you are done with the django installation. Create a new django project : django-admin startproject dj_recaptcha Create a new app say “contact” : cd dj_recaptcha python manage.py startapp contact Go to dj_recaptcha/settings.py add the contact app. INSTALLED_APPS = [ ... 'contact', ... ] First you need register your site on the reCaptcha admin console. In the domains section add 127.0.0.1 since we are testing it out locally. Later on, you can add your production URL. recaptcha admin console You can specify whichever reCaptcha type you want, here we have selected v2 with ” I’m not a robot tickbox ” . You will get the API keys on form submission. recaptcha api keys Copy the site key and secret key into settings.py as follows: RECAPTCHA_PUBLIC_KEY = Your_Site_Key RECAPTCHA_PRIVATE_KEY = Your_Secret_key As mentioned before we will be using a third-party library called django-recaptcha to make the process simpler for us. Let’s just install it now using pip, enter the following command. pip install django-recaptcha Add the app to the INSTALLED_APPS list in settings.py INSTALLED_APPS = [ ... 'contact', 'captcha', ... ] Now let’s move on to creating a contact form in forms.py with email, feedback, and captcha as the fields. Python3 # forms.py from django import formsfrom captcha.fields import ReCaptchaFieldfrom captcha.widgets import ReCaptchaV2Checkbox class ContactForm(forms.Form): email = forms.EmailField() feedback = forms.CharField(widget=forms.Textarea) captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox) The captcha field will be rendered as a checkbox field. If you specified a different type than the v2 checkbox while registering the site on recaptcha admin console, you need to change the widget attribute of ReCaptchaField above. If you don’t specify one ReCaptchaV2Checkbox will be default There are three widgets that can be used with the ReCaptchaField class: ReCaptchaV2Checkbox for Google reCAPTCHA V2 – Checkbox ReCaptchaV2Invisible for Google reCAPTCHA V2 – Invisible ReCaptchaV3 for Google reCAPTCHA V3 Make an HTML template say contact.html to render the form. We will be using the default styling with {{ form.as_p }}. If you want to manually style a Django form try using widget tweaks. HTML <!DOCTYPE html><html lang="en"><head> <title>Contact</title></head><body> <h2>Contact Form</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form></body></html> Now create a view to handle the form submission in views.py. Python3 # views.pyfrom django.shortcuts import render, HttpResponsefrom .forms import ContactForm def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): return HttpResponse("Yay! you are human.") else: return HttpResponse("OOPS! Bot suspected.") else: form = ContactForm() return render(request, 'contact.html', {'form':form}) Map the view to a URL. Here we are rendering the form on the homepage so let’s add the URL mapping for the same. Python3 # urls.pyfrom django.contrib import adminfrom django.urls import pathfrom contact import views urlpatterns = [ path('',views.contact, name='index'), path('admin/', admin.site.urls),] We are pretty much done, lets test it out by running the server and open 127.0.0.1:8000 in the browser. python manage.py runserver recaptcha demo Django-Projects Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python OOPs Concepts How to Install PIP on Windows ? Bar Plot in Matplotlib Defaultdict in Python Python Classes and Objects Deque in Python Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python - Ways to remove duplicates from list Class method vs Static method in Python
[ { "code": null, "e": 23927, "s": 23899, "text": "\n30 May, 2021" }, { "code": null, "e": 24100, "s": 23927, "text": "This tutorial explains to integrate Google’s reCaptcha system to your Django site. To create a form in Django you can check out – How to create a form using Django Forms ? " }, { "code": null, "e": 24164, "s": 24100, "text": "Adding reCaptcha to any HTML form involves the following steps:" }, { "code": null, "e": 24500, "s": 24164, "text": "Register your site domain to reCaptcha Admin Console.Add recaptcha keys to project settings.Add reCaptcha scripts and input element to HTML template.On form submission, make a post request to google reCaptcha API in the backend with the form’s reCaptcha field value and recaptcha keys as the POST data.Process the response from Google." }, { "code": null, "e": 24554, "s": 24500, "text": "Register your site domain to reCaptcha Admin Console." }, { "code": null, "e": 24594, "s": 24554, "text": "Add recaptcha keys to project settings." }, { "code": null, "e": 24652, "s": 24594, "text": "Add reCaptcha scripts and input element to HTML template." }, { "code": null, "e": 24806, "s": 24652, "text": "On form submission, make a post request to google reCaptcha API in the backend with the form’s reCaptcha field value and recaptcha keys as the POST data." }, { "code": null, "e": 24840, "s": 24806, "text": "Process the response from Google." }, { "code": null, "e": 25037, "s": 24840, "text": "While this can be done manually, we will be using a third-party library as it makes the process much faster and simpler. Now let’s make a sample contact form where we will integrate the reCaptcha " }, { "code": null, "e": 25090, "s": 25037, "text": "Make sure you are done with the django installation." }, { "code": null, "e": 25120, "s": 25090, "text": "Create a new django project :" }, { "code": null, "e": 25159, "s": 25120, "text": "django-admin startproject dj_recaptcha" }, { "code": null, "e": 25192, "s": 25159, "text": "Create a new app say “contact” :" }, { "code": null, "e": 25242, "s": 25192, "text": "cd dj_recaptcha\npython manage.py startapp contact" }, { "code": null, "e": 25294, "s": 25242, "text": "Go to dj_recaptcha/settings.py add the contact app." }, { "code": null, "e": 25346, "s": 25294, "text": "INSTALLED_APPS = [\n ...\n 'contact',\n ...\n]" }, { "code": null, "e": 25530, "s": 25346, "text": "First you need register your site on the reCaptcha admin console. In the domains section add 127.0.0.1 since we are testing it out locally. Later on, you can add your production URL. " }, { "code": null, "e": 25554, "s": 25530, "text": "recaptcha admin console" }, { "code": null, "e": 25711, "s": 25554, "text": "You can specify whichever reCaptcha type you want, here we have selected v2 with ” I’m not a robot tickbox ” . You will get the API keys on form submission." }, { "code": null, "e": 25730, "s": 25711, "text": "recaptcha api keys" }, { "code": null, "e": 25792, "s": 25730, "text": "Copy the site key and secret key into settings.py as follows:" }, { "code": null, "e": 25869, "s": 25792, "text": "RECAPTCHA_PUBLIC_KEY = Your_Site_Key\nRECAPTCHA_PRIVATE_KEY = Your_Secret_key" }, { "code": null, "e": 26054, "s": 25869, "text": "As mentioned before we will be using a third-party library called django-recaptcha to make the process simpler for us. Let’s just install it now using pip, enter the following command." }, { "code": null, "e": 26083, "s": 26054, "text": "pip install django-recaptcha" }, { "code": null, "e": 26137, "s": 26083, "text": "Add the app to the INSTALLED_APPS list in settings.py" }, { "code": null, "e": 26204, "s": 26137, "text": "INSTALLED_APPS = [\n ...\n 'contact',\n 'captcha',\n ...\n]" }, { "code": null, "e": 26310, "s": 26204, "text": "Now let’s move on to creating a contact form in forms.py with email, feedback, and captcha as the fields." }, { "code": null, "e": 26318, "s": 26310, "text": "Python3" }, { "code": "# forms.py from django import formsfrom captcha.fields import ReCaptchaFieldfrom captcha.widgets import ReCaptchaV2Checkbox class ContactForm(forms.Form): email = forms.EmailField() feedback = forms.CharField(widget=forms.Textarea) captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox)", "e": 26616, "s": 26318, "text": null }, { "code": null, "e": 26980, "s": 26616, "text": "The captcha field will be rendered as a checkbox field. If you specified a different type than the v2 checkbox while registering the site on recaptcha admin console, you need to change the widget attribute of ReCaptchaField above. If you don’t specify one ReCaptchaV2Checkbox will be default There are three widgets that can be used with the ReCaptchaField class:" }, { "code": null, "e": 27035, "s": 26980, "text": "ReCaptchaV2Checkbox for Google reCAPTCHA V2 – Checkbox" }, { "code": null, "e": 27092, "s": 27035, "text": "ReCaptchaV2Invisible for Google reCAPTCHA V2 – Invisible" }, { "code": null, "e": 27128, "s": 27092, "text": "ReCaptchaV3 for Google reCAPTCHA V3" }, { "code": null, "e": 27315, "s": 27128, "text": "Make an HTML template say contact.html to render the form. We will be using the default styling with {{ form.as_p }}. If you want to manually style a Django form try using widget tweaks." }, { "code": null, "e": 27320, "s": 27315, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Contact</title></head><body> <h2>Contact Form</h2> <form method=\"post\"> {% csrf_token %} {{ form.as_p }} <button type=\"submit\">Submit</button> </form></body></html>", "e": 27563, "s": 27320, "text": null }, { "code": null, "e": 27624, "s": 27563, "text": "Now create a view to handle the form submission in views.py." }, { "code": null, "e": 27632, "s": 27624, "text": "Python3" }, { "code": "# views.pyfrom django.shortcuts import render, HttpResponsefrom .forms import ContactForm def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): return HttpResponse(\"Yay! you are human.\") else: return HttpResponse(\"OOPS! Bot suspected.\") else: form = ContactForm() return render(request, 'contact.html', {'form':form})", "e": 28092, "s": 27632, "text": null }, { "code": null, "e": 28205, "s": 28092, "text": "Map the view to a URL. Here we are rendering the form on the homepage so let’s add the URL mapping for the same." }, { "code": null, "e": 28213, "s": 28205, "text": "Python3" }, { "code": "# urls.pyfrom django.contrib import adminfrom django.urls import pathfrom contact import views urlpatterns = [ path('',views.contact, name='index'), path('admin/', admin.site.urls),]", "e": 28403, "s": 28213, "text": null }, { "code": null, "e": 28508, "s": 28403, "text": "We are pretty much done, lets test it out by running the server and open 127.0.0.1:8000 in the browser. " }, { "code": null, "e": 28535, "s": 28508, "text": "python manage.py runserver" }, { "code": null, "e": 28550, "s": 28535, "text": "recaptcha demo" }, { "code": null, "e": 28566, "s": 28550, "text": "Django-Projects" }, { "code": null, "e": 28580, "s": 28566, "text": "Python Django" }, { "code": null, "e": 28587, "s": 28580, "text": "Python" }, { "code": null, "e": 28685, "s": 28587, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28694, "s": 28685, "text": "Comments" }, { "code": null, "e": 28707, "s": 28694, "text": "Old Comments" }, { "code": null, "e": 28728, "s": 28707, "text": "Python OOPs Concepts" }, { "code": null, "e": 28760, "s": 28728, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28783, "s": 28760, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 28805, "s": 28783, "text": "Defaultdict in Python" }, { "code": null, "e": 28832, "s": 28805, "text": "Python Classes and Objects" }, { "code": null, "e": 28848, "s": 28832, "text": "Deque in Python" }, { "code": null, "e": 28890, "s": 28848, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28946, "s": 28890, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28991, "s": 28946, "text": "Python - Ways to remove duplicates from list" } ]
A quick tutorial on how to deploy your Streamlit app to Heroku. | by Navid Mashinchi | Towards Data Science
Welcome to the step-by-step tutorial on how to deploy your Streamlit app to Heroku. For the past two weeks, I have been working with Streamlit, and I was very impressed with its capabilities. It’s ideal for sharing your data science project with the world since it’s very straightforward. In this tutorial, I assume you have already completed your app and you are at the final stage of deploying your project. Based on my experiences from the past two weeks, you would think you can immediately deploy your project using Streamlit Sharing. However, you need to apply for the functionality, and it could potentially take a couple of days for them to send you the invite. Worst come worse, I even heard of stories where people waited a week to get the invitation to take advantage of Streamlit Sharing. If waiting isn’t an option for you, you can always deploy your app to Heroku or some other host. In this guide, I will go only over how to deploy your app to Heroku and note that the steps below won’t work if you would like to host it on AWS or somewhere else. The first step is to make sure you have a python file. If you are working in Jupyter Notebook, make sure to download your file as a .py file. This is necessary if you want to run your code locally with Streamlit and push it later to Heroku. I have created a sample Streamlit app so we can follow along here. The name of my python script is app.py. To run your code locally, go to the directory where your script is saved using the command-line interface (CLI). Once you are in the directory, run the following command. streamlit run app.py A window will open automatically in your browser, as you can see below. Voila, you have your Streamlit app running on your local machine. The next step is to create a GitHub repo for your app. Log in into your GitHub account and follow the steps below: Type in your repository name and click “Create repository.” Now that you have created the repo, it’s time to make your first commit and push to the repo. In your terminal, move to the directory where your app.py is in and copy-paste the following code. echo "# streamlit-to-heroku-tutorial" >> README.mdgit initgit add README.mdgit commit -m "first commit"git branch -M mastergit remote add origin https://github.com/your_username/your_repo_name.gitgit push -u origin master I am initializing my directory in the above code, adding a README.md file, a remote origin with the URL you see above, and conducting my first push. The next step is crucial, and you want to make sure you don’t have any typos or make any mistakes. Otherwise, Heroku will run an error when you deploy your app. Before you move on, make sure you have the app.py and the README.md file in your directory. requirements.txt: Create a requirements.txt file (No capital letters!)and add all the libraries to that file you are using in your python script. In my app.py example, I just imported the following library: import streamlit as st As a result, I add “streamlit” to my requirements.txt file. This file is necessary for Heroku to know which libraries it needs to run your application. setup.sh: The next file is the setup.sh file. This is a shell file, and you need to add the following shell command inside the file. Copy-paste the code below into the file: mkdir -p ~/.streamlit/echo "\[server]\n\headless = true\n\port = $PORT\n\enableCORS = false\n\\n\" > ~/.streamlit/config.toml If you don’t add this file, you will get an error message when you deploy your app to Heroku. So make sure you create this app and name it as I wrote it above. No capital letters! Procfile: Inside your directory, create a text file and call it “Procfile.” Inside the file, copy-paste the following code: web: sh setup.sh && streamlit run app.py The “web” means that it’s a web app. The Procfile pretty much specifies the commands once you run the app on Heroku. We specify the shell file that we created above and then call Streamlit to run app.py. Once you have created the files above, review the steps and make sure you named the files as I named them above. It’s without saying that if you have more libraries for your app that you need to list them in your requirements.txt file. Any library that you are importing needs to be in that file. Once you have created all the required files, it’s now time to set up your app so it can interact with Heroku. The first thing you will do is make sure you have installed Heroku on your machine and created a free account. See the link below to create an account. www.heroku.com According to the documents, Heroku CLI requires Git. Hence, if you don’t have Heroku, click on the link below, and you can install it. devcenter.heroku.com When you installed Heroku on your machine and created an account, it’s time to log in to your Heroku account from the terminal. Run the following command in your terminal: heroku login The terminal returns the following line: ‘’heroku: Press any key to open up the browser to login or q to exit:’’ Just click any key, and your browser will automatically open up. You should see the following: Next, you click Log In and enter your credentials. After that, you will see the following: As the picture above says, you can close the window and return to the CLI. The next step is to create the Heroku app. Type in the following command: heroku create sample_app22a Here I am creating an app called “sample_app22a”. If you don’t specify a name, it will create an app with random numbers. Hence I suggest picking a name for your app. The last step is to push our files to Heroku. Since Heroku uses git, the command line will be easy to understand. Type in the following: git push heroku master Once you executed the command above, it will take a couple of seconds for Heroku to install all the libraries and set up your app. You will see a URL in the output, and that will be the URL of your app. Please see below for reference. We didn’t receive an error message, and it’s now time to check out the app. Click on the link below, and you can see our Streamlit app on Heroku. sample-app22a.herokuapp.com There you have it, folks. Now that your app is working, you want to push your changes to your repo as well. git add -Agit commit -m "Type in a message"git push I suggest waiting until you get the Streamlit Sharing invitation, so you can take advantage of that feature instead of deploying it to Heroku. I created an app myself, which I will write about in the coming days. The rendering time took a bit longer for a few plots when using Heroku. However, if you don’t have the time and need to deploy as soon as possible, Heroku will get the job done too. Hopefully, this article gives you a better understanding of how to deploy your Streamlit app to Heroku. Let me know if you have any questions on this topic or have some feedback. If you enjoyed this article, I’d be very grateful if you would share it on any social media platforms. I will introduce you to the Covid19-Dashboard web app that I created with Streamlit and its Sharing feature in my next article. Stay tuned for that! Until next time️ ✌️
[ { "code": null, "e": 1234, "s": 172, "text": "Welcome to the step-by-step tutorial on how to deploy your Streamlit app to Heroku. For the past two weeks, I have been working with Streamlit, and I was very impressed with its capabilities. It’s ideal for sharing your data science project with the world since it’s very straightforward. In this tutorial, I assume you have already completed your app and you are at the final stage of deploying your project. Based on my experiences from the past two weeks, you would think you can immediately deploy your project using Streamlit Sharing. However, you need to apply for the functionality, and it could potentially take a couple of days for them to send you the invite. Worst come worse, I even heard of stories where people waited a week to get the invitation to take advantage of Streamlit Sharing. If waiting isn’t an option for you, you can always deploy your app to Heroku or some other host. In this guide, I will go only over how to deploy your app to Heroku and note that the steps below won’t work if you would like to host it on AWS or somewhere else." }, { "code": null, "e": 1753, "s": 1234, "text": "The first step is to make sure you have a python file. If you are working in Jupyter Notebook, make sure to download your file as a .py file. This is necessary if you want to run your code locally with Streamlit and push it later to Heroku. I have created a sample Streamlit app so we can follow along here. The name of my python script is app.py. To run your code locally, go to the directory where your script is saved using the command-line interface (CLI). Once you are in the directory, run the following command." }, { "code": null, "e": 1774, "s": 1753, "text": "streamlit run app.py" }, { "code": null, "e": 1846, "s": 1774, "text": "A window will open automatically in your browser, as you can see below." }, { "code": null, "e": 1912, "s": 1846, "text": "Voila, you have your Streamlit app running on your local machine." }, { "code": null, "e": 2027, "s": 1912, "text": "The next step is to create a GitHub repo for your app. Log in into your GitHub account and follow the steps below:" }, { "code": null, "e": 2087, "s": 2027, "text": "Type in your repository name and click “Create repository.”" }, { "code": null, "e": 2280, "s": 2087, "text": "Now that you have created the repo, it’s time to make your first commit and push to the repo. In your terminal, move to the directory where your app.py is in and copy-paste the following code." }, { "code": null, "e": 2502, "s": 2280, "text": "echo \"# streamlit-to-heroku-tutorial\" >> README.mdgit initgit add README.mdgit commit -m \"first commit\"git branch -M mastergit remote add origin https://github.com/your_username/your_repo_name.gitgit push -u origin master" }, { "code": null, "e": 2651, "s": 2502, "text": "I am initializing my directory in the above code, adding a README.md file, a remote origin with the URL you see above, and conducting my first push." }, { "code": null, "e": 2904, "s": 2651, "text": "The next step is crucial, and you want to make sure you don’t have any typos or make any mistakes. Otherwise, Heroku will run an error when you deploy your app. Before you move on, make sure you have the app.py and the README.md file in your directory." }, { "code": null, "e": 3111, "s": 2904, "text": "requirements.txt: Create a requirements.txt file (No capital letters!)and add all the libraries to that file you are using in your python script. In my app.py example, I just imported the following library:" }, { "code": null, "e": 3134, "s": 3111, "text": "import streamlit as st" }, { "code": null, "e": 3286, "s": 3134, "text": "As a result, I add “streamlit” to my requirements.txt file. This file is necessary for Heroku to know which libraries it needs to run your application." }, { "code": null, "e": 3460, "s": 3286, "text": "setup.sh: The next file is the setup.sh file. This is a shell file, and you need to add the following shell command inside the file. Copy-paste the code below into the file:" }, { "code": null, "e": 3586, "s": 3460, "text": "mkdir -p ~/.streamlit/echo \"\\[server]\\n\\headless = true\\n\\port = $PORT\\n\\enableCORS = false\\n\\\\n\\\" > ~/.streamlit/config.toml" }, { "code": null, "e": 3766, "s": 3586, "text": "If you don’t add this file, you will get an error message when you deploy your app to Heroku. So make sure you create this app and name it as I wrote it above. No capital letters!" }, { "code": null, "e": 3890, "s": 3766, "text": "Procfile: Inside your directory, create a text file and call it “Procfile.” Inside the file, copy-paste the following code:" }, { "code": null, "e": 3931, "s": 3890, "text": "web: sh setup.sh && streamlit run app.py" }, { "code": null, "e": 4135, "s": 3931, "text": "The “web” means that it’s a web app. The Procfile pretty much specifies the commands once you run the app on Heroku. We specify the shell file that we created above and then call Streamlit to run app.py." }, { "code": null, "e": 4432, "s": 4135, "text": "Once you have created the files above, review the steps and make sure you named the files as I named them above. It’s without saying that if you have more libraries for your app that you need to list them in your requirements.txt file. Any library that you are importing needs to be in that file." }, { "code": null, "e": 4543, "s": 4432, "text": "Once you have created all the required files, it’s now time to set up your app so it can interact with Heroku." }, { "code": null, "e": 4695, "s": 4543, "text": "The first thing you will do is make sure you have installed Heroku on your machine and created a free account. See the link below to create an account." }, { "code": null, "e": 4710, "s": 4695, "text": "www.heroku.com" }, { "code": null, "e": 4845, "s": 4710, "text": "According to the documents, Heroku CLI requires Git. Hence, if you don’t have Heroku, click on the link below, and you can install it." }, { "code": null, "e": 4866, "s": 4845, "text": "devcenter.heroku.com" }, { "code": null, "e": 5038, "s": 4866, "text": "When you installed Heroku on your machine and created an account, it’s time to log in to your Heroku account from the terminal. Run the following command in your terminal:" }, { "code": null, "e": 5051, "s": 5038, "text": "heroku login" }, { "code": null, "e": 5092, "s": 5051, "text": "The terminal returns the following line:" }, { "code": null, "e": 5164, "s": 5092, "text": "‘’heroku: Press any key to open up the browser to login or q to exit:’’" }, { "code": null, "e": 5259, "s": 5164, "text": "Just click any key, and your browser will automatically open up. You should see the following:" }, { "code": null, "e": 5350, "s": 5259, "text": "Next, you click Log In and enter your credentials. After that, you will see the following:" }, { "code": null, "e": 5499, "s": 5350, "text": "As the picture above says, you can close the window and return to the CLI. The next step is to create the Heroku app. Type in the following command:" }, { "code": null, "e": 5527, "s": 5499, "text": "heroku create sample_app22a" }, { "code": null, "e": 5831, "s": 5527, "text": "Here I am creating an app called “sample_app22a”. If you don’t specify a name, it will create an app with random numbers. Hence I suggest picking a name for your app. The last step is to push our files to Heroku. Since Heroku uses git, the command line will be easy to understand. Type in the following:" }, { "code": null, "e": 5854, "s": 5831, "text": "git push heroku master" }, { "code": null, "e": 6089, "s": 5854, "text": "Once you executed the command above, it will take a couple of seconds for Heroku to install all the libraries and set up your app. You will see a URL in the output, and that will be the URL of your app. Please see below for reference." }, { "code": null, "e": 6235, "s": 6089, "text": "We didn’t receive an error message, and it’s now time to check out the app. Click on the link below, and you can see our Streamlit app on Heroku." }, { "code": null, "e": 6263, "s": 6235, "text": "sample-app22a.herokuapp.com" }, { "code": null, "e": 6371, "s": 6263, "text": "There you have it, folks. Now that your app is working, you want to push your changes to your repo as well." }, { "code": null, "e": 6424, "s": 6371, "text": "git add -Agit commit -m \"Type in a message\"git push " }, { "code": null, "e": 6819, "s": 6424, "text": "I suggest waiting until you get the Streamlit Sharing invitation, so you can take advantage of that feature instead of deploying it to Heroku. I created an app myself, which I will write about in the coming days. The rendering time took a bit longer for a few plots when using Heroku. However, if you don’t have the time and need to deploy as soon as possible, Heroku will get the job done too." } ]
C# - Multithreading
A thread is defined as the execution path of a program. Each thread defines a unique flow of control. If your application involves complicated and time consuming operations, then it is often helpful to set different execution paths or threads, with each thread performing a particular job. Threads are lightweight processes. One common example of use of thread is implementation of concurrent programming by modern operating systems. Use of threads saves wastage of CPU cycle and increase efficiency of an application. So far we wrote the programs where a single thread runs as a single process which is the running instance of the application. However, this way the application can perform one job at a time. To make it execute more than one task at a time, it could be divided into smaller threads. The life cycle of a thread starts when an object of the System.Threading.Thread class is created and ends when the thread is terminated or completes execution. Following are the various states in the life cycle of a thread − The Unstarted State − It is the situation when the instance of the thread is created but the Start method is not called. The Unstarted State − It is the situation when the instance of the thread is created but the Start method is not called. The Ready State − It is the situation when the thread is ready to run and waiting CPU cycle. The Ready State − It is the situation when the thread is ready to run and waiting CPU cycle. The Not Runnable State − A thread is not executable, when Sleep method has been called Wait method has been called Blocked by I/O operations The Not Runnable State − A thread is not executable, when Sleep method has been called Wait method has been called Blocked by I/O operations The Dead State − It is the situation when the thread completes execution or is aborted. The Dead State − It is the situation when the thread completes execution or is aborted. In C#, the System.Threading.Thread class is used for working with threads. It allows creating and accessing individual threads in a multithreaded application. The first thread to be executed in a process is called the main thread. When a C# program starts execution, the main thread is automatically created. The threads created using the Thread class are called the child threads of the main thread. You can access a thread using the CurrentThread property of the Thread class. The following program demonstrates main thread execution − using System; using System.Threading; namespace MultithreadingApplication { class MainThreadProgram { static void Main(string[] args) { Thread th = Thread.CurrentThread; th.Name = "MainThread"; Console.WriteLine("This is {0}", th.Name); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − This is MainThread The following table shows some most commonly used properties of the Thread class − CurrentContext Gets the current context in which the thread is executing. CurrentCulture Gets or sets the culture for the current thread. CurrentPrinciple Gets or sets the thread's current principal (for role-based security). CurrentThread Gets the currently running thread. CurrentUICulture Gets or sets the current culture used by the Resource Manager to look up culture-specific resources at run-time. ExecutionContext Gets an ExecutionContext object that contains information about the various contexts of the current thread. IsAlive Gets a value indicating the execution status of the current thread. IsBackground Gets or sets a value indicating whether or not a thread is a background thread. IsThreadPoolThread Gets a value indicating whether or not a thread belongs to the managed thread pool. ManagedThreadId Gets a unique identifier for the current managed thread. Name Gets or sets the name of the thread. Priority Gets or sets a value indicating the scheduling priority of a thread. ThreadState Gets a value containing the states of the current thread. The following table shows some of the most commonly used methods of the Thread class − public void Abort() Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. Calling this method usually terminates the thread. public static LocalDataStoreSlot AllocateDataSlot() Allocates an unnamed data slot on all the threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. public static LocalDataStoreSlot AllocateNamedDataSlot(string name) Allocates a named data slot on all threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. public static void BeginCriticalRegion() Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception might jeopardize other tasks in the application domain. public static void BeginThreadAffinity() Notifies a host that managed code is about to execute instructions that depend on the identity of the current physical operating system thread. public static void EndCriticalRegion() Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception are limited to the current task. public static void EndThreadAffinity() Notifies a host that managed code has finished executing instructions that depend on the identity of the current physical operating system thread. public static void FreeNamedDataSlot(string name) Eliminates the association between a name and a slot, for all threads in the process. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. public static Object GetData(LocalDataStoreSlot slot) Retrieves the value from the specified slot on the current thread, within the current thread's current domain. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. public static AppDomain GetDomain() Returns the current domain in which the current thread is running. public static AppDomain GetDomainID() Returns a unique application domain identifier public static LocalDataStoreSlot GetNamedDataSlot(string name) Looks up a named data slot. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. public void Interrupt() Interrupts a thread that is in the WaitSleepJoin thread state. public void Join() Blocks the calling thread until a thread terminates, while continuing to perform standard COM and SendMessage pumping. This method has different overloaded forms. public static void MemoryBarrier() Synchronizes memory access as follows: The processor executing the current thread cannot reorder instructions in such a way that memory accesses prior to the call to MemoryBarrier execute after memory accesses that follow the call to MemoryBarrier. public static void ResetAbort() Cancels an Abort requested for the current thread. public static void SetData(LocalDataStoreSlot slot, Object data) Sets the data in the specified slot on the currently running thread, for that thread's current domain. For better performance, use fields marked with the ThreadStaticAttribute attribute instead. public void Start() Starts a thread. public static void Sleep(int millisecondsTimeout) Makes the thread pause for a period of time. public static void SpinWait(int iterations) Causes a thread to wait the number of times defined by the iterations parameter public static byte VolatileRead(ref byte address) public static double VolatileRead(ref double address) public static int VolatileRead(ref int address) public static Object VolatileRead(ref Object address) Reads the value of a field. The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache. This method has different overloaded forms. Only some are given above. public static void VolatileWrite(ref byte address,byte value) public static void VolatileWrite(ref double address, double value) public static void VolatileWrite(ref int address, int value) public static void VolatileWrite(ref Object address, Object value) Writes a value to a field immediately, so that the value is visible to all processors in the computer. This method has different overloaded forms. Only some are given above. public static bool Yield() Causes the calling thread to yield execution to another thread that is ready to run on the current processor. The operating system selects the thread to yield to. Threads are created by extending the Thread class. The extended Thread class then calls the Start() method to begin the child thread execution. The following program demonstrates the concept − using System; using System.Threading; namespace MultithreadingApplication { class ThreadCreationProgram { public static void CallToChildThread() { Console.WriteLine("Child thread starts"); } static void Main(string[] args) { ThreadStart childref = new ThreadStart(CallToChildThread); Console.WriteLine("In Main: Creating the Child thread"); Thread childThread = new Thread(childref); childThread.Start(); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − In Main: Creating the Child thread Child thread starts The Thread class provides various methods for managing threads. The following example demonstrates the use of the sleep() method for making a thread pause for a specific period of time. using System; using System.Threading; namespace MultithreadingApplication { class ThreadCreationProgram { public static void CallToChildThread() { Console.WriteLine("Child thread starts"); // the thread is paused for 5000 milliseconds int sleepfor = 5000; Console.WriteLine("Child Thread Paused for {0} seconds", sleepfor / 1000); Thread.Sleep(sleepfor); Console.WriteLine("Child thread resumes"); } static void Main(string[] args) { ThreadStart childref = new ThreadStart(CallToChildThread); Console.WriteLine("In Main: Creating the Child thread"); Thread childThread = new Thread(childref); childThread.Start(); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − In Main: Creating the Child thread Child thread starts Child Thread Paused for 5 seconds Child thread resumes The Abort() method is used for destroying threads. The runtime aborts the thread by throwing a ThreadAbortException. This exception cannot be caught, the control is sent to the finally block, if any. The following program illustrates this − using System; using System.Threading; namespace MultithreadingApplication { class ThreadCreationProgram { public static void CallToChildThread() { try { Console.WriteLine("Child thread starts"); // do some work, like counting to 10 for (int counter = 0; counter <= 10; counter++) { Thread.Sleep(500); Console.WriteLine(counter); } Console.WriteLine("Child Thread Completed"); } catch (ThreadAbortException e) { Console.WriteLine("Thread Abort Exception"); } finally { Console.WriteLine("Couldn't catch the Thread Exception"); } } static void Main(string[] args) { ThreadStart childref = new ThreadStart(CallToChildThread); Console.WriteLine("In Main: Creating the Child thread"); Thread childThread = new Thread(childref); childThread.Start(); //stop the main thread for some time Thread.Sleep(2000); //now abort the child Console.WriteLine("In Main: Aborting the Child thread"); childThread.Abort(); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − In Main: Creating the Child thread Child thread starts 0 1 2 In Main: Aborting the Child thread Thread Abort Exception Couldn't catch the Thread Exception 119 Lectures 23.5 hours Raja Biswas 37 Lectures 13 hours Trevoir Williams 16 Lectures 1 hours Peter Jepson 159 Lectures 21.5 hours Ebenezer Ogbu 193 Lectures 17 hours Arnold Higuit 24 Lectures 2.5 hours Eric Frick Print Add Notes Bookmark this page
[ { "code": null, "e": 2560, "s": 2270, "text": "A thread is defined as the execution path of a program. Each thread defines a unique flow of control. If your application involves complicated and time consuming operations, then it is often helpful to set different execution paths or threads, with each thread performing a particular job." }, { "code": null, "e": 2789, "s": 2560, "text": "Threads are lightweight processes. One common example of use of thread is implementation of concurrent programming by modern operating systems. Use of threads saves wastage of CPU cycle and increase efficiency of an application." }, { "code": null, "e": 3071, "s": 2789, "text": "So far we wrote the programs where a single thread runs as a single process which is the running instance of the application. However, this way the application can perform one job at a time. To make it execute more than one task at a time, it could be divided into smaller threads." }, { "code": null, "e": 3231, "s": 3071, "text": "The life cycle of a thread starts when an object of the System.Threading.Thread class is created and ends when the thread is terminated or completes execution." }, { "code": null, "e": 3296, "s": 3231, "text": "Following are the various states in the life cycle of a thread −" }, { "code": null, "e": 3417, "s": 3296, "text": "The Unstarted State − It is the situation when the instance of the thread is created but the Start method is not called." }, { "code": null, "e": 3538, "s": 3417, "text": "The Unstarted State − It is the situation when the instance of the thread is created but the Start method is not called." }, { "code": null, "e": 3631, "s": 3538, "text": "The Ready State − It is the situation when the thread is ready to run and waiting CPU cycle." }, { "code": null, "e": 3724, "s": 3631, "text": "The Ready State − It is the situation when the thread is ready to run and waiting CPU cycle." }, { "code": null, "e": 3868, "s": 3724, "text": "The Not Runnable State − A thread is not executable, when\n\nSleep method has been called\nWait method has been called\nBlocked by I/O operations\n\n" }, { "code": null, "e": 3926, "s": 3868, "text": "The Not Runnable State − A thread is not executable, when" }, { "code": null, "e": 3955, "s": 3926, "text": "Sleep method has been called" }, { "code": null, "e": 3983, "s": 3955, "text": "Wait method has been called" }, { "code": null, "e": 4009, "s": 3983, "text": "Blocked by I/O operations" }, { "code": null, "e": 4097, "s": 4009, "text": "The Dead State − It is the situation when the thread completes execution or is aborted." }, { "code": null, "e": 4185, "s": 4097, "text": "The Dead State − It is the situation when the thread completes execution or is aborted." }, { "code": null, "e": 4416, "s": 4185, "text": "In C#, the System.Threading.Thread class is used for working with threads. It allows creating and accessing individual threads in a multithreaded application. The first thread to be executed in a process is called the main thread." }, { "code": null, "e": 4664, "s": 4416, "text": "When a C# program starts execution, the main thread is automatically created. The threads created using the Thread class are called the child threads of the main thread. You can access a thread using the CurrentThread property of the Thread class." }, { "code": null, "e": 4723, "s": 4664, "text": "The following program demonstrates main thread execution −" }, { "code": null, "e": 5050, "s": 4723, "text": "using System;\nusing System.Threading;\n\nnamespace MultithreadingApplication {\n class MainThreadProgram {\n static void Main(string[] args) {\n Thread th = Thread.CurrentThread;\n th.Name = \"MainThread\";\n \n Console.WriteLine(\"This is {0}\", th.Name);\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 5131, "s": 5050, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 5151, "s": 5131, "text": "This is MainThread\n" }, { "code": null, "e": 5234, "s": 5151, "text": "The following table shows some most commonly used properties of the Thread class −" }, { "code": null, "e": 5249, "s": 5234, "text": "CurrentContext" }, { "code": null, "e": 5308, "s": 5249, "text": "Gets the current context in which the thread is executing." }, { "code": null, "e": 5323, "s": 5308, "text": "CurrentCulture" }, { "code": null, "e": 5372, "s": 5323, "text": "Gets or sets the culture for the current thread." }, { "code": null, "e": 5389, "s": 5372, "text": "CurrentPrinciple" }, { "code": null, "e": 5460, "s": 5389, "text": "Gets or sets the thread's current principal (for role-based security)." }, { "code": null, "e": 5474, "s": 5460, "text": "CurrentThread" }, { "code": null, "e": 5509, "s": 5474, "text": "Gets the currently running thread." }, { "code": null, "e": 5526, "s": 5509, "text": "CurrentUICulture" }, { "code": null, "e": 5639, "s": 5526, "text": "Gets or sets the current culture used by the Resource Manager to look up culture-specific resources at run-time." }, { "code": null, "e": 5656, "s": 5639, "text": "ExecutionContext" }, { "code": null, "e": 5764, "s": 5656, "text": "Gets an ExecutionContext object that contains information about the various contexts of the current thread." }, { "code": null, "e": 5772, "s": 5764, "text": "IsAlive" }, { "code": null, "e": 5840, "s": 5772, "text": "Gets a value indicating the execution status of the current thread." }, { "code": null, "e": 5853, "s": 5840, "text": "IsBackground" }, { "code": null, "e": 5933, "s": 5853, "text": "Gets or sets a value indicating whether or not a thread is a background thread." }, { "code": null, "e": 5952, "s": 5933, "text": "IsThreadPoolThread" }, { "code": null, "e": 6036, "s": 5952, "text": "Gets a value indicating whether or not a thread belongs to the managed thread pool." }, { "code": null, "e": 6052, "s": 6036, "text": "ManagedThreadId" }, { "code": null, "e": 6109, "s": 6052, "text": "Gets a unique identifier for the current managed thread." }, { "code": null, "e": 6114, "s": 6109, "text": "Name" }, { "code": null, "e": 6151, "s": 6114, "text": "Gets or sets the name of the thread." }, { "code": null, "e": 6160, "s": 6151, "text": "Priority" }, { "code": null, "e": 6229, "s": 6160, "text": "Gets or sets a value indicating the scheduling priority of a thread." }, { "code": null, "e": 6241, "s": 6229, "text": "ThreadState" }, { "code": null, "e": 6299, "s": 6241, "text": "Gets a value containing the states of the current thread." }, { "code": null, "e": 6386, "s": 6299, "text": "The following table shows some of the most commonly used methods of the Thread class −" }, { "code": null, "e": 6406, "s": 6386, "text": "public void Abort()" }, { "code": null, "e": 6573, "s": 6406, "text": "Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. Calling this method usually terminates the thread." }, { "code": null, "e": 6625, "s": 6573, "text": "public static LocalDataStoreSlot AllocateDataSlot()" }, { "code": null, "e": 6777, "s": 6625, "text": "Allocates an unnamed data slot on all the threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead." }, { "code": null, "e": 6845, "s": 6777, "text": "public static LocalDataStoreSlot AllocateNamedDataSlot(string name)" }, { "code": null, "e": 6990, "s": 6845, "text": "Allocates a named data slot on all threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead." }, { "code": null, "e": 7031, "s": 6990, "text": "public static void BeginCriticalRegion()" }, { "code": null, "e": 7215, "s": 7031, "text": "Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception might jeopardize other tasks in the application domain." }, { "code": null, "e": 7256, "s": 7215, "text": "public static void BeginThreadAffinity()" }, { "code": null, "e": 7400, "s": 7256, "text": "Notifies a host that managed code is about to execute instructions that depend on the identity of the current physical operating system thread." }, { "code": null, "e": 7439, "s": 7400, "text": "public static void EndCriticalRegion()" }, { "code": null, "e": 7600, "s": 7439, "text": "Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception are limited to the current task." }, { "code": null, "e": 7639, "s": 7600, "text": "public static void EndThreadAffinity()" }, { "code": null, "e": 7786, "s": 7639, "text": "Notifies a host that managed code has finished executing instructions that depend on the identity of the current physical operating system thread." }, { "code": null, "e": 7836, "s": 7786, "text": "public static void FreeNamedDataSlot(string name)" }, { "code": null, "e": 8023, "s": 7836, "text": "Eliminates the association between a name and a slot, for all threads in the process. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead." }, { "code": null, "e": 8077, "s": 8023, "text": "public static Object GetData(LocalDataStoreSlot slot)" }, { "code": null, "e": 8289, "s": 8077, "text": "Retrieves the value from the specified slot on the current thread, within the current thread's current domain. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead." }, { "code": null, "e": 8325, "s": 8289, "text": "public static AppDomain GetDomain()" }, { "code": null, "e": 8392, "s": 8325, "text": "Returns the current domain in which the current thread is running." }, { "code": null, "e": 8430, "s": 8392, "text": "public static AppDomain GetDomainID()" }, { "code": null, "e": 8477, "s": 8430, "text": "Returns a unique application domain identifier" }, { "code": null, "e": 8540, "s": 8477, "text": "public static LocalDataStoreSlot GetNamedDataSlot(string name)" }, { "code": null, "e": 8669, "s": 8540, "text": "Looks up a named data slot. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead." }, { "code": null, "e": 8693, "s": 8669, "text": "public void Interrupt()" }, { "code": null, "e": 8756, "s": 8693, "text": "Interrupts a thread that is in the WaitSleepJoin thread state." }, { "code": null, "e": 8775, "s": 8756, "text": "public void Join()" }, { "code": null, "e": 8938, "s": 8775, "text": "Blocks the calling thread until a thread terminates, while continuing to perform standard COM and SendMessage pumping. This method has different overloaded forms." }, { "code": null, "e": 8973, "s": 8938, "text": "public static void MemoryBarrier()" }, { "code": null, "e": 9222, "s": 8973, "text": "Synchronizes memory access as follows: The processor executing the current thread cannot reorder instructions in such a way that memory accesses prior to the call to MemoryBarrier execute after memory accesses that follow the call to MemoryBarrier." }, { "code": null, "e": 9254, "s": 9222, "text": "public static void ResetAbort()" }, { "code": null, "e": 9305, "s": 9254, "text": "Cancels an Abort requested for the current thread." }, { "code": null, "e": 9370, "s": 9305, "text": "public static void SetData(LocalDataStoreSlot slot, Object data)" }, { "code": null, "e": 9565, "s": 9370, "text": "Sets the data in the specified slot on the currently running thread, for that thread's current domain. For better performance, use fields marked with the ThreadStaticAttribute attribute instead." }, { "code": null, "e": 9585, "s": 9565, "text": "public void Start()" }, { "code": null, "e": 9602, "s": 9585, "text": "Starts a thread." }, { "code": null, "e": 9652, "s": 9602, "text": "public static void Sleep(int millisecondsTimeout)" }, { "code": null, "e": 9697, "s": 9652, "text": "Makes the thread pause for a period of time." }, { "code": null, "e": 9741, "s": 9697, "text": "public static void SpinWait(int iterations)" }, { "code": null, "e": 9821, "s": 9741, "text": "Causes a thread to wait the number of times defined by the iterations parameter" }, { "code": null, "e": 9871, "s": 9821, "text": "public static byte VolatileRead(ref byte address)" }, { "code": null, "e": 9925, "s": 9871, "text": "public static double VolatileRead(ref double address)" }, { "code": null, "e": 9973, "s": 9925, "text": "public static int VolatileRead(ref int address)" }, { "code": null, "e": 10027, "s": 9973, "text": "public static Object VolatileRead(ref Object address)" }, { "code": null, "e": 10262, "s": 10027, "text": "Reads the value of a field. The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache. This method has different overloaded forms. Only some are given above." }, { "code": null, "e": 10324, "s": 10262, "text": "public static void VolatileWrite(ref byte address,byte value)" }, { "code": null, "e": 10391, "s": 10324, "text": "public static void VolatileWrite(ref double address, double value)" }, { "code": null, "e": 10452, "s": 10391, "text": "public static void VolatileWrite(ref int address, int value)" }, { "code": null, "e": 10519, "s": 10452, "text": "public static void VolatileWrite(ref Object address, Object value)" }, { "code": null, "e": 10693, "s": 10519, "text": "Writes a value to a field immediately, so that the value is visible to all processors in the computer. This method has different overloaded forms. Only some are given above." }, { "code": null, "e": 10720, "s": 10693, "text": "public static bool Yield()" }, { "code": null, "e": 10883, "s": 10720, "text": "Causes the calling thread to yield execution to another thread that is ready to run on the current processor. The operating system selects the thread to yield to." }, { "code": null, "e": 11027, "s": 10883, "text": "Threads are created by extending the Thread class. The extended Thread class then calls the Start() method to begin the child thread execution." }, { "code": null, "e": 11076, "s": 11027, "text": "The following program demonstrates the concept −" }, { "code": null, "e": 11591, "s": 11076, "text": "using System;\nusing System.Threading;\n\nnamespace MultithreadingApplication {\n class ThreadCreationProgram {\n public static void CallToChildThread() {\n Console.WriteLine(\"Child thread starts\");\n }\n static void Main(string[] args) {\n ThreadStart childref = new ThreadStart(CallToChildThread);\n Console.WriteLine(\"In Main: Creating the Child thread\");\n Thread childThread = new Thread(childref);\n childThread.Start();\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 11672, "s": 11591, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 11728, "s": 11672, "text": "In Main: Creating the Child thread\nChild thread starts\n" }, { "code": null, "e": 11792, "s": 11728, "text": "The Thread class provides various methods for managing threads." }, { "code": null, "e": 11914, "s": 11792, "text": "The following example demonstrates the use of the sleep() method for making a thread pause for a specific period of time." }, { "code": null, "e": 12721, "s": 11914, "text": "using System;\nusing System.Threading;\n\nnamespace MultithreadingApplication {\n class ThreadCreationProgram {\n public static void CallToChildThread() {\n Console.WriteLine(\"Child thread starts\");\n \n // the thread is paused for 5000 milliseconds\n int sleepfor = 5000; \n \n Console.WriteLine(\"Child Thread Paused for {0} seconds\", sleepfor / 1000);\n Thread.Sleep(sleepfor);\n Console.WriteLine(\"Child thread resumes\");\n }\n \n static void Main(string[] args) {\n ThreadStart childref = new ThreadStart(CallToChildThread);\n Console.WriteLine(\"In Main: Creating the Child thread\");\n \n Thread childThread = new Thread(childref);\n childThread.Start();\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 12802, "s": 12721, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 12913, "s": 12802, "text": "In Main: Creating the Child thread\nChild thread starts\nChild Thread Paused for 5 seconds\nChild thread resumes\n" }, { "code": null, "e": 12964, "s": 12913, "text": "The Abort() method is used for destroying threads." }, { "code": null, "e": 13113, "s": 12964, "text": "The runtime aborts the thread by throwing a ThreadAbortException. This exception cannot be caught, the control is sent to the finally block, if any." }, { "code": null, "e": 13154, "s": 13113, "text": "The following program illustrates this −" }, { "code": null, "e": 14417, "s": 13154, "text": "using System;\nusing System.Threading;\n\nnamespace MultithreadingApplication {\n class ThreadCreationProgram {\n public static void CallToChildThread() {\n try {\n Console.WriteLine(\"Child thread starts\");\n \n // do some work, like counting to 10\n for (int counter = 0; counter <= 10; counter++) {\n Thread.Sleep(500);\n Console.WriteLine(counter);\n }\n \n Console.WriteLine(\"Child Thread Completed\");\n } catch (ThreadAbortException e) {\n Console.WriteLine(\"Thread Abort Exception\");\n } finally {\n Console.WriteLine(\"Couldn't catch the Thread Exception\");\n }\n }\n static void Main(string[] args) {\n ThreadStart childref = new ThreadStart(CallToChildThread);\n Console.WriteLine(\"In Main: Creating the Child thread\");\n \n Thread childThread = new Thread(childref);\n childThread.Start();\n \n //stop the main thread for some time\n Thread.Sleep(2000);\n \n //now abort the child\n Console.WriteLine(\"In Main: Aborting the Child thread\");\n \n childThread.Abort();\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 14498, "s": 14417, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 14655, "s": 14498, "text": "In Main: Creating the Child thread\nChild thread starts\n0\n1\n2\nIn Main: Aborting the Child thread\nThread Abort Exception\nCouldn't catch the Thread Exception \n" }, { "code": null, "e": 14692, "s": 14655, "text": "\n 119 Lectures \n 23.5 hours \n" }, { "code": null, "e": 14705, "s": 14692, "text": " Raja Biswas" }, { "code": null, "e": 14739, "s": 14705, "text": "\n 37 Lectures \n 13 hours \n" }, { "code": null, "e": 14757, "s": 14739, "text": " Trevoir Williams" }, { "code": null, "e": 14790, "s": 14757, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 14804, "s": 14790, "text": " Peter Jepson" }, { "code": null, "e": 14841, "s": 14804, "text": "\n 159 Lectures \n 21.5 hours \n" }, { "code": null, "e": 14856, "s": 14841, "text": " Ebenezer Ogbu" }, { "code": null, "e": 14891, "s": 14856, "text": "\n 193 Lectures \n 17 hours \n" }, { "code": null, "e": 14906, "s": 14891, "text": " Arnold Higuit" }, { "code": null, "e": 14941, "s": 14906, "text": "\n 24 Lectures \n 2.5 hours \n" }, { "code": null, "e": 14953, "s": 14941, "text": " Eric Frick" }, { "code": null, "e": 14960, "s": 14953, "text": " Print" }, { "code": null, "e": 14971, "s": 14960, "text": " Add Notes" } ]
D3.js selection.node() Function - GeeksforGeeks
21 Dec, 2021 The selection.node() function in D3.js is used to return the first element in the selection. If the selection does not contain any elements then it returns null. Syntax: selection.node() Parameters: This function does not accept any parameters. Return Values: This function returns the first element in the selection. Example 1: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" path1tent= "width=device-width,initial-scale=1.0"> <script src="https://d3js.org/d3.v4.min.js"> </script> <script src= "https://d3js.org/d3-selection.v1.min.js"> </script></head> <body> <h2>Some text</h2> <div>Geeks for Geeks </div> <script> let selection = d3.selectAll("div") let div = selection.node(); console.log(div) // Printing innerHTML of the tag console.log(div.innerHTML) selection = d3.selectAll("h1") // Null is returned console.log(selection.node()) </script></body> </html> Example 2: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" path1tent= "width=device-width,initial-scale=1.0"> <script src="https://d3js.org/d3.v4.min.js"> </script> <script src= "https://d3js.org/d3-selection.v1.min.js"> </script></head> <body> <div>Some text</div> <div>Geeks for <div>geeks</div> </div> <div>Geeks <div></div> for geeks</div> <div>Some text</div> <script> let selection = d3.selectAll("div") console.log(selection.node()) selection = d3.selectAll("h2") // Null is returned console.log(selection.node()) </script></body> </html> Output: kapoorsagar226 D3.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to get character array from string in JavaScript? How to filter object array based on attributes? Remove elements from a JavaScript Array Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25300, "s": 25272, "text": "\n21 Dec, 2021" }, { "code": null, "e": 25463, "s": 25300, "text": "The selection.node() function in D3.js is used to return the first element in the selection. If the selection does not contain any elements then it returns null. " }, { "code": null, "e": 25471, "s": 25463, "text": "Syntax:" }, { "code": null, "e": 25488, "s": 25471, "text": "selection.node()" }, { "code": null, "e": 25546, "s": 25488, "text": "Parameters: This function does not accept any parameters." }, { "code": null, "e": 25619, "s": 25546, "text": "Return Values: This function returns the first element in the selection." }, { "code": null, "e": 25630, "s": 25619, "text": "Example 1:" }, { "code": null, "e": 25635, "s": 25630, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" path1tent= \"width=device-width,initial-scale=1.0\"> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <script src= \"https://d3js.org/d3-selection.v1.min.js\"> </script></head> <body> <h2>Some text</h2> <div>Geeks for Geeks </div> <script> let selection = d3.selectAll(\"div\") let div = selection.node(); console.log(div) // Printing innerHTML of the tag console.log(div.innerHTML) selection = d3.selectAll(\"h1\") // Null is returned console.log(selection.node()) </script></body> </html>", "e": 26321, "s": 25635, "text": null }, { "code": null, "e": 26332, "s": 26321, "text": "Example 2:" }, { "code": null, "e": 26337, "s": 26332, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" path1tent= \"width=device-width,initial-scale=1.0\"> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <script src= \"https://d3js.org/d3-selection.v1.min.js\"> </script></head> <body> <div>Some text</div> <div>Geeks for <div>geeks</div> </div> <div>Geeks <div></div> for geeks</div> <div>Some text</div> <script> let selection = d3.selectAll(\"div\") console.log(selection.node()) selection = d3.selectAll(\"h2\") // Null is returned console.log(selection.node()) </script></body> </html>", "e": 26999, "s": 26337, "text": null }, { "code": null, "e": 27007, "s": 26999, "text": "Output:" }, { "code": null, "e": 27022, "s": 27007, "text": "kapoorsagar226" }, { "code": null, "e": 27028, "s": 27022, "text": "D3.js" }, { "code": null, "e": 27039, "s": 27028, "text": "JavaScript" }, { "code": null, "e": 27056, "s": 27039, "text": "Web Technologies" }, { "code": null, "e": 27154, "s": 27056, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27215, "s": 27154, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27256, "s": 27215, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27310, "s": 27256, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 27358, "s": 27310, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 27398, "s": 27358, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27440, "s": 27398, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27473, "s": 27440, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27516, "s": 27473, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27578, "s": 27516, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Reading and writing files from/to Amazon S3 with Pandas | by Onel Harrison | Feb, 2021 | Towards Data Science
Write pandas data frame to CSV file on S3 > Using boto3 > Using s3fs-supported pandas API Read a CSV file on S3 into a pandas data frame > Using boto3 > Using s3fs-supported pandas API Summary There is an outstanding issue regarding dependency resolution when both boto3 and s3fs are specified as dependencies in a project. See this GitHub issue if you’re interested in the details. This is still an issue as of 2021–02–19. If you need both packages (e.g. to run the following examples in the same environment, or more generally to use s3fs for convenient pandas-to-S3 interactions and boto3 for other programmatic interactions with AWS), you will need to pin your s3fs to version “≤0.4” as a workaround (thanks Martin Campbell). To follow along, you’ll need to install the following Python packages boto3 s3fs (version ≤0.4) pandas python -m pip install boto3 pandas "s3fs<=0.4" 💭 You will notice that while we need to import boto3 and pandas in the following examples, we do not need to import s3fs despite needing to install the package. The reason is that we directly use boto3 and pandas in our code, but we won’t use the s3fs directly. Still, pandas needs it to connect with Amazon S3 under-the-hood. pandas now uses s3fs for handling S3 connections. This shouldn’t break any code. However, since s3fs is not a required dependency, you will need to install it separately, like boto in prior versions of pandas. (GH11915). Release notes for pandas version 0.20.1 You may want to use boto3 if you are using pandas in an environment where boto3 is already available and you have to interact with other AWS services too. However, using boto3 requires slightly more code, and makes use of the io.StringIO (“an in-memory stream for text I/O”) and Python’s context manager (the with statement). Those are two additional things you may not have already known about, or wanted to learn or think about to “simply” read/write a file to Amazon S3. I do recommend learning them, though; they come up fairly often, especially the with statement. But, pandas accommodates those of us who “simply” want to read and write files from/to Amazon S3 by using s3fs under-the-hood to do just that, with code that even novice pandas users would find familiar. aws_credentials = { "key": "***", "secret": "***", "token": "***" }df = pd.read_csv("s3://...", storage_options=aws_credientials) or aws_credentials = { "key": "***", "secret": "***", "token": "***" }df.to_csv("s3://...", index=False, storage_options=aws_credentials) Thank you for reading! 4 Cute Python Functions for Working with Dirty Data Improving Code Quality in Python Codebases How to recursively reverse a linked list Watch videos covering a variety of topics in Computing at OnelTalksTech.com
[ { "code": null, "e": 214, "s": 172, "text": "Write pandas data frame to CSV file on S3" }, { "code": null, "e": 228, "s": 214, "text": "> Using boto3" }, { "code": null, "e": 262, "s": 228, "text": "> Using s3fs-supported pandas API" }, { "code": null, "e": 309, "s": 262, "text": "Read a CSV file on S3 into a pandas data frame" }, { "code": null, "e": 323, "s": 309, "text": "> Using boto3" }, { "code": null, "e": 357, "s": 323, "text": "> Using s3fs-supported pandas API" }, { "code": null, "e": 365, "s": 357, "text": "Summary" }, { "code": null, "e": 555, "s": 365, "text": "There is an outstanding issue regarding dependency resolution when both boto3 and s3fs are specified as dependencies in a project. See this GitHub issue if you’re interested in the details." }, { "code": null, "e": 596, "s": 555, "text": "This is still an issue as of 2021–02–19." }, { "code": null, "e": 902, "s": 596, "text": "If you need both packages (e.g. to run the following examples in the same environment, or more generally to use s3fs for convenient pandas-to-S3 interactions and boto3 for other programmatic interactions with AWS), you will need to pin your s3fs to version “≤0.4” as a workaround (thanks Martin Campbell)." }, { "code": null, "e": 972, "s": 902, "text": "To follow along, you’ll need to install the following Python packages" }, { "code": null, "e": 978, "s": 972, "text": "boto3" }, { "code": null, "e": 998, "s": 978, "text": "s3fs (version ≤0.4)" }, { "code": null, "e": 1005, "s": 998, "text": "pandas" }, { "code": null, "e": 1052, "s": 1005, "text": "python -m pip install boto3 pandas \"s3fs<=0.4\"" }, { "code": null, "e": 1379, "s": 1052, "text": "💭 You will notice that while we need to import boto3 and pandas in the following examples, we do not need to import s3fs despite needing to install the package. The reason is that we directly use boto3 and pandas in our code, but we won’t use the s3fs directly. Still, pandas needs it to connect with Amazon S3 under-the-hood." }, { "code": null, "e": 1600, "s": 1379, "text": "pandas now uses s3fs for handling S3 connections. This shouldn’t break any code. However, since s3fs is not a required dependency, you will need to install it separately, like boto in prior versions of pandas. (GH11915)." }, { "code": null, "e": 1640, "s": 1600, "text": "Release notes for pandas version 0.20.1" }, { "code": null, "e": 1795, "s": 1640, "text": "You may want to use boto3 if you are using pandas in an environment where boto3 is already available and you have to interact with other AWS services too." }, { "code": null, "e": 2114, "s": 1795, "text": "However, using boto3 requires slightly more code, and makes use of the io.StringIO (“an in-memory stream for text I/O”) and Python’s context manager (the with statement). Those are two additional things you may not have already known about, or wanted to learn or think about to “simply” read/write a file to Amazon S3." }, { "code": null, "e": 2414, "s": 2114, "text": "I do recommend learning them, though; they come up fairly often, especially the with statement. But, pandas accommodates those of us who “simply” want to read and write files from/to Amazon S3 by using s3fs under-the-hood to do just that, with code that even novice pandas users would find familiar." }, { "code": null, "e": 2544, "s": 2414, "text": "aws_credentials = { \"key\": \"***\", \"secret\": \"***\", \"token\": \"***\" }df = pd.read_csv(\"s3://...\", storage_options=aws_credientials)" }, { "code": null, "e": 2547, "s": 2544, "text": "or" }, { "code": null, "e": 2682, "s": 2547, "text": "aws_credentials = { \"key\": \"***\", \"secret\": \"***\", \"token\": \"***\" }df.to_csv(\"s3://...\", index=False, storage_options=aws_credentials)" }, { "code": null, "e": 2705, "s": 2682, "text": "Thank you for reading!" }, { "code": null, "e": 2757, "s": 2705, "text": "4 Cute Python Functions for Working with Dirty Data" }, { "code": null, "e": 2800, "s": 2757, "text": "Improving Code Quality in Python Codebases" }, { "code": null, "e": 2841, "s": 2800, "text": "How to recursively reverse a linked list" } ]
GATE | GATE-CS-2015 (Set 3) | Question 65 - GeeksforGeeks
28 Jun, 2021 Consider three software items: Program-X, Control Flow Diagram of Program-Y and Control Flow Diagram of Program-Z as shown belowThe values of McCabe’s Cyclomatic complexity of Program-X, Program-Y and Program-Z respectively are(A) 4, 4, 7(B) 3, 4, 7(C) 4, 4, 8(D) 4, 3, 8Answer: (A)Explanation: The cyclomatic complexity of a structured program[a] is defined with reference to the control flow graph of the program, a directed graph containing the basic blocks of the program, with an edge between two basic blocks if control may pass from the first to the second. The complexity M is then defined as. M = E − N + 2P, where E = the number of edges of the graph. N = the number of nodes of the graph. P = the number of connected components. Source: http://en.wikipedia.org/wiki/Cyclomatic_complexity For first program X, E = 11, N = 9, P = 1, So M = 11-9+2*1 = 4 For second program Y, E = 10, N = 8, p = 1, So M = 10-8+2*1 = 4 For Third program X, E = 22, N = 17, p = 1, So M = 22-17+2*1 = 7 Quiz of this Question GATE-CS-2015 (Set 3) GATE-GATE-CS-2015 (Set 3) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE CS 2019 | Question 27 GATE | GATE-IT-2004 | Question 66 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2006 | Question 49 GATE | GATE-CS-2004 | Question 3 GATE | GATE-CS-2017 (Set 2) | Question 42 GATE | GATE CS 2010 | Question 24 GATE | GATE-CS-2000 | Question 43 GATE | GATE CS 2021 | Set 1 | Question 47
[ { "code": null, "e": 24516, "s": 24488, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24811, "s": 24516, "text": "Consider three software items: Program-X, Control Flow Diagram of Program-Y and Control Flow Diagram of Program-Z as shown belowThe values of McCabe’s Cyclomatic complexity of Program-X, Program-Y and Program-Z respectively are(A) 4, 4, 7(B) 3, 4, 7(C) 4, 4, 8(D) 4, 3, 8Answer: (A)Explanation:" }, { "code": null, "e": 25532, "s": 24811, "text": "The cyclomatic complexity of a structured program[a] is defined\nwith reference to the control flow graph of the program, a directed\ngraph containing the basic blocks of the program, with an edge \nbetween two basic blocks if control may pass from the first to the\nsecond. The complexity M is then defined as.\n\n M = E − N + 2P,\n\nwhere\n\n E = the number of edges of the graph.\n N = the number of nodes of the graph.\n P = the number of connected components. \n\nSource: http://en.wikipedia.org/wiki/Cyclomatic_complexity\n\n\nFor first program X, E = 11, N = 9, P = 1, So M = 11-9+2*1 = 4\nFor second program Y, E = 10, N = 8, p = 1, So M = 10-8+2*1 = 4\nFor Third program X, E = 22, N = 17, p = 1, So M = 22-17+2*1 = 7" }, { "code": null, "e": 25554, "s": 25532, "text": "Quiz of this Question" }, { "code": null, "e": 25575, "s": 25554, "text": "GATE-CS-2015 (Set 3)" }, { "code": null, "e": 25601, "s": 25575, "text": "GATE-GATE-CS-2015 (Set 3)" }, { "code": null, "e": 25606, "s": 25601, "text": "GATE" }, { "code": null, "e": 25704, "s": 25606, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25738, "s": 25704, "text": "GATE | GATE CS 2019 | Question 27" }, { "code": null, "e": 25772, "s": 25738, "text": "GATE | GATE-IT-2004 | Question 66" }, { "code": null, "e": 25814, "s": 25772, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 25856, "s": 25814, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 25890, "s": 25856, "text": "GATE | GATE-CS-2006 | Question 49" }, { "code": null, "e": 25923, "s": 25890, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 25965, "s": 25923, "text": "GATE | GATE-CS-2017 (Set 2) | Question 42" }, { "code": null, "e": 25999, "s": 25965, "text": "GATE | GATE CS 2010 | Question 24" }, { "code": null, "e": 26033, "s": 25999, "text": "GATE | GATE-CS-2000 | Question 43" } ]
Stylized Facts. What does it take to predict the future... | by Ke Gui | Towards Data Science
Warning: There is no magical formula or Holy Grail here, though a new world might open the door for you. Identifying OutliersIdentifying Outliers — Part TwoIdentifying Outliers — Part ThreeStylized FactsFeature Engineering & Feature SelectionData TransformationFractionally Differentiated FeaturesData LabellingMeta-labeling and Stacking Identifying Outliers Identifying Outliers — Part Two Identifying Outliers — Part Three Stylized Facts Feature Engineering & Feature Selection Data Transformation Fractionally Differentiated Features Data Labelling Meta-labeling and Stacking We always say “let the data speak for themselves”. But data can either shout loud or whispering low. Some data properties are easy to spot, while others are not so obvious and buried in the noise. Like a whisper in your ear, you got to work hard to figure out what they say. Once you reveal the hidden message from data, in some circumstance you may have a chance to predict the future by looking for statistical patterns in currently available data that you believe will continue into the future. In other words, figure out a way in which the future will look very much like the present, only longer. The purpose of this article is to show you how to get those properties from data usually unnoticed but useful. Before we start, let’s take one minute to think about a simple question of how much information we can draw from a giving set of randomly generated data. Most people probably can give a long list, like max, min, mean, mode, median, variance, standard deviation, range, etc.. Human brain can think abstractly and no other animals can do. Those are the reasons why statistics is useful because it can convert data into information that is meaningful to people. What is more, that deducted information can be utilized to extrapolate some empirical finding, so-called stylized empirical facts in finance. The definition of stylized facts from reference 1 at the end of this article says: “the seemingly random variations of asset prices do share some quite nontrivial statistical properties. Such properties, common across a wide range of instruments, markets and time periods are called stylized empirical facts.” In plain language, it pretty much says if you want to use the past data to predict the future, the data in the future get to have something in common with the data in the past. Otherwise, nothing makes sense. So, these common patterns from the past and in the future in the data are called stylized facts. There is a wide range set of stylized facts in financial assets as well explained in the reference1. With stylized facts in mind, comes another concept, stationary. For times series data, a stationary time series is one whose statistical properties such as mean, variance, autocorrelation, etc. are all constant over time. Most statistical forecasting methods are based on the assumption that the time series can be rendered approximately stationary through the use of mathematical transformations. The predictions for the stationarized series can then be “untransformed,” by reversing whatever mathematical transformations were previously used, to obtain predictions for the original series. Ok, that is enough talking of “stylized facts” and “stationary”, let’s do some coding to illustrate those two concepts. For consistency, in all the 📈Python for finance series, I will try to reuse the same data as much as I can. More details about data preparation can be found here, here and here. #import all the librariesimport pandas as pdimport numpy as npimport seaborn as sns import scipy.stats as scsimport yfinance as yf #the stock data from Yahoo Financeimport matplotlib.pyplot as plt #set the parameters for plottingplt.style.use('seaborn')plt.rcParams['figure.dpi'] = 300df = yf.download('AAPL', start = '2000-01-01', end= '2010-12-31') #download Apple stock priced1 = pd.DataFrame(df['Adj Close'])#create a df with only stock priced1.rename(columns={'Adj Close':'adj_close'}, inplace=True)d1['simple_rtn']=d1.adj_close.pct_change()#percentage returnd1['log_rtn'] = np.log(d1.adj_close/d1.adj_close.shift(1))#log return with 1 day lagd1.head() One more thing I want to wrangle the data is to remove the outliers, I use simple mean and 2 times of standard deviation to set the boundary. #get mean and stdmu = d1.describe().loc['mean', 'log_rtn']sigma = d1.describe().loc['std', 'log_rtn']condition = (d1['log_rtn'] > mu + sigma * 2) | (d1['log_rtn'] < mu - sigma * 2) #set the condition to be 2 times of std around meand1['outliers'] = np.where(condition, 1, 0)#like an if, else d1.head() then, I remove all the outliers. #using pd's bool selection to remove outliersd1_removed_outliers = d1.loc[d1['outliers'] == 0].iloc[:, :-1]d1_removed_outliers.head() d1_removed_outliers.info() As you can see, there are 2667 data points left out of 2765. For convenience, let’s use the d1 as the DataFrame name again. d1 = d1_removed_outliers Again, all the details of how to remove outliers can be found here, here and here. The difference between the log return and simple percentage return can be found here. In short, small changes in the natural log of a variable are directly interpretable as percentage changes. In another word, percentage changes and natural log change are almost exactly the same as long as the change is small enough(within the range +/- 5%). Indeed, the number in simple_rtn and log_rtn are very close as shown in the table above. We can check the correlation of simple_rtn and log_rtn, #calculate the pearson correlationd1[['simple_rtn', 'log_rtn']].corr() These two returns are highly correlated. It is even clear from the heatmap: #draw heatmap with seabornecmap = sns.diverging_palette(220, 20, as_cmap=True)ax = sns.heatmap(corr, annot=True, cmap=cmap, square=True, linewidths=3, linecolor='w')ax.set_title('Autocorrelation Plots', fontsize=26)sns.set(font_scale=2); One nice thing about Pandas is that it is very easy to get those descriptive statistics straight away. d1.describe().round(4) One of the most discussed stylized facts is the normal (Gaussian) distribution of returns. A large number of important financial models rest on the assumption that returns of stocks are normally distributed, which you will see at the end of this article, may not be the case. Therefore, the normal distribution can be considered one of the most important distribution in finance and one of the major statistical building blocks of many financial theories. Let’s have a look at the normality of adjusted price, percentage return and natural logarithm return. First, we define a function to extract the descriptive statistics from d1.describe() #extract all the stats from describe() functiondef extract_data_stats(col): d_stat = col.describe() mu = d_stat['mean'] sigma = d_stat['std'] rtn_range = np.linspace(d_stat['min'], d_stat['max'], num=1000) norm_pdf = scs.norm.pdf(rtn_range, loc=mu, scale=sigma) return mu, sigma, rtn_range, norm_pdf With the mean, standard deviation and normal Probability Density Function (PDF) ready, we can plot the histogram and PDF. #draw the histogram with Probability Density Functiondef draw_hist(col, xlim=(-0.2, 0.2)): mu, sigma, rtn_range, norm_pdf = extract_data_stats(col) sns.distplot(col, kde=True, norm_hist=True, label='Hist') plt.plot(rtn_range, norm_pdf, 'r', lw=3, label=f'N({mu:.3f}, {sigma**2:.4f})') plt.axvline(x=0, c='c',linestyle='--', lw=3) plt.title(f'Distribution of {col.name}', fontsize=24) plt.xlim(xlim) plt.legend(loc='upper right', fontsize=20, frameon=True,fancybox=True, framealpha=1, shadow=True, borderpad=1); The histogram and PDF of percentage return. draw_hist(d1.simple_rtn) The histogram and PDF of natural logarithm return. draw_hist(d1.log_rtn) The histogram and PDF of adjusted price. draw_hist(d1.adj_close,xlim=(-10,50)) Clearly, the stock price has trend or cycles which cause it far from a normal distribution. Whereas, the log return and percentage return are very similar and close to normal. But can the normality be tested? In case your plot may look different, here are the matplotlib parameters I used: plt.rcParams['figure.figsize'] = [16, 9]plt.rcParams['figure.dpi'] = 300plt.rcParams['font.size'] = 20plt.rcParams['axes.labelsize'] = 20plt.rcParams['axes.titlesize'] = 24plt.rcParams['xtick.labelsize'] = 16plt.rcParams['ytick.labelsize'] = 16plt.rcParams['font.family'] = 'serif' more about matplotlib, please go to 👉Everything about plotting in Python. There is one stylized fact from reference1 at the end of the article related to the normality, which says: “4. Aggregational Gaussianity: as one increases the time scale over which returns are calculated, their distribution looks more and more like a normal distribution. In particular, the shape of the distribution is not the same at different time scales.” Let’s see does this hold water. We create a new DataFrame to hold all the lagged stock price returns. #get 5 days lagged return by a for loopdf_simple_rtn = pd.DataFrame(d1['adj_close'])lags = 5for lag in range(1, lags+1): col = f'lag_{lag}_simple_rtn' df_simple_rtn[col] = df_simple_rtn['adj_close']. \ pct_change(periods=lag) df_simple_rtn.dropna(inplace=True)df_simple_rtn.head() #get 5 days lagged return by a for loopdf_log_rtn = pd.DataFrame(d1['adj_close'])lags = 5for lag in range(1, lags+1): col = f'lag_{lag}_log_rtn' df_log_rtn[col] = np.log(df_log_rtn['adj_close']/\ df_log_rtn['adj_close'].shift(lag)) df_log_rtn.dropna(inplace=True)df_log_rtn.head() we can plot the histogram and PDF by modifying the previous function draw_hist()to give it extra ability to draw multiple plots at once. #using ax to draw multi-grahpsdef draw_hist_multi(col, xlim=(-0.2, 0.2), ax=None): mu, sigma, rtn_range, norm_pdf = extract_data_stats(col) sns.distplot(col, kde=True, norm_hist=True, \ label='Hist', ax=ax) ax.plot(rtn_range, norm_pdf, 'r', lw=3, \ label=f'N({mu:.3f}, {sigma**2:.4f})') ax.axvline(x=0, c='c',linestyle='--', lw=3) #adj_close x axis range is wider if ( col.name == 'adj_close'): ax.set_xlim(-10,50) else: ax.set_xlim(xlim) ax.legend(loc='upper right', fontsize=8, frameon=True,fancybox=True); You may notice here, I use ax instead of plt to draw the plots, the reason is well explained in 👉Everything about plotting in Python. Now we can put all plots in a single figure with 2 X 3 subplots. #create subplots figure with each plot drawed by draw_hist_multi() def draw_hist_subplots(df): fig, axs = plt.subplots(nrows=2, ncols=3, figsize=(16,9)) fig.subplots_adjust(hspace = .5) #wspace=.001 fig.suptitle('Distribution of returns with increased \ time scale', fontsize=24) axs = axs.ravel() for i, col in enumerate(df.columns): draw_hist_multi(df[col], ax=axs[i]) The key to draw multi-subplots in a loop is to use axs = axs.ravel(), by flatting out the subplots matrix, we can go through all the subplots one by one. draw_hist_subplots(df_simple_rtn) In terms of natural logarithm return, as expected, there is no obvious difference. draw_hist_subplots(df_log_rtn) From both lagged log and percentage returns, indeed, as one increases the time scale over which returns are calculated, their distribution looks more and more like a normal distribution. In particular, the shape of the distribution is not the same at different time scales. From the graphs above, it is actually hard to tell the normality, even though the trend is obvious. By utilizing the scipy.stats package, we can do a more rigorous normality test with descriptive statistics. Before we start to do the normality test, there are two concepts we need to know. Skewness, in statistics, is the degree of distortion from the symmetrical bell curve in a probability distribution. Whereas The kurtosis is to measure the peakiness and flatness of a distribution. High kurtosis and skewness of the return distribution imply that the investor will experience occasional extreme returns (either positive or negative). For normally distributed data, the skewness should be about zero. A skewness value greater than zero means that there is more weight in the right tail of the distribution, vice versa. #using DataFrame to contain all the statsdef build_stats(df): stats = pd.DataFrame({'skew':scs.skew(df), 'skew_test':scs.skewtest(df)[1], 'kurtosis': scs.kurtosis(df), 'kurtosis_test' : scs.kurtosistest(df)[1], 'normal_test' : scs.normaltest(df)[1]}, index = df.columns) return stats for percentage return build_stats(df_simple_rtn) for log return build_stats(df_log_rtn) All p-values are well below 0.05 mark and close to zero. A statistically significant test result ( p-value ≤ 0.05) means that the test hypothesis is false or should be rejected. A p-value is greater than 0.05 means that no effect was observed. With a p-value of zero, we have to reject the null hypothesis that the return of sample data has skewness and kurtosis matching those of a Gaussian distribution. One thing I noticed is that the absolute value of skewness and kurtosis of log return actually larger than those of percentage return. After removed outliers, the mean is getting larger, the standard deviation is getting smaller and there is no change for skewness and kurtosis. Before the end of this article, I want to have a quick look at the correlation of lagged returns, as claimed in reference1 down below. “1. Absence of autocorrelations: (linear) autocorrelation of asset returns are often insignificant, except for very small intraday time scales (20 minutes) for which microstructure effects come into play.” In terms of correlations, there are 3 different types, cross-correlation, autocorrelation and circus-correlation. The cross-correlation of percentage returns are corr_s = df_simple_rtn.corr()corr_s and correlation of log return corr_l = df_log_rtn.corr()corr_l The cross-correlations are trailing off with time for both percentage returns and log returns. As illustrated in the heatmap. #using seaborne to draw heatmapsns.set(style="white")cmap = sns.diverging_palette(220, 20, as_cmap=True)ax = sns.heatmap(corr_s, annot=True, cmap=cmap, square=True, linewidths=3, linecolor='w')ax.set_title('Correlation Plots', fontsize=32)ax.set_xticklabels( ax.get_xticklabels(), rotation=45, horizontalalignment='right'); #using seaborne to draw heatmapsns.set(style="white")cmap = sns.diverging_palette(220, 20, as_cmap=True)ax = sns.heatmap(corr_l, annot=True, cmap=cmap, square=True, linewidths=3, linecolor='w')ax.set_title('Correlation Plots', fontsize=32)ax.set_xticklabels( ax.get_xticklabels(), rotation=45, horizontalalignment='right'); Most of the correlation of return for a day lag (before or after) are correlated as their coefficiency are over 0.8. But the correlation fades away very quickly. I am still having trouble to fully understand autocorrelation, even though to plot the autocorrelation is very easy. #draw autocorrelation for log return with 50 days time lagfrom statsmodels.graphics.tsaplots import plot_acffig, ax = plt.subplots()acf = plot_acf(d1.log_rtn, lags=50, ax=ax) ax.set_xlabel('lags') ax.set_ylabel('auto-correlation'); I would really appreciate it if you could shed some light on the auto-correlation, cross-correlation and partial auto-correlation and leave your comments below, thanks. There is one big question now, how to transfer your return to a normal distribution? Stay tuned for more, coming soon! Cont, R., Empirical properties of asset returns: stylized facts and statistical issues. Quantitative Finance 2001, 1 (2), 223–236. Cont, R., Empirical properties of asset returns: stylized facts and statistical issues. Quantitative Finance 2001, 1 (2), 223–236.
[ { "code": null, "e": 277, "s": 172, "text": "Warning: There is no magical formula or Holy Grail here, though a new world might open the door for you." }, { "code": null, "e": 510, "s": 277, "text": "Identifying OutliersIdentifying Outliers — Part TwoIdentifying Outliers — Part ThreeStylized FactsFeature Engineering & Feature SelectionData TransformationFractionally Differentiated FeaturesData LabellingMeta-labeling and Stacking" }, { "code": null, "e": 531, "s": 510, "text": "Identifying Outliers" }, { "code": null, "e": 563, "s": 531, "text": "Identifying Outliers — Part Two" }, { "code": null, "e": 597, "s": 563, "text": "Identifying Outliers — Part Three" }, { "code": null, "e": 612, "s": 597, "text": "Stylized Facts" }, { "code": null, "e": 652, "s": 612, "text": "Feature Engineering & Feature Selection" }, { "code": null, "e": 672, "s": 652, "text": "Data Transformation" }, { "code": null, "e": 709, "s": 672, "text": "Fractionally Differentiated Features" }, { "code": null, "e": 724, "s": 709, "text": "Data Labelling" }, { "code": null, "e": 751, "s": 724, "text": "Meta-labeling and Stacking" }, { "code": null, "e": 1464, "s": 751, "text": "We always say “let the data speak for themselves”. But data can either shout loud or whispering low. Some data properties are easy to spot, while others are not so obvious and buried in the noise. Like a whisper in your ear, you got to work hard to figure out what they say. Once you reveal the hidden message from data, in some circumstance you may have a chance to predict the future by looking for statistical patterns in currently available data that you believe will continue into the future. In other words, figure out a way in which the future will look very much like the present, only longer. The purpose of this article is to show you how to get those properties from data usually unnoticed but useful." }, { "code": null, "e": 2065, "s": 1464, "text": "Before we start, let’s take one minute to think about a simple question of how much information we can draw from a giving set of randomly generated data. Most people probably can give a long list, like max, min, mean, mode, median, variance, standard deviation, range, etc.. Human brain can think abstractly and no other animals can do. Those are the reasons why statistics is useful because it can convert data into information that is meaningful to people. What is more, that deducted information can be utilized to extrapolate some empirical finding, so-called stylized empirical facts in finance." }, { "code": null, "e": 2148, "s": 2065, "text": "The definition of stylized facts from reference 1 at the end of this article says:" }, { "code": null, "e": 2375, "s": 2148, "text": "“the seemingly random variations of asset prices do share some quite nontrivial statistical properties. Such properties, common across a wide range of instruments, markets and time periods are called stylized empirical facts.”" }, { "code": null, "e": 2782, "s": 2375, "text": "In plain language, it pretty much says if you want to use the past data to predict the future, the data in the future get to have something in common with the data in the past. Otherwise, nothing makes sense. So, these common patterns from the past and in the future in the data are called stylized facts. There is a wide range set of stylized facts in financial assets as well explained in the reference1." }, { "code": null, "e": 3374, "s": 2782, "text": "With stylized facts in mind, comes another concept, stationary. For times series data, a stationary time series is one whose statistical properties such as mean, variance, autocorrelation, etc. are all constant over time. Most statistical forecasting methods are based on the assumption that the time series can be rendered approximately stationary through the use of mathematical transformations. The predictions for the stationarized series can then be “untransformed,” by reversing whatever mathematical transformations were previously used, to obtain predictions for the original series." }, { "code": null, "e": 3494, "s": 3374, "text": "Ok, that is enough talking of “stylized facts” and “stationary”, let’s do some coding to illustrate those two concepts." }, { "code": null, "e": 3672, "s": 3494, "text": "For consistency, in all the 📈Python for finance series, I will try to reuse the same data as much as I can. More details about data preparation can be found here, here and here." }, { "code": null, "e": 4363, "s": 3672, "text": "#import all the librariesimport pandas as pdimport numpy as npimport seaborn as sns import scipy.stats as scsimport yfinance as yf #the stock data from Yahoo Financeimport matplotlib.pyplot as plt #set the parameters for plottingplt.style.use('seaborn')plt.rcParams['figure.dpi'] = 300df = yf.download('AAPL', start = '2000-01-01', end= '2010-12-31') #download Apple stock priced1 = pd.DataFrame(df['Adj Close'])#create a df with only stock priced1.rename(columns={'Adj Close':'adj_close'}, inplace=True)d1['simple_rtn']=d1.adj_close.pct_change()#percentage returnd1['log_rtn'] = np.log(d1.adj_close/d1.adj_close.shift(1))#log return with 1 day lagd1.head()" }, { "code": null, "e": 4505, "s": 4363, "text": "One more thing I want to wrangle the data is to remove the outliers, I use simple mean and 2 times of standard deviation to set the boundary." }, { "code": null, "e": 4807, "s": 4505, "text": "#get mean and stdmu = d1.describe().loc['mean', 'log_rtn']sigma = d1.describe().loc['std', 'log_rtn']condition = (d1['log_rtn'] > mu + sigma * 2) | (d1['log_rtn'] < mu - sigma * 2) #set the condition to be 2 times of std around meand1['outliers'] = np.where(condition, 1, 0)#like an if, else d1.head()" }, { "code": null, "e": 4840, "s": 4807, "text": "then, I remove all the outliers." }, { "code": null, "e": 4974, "s": 4840, "text": "#using pd's bool selection to remove outliersd1_removed_outliers = d1.loc[d1['outliers'] == 0].iloc[:, :-1]d1_removed_outliers.head()" }, { "code": null, "e": 5001, "s": 4974, "text": "d1_removed_outliers.info()" }, { "code": null, "e": 5125, "s": 5001, "text": "As you can see, there are 2667 data points left out of 2765. For convenience, let’s use the d1 as the DataFrame name again." }, { "code": null, "e": 5150, "s": 5125, "text": "d1 = d1_removed_outliers" }, { "code": null, "e": 5233, "s": 5150, "text": "Again, all the details of how to remove outliers can be found here, here and here." }, { "code": null, "e": 5666, "s": 5233, "text": "The difference between the log return and simple percentage return can be found here. In short, small changes in the natural log of a variable are directly interpretable as percentage changes. In another word, percentage changes and natural log change are almost exactly the same as long as the change is small enough(within the range +/- 5%). Indeed, the number in simple_rtn and log_rtn are very close as shown in the table above." }, { "code": null, "e": 5722, "s": 5666, "text": "We can check the correlation of simple_rtn and log_rtn," }, { "code": null, "e": 5793, "s": 5722, "text": "#calculate the pearson correlationd1[['simple_rtn', 'log_rtn']].corr()" }, { "code": null, "e": 5869, "s": 5793, "text": "These two returns are highly correlated. It is even clear from the heatmap:" }, { "code": null, "e": 6139, "s": 5869, "text": "#draw heatmap with seabornecmap = sns.diverging_palette(220, 20, as_cmap=True)ax = sns.heatmap(corr, annot=True, cmap=cmap, square=True, linewidths=3, linecolor='w')ax.set_title('Autocorrelation Plots', fontsize=26)sns.set(font_scale=2);" }, { "code": null, "e": 6242, "s": 6139, "text": "One nice thing about Pandas is that it is very easy to get those descriptive statistics straight away." }, { "code": null, "e": 6265, "s": 6242, "text": "d1.describe().round(4)" }, { "code": null, "e": 6721, "s": 6265, "text": "One of the most discussed stylized facts is the normal (Gaussian) distribution of returns. A large number of important financial models rest on the assumption that returns of stocks are normally distributed, which you will see at the end of this article, may not be the case. Therefore, the normal distribution can be considered one of the most important distribution in finance and one of the major statistical building blocks of many financial theories." }, { "code": null, "e": 6908, "s": 6721, "text": "Let’s have a look at the normality of adjusted price, percentage return and natural logarithm return. First, we define a function to extract the descriptive statistics from d1.describe()" }, { "code": null, "e": 7230, "s": 6908, "text": "#extract all the stats from describe() functiondef extract_data_stats(col): d_stat = col.describe() mu = d_stat['mean'] sigma = d_stat['std'] rtn_range = np.linspace(d_stat['min'], d_stat['max'], num=1000) norm_pdf = scs.norm.pdf(rtn_range, loc=mu, scale=sigma) return mu, sigma, rtn_range, norm_pdf" }, { "code": null, "e": 7352, "s": 7230, "text": "With the mean, standard deviation and normal Probability Density Function (PDF) ready, we can plot the histogram and PDF." }, { "code": null, "e": 7930, "s": 7352, "text": "#draw the histogram with Probability Density Functiondef draw_hist(col, xlim=(-0.2, 0.2)): mu, sigma, rtn_range, norm_pdf = extract_data_stats(col) sns.distplot(col, kde=True, norm_hist=True, label='Hist') plt.plot(rtn_range, norm_pdf, 'r', lw=3, label=f'N({mu:.3f}, {sigma**2:.4f})') plt.axvline(x=0, c='c',linestyle='--', lw=3) plt.title(f'Distribution of {col.name}', fontsize=24) plt.xlim(xlim) plt.legend(loc='upper right', fontsize=20, frameon=True,fancybox=True, framealpha=1, shadow=True, borderpad=1);" }, { "code": null, "e": 7974, "s": 7930, "text": "The histogram and PDF of percentage return." }, { "code": null, "e": 7999, "s": 7974, "text": "draw_hist(d1.simple_rtn)" }, { "code": null, "e": 8050, "s": 7999, "text": "The histogram and PDF of natural logarithm return." }, { "code": null, "e": 8072, "s": 8050, "text": "draw_hist(d1.log_rtn)" }, { "code": null, "e": 8113, "s": 8072, "text": "The histogram and PDF of adjusted price." }, { "code": null, "e": 8151, "s": 8113, "text": "draw_hist(d1.adj_close,xlim=(-10,50))" }, { "code": null, "e": 8360, "s": 8151, "text": "Clearly, the stock price has trend or cycles which cause it far from a normal distribution. Whereas, the log return and percentage return are very similar and close to normal. But can the normality be tested?" }, { "code": null, "e": 8441, "s": 8360, "text": "In case your plot may look different, here are the matplotlib parameters I used:" }, { "code": null, "e": 8723, "s": 8441, "text": "plt.rcParams['figure.figsize'] = [16, 9]plt.rcParams['figure.dpi'] = 300plt.rcParams['font.size'] = 20plt.rcParams['axes.labelsize'] = 20plt.rcParams['axes.titlesize'] = 24plt.rcParams['xtick.labelsize'] = 16plt.rcParams['ytick.labelsize'] = 16plt.rcParams['font.family'] = 'serif'" }, { "code": null, "e": 8797, "s": 8723, "text": "more about matplotlib, please go to 👉Everything about plotting in Python." }, { "code": null, "e": 8904, "s": 8797, "text": "There is one stylized fact from reference1 at the end of the article related to the normality, which says:" }, { "code": null, "e": 9157, "s": 8904, "text": "“4. Aggregational Gaussianity: as one increases the time scale over which returns are calculated, their distribution looks more and more like a normal distribution. In particular, the shape of the distribution is not the same at different time scales.”" }, { "code": null, "e": 9259, "s": 9157, "text": "Let’s see does this hold water. We create a new DataFrame to hold all the lagged stock price returns." }, { "code": null, "e": 9573, "s": 9259, "text": "#get 5 days lagged return by a for loopdf_simple_rtn = pd.DataFrame(d1['adj_close'])lags = 5for lag in range(1, lags+1): col = f'lag_{lag}_simple_rtn' df_simple_rtn[col] = df_simple_rtn['adj_close']. \\ pct_change(periods=lag) df_simple_rtn.dropna(inplace=True)df_simple_rtn.head()" }, { "code": null, "e": 9882, "s": 9573, "text": "#get 5 days lagged return by a for loopdf_log_rtn = pd.DataFrame(d1['adj_close'])lags = 5for lag in range(1, lags+1): col = f'lag_{lag}_log_rtn' df_log_rtn[col] = np.log(df_log_rtn['adj_close']/\\ df_log_rtn['adj_close'].shift(lag)) df_log_rtn.dropna(inplace=True)df_log_rtn.head()" }, { "code": null, "e": 10019, "s": 9882, "text": "we can plot the histogram and PDF by modifying the previous function draw_hist()to give it extra ability to draw multiple plots at once." }, { "code": null, "e": 10609, "s": 10019, "text": "#using ax to draw multi-grahpsdef draw_hist_multi(col, xlim=(-0.2, 0.2), ax=None): mu, sigma, rtn_range, norm_pdf = extract_data_stats(col) sns.distplot(col, kde=True, norm_hist=True, \\ label='Hist', ax=ax) ax.plot(rtn_range, norm_pdf, 'r', lw=3, \\ label=f'N({mu:.3f}, {sigma**2:.4f})') ax.axvline(x=0, c='c',linestyle='--', lw=3) #adj_close x axis range is wider if ( col.name == 'adj_close'): ax.set_xlim(-10,50) else: ax.set_xlim(xlim) ax.legend(loc='upper right', fontsize=8, frameon=True,fancybox=True);" }, { "code": null, "e": 10743, "s": 10609, "text": "You may notice here, I use ax instead of plt to draw the plots, the reason is well explained in 👉Everything about plotting in Python." }, { "code": null, "e": 10808, "s": 10743, "text": "Now we can put all plots in a single figure with 2 X 3 subplots." }, { "code": null, "e": 11233, "s": 10808, "text": "#create subplots figure with each plot drawed by draw_hist_multi() def draw_hist_subplots(df): fig, axs = plt.subplots(nrows=2, ncols=3, figsize=(16,9)) fig.subplots_adjust(hspace = .5) #wspace=.001 fig.suptitle('Distribution of returns with increased \\ time scale', fontsize=24) axs = axs.ravel() for i, col in enumerate(df.columns): draw_hist_multi(df[col], ax=axs[i])" }, { "code": null, "e": 11387, "s": 11233, "text": "The key to draw multi-subplots in a loop is to use axs = axs.ravel(), by flatting out the subplots matrix, we can go through all the subplots one by one." }, { "code": null, "e": 11421, "s": 11387, "text": "draw_hist_subplots(df_simple_rtn)" }, { "code": null, "e": 11504, "s": 11421, "text": "In terms of natural logarithm return, as expected, there is no obvious difference." }, { "code": null, "e": 11535, "s": 11504, "text": "draw_hist_subplots(df_log_rtn)" }, { "code": null, "e": 11809, "s": 11535, "text": "From both lagged log and percentage returns, indeed, as one increases the time scale over which returns are calculated, their distribution looks more and more like a normal distribution. In particular, the shape of the distribution is not the same at different time scales." }, { "code": null, "e": 12017, "s": 11809, "text": "From the graphs above, it is actually hard to tell the normality, even though the trend is obvious. By utilizing the scipy.stats package, we can do a more rigorous normality test with descriptive statistics." }, { "code": null, "e": 12448, "s": 12017, "text": "Before we start to do the normality test, there are two concepts we need to know. Skewness, in statistics, is the degree of distortion from the symmetrical bell curve in a probability distribution. Whereas The kurtosis is to measure the peakiness and flatness of a distribution. High kurtosis and skewness of the return distribution imply that the investor will experience occasional extreme returns (either positive or negative)." }, { "code": null, "e": 12632, "s": 12448, "text": "For normally distributed data, the skewness should be about zero. A skewness value greater than zero means that there is more weight in the right tail of the distribution, vice versa." }, { "code": null, "e": 13003, "s": 12632, "text": "#using DataFrame to contain all the statsdef build_stats(df): stats = pd.DataFrame({'skew':scs.skew(df), 'skew_test':scs.skewtest(df)[1], 'kurtosis': scs.kurtosis(df), 'kurtosis_test' : scs.kurtosistest(df)[1], 'normal_test' : scs.normaltest(df)[1]}, index = df.columns) return stats" }, { "code": null, "e": 13025, "s": 13003, "text": "for percentage return" }, { "code": null, "e": 13052, "s": 13025, "text": "build_stats(df_simple_rtn)" }, { "code": null, "e": 13067, "s": 13052, "text": "for log return" }, { "code": null, "e": 13091, "s": 13067, "text": "build_stats(df_log_rtn)" }, { "code": null, "e": 13497, "s": 13091, "text": "All p-values are well below 0.05 mark and close to zero. A statistically significant test result ( p-value ≤ 0.05) means that the test hypothesis is false or should be rejected. A p-value is greater than 0.05 means that no effect was observed. With a p-value of zero, we have to reject the null hypothesis that the return of sample data has skewness and kurtosis matching those of a Gaussian distribution." }, { "code": null, "e": 13776, "s": 13497, "text": "One thing I noticed is that the absolute value of skewness and kurtosis of log return actually larger than those of percentage return. After removed outliers, the mean is getting larger, the standard deviation is getting smaller and there is no change for skewness and kurtosis." }, { "code": null, "e": 13911, "s": 13776, "text": "Before the end of this article, I want to have a quick look at the correlation of lagged returns, as claimed in reference1 down below." }, { "code": null, "e": 14117, "s": 13911, "text": "“1. Absence of autocorrelations: (linear) autocorrelation of asset returns are often insignificant, except for very small intraday time scales (20 minutes) for which microstructure effects come into play.”" }, { "code": null, "e": 14231, "s": 14117, "text": "In terms of correlations, there are 3 different types, cross-correlation, autocorrelation and circus-correlation." }, { "code": null, "e": 14279, "s": 14231, "text": "The cross-correlation of percentage returns are" }, { "code": null, "e": 14315, "s": 14279, "text": "corr_s = df_simple_rtn.corr()corr_s" }, { "code": null, "e": 14345, "s": 14315, "text": "and correlation of log return" }, { "code": null, "e": 14378, "s": 14345, "text": "corr_l = df_log_rtn.corr()corr_l" }, { "code": null, "e": 14504, "s": 14378, "text": "The cross-correlations are trailing off with time for both percentage returns and log returns. As illustrated in the heatmap." }, { "code": null, "e": 14869, "s": 14504, "text": "#using seaborne to draw heatmapsns.set(style=\"white\")cmap = sns.diverging_palette(220, 20, as_cmap=True)ax = sns.heatmap(corr_s, annot=True, cmap=cmap, square=True, linewidths=3, linecolor='w')ax.set_title('Correlation Plots', fontsize=32)ax.set_xticklabels( ax.get_xticklabels(), rotation=45, horizontalalignment='right');" }, { "code": null, "e": 15234, "s": 14869, "text": "#using seaborne to draw heatmapsns.set(style=\"white\")cmap = sns.diverging_palette(220, 20, as_cmap=True)ax = sns.heatmap(corr_l, annot=True, cmap=cmap, square=True, linewidths=3, linecolor='w')ax.set_title('Correlation Plots', fontsize=32)ax.set_xticklabels( ax.get_xticklabels(), rotation=45, horizontalalignment='right');" }, { "code": null, "e": 15396, "s": 15234, "text": "Most of the correlation of return for a day lag (before or after) are correlated as their coefficiency are over 0.8. But the correlation fades away very quickly." }, { "code": null, "e": 15513, "s": 15396, "text": "I am still having trouble to fully understand autocorrelation, even though to plot the autocorrelation is very easy." }, { "code": null, "e": 15770, "s": 15513, "text": "#draw autocorrelation for log return with 50 days time lagfrom statsmodels.graphics.tsaplots import plot_acffig, ax = plt.subplots()acf = plot_acf(d1.log_rtn, lags=50, ax=ax) ax.set_xlabel('lags') ax.set_ylabel('auto-correlation');" }, { "code": null, "e": 15939, "s": 15770, "text": "I would really appreciate it if you could shed some light on the auto-correlation, cross-correlation and partial auto-correlation and leave your comments below, thanks." }, { "code": null, "e": 16058, "s": 15939, "text": "There is one big question now, how to transfer your return to a normal distribution? Stay tuned for more, coming soon!" }, { "code": null, "e": 16189, "s": 16058, "text": "Cont, R., Empirical properties of asset returns: stylized facts and statistical issues. Quantitative Finance 2001, 1 (2), 223–236." } ]
Requests - HTTP Requests Headers
In the previous chapter, we have seen how to make the request and get the response. This chapter will explore a little more on the header section of the URL. So, we are going to look into the following − Understanding Request Headers Custom Headers Response Headers Hit any URL in the browser, inspect it and check in developer tool network tab. You will get response headers, request headers, payload, etc. For example, consider the following URL − https://jsonplaceholder.typicode.com/users You can get the header details as follows − import requests getdata = requests.get('https://jsonplaceholder.typicode.com/users', stream = True) print(getdata.headers) E:\prequests>python makeRequest.py {'Date': 'Sat, 30 Nov 2019 05:15:00 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'Set-Cookie': '__cfduid=d2b84ccf43c40e18b95122b0b49f5cf091575090900; expires=Mon, 30-De c-19 05:15:00 GMT; path=/; domain=.typicode.com; HttpOnly', 'X-Powered-By': 'Express', 'Vary': 'Origin, Accept-Encoding', 'Access-Control-Allow-Credentials': 't rue', 'Cache-Control': 'max-age=14400', 'Pragma': 'no-cache', 'Expires': '-1', ' X-Content-Type-Options': 'nosniff', 'Etag': 'W/"160d-1eMSsxeJRfnVLRBmYJSbCiJZ1qQ "', 'Content-Encoding': 'gzip', 'Via': '1.1 vegur', 'CF-Cache-Status': 'HIT', 'Age': '2271', 'Expect-CT': 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"', 'Server': 'cloudflare', 'CF-RAY': '53da574f f99fc331-SIN'} To read any http header you can do so as follows − getdata.headers["Content-Encoding"] // gzip You can also send headers to the URL being called as shown below. import requests headers = {'x-user': 'test123'} getdata = requests.get('https://jsonplaceholder.typicode.com/users', headers=headers) The headers passed has to be string, bytestring, or Unicode format. The behavior of the request will not change as per the custom headers passed. The response headers look like below when you check the URL in the browser developer tool, network tab − To get the details of the headers from the requests module use. Response.headers are as shown below − import requests getdata = requests.get('https://jsonplaceholder.typicode.com/users') print(getdata.headers) E:\prequests>python makeRequest.py {'Date': 'Sat, 30 Nov 2019 06:08:10 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'Set-Cookie': '__cfduid=de1158f1a5116f3754c2c353055694e0d1575094090; expires=Mon, 30-Dec-19 06:08:10 GMT; path=/; domain=.typicode.com; HttpOnly', 'X-Powered-By': 'Express', 'Vary': 'Origin, Accept-Encoding', 'Access-Control-Allow-Credentials': 't rue', 'Cache-Control': 'max-age=14400', 'Pragma': 'no-cache', 'Expires': '-1', ' X-Content-Type-Options': 'nosniff', 'Etag': 'W/"160d-1eMSsxeJRfnVLRBmYJSbCiJZ1qQ "', 'Content-Encoding': 'gzip', 'Via': '1.1 vegur', 'CF-Cache-Status': 'HIT', 'Age': '5461', 'Expect-CT': 'max-age=604800, report-uri="https://report-uri.cloudf lare.com/cdn-cgi/beacon/expect-ct"', 'Server': 'cloudflare', 'CF-RAY': '53daa52f 3b7ec395-SIN'} You can get any specific header you want as follows − print(getdata.headers["Expect-CT"]) max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/exp ect-ct You can also get the header details by using the get() method. print(getdata.headers.get("Expect-CT")) max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/exp ect-ct Print Add Notes Bookmark this page
[ { "code": null, "e": 2392, "s": 2188, "text": "In the previous chapter, we have seen how to make the request and get the response. This chapter will explore a little more on the header section of the URL. So, we are going to look into the following −" }, { "code": null, "e": 2422, "s": 2392, "text": "Understanding Request Headers" }, { "code": null, "e": 2437, "s": 2422, "text": "Custom Headers" }, { "code": null, "e": 2454, "s": 2437, "text": "Response Headers" }, { "code": null, "e": 2534, "s": 2454, "text": "Hit any URL in the browser, inspect it and check in developer tool network tab." }, { "code": null, "e": 2596, "s": 2534, "text": "You will get response headers, request headers, payload, etc." }, { "code": null, "e": 2638, "s": 2596, "text": "For example, consider the following URL −" }, { "code": null, "e": 2681, "s": 2638, "text": "https://jsonplaceholder.typicode.com/users" }, { "code": null, "e": 2725, "s": 2681, "text": "You can get the header details as follows −" }, { "code": null, "e": 2849, "s": 2725, "text": "import requests\ngetdata = requests.get('https://jsonplaceholder.typicode.com/users', \nstream = True)\nprint(getdata.headers)" }, { "code": null, "e": 3710, "s": 2849, "text": "E:\\prequests>python makeRequest.py\n{'Date': 'Sat, 30 Nov 2019 05:15:00 GMT', 'Content-Type': 'application/json; \ncharset=utf-8', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', \n'Set-Cookie': '__cfduid=d2b84ccf43c40e18b95122b0b49f5cf091575090900; expires=Mon, 30-De\nc-19 05:15:00 GMT; path=/; domain=.typicode.com; HttpOnly', 'X-Powered-By': \n'Express', 'Vary': 'Origin, Accept-Encoding', 'Access-Control-Allow-Credentials': 't\nrue', 'Cache-Control': 'max-age=14400', 'Pragma': 'no-cache', 'Expires': '-1', '\nX-Content-Type-Options': 'nosniff', 'Etag': 'W/\"160d-1eMSsxeJRfnVLRBmYJSbCiJZ1qQ\n\"', 'Content-Encoding': 'gzip', 'Via': '1.1 vegur', 'CF-Cache-Status': 'HIT', \n'Age': '2271', 'Expect-CT': 'max-age=604800, \nreport-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\"', 'Server': 'cloudflare', 'CF-RAY': '53da574f\nf99fc331-SIN'}\n" }, { "code": null, "e": 3761, "s": 3710, "text": "To read any http header you can do so as follows −" }, { "code": null, "e": 3806, "s": 3761, "text": "getdata.headers[\"Content-Encoding\"] // gzip\n" }, { "code": null, "e": 3872, "s": 3806, "text": "You can also send headers to the URL being called as shown below." }, { "code": null, "e": 4008, "s": 3872, "text": "import requests\nheaders = {'x-user': 'test123'}\ngetdata = requests.get('https://jsonplaceholder.typicode.com/users', \nheaders=headers)\n" }, { "code": null, "e": 4154, "s": 4008, "text": "The headers passed has to be string, bytestring, or Unicode format. The behavior of the request will not change as per the custom headers passed." }, { "code": null, "e": 4259, "s": 4154, "text": "The response headers look like below when you check the URL in the browser developer tool, network tab −" }, { "code": null, "e": 4361, "s": 4259, "text": "To get the details of the headers from the requests module use. Response.headers are as shown below −" }, { "code": null, "e": 4469, "s": 4361, "text": "import requests\ngetdata = requests.get('https://jsonplaceholder.typicode.com/users')\nprint(getdata.headers)" }, { "code": null, "e": 5329, "s": 4469, "text": "E:\\prequests>python makeRequest.py\n{'Date': 'Sat, 30 Nov 2019 06:08:10 GMT', 'Content-Type': 'application/json; \ncharset=utf-8', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', \n'Set-Cookie': '__cfduid=de1158f1a5116f3754c2c353055694e0d1575094090; expires=Mon,\n30-Dec-19 06:08:10 GMT; path=/; domain=.typicode.com; HttpOnly', 'X-Powered-By': \n'Express', 'Vary': 'Origin, Accept-Encoding', 'Access-Control-Allow-Credentials': 't\nrue', 'Cache-Control': 'max-age=14400', 'Pragma': 'no-cache', 'Expires': '-1', '\nX-Content-Type-Options': 'nosniff', 'Etag': 'W/\"160d-1eMSsxeJRfnVLRBmYJSbCiJZ1qQ\n\"', 'Content-Encoding': 'gzip', 'Via': '1.1 vegur', 'CF-Cache-Status': 'HIT', \n'Age': '5461', 'Expect-CT': 'max-age=604800, report-uri=\"https://report-uri.cloudf\nlare.com/cdn-cgi/beacon/expect-ct\"', 'Server': 'cloudflare', 'CF-RAY': '53daa52f\n3b7ec395-SIN'}\n" }, { "code": null, "e": 5383, "s": 5329, "text": "You can get any specific header you want as follows −" }, { "code": null, "e": 5420, "s": 5383, "text": "print(getdata.headers[\"Expect-CT\"])\n" }, { "code": null, "e": 5509, "s": 5420, "text": "max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/exp\nect-ct\n" }, { "code": null, "e": 5572, "s": 5509, "text": "You can also get the header details by using the get() method." }, { "code": null, "e": 5613, "s": 5572, "text": "print(getdata.headers.get(\"Expect-CT\"))\n" }, { "code": null, "e": 5702, "s": 5613, "text": "max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/exp\nect-ct\n" }, { "code": null, "e": 5709, "s": 5702, "text": " Print" }, { "code": null, "e": 5720, "s": 5709, "text": " Add Notes" } ]
Python Program for Print Number series without using any loop
In this article, we will learn about the solution to the problem statement given below − Problem statement − Given Two number N and K, our problem is to subtract a number K from N until number(N) is greater than zero(0), once the N becomes negative or zero then we start adding K to it until that number become the original number(N). For example, N = 10 K = 4 Output will be: 10 6 2 -2 2 6 10 1. we call the function again and again until N is greater than zero (in every function call we subtract K from N ). 2. Once the number becomes negative or zero we start adding K in each function call until the number becomes the original number. 3. Here we used a single function for purpose of addition and subtraction but to switch between addition or subtraction function we used a Boolean type variable flag. Now let’s observe the implementation in Python Live Demo def PrintNumber(N, Original, K, flag): #print the number print(N, end = " ") #if number become negative if (N <= 0): if(flag==0): flag = 1 else: flag = 0 if (N == Original and (not(flag))): return # if flag is true if (flag == True): PrintNumber(N - K, Original, K, flag) return if (not(flag)): PrintNumber(N + K, Original, K, flag); return N = 10 K = 4 PrintNumber(N, N, K, True) 10 6 2 -2 2 6 10 Here all variables are declared in global namespace as shown in the image below − In this article, we learned about the terminology for printing a number series without using any kind of looping construct in Python 3.x. Or earlier.
[ { "code": null, "e": 1151, "s": 1062, "text": "In this article, we will learn about the solution to the problem statement given below −" }, { "code": null, "e": 1397, "s": 1151, "text": "Problem statement − Given Two number N and K, our problem is to subtract a number K from N until number(N) is greater than zero(0), once the N becomes negative or zero then we start adding K to it until that number become the original number(N)." }, { "code": null, "e": 1410, "s": 1397, "text": "For example," }, { "code": null, "e": 1456, "s": 1410, "text": "N = 10\nK = 4\nOutput will be: 10 6 2 -2 2 6 10" }, { "code": null, "e": 1882, "s": 1456, "text": "1. we call the function again and again until N is greater than zero (in every function \n call we subtract K from N ).\n2. Once the number becomes negative or zero we start adding K in each function call \n until the number becomes the original number.\n3. Here we used a single function for purpose of addition and subtraction but to switch \n between addition or subtraction function we used a Boolean type variable flag." }, { "code": null, "e": 1929, "s": 1882, "text": "Now let’s observe the implementation in Python" }, { "code": null, "e": 1940, "s": 1929, "text": " Live Demo" }, { "code": null, "e": 2399, "s": 1940, "text": "def PrintNumber(N, Original, K, flag):\n #print the number\n print(N, end = \" \")\n #if number become negative\n if (N <= 0):\n if(flag==0):\n flag = 1\n else:\n flag = 0\n if (N == Original and (not(flag))):\n return\n # if flag is true\n if (flag == True):\n PrintNumber(N - K, Original, K, flag)\n return\n if (not(flag)):\n PrintNumber(N + K, Original, K, flag);\n return\nN = 10\nK = 4\nPrintNumber(N, N, K, True)" }, { "code": null, "e": 2416, "s": 2399, "text": "10 6 2 -2 2 6 10" }, { "code": null, "e": 2498, "s": 2416, "text": "Here all variables are declared in global namespace as shown in the image below −" }, { "code": null, "e": 2648, "s": 2498, "text": "In this article, we learned about the terminology for printing a number series without using any kind of looping construct in Python 3.x. Or earlier." } ]
Number of paths | Practice | GeeksforGeeks
The problem is to count all the possible paths from top left to bottom right of a MxN matrix with the constraints that from each cell you can either move to right or down. Example 1: Input: M = 3 and N = 3 Output: 6 Explanation: Let the given input 3*3 matrix is filled as such: A B C D E F G H I The possible paths which exists to reach 'I' from 'A' following above conditions are as follows:ABCFI, ABEHI, ADGHI, ADEFI, ADEHI, ABEFI Example 2: Input: M = 2 and N = 8 Output: 8 Your Task: You don't need to read input or print anything. Your task is to complete the function numberOfPaths() which takes the integer M and integer N as input parameters and returns the number of paths.. Expected Time Complexity: O(m + n - 1)) Expected Auxiliary Space: O(1) Constraints: 1 ≤ M, N ≤ 10 0 sangamme1113 weeks ago if(n==1 || m==1){ return 1;} return numberOfPaths(m-1,n) + numberOfPaths(m,n-1); easy method 0 mohdraza3 weeks ago class Solution{ long numberOfPaths(int m, int n) { return fact(m+n-2)/ (fact(n-1)* fact(m-1)); //numberOfPaths(m - 1, n) + numberOfPaths(m, n - 1); } long fact(int n) { if (n == 0) return 1; return n*fact(n-1); } } +2 aakasshuit2 months ago //Java Solution if (m == 1 || n == 1) return 1; return numberOfPaths(m - 1, n) + numberOfPaths(m, n - 1); 0 saurabhsharma295202 months ago if(i == m || j == n) return 1; return numberOfPaths(m,n,i+1,j)+numberOfPaths(m,n,i,j+1); 0 pardeep12 months ago long long numberOfPaths(int m, int n){ int t[m]; memset(t, 0, sizeof(t)); t[0]=1; for(int i=0;i<n;i++) { for(int j=1;j<m;j++) { t[j]=t[j]+t[j-1]; //cout<<t[j]<<" "; } //cout<<endl; } return t[m-1];} +1 chechipresh2 months ago Total steps to traverse=m+n-2 Steps in downward direction=m-1 Steps in right direction=n-1 Then,Total no. of ways=(m+n-2)!/(m-1)!(n-1)! long long numberOfPaths(int m, int n){ // Code Here long long ft=1,fm=1,fn=1; int i; for (i=1;i<=m+n-2;i++){ if (i<=m-1) fm*=i; if (i<=n-1) fn*=i; ft*=i; } return ft/(fm*fn); } +1 cs21m0592 months ago long long dp[m][n]; memset(dp,0,sizeof(dp)); for(int i = 0 ; i < m ; i ++) { for(int j = 0 ; j < n ; j ++) { if(i == 0 && j == 0) dp[i][j] = 1; else if( i == 0) { dp[i][j] = 1 ; } else if(j == 0) { dp[i][j] = 1 ; } else { dp[i][j] = dp[i][j-1] + dp[i-1][j]; } } } return dp[m-1][n-1]; 0 huzefabohra5262 months ago Solution Approach is iterative . Basically based on combinatorics.... in order to cover (m+n) distance of which m right moves and n down moves can be done in (m+n)!/(m!*n!) Now challenge is to do in O(m+n-1) time complexity which can be done by cancelling (m-1)! or (n-1)! term from numertor. Interestingly i have checked bigger of m & n and cancelled bigger term so that loop iterates for less number . long long numberOfPaths(int m, int n){ double result=1; if(m==1 || n==1) return 1; else{ if(m<n) { for(int j=1;j<=(m-1);j++) result = result*(n-1+j)/j; // (n-1)! is cancelled as n is greater } else { for(int j=1;j<=(n-1);j++) result = result*(m-1+j)/j; // (m-1)! is cancelled as m is greater } } } return int(result);} 0 hamidnourashraf2 months ago def rec_path(self, n, m, i, j): if i == m -1 and j == n-1: return 1 if i > m-1 or j > n-1: return 0 return self.rec_path(n,m, i+1, j) + self.rec_path(n,m, i, j+1) def numberOfPaths (self, n, m): res = [[-1 for x in range(n+1)] for y in range(m+1)] res[m-1][n-1] = 1 for i in range(m-1, -1, -1): for j in range(n-1, -1, -1): if res[i][j] == -1: if res[i][j+1] == -1: res[i][j+1] = self.rec_path(n, m, i, j+1) if res[i+1][j] == -1: res[i+1][j] = self.rec_path(n, m, i+1, j) res[i][j] = res[i+1][j] + res[i][j+1] return res[0][0] 0 hamidnourashraf2 months ago def rec_path(self, n, m, i, j): if i == m -1 and j == n-1: return 1 if i > m-1 or j > n-1: return 0 return self.rec_path(n,m, i+1, j) + self.rec_path(n,m, i, j+1) def numberOfPaths (self, n, m): ## recursive return self.rec_path(n, m, 0, 0) 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": 410, "s": 238, "text": "The problem is to count all the possible paths from top left to bottom right of a MxN matrix with the constraints that from each cell you can either move to right or down." }, { "code": null, "e": 421, "s": 410, "text": "Example 1:" }, { "code": null, "e": 677, "s": 421, "text": "Input:\nM = 3 and N = 3\nOutput: 6\nExplanation:\nLet the given input 3*3 matrix is filled \nas such:\nA B C\nD E F\nG H I\nThe possible paths which exists to reach \n'I' from 'A' following above conditions \nare as follows:ABCFI, ABEHI, ADGHI, ADEFI, \nADEHI, ABEFI\n" }, { "code": null, "e": 690, "s": 679, "text": "Example 2:" }, { "code": null, "e": 724, "s": 690, "text": "Input:\nM = 2 and N = 8\nOutput: 8\n" }, { "code": null, "e": 1006, "s": 724, "text": "\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function numberOfPaths() which takes the integer M and integer N as input parameters and returns the number of paths..\n\nExpected Time Complexity: O(m + n - 1))\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1035, "s": 1008, "text": "Constraints:\n1 ≤ M, N ≤ 10" }, { "code": null, "e": 1037, "s": 1035, "text": "0" }, { "code": null, "e": 1060, "s": 1037, "text": "sangamme1113 weeks ago" }, { "code": null, "e": 1078, "s": 1060, "text": "if(n==1 || m==1){" }, { "code": null, "e": 1089, "s": 1078, "text": "return 1;}" }, { "code": null, "e": 1141, "s": 1089, "text": "return numberOfPaths(m-1,n) + numberOfPaths(m,n-1);" }, { "code": null, "e": 1153, "s": 1141, "text": "easy method" }, { "code": null, "e": 1155, "s": 1153, "text": "0" }, { "code": null, "e": 1175, "s": 1155, "text": "mohdraza3 weeks ago" }, { "code": null, "e": 1440, "s": 1175, "text": "class Solution{ long numberOfPaths(int m, int n) { return fact(m+n-2)/ (fact(n-1)* fact(m-1)); //numberOfPaths(m - 1, n) + numberOfPaths(m, n - 1); } long fact(int n) { if (n == 0) return 1; return n*fact(n-1); } }" }, { "code": null, "e": 1443, "s": 1440, "text": "+2" }, { "code": null, "e": 1466, "s": 1443, "text": "aakasshuit2 months ago" }, { "code": null, "e": 1595, "s": 1466, "text": "//Java Solution\n\n if (m == 1 || n == 1)\n return 1;\n return numberOfPaths(m - 1, n) + numberOfPaths(m, n - 1);" }, { "code": null, "e": 1597, "s": 1595, "text": "0" }, { "code": null, "e": 1628, "s": 1597, "text": "saurabhsharma295202 months ago" }, { "code": null, "e": 1719, "s": 1628, "text": "if(i == m || j == n) return 1; return numberOfPaths(m,n,i+1,j)+numberOfPaths(m,n,i,j+1);" }, { "code": null, "e": 1721, "s": 1719, "text": "0" }, { "code": null, "e": 1742, "s": 1721, "text": "pardeep12 months ago" }, { "code": null, "e": 2001, "s": 1742, "text": "long long numberOfPaths(int m, int n){ int t[m]; memset(t, 0, sizeof(t)); t[0]=1; for(int i=0;i<n;i++) { for(int j=1;j<m;j++) { t[j]=t[j]+t[j-1]; //cout<<t[j]<<\" \"; } //cout<<endl; } return t[m-1];}" }, { "code": null, "e": 2004, "s": 2001, "text": "+1" }, { "code": null, "e": 2028, "s": 2004, "text": "chechipresh2 months ago" }, { "code": null, "e": 2059, "s": 2028, "text": "Total steps to traverse=m+n-2 " }, { "code": null, "e": 2092, "s": 2059, "text": "Steps in downward direction=m-1 " }, { "code": null, "e": 2122, "s": 2092, "text": "Steps in right direction=n-1 " }, { "code": null, "e": 2167, "s": 2122, "text": "Then,Total no. of ways=(m+n-2)!/(m-1)!(n-1)!" }, { "code": null, "e": 2392, "s": 2167, "text": "long long numberOfPaths(int m, int n){ // Code Here long long ft=1,fm=1,fn=1; int i; for (i=1;i<=m+n-2;i++){ if (i<=m-1) fm*=i; if (i<=n-1) fn*=i; ft*=i; } return ft/(fm*fn);" }, { "code": null, "e": 2394, "s": 2392, "text": "}" }, { "code": null, "e": 2397, "s": 2394, "text": "+1" }, { "code": null, "e": 2418, "s": 2397, "text": "cs21m0592 months ago" }, { "code": null, "e": 2886, "s": 2418, "text": " long long dp[m][n]; memset(dp,0,sizeof(dp)); for(int i = 0 ; i < m ; i ++) { for(int j = 0 ; j < n ; j ++) { if(i == 0 && j == 0) dp[i][j] = 1; else if( i == 0) { dp[i][j] = 1 ; } else if(j == 0) { dp[i][j] = 1 ; } else { dp[i][j] = dp[i][j-1] + dp[i-1][j]; } } } return dp[m-1][n-1];" }, { "code": null, "e": 2888, "s": 2886, "text": "0" }, { "code": null, "e": 2915, "s": 2888, "text": "huzefabohra5262 months ago" }, { "code": null, "e": 2926, "s": 2917, "text": "Solution" }, { "code": null, "e": 2951, "s": 2926, "text": " Approach is iterative ." }, { "code": null, "e": 2988, "s": 2951, "text": "Basically based on combinatorics...." }, { "code": null, "e": 3091, "s": 2988, "text": "in order to cover (m+n) distance of which m right moves and n down moves can be done in (m+n)!/(m!*n!)" }, { "code": null, "e": 3214, "s": 3093, "text": "Now challenge is to do in O(m+n-1) time complexity which can be done by cancelling (m-1)! or (n-1)! term from numertor." }, { "code": null, "e": 3325, "s": 3214, "text": "Interestingly i have checked bigger of m & n and cancelled bigger term so that loop iterates for less number ." }, { "code": null, "e": 3444, "s": 3329, "text": "long long numberOfPaths(int m, int n){ double result=1; if(m==1 || n==1) return 1; else{ if(m<n)" }, { "code": null, "e": 3567, "s": 3444, "text": " { for(int j=1;j<=(m-1);j++) result = result*(n-1+j)/j; // (n-1)! is cancelled as n is greater" }, { "code": null, "e": 3700, "s": 3567, "text": " } else { for(int j=1;j<=(n-1);j++) result = result*(m-1+j)/j; // (m-1)! is cancelled as m is greater" }, { "code": null, "e": 3717, "s": 3700, "text": " } " }, { "code": null, "e": 3734, "s": 3717, "text": " } }" }, { "code": null, "e": 3758, "s": 3734, "text": " return int(result);}" }, { "code": null, "e": 3760, "s": 3758, "text": "0" }, { "code": null, "e": 3788, "s": 3760, "text": "hamidnourashraf2 months ago" }, { "code": null, "e": 3997, "s": 3788, "text": "def rec_path(self, n, m, i, j):\n if i == m -1 and j == n-1:\n return 1\n if i > m-1 or j > n-1: \n return 0\n return self.rec_path(n,m, i+1, j) + self.rec_path(n,m, i, j+1) " }, { "code": null, "e": 4526, "s": 4001, "text": " def numberOfPaths (self, n, m):\n res = [[-1 for x in range(n+1)] for y in range(m+1)]\n res[m-1][n-1] = 1\n for i in range(m-1, -1, -1):\n for j in range(n-1, -1, -1):\n if res[i][j] == -1:\n if res[i][j+1] == -1:\n res[i][j+1] = self.rec_path(n, m, i, j+1)\n if res[i+1][j] == -1:\n res[i+1][j] = self.rec_path(n, m, i+1, j)\n res[i][j] = res[i+1][j] + res[i][j+1]\n return res[0][0]" }, { "code": null, "e": 4528, "s": 4526, "text": "0" }, { "code": null, "e": 4556, "s": 4528, "text": "hamidnourashraf2 months ago" }, { "code": null, "e": 4768, "s": 4556, "text": "def rec_path(self, n, m, i, j):\n if i == m -1 and j == n-1:\n return 1\n if i > m-1 or j > n-1: \n return 0\n return self.rec_path(n,m, i+1, j) + self.rec_path(n,m, i, j+1)" }, { "code": null, "e": 4867, "s": 4768, "text": "def numberOfPaths (self, n, m): ## recursive\n return self.rec_path(n, m, 0, 0)\n " }, { "code": null, "e": 5013, "s": 4867, "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": 5049, "s": 5013, "text": " Login to access your submissions. " }, { "code": null, "e": 5059, "s": 5049, "text": "\nProblem\n" }, { "code": null, "e": 5069, "s": 5059, "text": "\nContest\n" }, { "code": null, "e": 5132, "s": 5069, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5280, "s": 5132, "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": 5488, "s": 5280, "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": 5594, "s": 5488, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to convert a matrix into a matrix with single column in R?
If we have a matrix then we might want to convert it to matrix with single column for some analytical purpose such as multiplying with a vector that has the length equal to the total number of elements as in the matrix. Thus, the matrix can be converted to a single column matrix by using matrix function itself but for this we would need to nullify the column names and row names. Live Demo > M1<-matrix(rnorm(20),nrow=5) > M1 [,1] [,2] [,3] [,4] [1,] -0.8067677 1.9855697 -2.5012312 1.01283626 [2,] -0.5107091 0.4632027 -1.3966282 0.02534344 [3,] -0.5564871 0.2924344 -0.8991352 -0.50715002 [4,] 0.2411252 -0.5139827 -1.3272964 -0.50694324 [5,] -0.5753370 -1.2357388 0.2028664 0.26498877 > matrix(M1,dimnames=list(t(outer(colnames(M1),rownames(M1),FUN=paste)),NULL)) [,1] [1,] -0.80676768 [2,] -0.51070906 [3,] -0.55648712 [4,] 0.24112516 [5,] -0.57533702 [6,] 1.98556973 [7,] 0.46320275 [8,] 0.29243441 [9,] -0.51398265 [10,] -1.23573882 [11,] -2.50123125 [12,] -1.39662824 [13,] -0.89913524 [14,] -1.32729635 [15,] 0.20286643 [16,] 1.01283626 [17,] 0.02534344 [18,] -0.50715002 [19,] -0.50694324 [20,] 0.26498877 Live Demo > M2<-matrix(rpois(20,5),ncol=2) > M2 [,1] [,2] [1,] 6 1 [2,] 6 7 [3,] 4 5 [4,] 6 5 [5,] 4 5 [6,] 5 4 [7,] 4 9 [8,] 4 6 [9,] 3 6 [10,] 8 10 > matrix(M2,dimnames=list(t(outer(colnames(M2),rownames(M2),FUN=paste)),NULL)) [,1] [1,] 6 [2,] 6 [3,] 4 [4,] 6 [5,] 4 [6,] 5 [7,] 4 [8,] 4 [9,] 3 [10,] 8 [11,] 1 [12,] 7 [13,] 5 [14,] 5 [15,] 5 [16,] 4 [17,] 9 [18,] 6 [19,] 6 [20,] 10 Live Demo > M3<-matrix(sample(0:9,20,replace=TRUE),ncol=10) > M3 [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 2 2 6 1 7 3 8 6 1 2 [2,] 8 0 4 7 8 8 8 2 1 3 > matrix(M3,dimnames=list(t(outer(colnames(M3),rownames(M3),FUN=paste)),NULL)) [,1] [1,] 2 [2,] 8 [3,] 2 [4,] 0 [5,] 6 [6,] 4 [7,] 1 [8,] 7 [9,] 7 [10,] 8 [11,] 3 [12,] 8 [13,] 8 [14,] 8 [15,] 6 [16,] 2 [17,] 1 [18,] 1 [19,] 2 [20,] 3
[ { "code": null, "e": 1444, "s": 1062, "text": "If we have a matrix then we might want to convert it to matrix with single column for some analytical purpose such as multiplying with a vector that has the length equal to the total number of elements as in the matrix. Thus, the matrix can be converted to a single column matrix by using matrix function itself but for this we would need to nullify the column names and row names." }, { "code": null, "e": 1454, "s": 1444, "text": "Live Demo" }, { "code": null, "e": 1490, "s": 1454, "text": "> M1<-matrix(rnorm(20),nrow=5)\n> M1" }, { "code": null, "e": 1778, "s": 1490, "text": " [,1] [,2] [,3] [,4]\n[1,] -0.8067677 1.9855697 -2.5012312 1.01283626\n[2,] -0.5107091 0.4632027 -1.3966282 0.02534344\n[3,] -0.5564871 0.2924344 -0.8991352 -0.50715002\n[4,] 0.2411252 -0.5139827 -1.3272964 -0.50694324\n[5,] -0.5753370 -1.2357388 0.2028664 0.26498877" }, { "code": null, "e": 1857, "s": 1778, "text": "> matrix(M1,dimnames=list(t(outer(colnames(M1),rownames(M1),FUN=paste)),NULL))" }, { "code": null, "e": 2214, "s": 1857, "text": " [,1]\n[1,] -0.80676768\n[2,] -0.51070906\n[3,] -0.55648712\n[4,] 0.24112516\n[5,] -0.57533702\n[6,] 1.98556973\n[7,] 0.46320275\n[8,] 0.29243441\n[9,] -0.51398265\n[10,] -1.23573882\n[11,] -2.50123125\n[12,] -1.39662824\n[13,] -0.89913524\n[14,] -1.32729635\n[15,] 0.20286643\n[16,] 1.01283626\n[17,] 0.02534344\n[18,] -0.50715002\n[19,] -0.50694324\n[20,] 0.26498877" }, { "code": null, "e": 2224, "s": 2214, "text": "Live Demo" }, { "code": null, "e": 2262, "s": 2224, "text": "> M2<-matrix(rpois(20,5),ncol=2)\n> M2" }, { "code": null, "e": 2364, "s": 2262, "text": "[,1] [,2]\n[1,] 6 1\n[2,] 6 7\n[3,] 4 5\n[4,] 6 5\n[5,] 4 5\n[6,] 5 4\n[7,] 4 9\n[8,] 4 6\n[9,] 3 6\n[10,] 8 10" }, { "code": null, "e": 2443, "s": 2364, "text": "> matrix(M2,dimnames=list(t(outer(colnames(M2),rownames(M2),FUN=paste)),NULL))" }, { "code": null, "e": 2600, "s": 2443, "text": "[,1]\n[1,] 6\n[2,] 6\n[3,] 4\n[4,] 6\n[5,] 4\n[6,] 5\n[7,] 4\n[8,] 4\n[9,] 3\n[10,] 8\n[11,] 1\n[12,] 7\n[13,] 5\n[14,] 5\n[15,] 5\n[16,] 4\n[17,] 9\n[18,] 6\n[19,] 6\n[20,] 10" }, { "code": null, "e": 2610, "s": 2600, "text": "Live Demo" }, { "code": null, "e": 2665, "s": 2610, "text": "> M3<-matrix(sample(0:9,20,replace=TRUE),ncol=10)\n> M3" }, { "code": null, "e": 2766, "s": 2665, "text": "[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] 2 2 6 1 7 3 8 6 1 2\n[2,] 8 0 4 7 8 8 8 2 1 3" }, { "code": null, "e": 2845, "s": 2766, "text": "> matrix(M3,dimnames=list(t(outer(colnames(M3),rownames(M3),FUN=paste)),NULL))" }, { "code": null, "e": 3001, "s": 2845, "text": "[,1]\n[1,] 2\n[2,] 8\n[3,] 2\n[4,] 0\n[5,] 6\n[6,] 4\n[7,] 1\n[8,] 7\n[9,] 7\n[10,] 8\n[11,] 3\n[12,] 8\n[13,] 8\n[14,] 8\n[15,] 6\n[16,] 2\n[17,] 1\n[18,] 1\n[19,] 2\n[20,] 3" } ]
SQL Tryit Editor v1.6
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName FROM Orders RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID ORDER BY Orders.OrderID; ​ Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, Opera, and Edge(79). If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 63, "s": 0, "text": "SELECT Orders.OrderID, Employees.LastName, Employees.FirstName" }, { "code": null, "e": 75, "s": 63, "text": "FROM Orders" }, { "code": null, "e": 96, "s": 75, "text": "RIGHT JOIN Employees" }, { "code": null, "e": 140, "s": 96, "text": "ON Orders.EmployeeID = Employees.EmployeeID" }, { "code": null, "e": 165, "s": 140, "text": "ORDER BY Orders.OrderID;" }, { "code": null, "e": 167, "s": 165, "text": "​" }, { "code": null, "e": 230, "s": 167, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "code": null, "e": 290, "s": 230, "text": "This SQL-Statement is not supported in the WebSQL Database." }, { "code": null, "e": 358, "s": 290, "text": "The example still works, because it uses a modified version of SQL." }, { "code": null, "e": 396, "s": 358, "text": "Your browser does not support WebSQL." }, { "code": null, "e": 481, "s": 396, "text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database." }, { "code": null, "e": 655, "s": 481, "text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time." }, { "code": null, "e": 706, "s": 655, "text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL." }, { "code": null, "e": 774, "s": 706, "text": "A Database-object is created in your browser, for testing purposes." }, { "code": null, "e": 945, "s": 774, "text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button." }, { "code": null, "e": 1045, "s": 945, "text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object." }, { "code": null, "e": 1105, "s": 1045, "text": "WebSQL is supported in Chrome, Safari, Opera, and Edge(79)." } ]
How to test if a vector contains the given element in R ? - GeeksforGeeks
05 Apr, 2021 In this article, let’s discuss how to check a specific element in a vector in R Programming Language. Method 1: Using loop A for loop can be used to check if the element belongs to the vector. A boolean flag can be declared and initialized to False. As soon as the element is contained in the vector, the flag value is set to TRUE. The element is present at the corresponding position equivalent to loop counter value. The time operation required for checking is equivalent to O(n) where n is the size of the vector. Example: R # declaring a vector vec <- c(1,4,2,6) # elements x to check in the vectorx <- 2 # declare a flag to know if element has# occuredflag <- FALSE # computing length of vectorsize = length(vec) # iterating over elements of vectorfor (i in 1:size){ if(x==vec[i]){ flag <- TRUE cat("Element present in vector at pos",i) }} if(!flag) print("Element is not present in the vector") Output Element present in vector at pos 3 Method 2: %in% operator %in% operator can be used in R Programming Language, to check for the presence of an element inside a vector. It returns a boolean output, evaluating to TRUE if the element is present, else returns false. The first operand before the operator is the element to check and the second operator is the sequence of elements to check in. Example: R # declaring a vector vec <- c("first","second","third","fourth") # elements x and y to check in the vectorx <- "first"y <-"is it present" # check if the element x specified is present # in the vectorprint ("Check for x element")x %in% vec # check if the element y specified is present # in the vectorprint ("Check for y element")y %in% vec Output [1] “Check for x element” [1] TRUE [1] “Check for y element” [1] FALSE Method 3: any() any() method can also be used to check for any element’s presence in the sequence of elements provided. The any function in R Programming Language determines if there are ANY of the given search terms in the given vector. It returns either a boolean TRUE or FALSE value. any() method uses an expression == to evaluate the containment of the element in the vector, where the first operand is the element to check and right hand side operand is the vector to check the containment in. Example: R # declaring a vector comprising of # complex numbersvec <- c(1i,0+3i,5+6i,-7-2i) # declaring element to check x <- 1+3iy <- -7-2i # check for presence of element xprint ("Element x presence in vector")any(x==vec) # check for presence of element yprint ("Element y presence in vector")any(y==vec) Output [1] “Element x presence in vector” [1] FALSE [1] “Element y presence in vector” [1] TRUE Method 4: is.element() method This can also be used for a similar purpose, to determine if the object specified by first argument is contained in the object pertaining to second object. Syntax: is.element(x,y) Example: R # declaring a character vectorvec <- c('a','g','h','i') # check for presence of element 'a'print ("Element 'a' presence in vector")any('a'==vec) # check for presence of element 'y'print ("Element 'y' presence in vector")any('y'==vec) Output [1] “Element ‘a’ presence in vector” [1] TRUE [1] “Element ‘y’ presence in vector” [1] FALSE Picked R Vector-Programs R-Vectors R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Replace specific values in column in R DataFrame ? How to change Row Names of DataFrame in R ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R How to Replace specific values in column in R DataFrame ? How to change Row Names of DataFrame in R ? How to Split Column Into Multiple Columns in R DataFrame? Remove rows with NA in one column of R DataFrame How to filter R DataFrame by values in a column?
[ { "code": null, "e": 24481, "s": 24453, "text": "\n05 Apr, 2021" }, { "code": null, "e": 24583, "s": 24481, "text": "In this article, let’s discuss how to check a specific element in a vector in R Programming Language." }, { "code": null, "e": 24604, "s": 24583, "text": "Method 1: Using loop" }, { "code": null, "e": 24999, "s": 24604, "text": "A for loop can be used to check if the element belongs to the vector. A boolean flag can be declared and initialized to False. As soon as the element is contained in the vector, the flag value is set to TRUE. The element is present at the corresponding position equivalent to loop counter value. The time operation required for checking is equivalent to O(n) where n is the size of the vector. " }, { "code": null, "e": 25008, "s": 24999, "text": "Example:" }, { "code": null, "e": 25010, "s": 25008, "text": "R" }, { "code": "# declaring a vector vec <- c(1,4,2,6) # elements x to check in the vectorx <- 2 # declare a flag to know if element has# occuredflag <- FALSE # computing length of vectorsize = length(vec) # iterating over elements of vectorfor (i in 1:size){ if(x==vec[i]){ flag <- TRUE cat(\"Element present in vector at pos\",i) }} if(!flag) print(\"Element is not present in the vector\")", "e": 25411, "s": 25010, "text": null }, { "code": null, "e": 25418, "s": 25411, "text": "Output" }, { "code": null, "e": 25453, "s": 25418, "text": "Element present in vector at pos 3" }, { "code": null, "e": 25478, "s": 25453, "text": "Method 2: %in% operator " }, { "code": null, "e": 25811, "s": 25478, "text": "%in% operator can be used in R Programming Language, to check for the presence of an element inside a vector. It returns a boolean output, evaluating to TRUE if the element is present, else returns false. The first operand before the operator is the element to check and the second operator is the sequence of elements to check in. " }, { "code": null, "e": 25820, "s": 25811, "text": "Example:" }, { "code": null, "e": 25822, "s": 25820, "text": "R" }, { "code": "# declaring a vector vec <- c(\"first\",\"second\",\"third\",\"fourth\") # elements x and y to check in the vectorx <- \"first\"y <-\"is it present\" # check if the element x specified is present # in the vectorprint (\"Check for x element\")x %in% vec # check if the element y specified is present # in the vectorprint (\"Check for y element\")y %in% vec", "e": 26165, "s": 25822, "text": null }, { "code": null, "e": 26172, "s": 26165, "text": "Output" }, { "code": null, "e": 26198, "s": 26172, "text": "[1] “Check for x element”" }, { "code": null, "e": 26207, "s": 26198, "text": "[1] TRUE" }, { "code": null, "e": 26233, "s": 26207, "text": "[1] “Check for y element”" }, { "code": null, "e": 26243, "s": 26233, "text": "[1] FALSE" }, { "code": null, "e": 26260, "s": 26243, "text": "Method 3: any() " }, { "code": null, "e": 26745, "s": 26260, "text": "any() method can also be used to check for any element’s presence in the sequence of elements provided. The any function in R Programming Language determines if there are ANY of the given search terms in the given vector. It returns either a boolean TRUE or FALSE value. any() method uses an expression == to evaluate the containment of the element in the vector, where the first operand is the element to check and right hand side operand is the vector to check the containment in. " }, { "code": null, "e": 26754, "s": 26745, "text": "Example:" }, { "code": null, "e": 26756, "s": 26754, "text": "R" }, { "code": "# declaring a vector comprising of # complex numbersvec <- c(1i,0+3i,5+6i,-7-2i) # declaring element to check x <- 1+3iy <- -7-2i # check for presence of element xprint (\"Element x presence in vector\")any(x==vec) # check for presence of element yprint (\"Element y presence in vector\")any(y==vec)", "e": 27055, "s": 26756, "text": null }, { "code": null, "e": 27062, "s": 27055, "text": "Output" }, { "code": null, "e": 27097, "s": 27062, "text": "[1] “Element x presence in vector”" }, { "code": null, "e": 27107, "s": 27097, "text": "[1] FALSE" }, { "code": null, "e": 27142, "s": 27107, "text": "[1] “Element y presence in vector”" }, { "code": null, "e": 27151, "s": 27142, "text": "[1] TRUE" }, { "code": null, "e": 27182, "s": 27151, "text": "Method 4: is.element() method " }, { "code": null, "e": 27338, "s": 27182, "text": "This can also be used for a similar purpose, to determine if the object specified by first argument is contained in the object pertaining to second object." }, { "code": null, "e": 27346, "s": 27338, "text": "Syntax:" }, { "code": null, "e": 27362, "s": 27346, "text": "is.element(x,y)" }, { "code": null, "e": 27371, "s": 27362, "text": "Example:" }, { "code": null, "e": 27373, "s": 27371, "text": "R" }, { "code": "# declaring a character vectorvec <- c('a','g','h','i') # check for presence of element 'a'print (\"Element 'a' presence in vector\")any('a'==vec) # check for presence of element 'y'print (\"Element 'y' presence in vector\")any('y'==vec)", "e": 27609, "s": 27373, "text": null }, { "code": null, "e": 27616, "s": 27609, "text": "Output" }, { "code": null, "e": 27653, "s": 27616, "text": "[1] “Element ‘a’ presence in vector”" }, { "code": null, "e": 27662, "s": 27653, "text": "[1] TRUE" }, { "code": null, "e": 27699, "s": 27662, "text": "[1] “Element ‘y’ presence in vector”" }, { "code": null, "e": 27709, "s": 27699, "text": "[1] FALSE" }, { "code": null, "e": 27716, "s": 27709, "text": "Picked" }, { "code": null, "e": 27734, "s": 27716, "text": "R Vector-Programs" }, { "code": null, "e": 27744, "s": 27734, "text": "R-Vectors" }, { "code": null, "e": 27755, "s": 27744, "text": "R Language" }, { "code": null, "e": 27766, "s": 27755, "text": "R Programs" }, { "code": null, "e": 27864, "s": 27766, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27873, "s": 27864, "text": "Comments" }, { "code": null, "e": 27886, "s": 27873, "text": "Old Comments" }, { "code": null, "e": 27944, "s": 27886, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 27988, "s": 27944, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 28040, "s": 27988, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 28072, "s": 28040, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 28124, "s": 28072, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28182, "s": 28124, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 28226, "s": 28182, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 28284, "s": 28226, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28333, "s": 28284, "text": "Remove rows with NA in one column of R DataFrame" } ]
How to check internet connection in android?
This example demonstrate about how to check the state of internet connection through broadcast Receiver. 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 − To find the internet status we have to add network state permission to AndroidManifest.xml file as shown below. <?xml version="1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.andy.myapplication"> <uses-permission android:name = "android.permission.ACCESS_NETWORK_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> Step 3 − Following is the content of the modified main activity file MainActivity.java. This file can include each of the fundamental life cycle methods. We have created a text view, when use click on text view it going to call broadcastIntent() method to broadcast a CONNECTIVITY_ACTION intent. import android.content.BroadcastReceiver; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private BroadcastReceiver MyReceiver = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MyReceiver = new MyReceiver(); TextView click=findViewById(R.id.click); click.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { broadcastIntent(); } }); } public void broadcastIntent() { registerReceiver(MyReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); } @Override protected void onPause() { super.onPause(); unregisterReceiver(MyReceiver); } } Step 4 − Create a NetworkUtil class to find the net work status as show below. import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; class NetworkUtil { public static String getConnectivityStatusString(Context context) { String status = null; ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); if (activeNetwork != null) { if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) { status = "Wifi enabled"; return status; } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) { status = "Mobile data enabled"; return status; } } else { status = "No internet is available"; return status; } return status; } } Step 5 −Create a broadcast receiver class and named as MyReceiver.java .This broadcast receiver going to update the ui from NetworkUtil class. import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String status = NetworkUtil.getConnectivityStatusString(context); if(status.isEmpty()) { status="No Internet Connection"; } Toast.makeText(context, status, Toast.LENGTH_LONG).show(); } } Step 6 −Update your broadcast receiver in manifest file as shown below. <?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package = "com.example.andy.myapplication"> <uses-permission android:name="android.permission.ACCESS_NETWORK_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> <receiver android:name = "MyReceiver"> <intent-filter> <action android:name = "android.net.conn.CONNECTIVITY_CHANGE" /> <action android:name = "android.net.wifi.WIFI_STATE_CHANGED" /> </intent-filter> </receiver> </application> </manifest> Step 7 −Following will be the content of res/layout/activity_main.xml file to include a textview to broadcast connectivity state intent. <?xml version = "1.0" encoding = "utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity"> <TextView android:id="@+id/click" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click here" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout> 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. The above screen we have selected wifi connection and the output should be like this − The above screen we have selected wifi connection and the output should be like this − Click here to download the project code
[ { "code": null, "e": 1167, "s": 1062, "text": "This example demonstrate about how to check the state of internet connection through broadcast Receiver." }, { "code": null, "e": 1296, "s": 1167, "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": 1417, "s": 1296, "text": "Step 2 − To find the internet status we have to add network state permission to AndroidManifest.xml file as shown below." }, { "code": null, "e": 2209, "s": 1417, "text": "<?xml version=\"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.andy.myapplication\">\n <uses-permission android:name = \"android.permission.ACCESS_NETWORK_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": 2505, "s": 2209, "text": "Step 3 − Following is the content of the modified main activity file MainActivity.java. This file can include each of the fundamental life cycle methods. We have created a text view, when use click on text view it going to call broadcastIntent() method to broadcast a CONNECTIVITY_ACTION intent." }, { "code": null, "e": 3521, "s": 2505, "text": "import android.content.BroadcastReceiver;\nimport android.content.IntentFilter;\nimport android.net.ConnectivityManager;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n private BroadcastReceiver MyReceiver = null;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n MyReceiver = new MyReceiver();\n TextView click=findViewById(R.id.click);\n click.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n broadcastIntent();\n }\n });\n }\n public void broadcastIntent() {\n registerReceiver(MyReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));\n }\n @Override\n protected void onPause() {\n super.onPause();\n unregisterReceiver(MyReceiver);\n }\n}" }, { "code": null, "e": 3600, "s": 3521, "text": "Step 4 − Create a NetworkUtil class to find the net work status as show below." }, { "code": null, "e": 4447, "s": 3600, "text": "import android.content.Context;\nimport android.net.ConnectivityManager;\nimport android.net.NetworkInfo;\nclass NetworkUtil {\n public static String getConnectivityStatusString(Context context) {\n String status = null;\n ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo activeNetwork = cm.getActiveNetworkInfo();\n if (activeNetwork != null) {\n if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {\n status = \"Wifi enabled\";\n return status;\n } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {\n status = \"Mobile data enabled\";\n return status;\n }\n } else {\n status = \"No internet is available\";\n return status;\n }\n return status;\n }\n}" }, { "code": null, "e": 4590, "s": 4447, "text": "Step 5 −Create a broadcast receiver class and named as MyReceiver.java .This broadcast receiver going to update the ui from NetworkUtil class." }, { "code": null, "e": 5071, "s": 4590, "text": "import android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.widget.Toast;\npublic class MyReceiver extends BroadcastReceiver {\n @Override\n public void onReceive(Context context, Intent intent) {\n String status = NetworkUtil.getConnectivityStatusString(context);\n if(status.isEmpty()) {\n status=\"No Internet Connection\";\n }\n Toast.makeText(context, status, Toast.LENGTH_LONG).show();\n }\n}" }, { "code": null, "e": 5143, "s": 5071, "text": "Step 6 −Update your broadcast receiver in manifest file as shown below." }, { "code": null, "e": 6180, "s": 5143, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package = \"com.example.andy.myapplication\">\n <uses-permission android:name=\"android.permission.ACCESS_NETWORK_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 <receiver android:name = \"MyReceiver\">\n <intent-filter>\n <action android:name = \"android.net.conn.CONNECTIVITY_CHANGE\" />\n <action android:name = \"android.net.wifi.WIFI_STATE_CHANGED\" />\n </intent-filter>\n </receiver>\n </application>\n</manifest>" }, { "code": null, "e": 6317, "s": 6180, "text": "Step 7 −Following will be the content of res/layout/activity_main.xml file to include a textview to broadcast connectivity state intent." }, { "code": null, "e": 7077, "s": 6317, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.constraint.ConstraintLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n<TextView\n android:id=\"@+id/click\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Click here\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintLeft_toLeftOf=\"parent\"\n app:layout_constraintRight_toRightOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\" />\n</android.support.constraint.ConstraintLayout>" }, { "code": null, "e": 7424, "s": 7077, "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": 7511, "s": 7424, "text": "The above screen we have selected wifi connection and the output should be like this −" }, { "code": null, "e": 7598, "s": 7511, "text": "The above screen we have selected wifi connection and the output should be like this −" }, { "code": null, "e": 7638, "s": 7598, "text": "Click here to download the project code" } ]
Image Processing with Python — Blob Detection using Scikit-Image | by Tonichi Edeza | Towards Data Science
One of the most important skills a data scientist needs when working with images is being able to identify specific parts of the image. An image only becomes useful if specific points of interest can be identified and itemized. In this article we will learn how to do just that. Let’s get started! As always let us first import all the required libraries we need for this article. import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport skimagefrom skimage.io import imread, imshowfrom skimage.color import rgb2gray, rgb2hsvfrom skimage.measure import label, regionprops, regionprops_tablefrom skimage.filters import threshold_otsufrom scipy.ndimage import median_filterfrom matplotlib.patches import Rectanglefrom tqdm import tqdm Excellent, now let us load the image we will be working on. tree = imread('laughing_tree.png')imshow(tree); We will work with the above image. Our task is to identify and segregate the sections of the image that contain the tree’s unique fruit (which looks like an open mouth). The first thing we should do is try to see if there is any easy way to identify the image based on the value. Let us convert the image to greyscale and use Otsu’s Method to see if this gives us a decent mask. tree_gray = rgb2gray(tree)otsu_thresh = threshold_otsu(tree_gray)tree_binary = tree_gray < otsu_threshimshow(tree_binary, cmap = 'gray'); This is clearly not working out well, let us try to iterate over several threshold levels and see if we can find a threshold that will produce a better mask. def threshold_checker(image): thresholds = np.arange(0.1,1.1,0.1) tree_gray = rgb2gray(image) fig, ax = plt.subplots(2, 5, figsize=(17, 10)) for n, ax in enumerate(ax.flatten()): ax.set_title(f'Threshold : {round(thresholds[n],2)}', fontsize = 16) threshold_tree = tree_gray < thresholds[n] ax.imshow(threshold_tree); ax.axis('off') fig.tight_layout()threshold_checker(tree) We can see that though the thresholding seems to help, it still includes significant portions of the image that we are not interested in. Let us try another approach. tree_hsv = rgb2hsv(tree[:,:,:-1])plt.figure(num=None, figsize=(8, 6), dpi=80)plt.imshow(tree_hsv[:,:,0], cmap='hsv')plt.colorbar(); If we put the image into an HSV Colorspace, we can see that the fruits clearly have a red hue that is not present in other portions of the image. Let us try segregating these sections of the image. lower_mask = tree_hsv [:,:,0] > 0.80upper_mask = tree_hsv [:,:,0] <= 1.00mask = upper_mask*lower_maskred = tree[:,:,0]*maskgreen = tree[:,:,1]*maskblue = tree[:,:,2]*masktree_mask = np.dstack((red,green,blue))plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(tree_mask); We see that along with the fruits, large portions of the skylight sections are also retained. Referring to the previous Hue channel image, we can see that these sections also have the same kind of red present in the fruits. To go around this, let us check the Value channel of the image. tree_hsv = rgb2hsv(tree[:,:,:-1])plt.figure(num=None, figsize=(8, 6), dpi=80)plt.imshow(tree_hsv[:,:,2], cmap='gray')plt.colorbar(); We can see that those brightly lit areas have incredibly high values. Let us take this into account when we create the mask. lower_mask = tree_hsv [:,:,0] > 0.80upper_mask = tree_hsv [:,:,0] <= 1.00value_mask = tree_hsv [:,:,2] < .90mask = upper_mask*lower_mask*value_maskred = tree[:,:,0] * maskgreen = tree[:,:,1] * maskblue = tree[:,:,2] * masktree_mask = np.dstack((red, green, blue))plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(tree_mask); Great! We are almost there. We now have to find a way to clean the image and remove the little white dots. For this, we can simply use the median_filter function in the Skimage library. lower_mask = tree_hsv [:,:,0] > 0.80upper_mask = tree_hsv [:,:,0] <= 1.00value_mask = tree_hsv [:,:,2] < .90mask = median_filter(upper_mask*lower_mask*value_mask, 10)red = tree[:,:,0] * maskgreen = tree[:,:,1] * maskblue = tree[:,:,2] * masktree_mask = np.dstack((red, green, blue))plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(tree_mask); We can see that incorporating the Median Filter gets us an extremely clean image. Now we need to identify each blob, to do this we need to make use of the label function in Skimage. tree_blobs = label(rgb2gray(tree_mask) > 0)imshow(tree_blobs, cmap = 'tab10'); We can see that the function identifies the different blobs in the image. The next step now is to get the properties of each blob. To do this we must make use of the regionprops_table function in Skimage. properties =['area','bbox','convex_area','bbox_area', 'major_axis_length', 'minor_axis_length', 'eccentricity']df = pd.DataFrame(regionprops_table(tree_blobs, properties = properties)) The regionprops_table function gives us the properties of each of the blobs in a convenient pandas DataFrame. This allows us to easily manipulate the data and pin point specific blobs. As an example of how useful this DataFrame is, let us use the bbox feature to draw bounding boxes on the image. blob_coordinates = [(row['bbox-0'],row['bbox-1'], row['bbox-2'],row['bbox-3'] )for index, row in df.iterrows()]fig, ax = plt.subplots(1,1, figsize=(8, 6), dpi = 80)for blob in tqdm(blob_coordinates): width = blob[3] - blob[1] height = blob[2] - blob[0] patch = Rectangle((blob[1],blob[0]), width, height, edgecolor='r', facecolor='none') ax.add_patch(patch)ax.imshow(tree);ax.set_axis_off() If we look carefully we can see that there is a single bounding box on the upper left of the image. The object within the bounding box is clearly not a fruit. But how do we get rid of it? Well, what we can do is filter the pandas DataFrame. For simplicity we shall filter it via the eccentricity column, this is because of the unique shape the outlier blob has. df = df[df['eccentricity'] < df['eccentricity'].max()] If we plot out the bounding boxes again we see that we were able to successfully filter out the blob. Lastly, let us cut out the bounding boxes from the image and display them as their own images. fig, ax = plt.subplots(1, len(blob_coordinates), figsize=(15,5))for n, axis in enumerate(ax.flatten()): axis.imshow(tree[int(blob_coordinates[n][0]): int(blob_coordinates[n][2]), int(blob_coordinates[n][1]): int(blob_coordinates[n][3])]); fig.tight_layout() Excellent, we have successfully identified the interesting mouth-like fruits in the image. The images can now be saved into a file and used later on (perhaps for a machine learning project). In Conclusion Knowing how to do blob detection is a valuable skill for any data scientist working with images. It can be used to separate different sections of an image into different points of interest. You can actually use this technique to create the data that will be fed to your machine learning algorithm. Though this was a relatively simple and straightforward lesson, I hope you now have an idea of how to use blob detection to solve basic image problems.
[ { "code": null, "e": 451, "s": 172, "text": "One of the most important skills a data scientist needs when working with images is being able to identify specific parts of the image. An image only becomes useful if specific points of interest can be identified and itemized. In this article we will learn how to do just that." }, { "code": null, "e": 470, "s": 451, "text": "Let’s get started!" }, { "code": null, "e": 553, "s": 470, "text": "As always let us first import all the required libraries we need for this article." }, { "code": null, "e": 923, "s": 553, "text": "import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport skimagefrom skimage.io import imread, imshowfrom skimage.color import rgb2gray, rgb2hsvfrom skimage.measure import label, regionprops, regionprops_tablefrom skimage.filters import threshold_otsufrom scipy.ndimage import median_filterfrom matplotlib.patches import Rectanglefrom tqdm import tqdm" }, { "code": null, "e": 983, "s": 923, "text": "Excellent, now let us load the image we will be working on." }, { "code": null, "e": 1031, "s": 983, "text": "tree = imread('laughing_tree.png')imshow(tree);" }, { "code": null, "e": 1201, "s": 1031, "text": "We will work with the above image. Our task is to identify and segregate the sections of the image that contain the tree’s unique fruit (which looks like an open mouth)." }, { "code": null, "e": 1410, "s": 1201, "text": "The first thing we should do is try to see if there is any easy way to identify the image based on the value. Let us convert the image to greyscale and use Otsu’s Method to see if this gives us a decent mask." }, { "code": null, "e": 1548, "s": 1410, "text": "tree_gray = rgb2gray(tree)otsu_thresh = threshold_otsu(tree_gray)tree_binary = tree_gray < otsu_threshimshow(tree_binary, cmap = 'gray');" }, { "code": null, "e": 1706, "s": 1548, "text": "This is clearly not working out well, let us try to iterate over several threshold levels and see if we can find a threshold that will produce a better mask." }, { "code": null, "e": 2154, "s": 1706, "text": "def threshold_checker(image): thresholds = np.arange(0.1,1.1,0.1) tree_gray = rgb2gray(image) fig, ax = plt.subplots(2, 5, figsize=(17, 10)) for n, ax in enumerate(ax.flatten()): ax.set_title(f'Threshold : {round(thresholds[n],2)}', fontsize = 16) threshold_tree = tree_gray < thresholds[n] ax.imshow(threshold_tree); ax.axis('off') fig.tight_layout()threshold_checker(tree)" }, { "code": null, "e": 2321, "s": 2154, "text": "We can see that though the thresholding seems to help, it still includes significant portions of the image that we are not interested in. Let us try another approach." }, { "code": null, "e": 2453, "s": 2321, "text": "tree_hsv = rgb2hsv(tree[:,:,:-1])plt.figure(num=None, figsize=(8, 6), dpi=80)plt.imshow(tree_hsv[:,:,0], cmap='hsv')plt.colorbar();" }, { "code": null, "e": 2651, "s": 2453, "text": "If we put the image into an HSV Colorspace, we can see that the fruits clearly have a red hue that is not present in other portions of the image. Let us try segregating these sections of the image." }, { "code": null, "e": 2923, "s": 2651, "text": "lower_mask = tree_hsv [:,:,0] > 0.80upper_mask = tree_hsv [:,:,0] <= 1.00mask = upper_mask*lower_maskred = tree[:,:,0]*maskgreen = tree[:,:,1]*maskblue = tree[:,:,2]*masktree_mask = np.dstack((red,green,blue))plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(tree_mask);" }, { "code": null, "e": 3147, "s": 2923, "text": "We see that along with the fruits, large portions of the skylight sections are also retained. Referring to the previous Hue channel image, we can see that these sections also have the same kind of red present in the fruits." }, { "code": null, "e": 3211, "s": 3147, "text": "To go around this, let us check the Value channel of the image." }, { "code": null, "e": 3344, "s": 3211, "text": "tree_hsv = rgb2hsv(tree[:,:,:-1])plt.figure(num=None, figsize=(8, 6), dpi=80)plt.imshow(tree_hsv[:,:,2], cmap='gray')plt.colorbar();" }, { "code": null, "e": 3469, "s": 3344, "text": "We can see that those brightly lit areas have incredibly high values. Let us take this into account when we create the mask." }, { "code": null, "e": 3795, "s": 3469, "text": "lower_mask = tree_hsv [:,:,0] > 0.80upper_mask = tree_hsv [:,:,0] <= 1.00value_mask = tree_hsv [:,:,2] < .90mask = upper_mask*lower_mask*value_maskred = tree[:,:,0] * maskgreen = tree[:,:,1] * maskblue = tree[:,:,2] * masktree_mask = np.dstack((red, green, blue))plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(tree_mask);" }, { "code": null, "e": 3981, "s": 3795, "text": "Great! We are almost there. We now have to find a way to clean the image and remove the little white dots. For this, we can simply use the median_filter function in the Skimage library." }, { "code": null, "e": 4326, "s": 3981, "text": "lower_mask = tree_hsv [:,:,0] > 0.80upper_mask = tree_hsv [:,:,0] <= 1.00value_mask = tree_hsv [:,:,2] < .90mask = median_filter(upper_mask*lower_mask*value_mask, 10)red = tree[:,:,0] * maskgreen = tree[:,:,1] * maskblue = tree[:,:,2] * masktree_mask = np.dstack((red, green, blue))plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(tree_mask);" }, { "code": null, "e": 4508, "s": 4326, "text": "We can see that incorporating the Median Filter gets us an extremely clean image. Now we need to identify each blob, to do this we need to make use of the label function in Skimage." }, { "code": null, "e": 4587, "s": 4508, "text": "tree_blobs = label(rgb2gray(tree_mask) > 0)imshow(tree_blobs, cmap = 'tab10');" }, { "code": null, "e": 4792, "s": 4587, "text": "We can see that the function identifies the different blobs in the image. The next step now is to get the properties of each blob. To do this we must make use of the regionprops_table function in Skimage." }, { "code": null, "e": 5001, "s": 4792, "text": "properties =['area','bbox','convex_area','bbox_area', 'major_axis_length', 'minor_axis_length', 'eccentricity']df = pd.DataFrame(regionprops_table(tree_blobs, properties = properties))" }, { "code": null, "e": 5298, "s": 5001, "text": "The regionprops_table function gives us the properties of each of the blobs in a convenient pandas DataFrame. This allows us to easily manipulate the data and pin point specific blobs. As an example of how useful this DataFrame is, let us use the bbox feature to draw bounding boxes on the image." }, { "code": null, "e": 5764, "s": 5298, "text": "blob_coordinates = [(row['bbox-0'],row['bbox-1'], row['bbox-2'],row['bbox-3'] )for index, row in df.iterrows()]fig, ax = plt.subplots(1,1, figsize=(8, 6), dpi = 80)for blob in tqdm(blob_coordinates): width = blob[3] - blob[1] height = blob[2] - blob[0] patch = Rectangle((blob[1],blob[0]), width, height, edgecolor='r', facecolor='none') ax.add_patch(patch)ax.imshow(tree);ax.set_axis_off()" }, { "code": null, "e": 5952, "s": 5764, "text": "If we look carefully we can see that there is a single bounding box on the upper left of the image. The object within the bounding box is clearly not a fruit. But how do we get rid of it?" }, { "code": null, "e": 6126, "s": 5952, "text": "Well, what we can do is filter the pandas DataFrame. For simplicity we shall filter it via the eccentricity column, this is because of the unique shape the outlier blob has." }, { "code": null, "e": 6181, "s": 6126, "text": "df = df[df['eccentricity'] < df['eccentricity'].max()]" }, { "code": null, "e": 6283, "s": 6181, "text": "If we plot out the bounding boxes again we see that we were able to successfully filter out the blob." }, { "code": null, "e": 6378, "s": 6283, "text": "Lastly, let us cut out the bounding boxes from the image and display them as their own images." }, { "code": null, "e": 6703, "s": 6378, "text": "fig, ax = plt.subplots(1, len(blob_coordinates), figsize=(15,5))for n, axis in enumerate(ax.flatten()): axis.imshow(tree[int(blob_coordinates[n][0]): int(blob_coordinates[n][2]), int(blob_coordinates[n][1]): int(blob_coordinates[n][3])]); fig.tight_layout()" }, { "code": null, "e": 6894, "s": 6703, "text": "Excellent, we have successfully identified the interesting mouth-like fruits in the image. The images can now be saved into a file and used later on (perhaps for a machine learning project)." }, { "code": null, "e": 6908, "s": 6894, "text": "In Conclusion" } ]
How to remove white spaces from a string using jQuery ?
22 Mar, 2021 In this article, we will see how to remove the white spaces from string using jQuery. To remove the white spaces, we will use trim() method. The trim() method is used to remove the white spaces from the beginning and end of a string. Syntax: jQuery.trim( str ) Parameters: This method accepts a single parameter string that is to be trimmed. In this case, we write string containing white spaces in <pre> tag and then apply trim() method to remove all white spaces from starting and ending position. After removing the white spaces we use html() method to display the trimmed string. Example: HTML <!DOCTYpe html><html> <head> <title> How to remove white space from a string using jQuery? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> $(document).ready(function () { $("h1").css("color", "green"); $("button").click(function () { $(".str").html("String without whitespaces"); var str = $(".string").text(); var trimStr = $.trim(str); $(".res-string").html(trimStr); }) }); </script></head> <body> <h1>GeeksforGeeks</h1> <h3> How to remove white space from a string using jQuery? </h3> <h4>String containing white spaces</h4> <pre class="string"> GeeksforGeeks </pre> <button>Trim String</button> <h4 class="str"></h4> <pre class="res-string"></pre></body> </html> Output: HTML-Questions HTML-Tags jQuery-Methods jQuery-Questions HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Mar, 2021" }, { "code": null, "e": 262, "s": 28, "text": "In this article, we will see how to remove the white spaces from string using jQuery. To remove the white spaces, we will use trim() method. The trim() method is used to remove the white spaces from the beginning and end of a string." }, { "code": null, "e": 270, "s": 262, "text": "Syntax:" }, { "code": null, "e": 289, "s": 270, "text": "jQuery.trim( str )" }, { "code": null, "e": 370, "s": 289, "text": "Parameters: This method accepts a single parameter string that is to be trimmed." }, { "code": null, "e": 612, "s": 370, "text": "In this case, we write string containing white spaces in <pre> tag and then apply trim() method to remove all white spaces from starting and ending position. After removing the white spaces we use html() method to display the trimmed string." }, { "code": null, "e": 621, "s": 612, "text": "Example:" }, { "code": null, "e": 626, "s": 621, "text": "HTML" }, { "code": "<!DOCTYpe html><html> <head> <title> How to remove white space from a string using jQuery? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> $(document).ready(function () { $(\"h1\").css(\"color\", \"green\"); $(\"button\").click(function () { $(\".str\").html(\"String without whitespaces\"); var str = $(\".string\").text(); var trimStr = $.trim(str); $(\".res-string\").html(trimStr); }) }); </script></head> <body> <h1>GeeksforGeeks</h1> <h3> How to remove white space from a string using jQuery? </h3> <h4>String containing white spaces</h4> <pre class=\"string\"> GeeksforGeeks </pre> <button>Trim String</button> <h4 class=\"str\"></h4> <pre class=\"res-string\"></pre></body> </html>", "e": 1555, "s": 626, "text": null }, { "code": null, "e": 1563, "s": 1555, "text": "Output:" }, { "code": null, "e": 1578, "s": 1563, "text": "HTML-Questions" }, { "code": null, "e": 1588, "s": 1578, "text": "HTML-Tags" }, { "code": null, "e": 1603, "s": 1588, "text": "jQuery-Methods" }, { "code": null, "e": 1620, "s": 1603, "text": "jQuery-Questions" }, { "code": null, "e": 1625, "s": 1620, "text": "HTML" }, { "code": null, "e": 1632, "s": 1625, "text": "JQuery" }, { "code": null, "e": 1649, "s": 1632, "text": "Web Technologies" }, { "code": null, "e": 1654, "s": 1649, "text": "HTML" } ]
Message Dialogs in Java (GUI)
26 Oct, 2021 Message dialogs provide information to the user. Message dialogs are created with the JOptionPane.showMessageDialog() method. We call the static showMessageDialog() method of the JOptionPane class to create a message dialog. We provide the dialog’s parent, message text, title, and message type. The message type is one of the following constants : ERROR_MESSAGEWARNING_MESSAGEQUESTION_MESSAGEINFORMATION_MESSAGE ERROR_MESSAGE WARNING_MESSAGE QUESTION_MESSAGE INFORMATION_MESSAGE Methods Used : setLayout(...): method helps us to set the layout of the container, often a JPanel, to say FlowLayout, BorderLayout, GridLayout, null layout, or whatever layout we want to add on container.setBounds(...): method is used to set the location and size of components like JButton, and is only useful if null layout is used in JFrame.setVisible(...): method is used to set the Visibility status of JFrame. setVisible(true) will set JFrame visible to user.setVisible(false) will set JFrame not visible to user.getSource(): An event object contains a reference to the component that generated the event. To extract that reference from the event object we use getSource() Method.add(): It is used to add components like JButton etc, to the container of JFrame. setLayout(...): method helps us to set the layout of the container, often a JPanel, to say FlowLayout, BorderLayout, GridLayout, null layout, or whatever layout we want to add on container. setBounds(...): method is used to set the location and size of components like JButton, and is only useful if null layout is used in JFrame. setVisible(...): method is used to set the Visibility status of JFrame. setVisible(true) will set JFrame visible to user.setVisible(false) will set JFrame not visible to user. setVisible(true) will set JFrame visible to user.setVisible(false) will set JFrame not visible to user. setVisible(true) will set JFrame visible to user. setVisible(false) will set JFrame not visible to user. getSource(): An event object contains a reference to the component that generated the event. To extract that reference from the event object we use getSource() Method. add(): It is used to add components like JButton etc, to the container of JFrame. Below is the implementation of above discussed method to show Message Dialogs : Java // Java program to show ERROR_MESSAGE dialog// in Java. Importing different Package.import java.awt.*;import java.awt.event.*;import javax.swing.*; class Demo extends JFrame implements ActionListener{ // Declaration of object of JButton class. JButton b1; // Constructor of Demo class Demo() { // Setting layout as null of JFrame. this.setLayout(null); // Initialization of object of "JButton" class. b1 = new JButton("Button 1"); // Setting Bounds of a JButton. b1.setBounds(130, 05, 100, 50); //"this" keyword in java refers to current object. // Adding JButton on JFrame. this.add(b1); // Adding Listener toJButton. b1.addActionListener(this); } // Override Method public void actionPerformed(ActionEvent evt) { if (evt.getSource() == b1) { // Code To popup an ERROR_MESSAGE Dialog. JOptionPane.showMessageDialog(this, "Enter a valid Number", "ERROR", JOptionPane.ERROR_MESSAGE); } }} class MessageDialogs1 { // Driver code public static void main(String args[]) { // Creating Object of demo class. Demo f = new Demo(); // Setting Bounds of a Frame. f.setBounds(200, 200, 400, 300); // Setting Resizable status of frame as false f.setResizable(false); // Setting Visible status of frame as true. f.setVisible(true); }} Output : Java // Java program to show WARNING_MESSAGE dialog// in Java. Importing different Package.import java.awt.*;import java.awt.event.*;import javax.swing.*; class Demo extends JFrame implements ActionListener{ // Declaration of object of JButton class. JButton b1; // Constructor of Demo class Demo() { // Setting layout as null of JFrame. this.setLayout(null); // Initialization of object of "JButton" class. b1 = new JButton("Button 2"); // Setting Bounds of a JButton. b1.setBounds(130, 05, 100, 50); //"this" keyword in java refers to current object. // Adding JButton on JFrame. this.add(b1); // Adding Listener toJButton. b1.addActionListener(this); } // Override Method public void actionPerformed(ActionEvent evt) { if (evt.getSource() == b1) { // Code To popup an WARNING_MESSAGE Dialog. JOptionPane.showMessageDialog(this, "Enter a valid String", "WARNING", JOptionPane.WARNING_MESSAGE); } }} class MessageDialogs2 { // Driver code public static void main(String args[]) { // Creating Object of demo class. Demo f = new Demo(); // Setting Bounds of a Frame. f.setBounds(200, 200, 400, 300); // Setting Resizable status of frame as false f.setResizable(false); // Setting Visible status of frame as true. f.setVisible(true); }} Output : Java // Java program to show QUESTION_MESSAGE// dialog in Java. Importing different Package.import java.awt.*;import java.awt.event.*;import javax.swing.*; class Demo extends JFrame implements ActionListener{ // Declaration of object of JButton class. JButton b1; // Constructor of Demo class Demo() { // Setting layout as null of JFrame. this.setLayout(null); // Initialization of object of "JButton" class. b1 = new JButton("Button 3"); // Setting Bounds of a JButton. b1.setBounds(130, 05, 100, 50); //"this" keyword in java refers to current object. // Adding JButton on JFrame. this.add(b1); // Adding Listener toJButton. b1.addActionListener(this); } // Override Method public void actionPerformed(ActionEvent evt) { if (evt.getSource() == b1) { // Code TO popup a QUESTION_MESSAGE Dialog. JOptionPane.showMessageDialog(this, "Do you want to quit", "Question", JOptionPane.QUESTION_MESSAGE); } }} class MessageDialogs3 { // Driver code public static void main(String args[]) { // Creating Object of demo class. Demo f = new Demo(); // Setting Bounds of a Frame. f.setBounds(200, 200, 400, 300); // Setting Resizable status of frame as false f.setResizable(false); // Setting Visible status of frame as true. f.setVisible(true); }} Output : Java // Java program to show INFORMATION_MESSAGE// dialog in Java. Importing different Package.import java.awt.*;import java.awt.event.*;import javax.swing.*; class Demo extends JFrame implements ActionListener{ // Declaration of object of JButton class. JButton b1; // Constructor of Demo class Demo() { // Setting layout as null of JFrame. this.setLayout(null); // Initialization of object of "JButton" class. b1 = new JButton("Button 4"); // Setting Bounds of a JButton. b1.setBounds(130, 05, 100, 50); //"this" keyword in java refers to current object. // Adding JButton on JFrame. this.add(b1); // Adding Listener toJButton. b1.addActionListener(this); } // Override Method public void actionPerformed(ActionEvent evt) { if (evt.getSource() == b1) { // Code To popup an INFORMATION_MESSAGE Dialog. JOptionPane.showMessageDialog(this, "You Pressed Button FOUR", "INFORMATION", JOptionPane.INFORMATION_MESSAGE); } }} class MessageDialogs4 { // Driver code public static void main(String args[]) { // Creating Object of demo class. Demo f = new Demo(); // Setting Bounds of a Frame. f.setBounds(200, 200, 400, 300); // Setting Resizable status of frame as false f.setResizable(false); // Setting Visible status of frame as true. f.setVisible(true); }} Output : akshaysingh98088 ruhelaa48 Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n26 Oct, 2021" }, { "code": null, "e": 180, "s": 54, "text": "Message dialogs provide information to the user. Message dialogs are created with the JOptionPane.showMessageDialog() method." }, { "code": null, "e": 404, "s": 180, "text": "We call the static showMessageDialog() method of the JOptionPane class to create a message dialog. We provide the dialog’s parent, message text, title, and message type. The message type is one of the following constants : " }, { "code": null, "e": 468, "s": 404, "text": "ERROR_MESSAGEWARNING_MESSAGEQUESTION_MESSAGEINFORMATION_MESSAGE" }, { "code": null, "e": 482, "s": 468, "text": "ERROR_MESSAGE" }, { "code": null, "e": 498, "s": 482, "text": "WARNING_MESSAGE" }, { "code": null, "e": 515, "s": 498, "text": "QUESTION_MESSAGE" }, { "code": null, "e": 535, "s": 515, "text": "INFORMATION_MESSAGE" }, { "code": null, "e": 551, "s": 535, "text": "Methods Used : " }, { "code": null, "e": 1304, "s": 551, "text": "setLayout(...): method helps us to set the layout of the container, often a JPanel, to say FlowLayout, BorderLayout, GridLayout, null layout, or whatever layout we want to add on container.setBounds(...): method is used to set the location and size of components like JButton, and is only useful if null layout is used in JFrame.setVisible(...): method is used to set the Visibility status of JFrame. setVisible(true) will set JFrame visible to user.setVisible(false) will set JFrame not visible to user.getSource(): An event object contains a reference to the component that generated the event. To extract that reference from the event object we use getSource() Method.add(): It is used to add components like JButton etc, to the container of JFrame." }, { "code": null, "e": 1494, "s": 1304, "text": "setLayout(...): method helps us to set the layout of the container, often a JPanel, to say FlowLayout, BorderLayout, GridLayout, null layout, or whatever layout we want to add on container." }, { "code": null, "e": 1635, "s": 1494, "text": "setBounds(...): method is used to set the location and size of components like JButton, and is only useful if null layout is used in JFrame." }, { "code": null, "e": 1811, "s": 1635, "text": "setVisible(...): method is used to set the Visibility status of JFrame. setVisible(true) will set JFrame visible to user.setVisible(false) will set JFrame not visible to user." }, { "code": null, "e": 1915, "s": 1811, "text": "setVisible(true) will set JFrame visible to user.setVisible(false) will set JFrame not visible to user." }, { "code": null, "e": 1965, "s": 1915, "text": "setVisible(true) will set JFrame visible to user." }, { "code": null, "e": 2020, "s": 1965, "text": "setVisible(false) will set JFrame not visible to user." }, { "code": null, "e": 2188, "s": 2020, "text": "getSource(): An event object contains a reference to the component that generated the event. To extract that reference from the event object we use getSource() Method." }, { "code": null, "e": 2270, "s": 2188, "text": "add(): It is used to add components like JButton etc, to the container of JFrame." }, { "code": null, "e": 2350, "s": 2270, "text": "Below is the implementation of above discussed method to show Message Dialogs :" }, { "code": null, "e": 2355, "s": 2350, "text": "Java" }, { "code": "// Java program to show ERROR_MESSAGE dialog// in Java. Importing different Package.import java.awt.*;import java.awt.event.*;import javax.swing.*; class Demo extends JFrame implements ActionListener{ // Declaration of object of JButton class. JButton b1; // Constructor of Demo class Demo() { // Setting layout as null of JFrame. this.setLayout(null); // Initialization of object of \"JButton\" class. b1 = new JButton(\"Button 1\"); // Setting Bounds of a JButton. b1.setBounds(130, 05, 100, 50); //\"this\" keyword in java refers to current object. // Adding JButton on JFrame. this.add(b1); // Adding Listener toJButton. b1.addActionListener(this); } // Override Method public void actionPerformed(ActionEvent evt) { if (evt.getSource() == b1) { // Code To popup an ERROR_MESSAGE Dialog. JOptionPane.showMessageDialog(this, \"Enter a valid Number\", \"ERROR\", JOptionPane.ERROR_MESSAGE); } }} class MessageDialogs1 { // Driver code public static void main(String args[]) { // Creating Object of demo class. Demo f = new Demo(); // Setting Bounds of a Frame. f.setBounds(200, 200, 400, 300); // Setting Resizable status of frame as false f.setResizable(false); // Setting Visible status of frame as true. f.setVisible(true); }}", "e": 3903, "s": 2355, "text": null }, { "code": null, "e": 3913, "s": 3903, "text": "Output : " }, { "code": null, "e": 3918, "s": 3913, "text": "Java" }, { "code": "// Java program to show WARNING_MESSAGE dialog// in Java. Importing different Package.import java.awt.*;import java.awt.event.*;import javax.swing.*; class Demo extends JFrame implements ActionListener{ // Declaration of object of JButton class. JButton b1; // Constructor of Demo class Demo() { // Setting layout as null of JFrame. this.setLayout(null); // Initialization of object of \"JButton\" class. b1 = new JButton(\"Button 2\"); // Setting Bounds of a JButton. b1.setBounds(130, 05, 100, 50); //\"this\" keyword in java refers to current object. // Adding JButton on JFrame. this.add(b1); // Adding Listener toJButton. b1.addActionListener(this); } // Override Method public void actionPerformed(ActionEvent evt) { if (evt.getSource() == b1) { // Code To popup an WARNING_MESSAGE Dialog. JOptionPane.showMessageDialog(this, \"Enter a valid String\", \"WARNING\", JOptionPane.WARNING_MESSAGE); } }} class MessageDialogs2 { // Driver code public static void main(String args[]) { // Creating Object of demo class. Demo f = new Demo(); // Setting Bounds of a Frame. f.setBounds(200, 200, 400, 300); // Setting Resizable status of frame as false f.setResizable(false); // Setting Visible status of frame as true. f.setVisible(true); }}", "e": 5476, "s": 3918, "text": null }, { "code": null, "e": 5487, "s": 5476, "text": "Output : " }, { "code": null, "e": 5492, "s": 5487, "text": "Java" }, { "code": "// Java program to show QUESTION_MESSAGE// dialog in Java. Importing different Package.import java.awt.*;import java.awt.event.*;import javax.swing.*; class Demo extends JFrame implements ActionListener{ // Declaration of object of JButton class. JButton b1; // Constructor of Demo class Demo() { // Setting layout as null of JFrame. this.setLayout(null); // Initialization of object of \"JButton\" class. b1 = new JButton(\"Button 3\"); // Setting Bounds of a JButton. b1.setBounds(130, 05, 100, 50); //\"this\" keyword in java refers to current object. // Adding JButton on JFrame. this.add(b1); // Adding Listener toJButton. b1.addActionListener(this); } // Override Method public void actionPerformed(ActionEvent evt) { if (evt.getSource() == b1) { // Code TO popup a QUESTION_MESSAGE Dialog. JOptionPane.showMessageDialog(this, \"Do you want to quit\", \"Question\", JOptionPane.QUESTION_MESSAGE); } }} class MessageDialogs3 { // Driver code public static void main(String args[]) { // Creating Object of demo class. Demo f = new Demo(); // Setting Bounds of a Frame. f.setBounds(200, 200, 400, 300); // Setting Resizable status of frame as false f.setResizable(false); // Setting Visible status of frame as true. f.setVisible(true); }}", "e": 7044, "s": 5492, "text": null }, { "code": null, "e": 7054, "s": 7044, "text": "Output : " }, { "code": null, "e": 7059, "s": 7054, "text": "Java" }, { "code": "// Java program to show INFORMATION_MESSAGE// dialog in Java. Importing different Package.import java.awt.*;import java.awt.event.*;import javax.swing.*; class Demo extends JFrame implements ActionListener{ // Declaration of object of JButton class. JButton b1; // Constructor of Demo class Demo() { // Setting layout as null of JFrame. this.setLayout(null); // Initialization of object of \"JButton\" class. b1 = new JButton(\"Button 4\"); // Setting Bounds of a JButton. b1.setBounds(130, 05, 100, 50); //\"this\" keyword in java refers to current object. // Adding JButton on JFrame. this.add(b1); // Adding Listener toJButton. b1.addActionListener(this); } // Override Method public void actionPerformed(ActionEvent evt) { if (evt.getSource() == b1) { // Code To popup an INFORMATION_MESSAGE Dialog. JOptionPane.showMessageDialog(this, \"You Pressed Button FOUR\", \"INFORMATION\", JOptionPane.INFORMATION_MESSAGE); } }} class MessageDialogs4 { // Driver code public static void main(String args[]) { // Creating Object of demo class. Demo f = new Demo(); // Setting Bounds of a Frame. f.setBounds(200, 200, 400, 300); // Setting Resizable status of frame as false f.setResizable(false); // Setting Visible status of frame as true. f.setVisible(true); }}", "e": 8691, "s": 7059, "text": null }, { "code": null, "e": 8701, "s": 8691, "text": "Output : " }, { "code": null, "e": 8718, "s": 8701, "text": "akshaysingh98088" }, { "code": null, "e": 8728, "s": 8718, "text": "ruhelaa48" }, { "code": null, "e": 8733, "s": 8728, "text": "Java" }, { "code": null, "e": 8738, "s": 8733, "text": "Java" } ]
Sequence Alignment problem
18 Feb, 2022 Given as an input two strings, = , and = , output the alignment of the strings, character by character, so that the net penalty is minimized. The penalty is calculated as: 1. A penalty of occurs if a gap is inserted between the string. 2. A penalty of occurs for mis-matching the characters of and . Examples: Input : X = CG, Y = CA, p_gap = 3, p_xy = 7 Output : X = CG_, Y = C_A, Total penalty = 6 Input : X = AGGGCT, Y = AGGCA, p_gap = 3, p_xy = 2 Output : X = AGGGCT, Y = A_GGCA, Total penalty = 5 Input : X = CG, Y = CA, p_gap = 3, p_xy = 5 Output : X = CG, Y = CA, Total penalty = 5 A brief Note on the history of the problem The Sequence Alignment problem is one of the fundamental problems of Biological Sciences, aimed at finding the similarity of two amino-acid sequences. Comparing amino-acids is of prime importance to humans, since it gives vital information on evolution and development. Saul B. Needleman and Christian D. Wunsch devised a dynamic programming algorithm to the problem and got it published in 1970. Since then, numerous improvements have been made to improve the time complexity and space complexity, however these are beyond the scope of discussion in this post. Solution We can use dynamic programming to solve this problem. The feasible solution is to introduce gaps into the strings, so as to equalise the lengths. Since it can be easily proved that the addition of extra gaps after equalising the lengths will only lead to increment of penalty. Optimal Substructure It can be observed from an optimal solution, for example from the given sample input, that the optimal solution narrows down to only three candidates. 1. and . 2. and gap. 3. gap and .Proof of Optimal Substructure. We can easily prove by contradiction. Let be and be . Suppose that the induced alignment of , has some penalty , and a competitor alignment has a penalty , with . Now, appending and , we get an alignment with penalty . This contradicts the optimality of the original alignment of . Hence, proved.Let be the penalty of the optimal alignment of and . Then, from the optimal substructure, . The total minimum penalty is thus, . Reconstructing the solution To Reconstruct, 1. Trace back through the filled table, starting . 2. When .....2a. if it was filled using case 1, go to . .....2b. if it was filled using case 2, go to . .....2c. if it was filled using case 3, go to . 3. if either i = 0 or j = 0, match the remaining substring with gaps. Below is the implementation of the above solution. C++ Java Python3 C# PHP // CPP program to implement sequence alignment// problem.#include <bits/stdc++.h> using namespace std; // function to find out the minimum penaltyvoid getMinimumPenalty(string x, string y, int pxy, int pgap){ int i, j; // initialising variables int m = x.length(); // length of gene1 int n = y.length(); // length of gene2 // table for storing optimal substructure answers int dp[m+1][n+1] = {0}; // initialising the table for (i = 0; i <= (n+m); i++) { dp[i][0] = i * pgap; dp[0][i] = i * pgap; } // calculating the minimum penalty for (i = 1; i <= m; i++) { for (j = 1; j <= n; j++) { if (x[i - 1] == y[j - 1]) { dp[i][j] = dp[i - 1][j - 1]; } else { dp[i][j] = min({dp[i - 1][j - 1] + pxy , dp[i - 1][j] + pgap , dp[i][j - 1] + pgap }); } } } // Reconstructing the solution int l = n + m; // maximum possible length i = m; j = n; int xpos = l; int ypos = l; // Final answers for the respective strings int xans[l+1], yans[l+1]; while ( !(i == 0 || j == 0)) { if (x[i - 1] == y[j - 1]) { xans[xpos--] = (int)x[i - 1]; yans[ypos--] = (int)y[j - 1]; i--; j--; } else if (dp[i - 1][j - 1] + pxy == dp[i][j]) { xans[xpos--] = (int)x[i - 1]; yans[ypos--] = (int)y[j - 1]; i--; j--; } else if (dp[i - 1][j] + pgap == dp[i][j]) { xans[xpos--] = (int)x[i - 1]; yans[ypos--] = (int)'_'; i--; } else if (dp[i][j - 1] + pgap == dp[i][j]) { xans[xpos--] = (int)'_'; yans[ypos--] = (int)y[j - 1]; j--; } } while (xpos > 0) { if (i > 0) xans[xpos--] = (int)x[--i]; else xans[xpos--] = (int)'_'; } while (ypos > 0) { if (j > 0) yans[ypos--] = (int)y[--j]; else yans[ypos--] = (int)'_'; } // Since we have assumed the answer to be n+m long, // we need to remove the extra gaps in the starting // id represents the index from which the arrays // xans, yans are useful int id = 1; for (i = l; i >= 1; i--) { if ((char)yans[i] == '_' && (char)xans[i] == '_') { id = i + 1; break; } } // Printing the final answer cout << "Minimum Penalty in aligning the genes = "; cout << dp[m][n] << "\n"; cout << "The aligned genes are :\n"; for (i = id; i <= l; i++) { cout<<(char)xans[i]; } cout << "\n"; for (i = id; i <= l; i++) { cout << (char)yans[i]; } return;} // Driver codeint main(){ // input strings string gene1 = "AGGGCT"; string gene2 = "AGGCA"; // initialising penalties of different types int misMatchPenalty = 3; int gapPenalty = 2; // calling the function to calculate the result getMinimumPenalty(gene1, gene2, misMatchPenalty, gapPenalty); return 0;} // Java program to implement// sequence alignment problem.import java.io.*;import java.util.*;import java.lang.*; class GFG{// function to find out// the minimum penaltystatic void getMinimumPenalty(String x, String y, int pxy, int pgap){ int i, j; // initialising variables int m = x.length(); // length of gene1 int n = y.length(); // length of gene2 // table for storing optimal // substructure answers int dp[][] = new int[n + m + 1][n + m + 1]; for (int[] x1 : dp) Arrays.fill(x1, 0); // initialising the table for (i = 0; i <= (n + m); i++) { dp[i][0] = i * pgap; dp[0][i] = i * pgap; } // calculating the // minimum penalty for (i = 1; i <= m; i++) { for (j = 1; j <= n; j++) { if (x.charAt(i - 1) == y.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1]; } else { dp[i][j] = Math.min(Math.min(dp[i - 1][j - 1] + pxy , dp[i - 1][j] + pgap) , dp[i][j - 1] + pgap ); } } } // Reconstructing the solution int l = n + m; // maximum possible length i = m; j = n; int xpos = l; int ypos = l; // Final answers for // the respective strings int xans[] = new int[l + 1]; int yans[] = new int[l + 1]; while ( !(i == 0 || j == 0)) { if (x.charAt(i - 1) == y.charAt(j - 1)) { xans[xpos--] = (int)x.charAt(i - 1); yans[ypos--] = (int)y.charAt(j - 1); i--; j--; } else if (dp[i - 1][j - 1] + pxy == dp[i][j]) { xans[xpos--] = (int)x.charAt(i - 1); yans[ypos--] = (int)y.charAt(j - 1); i--; j--; } else if (dp[i - 1][j] + pgap == dp[i][j]) { xans[xpos--] = (int)x.charAt(i - 1); yans[ypos--] = (int)'_'; i--; } else if (dp[i][j - 1] + pgap == dp[i][j]) { xans[xpos--] = (int)'_'; yans[ypos--] = (int)y.charAt(j - 1); j--; } } while (xpos > 0) { if (i > 0) xans[xpos--] = (int)x.charAt(--i); else xans[xpos--] = (int)'_'; } while (ypos > 0) { if (j > 0) yans[ypos--] = (int)y.charAt(--j); else yans[ypos--] = (int)'_'; } // Since we have assumed the // answer to be n+m long, // we need to remove the extra // gaps in the starting id // represents the index from // which the arrays xans, // yans are useful int id = 1; for (i = l; i >= 1; i--) { if ((char)yans[i] == '_' && (char)xans[i] == '_') { id = i + 1; break; } } // Printing the final answer System.out.print("Minimum Penalty in " + "aligning the genes = "); System.out.print(dp[m][n] + "\n"); System.out.println("The aligned genes are :"); for (i = id; i <= l; i++) { System.out.print((char)xans[i]); } System.out.print("\n"); for (i = id; i <= l; i++) { System.out.print((char)yans[i]); } return;} // Driver codepublic static void main(String[] args){ // input strings String gene1 = "AGGGCT"; String gene2 = "AGGCA"; // initialising penalties // of different types int misMatchPenalty = 3; int gapPenalty = 2; // calling the function to // calculate the result getMinimumPenalty(gene1, gene2, misMatchPenalty, gapPenalty);}} #!/bin/python3"""Origin: https://www.geeksforgeeks.org/sequence-alignment-problem/Converted from C++ solution to Python3 Algorithm type / application: Bioinformatics Python Requirements: numpy """import numpy as np def get_minimum_penalty(x:str, y:str, pxy:int, pgap:int): """ Function to find out the minimum penalty :param x: pattern X :param y: pattern Y :param pxy: penalty of mis-matching the characters of X and Y :param pgap: penalty of a gap between pattern elements """ # initializing variables i = 0 j = 0 # pattern lengths m = len(x) n = len(y) # table for storing optimal substructure answers dp = np.zeros([m+1,n+1], dtype=int) #int dp[m+1][n+1] = {0}; # initialising the table dp[0:(m+1),0] = [ i * pgap for i in range(m+1)] dp[0,0:(n+1)] = [ i * pgap for i in range(n+1)] # calculating the minimum penalty i = 1 while i <= m: j = 1 while j <= n: if x[i - 1] == y[j - 1]: dp[i][j] = dp[i - 1][j - 1] else: dp[i][j] = min(dp[i - 1][j - 1] + pxy, dp[i - 1][j] + pgap, dp[i][j - 1] + pgap) j += 1 i += 1 # Reconstructing the solution l = n + m # maximum possible length i = m j = n xpos = l ypos = l # Final answers for the respective strings xans = np.zeros(l+1, dtype=int) yans = np.zeros(l+1, dtype=int) while not (i == 0 or j == 0): #print(f"i: {i}, j: {j}") if x[i - 1] == y[j - 1]: xans[xpos] = ord(x[i - 1]) yans[ypos] = ord(y[j - 1]) xpos -= 1 ypos -= 1 i -= 1 j -= 1 elif (dp[i - 1][j - 1] + pxy) == dp[i][j]: xans[xpos] = ord(x[i - 1]) yans[ypos] = ord(y[j - 1]) xpos -= 1 ypos -= 1 i -= 1 j -= 1 elif (dp[i - 1][j] + pgap) == dp[i][j]: xans[xpos] = ord(x[i - 1]) yans[ypos] = ord('_') xpos -= 1 ypos -= 1 i -= 1 elif (dp[i][j - 1] + pgap) == dp[i][j]: xans[xpos] = ord('_') yans[ypos] = ord(y[j - 1]) xpos -= 1 ypos -= 1 j -= 1 while xpos > 0: if i > 0: i -= 1 xans[xpos] = ord(x[i]) xpos -= 1 else: xans[xpos] = ord('_') xpos -= 1 while ypos > 0: if j > 0: j -= 1 yans[ypos] = ord(y[j]) ypos -= 1 else: yans[ypos] = ord('_') ypos -= 1 # Since we have assumed the answer to be n+m long, # we need to remove the extra gaps in the starting # id represents the index from which the arrays # xans, yans are useful id = 1 i = l while i >= 1: if (chr(yans[i]) == '_') and chr(xans[i]) == '_': id = i + 1 break i -= 1 # Printing the final answer print(f"Minimum Penalty in aligning the genes = {dp[m][n]}") print("The aligned genes are:") # X i = id x_seq = "" while i <= l: x_seq += chr(xans[i]) i += 1 print(f"X seq: {x_seq}") # Y i = id y_seq = "" while i <= l: y_seq += chr(yans[i]) i += 1 print(f"Y seq: {y_seq}") def test_get_minimum_penalty(): """ Test the get_minimum_penalty function """ # input strings gene1 = "AGGGCT" gene2 = "AGGCA" # initialising penalties of different types mismatch_penalty = 3 gap_penalty = 2 # calling the function to calculate the result get_minimum_penalty(gene1, gene2, mismatch_penalty, gap_penalty) test_get_minimum_penalty() # This code is contributed by wilderchirstopher. // C# program to implement sequence alignment// problem.using System; class GFG{ // function to find out the minimum penalty public static void getMinimumPenalty(string x, string y, int pxy, int pgap) { int i, j; // initialising variables int m = x.Length; // length of gene1 int n = y.Length; // length of gene2 // table for storing optimal substructure answers int[,] dp = new int[n+m+1,n+m+1]; for(int q = 0; q < n+m+1; q++) for(int w = 0; w < n+m+1; w++) dp[q,w] = 0; // initialising the table for (i = 0; i <= (n+m); i++) { dp[i,0] = i * pgap; dp[0,i] = i * pgap; } // calculating the minimum penalty for (i = 1; i <= m; i++) { for (j = 1; j <= n; j++) { if (x[i - 1] == y[j - 1]) { dp[i,j] = dp[i - 1,j - 1]; } else { dp[i,j] = Math.Min(Math.Min(dp[i - 1,j - 1] + pxy , dp[i - 1,j] + pgap) , dp[i,j - 1] + pgap ); } } } // Reconstructing the solution int l = n + m; // maximum possible length i = m; j = n; int xpos = l; int ypos = l; // Final answers for the respective strings int[] xans = new int[l+1]; int [] yans = new int[l+1]; while ( !(i == 0 || j == 0)) { if (x[i - 1] == y[j - 1]) { xans[xpos--] = (int)x[i - 1]; yans[ypos--] = (int)y[j - 1]; i--; j--; } else if (dp[i - 1,j - 1] + pxy == dp[i,j]) { xans[xpos--] = (int)x[i - 1]; yans[ypos--] = (int)y[j - 1]; i--; j--; } else if (dp[i - 1,j] + pgap == dp[i,j]) { xans[xpos--] = (int)x[i - 1]; yans[ypos--] = (int)'_'; i--; } else if (dp[i,j - 1] + pgap == dp[i,j]) { xans[xpos--] = (int)'_'; yans[ypos--] = (int)y[j - 1]; j--; } } while (xpos > 0) { if (i > 0) xans[xpos--] = (int)x[--i]; else xans[xpos--] = (int)'_'; } while (ypos > 0) { if (j > 0) yans[ypos--] = (int)y[--j]; else yans[ypos--] = (int)'_'; } // Since we have assumed the answer to be n+m long, // we need to remove the extra gaps in the starting // id represents the index from which the arrays // xans, yans are useful int id = 1; for (i = l; i >= 1; i--) { if ((char)yans[i] == '_' && (char)xans[i] == '_') { id = i + 1; break; } } // Printing the final answer Console.Write("Minimum Penalty in aligning the genes = " + dp[m,n] + "\n"); Console.Write("The aligned genes are :\n"); for (i = id; i <= l; i++) { Console.Write((char)xans[i]); } Console.Write("\n"); for (i = id; i <= l; i++) { Console.Write((char)yans[i]); } return; } // Driver code static void Main() { // input strings string gene1 = "AGGGCT"; string gene2 = "AGGCA"; // initialising penalties of different types int misMatchPenalty = 3; int gapPenalty = 2; // calling the function to calculate the result getMinimumPenalty(gene1, gene2, misMatchPenalty, gapPenalty); } //This code is contributed by DrRoot_} <?php// PHP program to implement// sequence alignment problem. // function to find out// the minimum penaltyfunction getMinimumPenalty($x, $y, $pxy, $pgap){ $i; $j; // initializing variables $m = strlen($x); // length of gene1 $n = strlen($y); // length of gene2 // table for storing optimal // substructure answers $dp[$n + $m + 1][$n + $m + 1] = array(0); // initialising the table for ($i = 0; $i <= ($n+$m); $i++) { $dp[$i][0] = $i * $pgap; $dp[0][$i] = $i * $pgap; } // calculating the // minimum penalty for ($i = 1; $i <= $m; $i++) { for ($j = 1; $j <= $n; $j++) { if ($x[$i - 1] == $y[$j - 1]) { $dp[$i][$j] = $dp[$i - 1][$j - 1]; } else { $dp[$i][$j] = min($dp[$i - 1][$j - 1] + $pxy , $dp[$i - 1][$j] + $pgap , $dp[$i][$j - 1] + $pgap ); } } } // Reconstructing the solution $l = $n + $m; // maximum possible length $i = $m; $j = $n; $xpos = $l; $ypos = $l; // Final answers for // the respective strings // $xans[$l + 1]; $yans[$l + 1]; while ( !($i == 0 || $j == 0)) { if ($x[$i - 1] == $y[$j - 1]) { $xans[$xpos--] = $x[$i - 1]; $yans[$ypos--] = $y[$j - 1]; $i--; $j--; } else if ($dp[$i - 1][$j - 1] + $pxy == $dp[$i][$j]) { $xans[$xpos--] = $x[$i - 1]; $yans[$ypos--] = $y[$j - 1]; $i--; $j--; } else if ($dp[$i - 1][$j] + $pgap == $dp[$i][$j]) { $xans[$xpos--] = $x[$i - 1]; $yans[$ypos--] = '_'; $i--; } else if ($dp[$i][$j - 1] + $pgap == $dp[$i][$j]) { $xans[$xpos--] = '_'; $yans[$ypos--] = $y[$j - 1]; $j--; } } while ($xpos > 0) { if ($i > 0) $xans[$xpos--] = $x[--$i]; else $xans[$xpos--] = '_'; } while ($ypos > 0) { if ($j > 0) $yans[$ypos--] = $y[--$j]; else $yans[$ypos--] = '_'; } // Since we have assumed the // answer to be n+m long, // we need to remove the extra // gaps in the starting // id represents the index // from which the arrays // xans, yans are useful $id = 1; for ($i = $l; $i >= 1; $i--) { if ($yans[$i] == '_' && $xans[$i] == '_') { $id = $i + 1; break; } } // Printing the final answer echo "Minimum Penalty in ". "aligning the genes = "; echo $dp[$m][$n] . "\n"; echo "The aligned genes are :\n"; for ($i = $id; $i <= $l; $i++) { echo $xans[$i]; } echo "\n"; for ($i = $id; $i <= $l; $i++) { echo $yans[$i]; } return;} // Driver code // input strings$gene1 = "AGGGCT";$gene2 = "AGGCA"; // initialising penalties// of different types$misMatchPenalty = 3;$gapPenalty = 2; // calling the function// to calculate the resultgetMinimumPenalty($gene1, $gene2, $misMatchPenalty, $gapPenalty); // This code is contributed by Abhinav96?> Minimum Penalty in aligning the genes = 5 The aligned genes are : AGGGCT A_GGCA Time Complexity : Space Complexity : AayushChaturvedi DrRoot_ myhome890131 adnanirshad158 sagartomar9927 sweetyty wilderchristopher rkbhola5 Competitive Programming Dynamic Programming Strings Strings Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Feb, 2022" }, { "code": null, "e": 352, "s": 52, "text": "Given as an input two strings, = , and = , output the alignment of the strings, character by character, so that the net penalty is minimized. The penalty is calculated as: 1. A penalty of occurs if a gap is inserted between the string. 2. A penalty of occurs for mis-matching the characters of and ." }, { "code": null, "e": 363, "s": 352, "text": "Examples: " }, { "code": null, "e": 643, "s": 363, "text": "Input : X = CG, Y = CA, p_gap = 3, p_xy = 7\nOutput : X = CG_, Y = C_A, Total penalty = 6\n\nInput : X = AGGGCT, Y = AGGCA, p_gap = 3, p_xy = 2\nOutput : X = AGGGCT, Y = A_GGCA, Total penalty = 5\n\nInput : X = CG, Y = CA, p_gap = 3, p_xy = 5\nOutput : X = CG, Y = CA, Total penalty = 5" }, { "code": null, "e": 1248, "s": 643, "text": "A brief Note on the history of the problem The Sequence Alignment problem is one of the fundamental problems of Biological Sciences, aimed at finding the similarity of two amino-acid sequences. Comparing amino-acids is of prime importance to humans, since it gives vital information on evolution and development. Saul B. Needleman and Christian D. Wunsch devised a dynamic programming algorithm to the problem and got it published in 1970. Since then, numerous improvements have been made to improve the time complexity and space complexity, however these are beyond the scope of discussion in this post." }, { "code": null, "e": 1534, "s": 1248, "text": "Solution We can use dynamic programming to solve this problem. The feasible solution is to introduce gaps into the strings, so as to equalise the lengths. Since it can be easily proved that the addition of extra gaps after equalising the lengths will only lead to increment of penalty." }, { "code": null, "e": 2195, "s": 1534, "text": "Optimal Substructure It can be observed from an optimal solution, for example from the given sample input, that the optimal solution narrows down to only three candidates. 1. and . 2. and gap. 3. gap and .Proof of Optimal Substructure. We can easily prove by contradiction. Let be and be . Suppose that the induced alignment of , has some penalty , and a competitor alignment has a penalty , with . Now, appending and , we get an alignment with penalty . This contradicts the optimality of the original alignment of . Hence, proved.Let be the penalty of the optimal alignment of and . Then, from the optimal substructure, . The total minimum penalty is thus, ." }, { "code": null, "e": 2512, "s": 2195, "text": "Reconstructing the solution To Reconstruct, 1. Trace back through the filled table, starting . 2. When .....2a. if it was filled using case 1, go to . .....2b. if it was filled using case 2, go to . .....2c. if it was filled using case 3, go to . 3. if either i = 0 or j = 0, match the remaining substring with gaps." }, { "code": null, "e": 2564, "s": 2512, "text": "Below is the implementation of the above solution. " }, { "code": null, "e": 2568, "s": 2564, "text": "C++" }, { "code": null, "e": 2573, "s": 2568, "text": "Java" }, { "code": null, "e": 2581, "s": 2573, "text": "Python3" }, { "code": null, "e": 2584, "s": 2581, "text": "C#" }, { "code": null, "e": 2588, "s": 2584, "text": "PHP" }, { "code": "// CPP program to implement sequence alignment// problem.#include <bits/stdc++.h> using namespace std; // function to find out the minimum penaltyvoid getMinimumPenalty(string x, string y, int pxy, int pgap){ int i, j; // initialising variables int m = x.length(); // length of gene1 int n = y.length(); // length of gene2 // table for storing optimal substructure answers int dp[m+1][n+1] = {0}; // initialising the table for (i = 0; i <= (n+m); i++) { dp[i][0] = i * pgap; dp[0][i] = i * pgap; } // calculating the minimum penalty for (i = 1; i <= m; i++) { for (j = 1; j <= n; j++) { if (x[i - 1] == y[j - 1]) { dp[i][j] = dp[i - 1][j - 1]; } else { dp[i][j] = min({dp[i - 1][j - 1] + pxy , dp[i - 1][j] + pgap , dp[i][j - 1] + pgap }); } } } // Reconstructing the solution int l = n + m; // maximum possible length i = m; j = n; int xpos = l; int ypos = l; // Final answers for the respective strings int xans[l+1], yans[l+1]; while ( !(i == 0 || j == 0)) { if (x[i - 1] == y[j - 1]) { xans[xpos--] = (int)x[i - 1]; yans[ypos--] = (int)y[j - 1]; i--; j--; } else if (dp[i - 1][j - 1] + pxy == dp[i][j]) { xans[xpos--] = (int)x[i - 1]; yans[ypos--] = (int)y[j - 1]; i--; j--; } else if (dp[i - 1][j] + pgap == dp[i][j]) { xans[xpos--] = (int)x[i - 1]; yans[ypos--] = (int)'_'; i--; } else if (dp[i][j - 1] + pgap == dp[i][j]) { xans[xpos--] = (int)'_'; yans[ypos--] = (int)y[j - 1]; j--; } } while (xpos > 0) { if (i > 0) xans[xpos--] = (int)x[--i]; else xans[xpos--] = (int)'_'; } while (ypos > 0) { if (j > 0) yans[ypos--] = (int)y[--j]; else yans[ypos--] = (int)'_'; } // Since we have assumed the answer to be n+m long, // we need to remove the extra gaps in the starting // id represents the index from which the arrays // xans, yans are useful int id = 1; for (i = l; i >= 1; i--) { if ((char)yans[i] == '_' && (char)xans[i] == '_') { id = i + 1; break; } } // Printing the final answer cout << \"Minimum Penalty in aligning the genes = \"; cout << dp[m][n] << \"\\n\"; cout << \"The aligned genes are :\\n\"; for (i = id; i <= l; i++) { cout<<(char)xans[i]; } cout << \"\\n\"; for (i = id; i <= l; i++) { cout << (char)yans[i]; } return;} // Driver codeint main(){ // input strings string gene1 = \"AGGGCT\"; string gene2 = \"AGGCA\"; // initialising penalties of different types int misMatchPenalty = 3; int gapPenalty = 2; // calling the function to calculate the result getMinimumPenalty(gene1, gene2, misMatchPenalty, gapPenalty); return 0;}", "e": 5750, "s": 2588, "text": null }, { "code": "// Java program to implement// sequence alignment problem.import java.io.*;import java.util.*;import java.lang.*; class GFG{// function to find out// the minimum penaltystatic void getMinimumPenalty(String x, String y, int pxy, int pgap){ int i, j; // initialising variables int m = x.length(); // length of gene1 int n = y.length(); // length of gene2 // table for storing optimal // substructure answers int dp[][] = new int[n + m + 1][n + m + 1]; for (int[] x1 : dp) Arrays.fill(x1, 0); // initialising the table for (i = 0; i <= (n + m); i++) { dp[i][0] = i * pgap; dp[0][i] = i * pgap; } // calculating the // minimum penalty for (i = 1; i <= m; i++) { for (j = 1; j <= n; j++) { if (x.charAt(i - 1) == y.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1]; } else { dp[i][j] = Math.min(Math.min(dp[i - 1][j - 1] + pxy , dp[i - 1][j] + pgap) , dp[i][j - 1] + pgap ); } } } // Reconstructing the solution int l = n + m; // maximum possible length i = m; j = n; int xpos = l; int ypos = l; // Final answers for // the respective strings int xans[] = new int[l + 1]; int yans[] = new int[l + 1]; while ( !(i == 0 || j == 0)) { if (x.charAt(i - 1) == y.charAt(j - 1)) { xans[xpos--] = (int)x.charAt(i - 1); yans[ypos--] = (int)y.charAt(j - 1); i--; j--; } else if (dp[i - 1][j - 1] + pxy == dp[i][j]) { xans[xpos--] = (int)x.charAt(i - 1); yans[ypos--] = (int)y.charAt(j - 1); i--; j--; } else if (dp[i - 1][j] + pgap == dp[i][j]) { xans[xpos--] = (int)x.charAt(i - 1); yans[ypos--] = (int)'_'; i--; } else if (dp[i][j - 1] + pgap == dp[i][j]) { xans[xpos--] = (int)'_'; yans[ypos--] = (int)y.charAt(j - 1); j--; } } while (xpos > 0) { if (i > 0) xans[xpos--] = (int)x.charAt(--i); else xans[xpos--] = (int)'_'; } while (ypos > 0) { if (j > 0) yans[ypos--] = (int)y.charAt(--j); else yans[ypos--] = (int)'_'; } // Since we have assumed the // answer to be n+m long, // we need to remove the extra // gaps in the starting id // represents the index from // which the arrays xans, // yans are useful int id = 1; for (i = l; i >= 1; i--) { if ((char)yans[i] == '_' && (char)xans[i] == '_') { id = i + 1; break; } } // Printing the final answer System.out.print(\"Minimum Penalty in \" + \"aligning the genes = \"); System.out.print(dp[m][n] + \"\\n\"); System.out.println(\"The aligned genes are :\"); for (i = id; i <= l; i++) { System.out.print((char)xans[i]); } System.out.print(\"\\n\"); for (i = id; i <= l; i++) { System.out.print((char)yans[i]); } return;} // Driver codepublic static void main(String[] args){ // input strings String gene1 = \"AGGGCT\"; String gene2 = \"AGGCA\"; // initialising penalties // of different types int misMatchPenalty = 3; int gapPenalty = 2; // calling the function to // calculate the result getMinimumPenalty(gene1, gene2, misMatchPenalty, gapPenalty);}}", "e": 9354, "s": 5750, "text": null }, { "code": "#!/bin/python3\"\"\"Origin: https://www.geeksforgeeks.org/sequence-alignment-problem/Converted from C++ solution to Python3 Algorithm type / application: Bioinformatics Python Requirements: numpy \"\"\"import numpy as np def get_minimum_penalty(x:str, y:str, pxy:int, pgap:int): \"\"\" Function to find out the minimum penalty :param x: pattern X :param y: pattern Y :param pxy: penalty of mis-matching the characters of X and Y :param pgap: penalty of a gap between pattern elements \"\"\" # initializing variables i = 0 j = 0 # pattern lengths m = len(x) n = len(y) # table for storing optimal substructure answers dp = np.zeros([m+1,n+1], dtype=int) #int dp[m+1][n+1] = {0}; # initialising the table dp[0:(m+1),0] = [ i * pgap for i in range(m+1)] dp[0,0:(n+1)] = [ i * pgap for i in range(n+1)] # calculating the minimum penalty i = 1 while i <= m: j = 1 while j <= n: if x[i - 1] == y[j - 1]: dp[i][j] = dp[i - 1][j - 1] else: dp[i][j] = min(dp[i - 1][j - 1] + pxy, dp[i - 1][j] + pgap, dp[i][j - 1] + pgap) j += 1 i += 1 # Reconstructing the solution l = n + m # maximum possible length i = m j = n xpos = l ypos = l # Final answers for the respective strings xans = np.zeros(l+1, dtype=int) yans = np.zeros(l+1, dtype=int) while not (i == 0 or j == 0): #print(f\"i: {i}, j: {j}\") if x[i - 1] == y[j - 1]: xans[xpos] = ord(x[i - 1]) yans[ypos] = ord(y[j - 1]) xpos -= 1 ypos -= 1 i -= 1 j -= 1 elif (dp[i - 1][j - 1] + pxy) == dp[i][j]: xans[xpos] = ord(x[i - 1]) yans[ypos] = ord(y[j - 1]) xpos -= 1 ypos -= 1 i -= 1 j -= 1 elif (dp[i - 1][j] + pgap) == dp[i][j]: xans[xpos] = ord(x[i - 1]) yans[ypos] = ord('_') xpos -= 1 ypos -= 1 i -= 1 elif (dp[i][j - 1] + pgap) == dp[i][j]: xans[xpos] = ord('_') yans[ypos] = ord(y[j - 1]) xpos -= 1 ypos -= 1 j -= 1 while xpos > 0: if i > 0: i -= 1 xans[xpos] = ord(x[i]) xpos -= 1 else: xans[xpos] = ord('_') xpos -= 1 while ypos > 0: if j > 0: j -= 1 yans[ypos] = ord(y[j]) ypos -= 1 else: yans[ypos] = ord('_') ypos -= 1 # Since we have assumed the answer to be n+m long, # we need to remove the extra gaps in the starting # id represents the index from which the arrays # xans, yans are useful id = 1 i = l while i >= 1: if (chr(yans[i]) == '_') and chr(xans[i]) == '_': id = i + 1 break i -= 1 # Printing the final answer print(f\"Minimum Penalty in aligning the genes = {dp[m][n]}\") print(\"The aligned genes are:\") # X i = id x_seq = \"\" while i <= l: x_seq += chr(xans[i]) i += 1 print(f\"X seq: {x_seq}\") # Y i = id y_seq = \"\" while i <= l: y_seq += chr(yans[i]) i += 1 print(f\"Y seq: {y_seq}\") def test_get_minimum_penalty(): \"\"\" Test the get_minimum_penalty function \"\"\" # input strings gene1 = \"AGGGCT\" gene2 = \"AGGCA\" # initialising penalties of different types mismatch_penalty = 3 gap_penalty = 2 # calling the function to calculate the result get_minimum_penalty(gene1, gene2, mismatch_penalty, gap_penalty) test_get_minimum_penalty() # This code is contributed by wilderchirstopher.", "e": 13215, "s": 9354, "text": null }, { "code": "// C# program to implement sequence alignment// problem.using System; class GFG{ // function to find out the minimum penalty public static void getMinimumPenalty(string x, string y, int pxy, int pgap) { int i, j; // initialising variables int m = x.Length; // length of gene1 int n = y.Length; // length of gene2 // table for storing optimal substructure answers int[,] dp = new int[n+m+1,n+m+1]; for(int q = 0; q < n+m+1; q++) for(int w = 0; w < n+m+1; w++) dp[q,w] = 0; // initialising the table for (i = 0; i <= (n+m); i++) { dp[i,0] = i * pgap; dp[0,i] = i * pgap; } // calculating the minimum penalty for (i = 1; i <= m; i++) { for (j = 1; j <= n; j++) { if (x[i - 1] == y[j - 1]) { dp[i,j] = dp[i - 1,j - 1]; } else { dp[i,j] = Math.Min(Math.Min(dp[i - 1,j - 1] + pxy , dp[i - 1,j] + pgap) , dp[i,j - 1] + pgap ); } } } // Reconstructing the solution int l = n + m; // maximum possible length i = m; j = n; int xpos = l; int ypos = l; // Final answers for the respective strings int[] xans = new int[l+1]; int [] yans = new int[l+1]; while ( !(i == 0 || j == 0)) { if (x[i - 1] == y[j - 1]) { xans[xpos--] = (int)x[i - 1]; yans[ypos--] = (int)y[j - 1]; i--; j--; } else if (dp[i - 1,j - 1] + pxy == dp[i,j]) { xans[xpos--] = (int)x[i - 1]; yans[ypos--] = (int)y[j - 1]; i--; j--; } else if (dp[i - 1,j] + pgap == dp[i,j]) { xans[xpos--] = (int)x[i - 1]; yans[ypos--] = (int)'_'; i--; } else if (dp[i,j - 1] + pgap == dp[i,j]) { xans[xpos--] = (int)'_'; yans[ypos--] = (int)y[j - 1]; j--; } } while (xpos > 0) { if (i > 0) xans[xpos--] = (int)x[--i]; else xans[xpos--] = (int)'_'; } while (ypos > 0) { if (j > 0) yans[ypos--] = (int)y[--j]; else yans[ypos--] = (int)'_'; } // Since we have assumed the answer to be n+m long, // we need to remove the extra gaps in the starting // id represents the index from which the arrays // xans, yans are useful int id = 1; for (i = l; i >= 1; i--) { if ((char)yans[i] == '_' && (char)xans[i] == '_') { id = i + 1; break; } } // Printing the final answer Console.Write(\"Minimum Penalty in aligning the genes = \" + dp[m,n] + \"\\n\"); Console.Write(\"The aligned genes are :\\n\"); for (i = id; i <= l; i++) { Console.Write((char)xans[i]); } Console.Write(\"\\n\"); for (i = id; i <= l; i++) { Console.Write((char)yans[i]); } return; } // Driver code static void Main() { // input strings string gene1 = \"AGGGCT\"; string gene2 = \"AGGCA\"; // initialising penalties of different types int misMatchPenalty = 3; int gapPenalty = 2; // calling the function to calculate the result getMinimumPenalty(gene1, gene2, misMatchPenalty, gapPenalty); } //This code is contributed by DrRoot_}", "e": 17132, "s": 13215, "text": null }, { "code": "<?php// PHP program to implement// sequence alignment problem. // function to find out// the minimum penaltyfunction getMinimumPenalty($x, $y, $pxy, $pgap){ $i; $j; // initializing variables $m = strlen($x); // length of gene1 $n = strlen($y); // length of gene2 // table for storing optimal // substructure answers $dp[$n + $m + 1][$n + $m + 1] = array(0); // initialising the table for ($i = 0; $i <= ($n+$m); $i++) { $dp[$i][0] = $i * $pgap; $dp[0][$i] = $i * $pgap; } // calculating the // minimum penalty for ($i = 1; $i <= $m; $i++) { for ($j = 1; $j <= $n; $j++) { if ($x[$i - 1] == $y[$j - 1]) { $dp[$i][$j] = $dp[$i - 1][$j - 1]; } else { $dp[$i][$j] = min($dp[$i - 1][$j - 1] + $pxy , $dp[$i - 1][$j] + $pgap , $dp[$i][$j - 1] + $pgap ); } } } // Reconstructing the solution $l = $n + $m; // maximum possible length $i = $m; $j = $n; $xpos = $l; $ypos = $l; // Final answers for // the respective strings // $xans[$l + 1]; $yans[$l + 1]; while ( !($i == 0 || $j == 0)) { if ($x[$i - 1] == $y[$j - 1]) { $xans[$xpos--] = $x[$i - 1]; $yans[$ypos--] = $y[$j - 1]; $i--; $j--; } else if ($dp[$i - 1][$j - 1] + $pxy == $dp[$i][$j]) { $xans[$xpos--] = $x[$i - 1]; $yans[$ypos--] = $y[$j - 1]; $i--; $j--; } else if ($dp[$i - 1][$j] + $pgap == $dp[$i][$j]) { $xans[$xpos--] = $x[$i - 1]; $yans[$ypos--] = '_'; $i--; } else if ($dp[$i][$j - 1] + $pgap == $dp[$i][$j]) { $xans[$xpos--] = '_'; $yans[$ypos--] = $y[$j - 1]; $j--; } } while ($xpos > 0) { if ($i > 0) $xans[$xpos--] = $x[--$i]; else $xans[$xpos--] = '_'; } while ($ypos > 0) { if ($j > 0) $yans[$ypos--] = $y[--$j]; else $yans[$ypos--] = '_'; } // Since we have assumed the // answer to be n+m long, // we need to remove the extra // gaps in the starting // id represents the index // from which the arrays // xans, yans are useful $id = 1; for ($i = $l; $i >= 1; $i--) { if ($yans[$i] == '_' && $xans[$i] == '_') { $id = $i + 1; break; } } // Printing the final answer echo \"Minimum Penalty in \". \"aligning the genes = \"; echo $dp[$m][$n] . \"\\n\"; echo \"The aligned genes are :\\n\"; for ($i = $id; $i <= $l; $i++) { echo $xans[$i]; } echo \"\\n\"; for ($i = $id; $i <= $l; $i++) { echo $yans[$i]; } return;} // Driver code // input strings$gene1 = \"AGGGCT\";$gene2 = \"AGGCA\"; // initialising penalties// of different types$misMatchPenalty = 3;$gapPenalty = 2; // calling the function// to calculate the resultgetMinimumPenalty($gene1, $gene2, $misMatchPenalty, $gapPenalty); // This code is contributed by Abhinav96?>", "e": 20421, "s": 17132, "text": null }, { "code": null, "e": 20501, "s": 20421, "text": "Minimum Penalty in aligning the genes = 5\nThe aligned genes are :\nAGGGCT\nA_GGCA" }, { "code": null, "e": 20542, "s": 20503, "text": "Time Complexity : Space Complexity : " }, { "code": null, "e": 20559, "s": 20542, "text": "AayushChaturvedi" }, { "code": null, "e": 20567, "s": 20559, "text": "DrRoot_" }, { "code": null, "e": 20580, "s": 20567, "text": "myhome890131" }, { "code": null, "e": 20595, "s": 20580, "text": "adnanirshad158" }, { "code": null, "e": 20610, "s": 20595, "text": "sagartomar9927" }, { "code": null, "e": 20619, "s": 20610, "text": "sweetyty" }, { "code": null, "e": 20637, "s": 20619, "text": "wilderchristopher" }, { "code": null, "e": 20646, "s": 20637, "text": "rkbhola5" }, { "code": null, "e": 20670, "s": 20646, "text": "Competitive Programming" }, { "code": null, "e": 20690, "s": 20670, "text": "Dynamic Programming" }, { "code": null, "e": 20698, "s": 20690, "text": "Strings" }, { "code": null, "e": 20706, "s": 20698, "text": "Strings" }, { "code": null, "e": 20726, "s": 20706, "text": "Dynamic Programming" } ]
How to change the style of alert box using CSS ?
12 Jun, 2022 An alert box is an important feature of JavaScript. It is used to inform the client or the user about the click events. Like if the user subscribes to your page for daily updates then you can wish them back, or thank them by showing an alert box message. Sometimes developers like us do not want to just show a normal text inside of the alert box we want to decorate that box in our own way. But the JavaScript alert box is a system object not the subject of CSS. To design the alert box we need jQuery then by using the only CSS we can do that. In this article, we will design the alert box. Normal alert box design: The below examples illustrate the complete approach: Example 1: Double button alert dialog box design. In this example we will create a double button, one will be for confirmation and another one will be for unsubscription. We will assign a class to the alert box, after that, we design that specific class in CSS. In this example, the class is a container. To design the button we will use the button tag in the CSS to design it. And the appeared messages also can be decorated like we attach a class and can design that too. The class and id can call for the design and events. HTML <!DOCTYPE html><html><head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script> <script> function geeks(msg, gfg) { var confirmBox = $("#container"); /* Trace message to display */ confirmBox.find(".message").text(msg); /* Calling function */ confirmBox.find(".yes").unbind().click(function() { confirmBox.hide(); }); confirmBox.find(".yes").click(gfg); confirmBox.show(); confirmBox.find(".no").unbind().click(function() { confirmBox.hide(); }); confirmBox.find(".no").click(gfg); confirmBox.show(); } </script> <style> /* Body alignment */ body { text-align: center; } /* Color for h1 tag */ h1 { color: green; } /* Designing dialog box */ #container { display: none; background-image: linear-gradient(to right, #66a80f, #c0eb75); background-size:cover; color: white; position: absolute; width: 350px; border-radius: 5px; left: 50%; margin-left: -160px; padding: 16px 8px 8px; box-sizing: border-box; } /* Designing dialog box's okay button */ #container .yes { background-color: #5c940d; display: inline-block; border-radius: 5px; border: 2px solid gray; padding: 5px; margin-right: 10px; text-align: center; width: 60px; float: right; } #container .no { background-color: #22b8cf; display: inline-block; border-radius: 5px; border: 2px solid gray; padding: 5px; margin-right: 10px; text-align: center; width: 95px; float: right; } #container .yes:hover { background-color: #82c91e; } #container .no:hover { background-color: #99e9f2; } /* Dialog box message decorating */ #container .message { text-align: left; padding: 10px 30px; } </style></head><body> <h1>GeeksforGeeks</h1> <b>Designing the alert box</b> <br><br> <div id="container"> <div class="message"> Thanks for Subscription<br>A Computer Science Portal for Geeks</div> <button class="yes">okay</button> <button class="no">Unsubscribe</button> </div> <input type="button" value="Subscribe" onclick="geeks();" /></body></html> Output: Example 2: Single-button dialog box. In this example, we will place a single button for confirmation. In a similar way, We will assign a class to the alert box, after that, we design that specific class in CSS. In this example, the class is a container. To design the button we will use the button tag in the CSS to design it. And the appeared messages also can be decorated like we attach a class and can design that too. The class and id can call for the design and events. Design the background in a solid single color. The button will be assigned a task after clicking it will vanish. HTML <!DOCTYPE html><html><head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script> <script> function geeks(msg, gfg) { var confirmBox = $("#container"); /* Trace message to display */ confirmBox.find(".message").text(msg); /* Calling function */ confirmBox.find(".yes").unbind().click(function() { confirmBox.hide(); }); confirmBox.find(".yes").click(gfg); confirmBox.show(); } </script> <style> /* Body alignment */ body { text-align: center; } /* Color for h1 tag */ h1 { color: green; } /* Designing dialog box */ #container { display: none; background-color: purple; color: white; position: absolute; width: 350px; border-radius: 5px; left: 50%; margin-left: -160px; padding: 16px 8px 8px; box-sizing: border-box; } /* Designing dialog box's okay button */ #container button { background-color: yellow; display: inline-block; border-radius: 5px; border: 2px solid gray; padding: 5px; text-align: center; width: 60px; } /* Dialog box message decorating */ #container .message { text-align: left; padding: 10px 30px; } </style></head><body> <h1>GeeksforGeeks</h1> <b>Designing the alert box</b> <br><br> <div id="container"> <div class="message"> Thanks for Subscription<br>A Computer Science Portal for Geeks</div> <button class="yes">okay</button> </div> <input type="button" value="Subscribe" onclick="geeks();" /></body></html> Output: HTML is the foundation of web pages and is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. CSS is the foundation of web pages and is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. sagartomar9927 sanjyotpanure CSS-Misc Picked 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 ? How to select all child elements recursively using CSS? CSS | :not(:last-child):after Selector Build a Survey Form using HTML and 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": "\n12 Jun, 2022" }, { "code": null, "e": 623, "s": 28, "text": "An alert box is an important feature of JavaScript. It is used to inform the client or the user about the click events. Like if the user subscribes to your page for daily updates then you can wish them back, or thank them by showing an alert box message. Sometimes developers like us do not want to just show a normal text inside of the alert box we want to decorate that box in our own way. But the JavaScript alert box is a system object not the subject of CSS. To design the alert box we need jQuery then by using the only CSS we can do that. In this article, we will design the alert box. " }, { "code": null, "e": 649, "s": 623, "text": "Normal alert box design: " }, { "code": null, "e": 702, "s": 649, "text": "The below examples illustrate the complete approach:" }, { "code": null, "e": 1230, "s": 702, "text": "Example 1: Double button alert dialog box design. In this example we will create a double button, one will be for confirmation and another one will be for unsubscription. We will assign a class to the alert box, after that, we design that specific class in CSS. In this example, the class is a container. To design the button we will use the button tag in the CSS to design it. And the appeared messages also can be decorated like we attach a class and can design that too. The class and id can call for the design and events. " }, { "code": null, "e": 1235, "s": 1230, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"> </script> <script> function geeks(msg, gfg) { var confirmBox = $(\"#container\"); /* Trace message to display */ confirmBox.find(\".message\").text(msg); /* Calling function */ confirmBox.find(\".yes\").unbind().click(function() { confirmBox.hide(); }); confirmBox.find(\".yes\").click(gfg); confirmBox.show(); confirmBox.find(\".no\").unbind().click(function() { confirmBox.hide(); }); confirmBox.find(\".no\").click(gfg); confirmBox.show(); } </script> <style> /* Body alignment */ body { text-align: center; } /* Color for h1 tag */ h1 { color: green; } /* Designing dialog box */ #container { display: none; background-image: linear-gradient(to right, #66a80f, #c0eb75); background-size:cover; color: white; position: absolute; width: 350px; border-radius: 5px; left: 50%; margin-left: -160px; padding: 16px 8px 8px; box-sizing: border-box; } /* Designing dialog box's okay button */ #container .yes { background-color: #5c940d; display: inline-block; border-radius: 5px; border: 2px solid gray; padding: 5px; margin-right: 10px; text-align: center; width: 60px; float: right; } #container .no { background-color: #22b8cf; display: inline-block; border-radius: 5px; border: 2px solid gray; padding: 5px; margin-right: 10px; text-align: center; width: 95px; float: right; } #container .yes:hover { background-color: #82c91e; } #container .no:hover { background-color: #99e9f2; } /* Dialog box message decorating */ #container .message { text-align: left; padding: 10px 30px; } </style></head><body> <h1>GeeksforGeeks</h1> <b>Designing the alert box</b> <br><br> <div id=\"container\"> <div class=\"message\"> Thanks for Subscription<br>A Computer Science Portal for Geeks</div> <button class=\"yes\">okay</button> <button class=\"no\">Unsubscribe</button> </div> <input type=\"button\" value=\"Subscribe\" onclick=\"geeks();\" /></body></html> ", "e": 4090, "s": 1235, "text": null }, { "code": null, "e": 4100, "s": 4090, "text": "Output: " }, { "code": null, "e": 4692, "s": 4102, "text": "Example 2: Single-button dialog box. In this example, we will place a single button for confirmation. In a similar way, We will assign a class to the alert box, after that, we design that specific class in CSS. In this example, the class is a container. To design the button we will use the button tag in the CSS to design it. And the appeared messages also can be decorated like we attach a class and can design that too. The class and id can call for the design and events. Design the background in a solid single color. The button will be assigned a task after clicking it will vanish. " }, { "code": null, "e": 4697, "s": 4692, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"> </script> <script> function geeks(msg, gfg) { var confirmBox = $(\"#container\"); /* Trace message to display */ confirmBox.find(\".message\").text(msg); /* Calling function */ confirmBox.find(\".yes\").unbind().click(function() { confirmBox.hide(); }); confirmBox.find(\".yes\").click(gfg); confirmBox.show(); } </script> <style> /* Body alignment */ body { text-align: center; } /* Color for h1 tag */ h1 { color: green; } /* Designing dialog box */ #container { display: none; background-color: purple; color: white; position: absolute; width: 350px; border-radius: 5px; left: 50%; margin-left: -160px; padding: 16px 8px 8px; box-sizing: border-box; } /* Designing dialog box's okay button */ #container button { background-color: yellow; display: inline-block; border-radius: 5px; border: 2px solid gray; padding: 5px; text-align: center; width: 60px; } /* Dialog box message decorating */ #container .message { text-align: left; padding: 10px 30px; } </style></head><body> <h1>GeeksforGeeks</h1> <b>Designing the alert box</b> <br><br> <div id=\"container\"> <div class=\"message\"> Thanks for Subscription<br>A Computer Science Portal for Geeks</div> <button class=\"yes\">okay</button> </div> <input type=\"button\" value=\"Subscribe\" onclick=\"geeks();\" /></body></html>", "e": 6668, "s": 4697, "text": null }, { "code": null, "e": 6678, "s": 6668, "text": "Output: " }, { "code": null, "e": 6879, "s": 6680, "text": "HTML is the foundation of web pages and is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples." }, { "code": null, "e": 7070, "s": 6879, "text": "CSS is the foundation of web pages and is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples." }, { "code": null, "e": 7085, "s": 7070, "text": "sagartomar9927" }, { "code": null, "e": 7099, "s": 7085, "text": "sanjyotpanure" }, { "code": null, "e": 7108, "s": 7099, "text": "CSS-Misc" }, { "code": null, "e": 7115, "s": 7108, "text": "Picked" }, { "code": null, "e": 7119, "s": 7115, "text": "CSS" }, { "code": null, "e": 7136, "s": 7119, "text": "Web Technologies" }, { "code": null, "e": 7234, "s": 7136, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7273, "s": 7234, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 7312, "s": 7273, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 7368, "s": 7312, "text": "How to select all child elements recursively using CSS?" }, { "code": null, "e": 7407, "s": 7368, "text": "CSS | :not(:last-child):after Selector" }, { "code": null, "e": 7446, "s": 7407, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 7479, "s": 7446, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 7540, "s": 7479, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 7583, "s": 7540, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 7655, "s": 7583, "text": "Differences between Functional Components and Class Components in React" } ]
ByteBuffer putInt() methods in Java with Examples
27 Jun, 2019 The putInt(int value) method of java.nio.ByteBuffer Class is used to write four bytes containing the given int value, in the current byte order, into this buffer at the current position, and then increments the position by four. Syntax : public abstract ByteBuffer putInt(int value) Parameters: This method takes the int value to be written as the parameter. Return Value: This method returns this ByteBuffer. Exception: This method throws the following exceptions: BufferOverflowException- If this buffer’s current position is not smaller than its limit ReadOnlyBufferException- If this buffer is read-only Below are the examples to illustrate the putInt(int value) method: Example 1: // Java program to demonstrate// putInt() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 12; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer // using putInt() method bb.putInt(23) .putInt(24) .putInt(30) .rewind(); // print the ByteBuffer System.out.print("Original ByteBuffer: [ "); for (int i = 1; i <= capacity / 4; i++) System.out.print(bb.getInt() + " "); System.out.print("]"); } catch (BufferOverflowException e) { System.out.println("Exception throws : " + e); } catch (ReadOnlyBufferException e) { System.out.println("Exception throws : " + e); } }} Original ByteBuffer: [ 23 24 30 ] Example 2: To demonstrate BufferOverflowException. // Java program to demonstrate// putInt() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 12; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer // using putInt() method bb.putInt(23) .putInt(24) .putInt(30) .rewind(); // print the ByteBuffer System.out.print("Original ByteBuffer: [ "); for (int i = 1; i <= capacity / 4; i++) System.out.print(bb.getInt() + " "); System.out.print("]"); // putting the value in ByteBuffer // using putInt() method bb.putInt(234); } catch (BufferOverflowException e) { System.out.println("\n\nbuffer's current position " + "is not smaller than its limit"); System.out.println("Exception throws : " + e); } catch (ReadOnlyBufferException e) { System.out.println("Exception throws : " + e); } }} Original ByteBuffer: [ 23 24 30 ] buffer's current position is not smaller than its limit Exception throws : java.nio.BufferOverflowException Examples 3: To demonstrate ReadOnlyBufferException. // Java program to demonstrate// putInt() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 12; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer // using putInt() method bb.putInt(23) .putInt(24) .putInt(30) .rewind(); // print the ByteBuffer System.out.print("Original ByteBuffer: [ "); for (int i = 1; i <= capacity / 4; i++) System.out.print(bb.getInt() + " "); System.out.print("]"); // Creating a read-only copy of ByteBuffer // using asReadOnlyBuffer() method ByteBuffer bb1 = bb.asReadOnlyBuffer(); System.out.println("\n\nTrying to put the int value" + " in read-only buffer"); // putting the value in readonly ByteBuffer // using putInt() method bb1.putInt(234); } catch (BufferOverflowException e) { System.out.println("Exception throws : " + e); } catch (ReadOnlyBufferException e) { System.out.println("Exception throws : " + e); } }} Original ByteBuffer: [ 23 24 30 ] Trying to put the int value in read only buffer Exception throws : java.nio.ReadOnlyBufferException The putInt(int index, int value) method of java.nio.ByteBuffer Class is used to write four bytes containing the given four value, in the current byte order, into this buffer at the given index. Syntax: public abstract ByteBuffer putInt(int index, int value) Parameters: This method takes the following arguments as a parameter: index: The index at which the byte will be written value: The int value to be written Return Value: This method returns the this buffer. Exception: This method throws the following exception: IndexOutOfBoundsException- If index is negative or not smaller than the buffer’s limit ReadOnlyBufferException- If this buffer is read-only Below are the examples to illustrate the putInt(int index, int value) method: Example 1: // Java program to demonstrate// putInt() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 12; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer // using putInt() at index 0 bb.putInt(0, 23); // putting the value in ByteBuffer // using putInt() at index 4 bb.putInt(4, 34); // putting the value in ByteBuffer // using putInt() at index 8 bb.putInt(8, 27); // rewinding the ByteBuffer bb.rewind(); // print the ByteBuffer System.out.print("Original ByteBuffer: [ "); for (int i = 1; i <= capacity / 4; i++) System.out.print(bb.getInt() + " "); System.out.print("]\n"); } catch (IndexOutOfBoundsException e) { System.out.println("Exception throws : " + e); } catch (ReadOnlyBufferException e) { System.out.println("Exception throws : " + e); } }} Original ByteBuffer: [ 23 34 27 ] Example 2: To demonstrate IndexOutOfBoundsException. // Java program to demonstrate// putInt() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 12; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer // using putInt() at index 0 bb.putInt(0, 23); // putting the value in ByteBuffer // using putInt() at index 4 bb.putInt(4, 34); // putting the value in ByteBuffer // using putInt() at index 8 bb.putInt(8, 27); // rewinding the ByteBuffer bb.rewind(); // print the ByteBuffer System.out.print("Original ByteBuffer: [ "); for (int i = 1; i <= capacity / 4; i++) System.out.print(bb.getInt() + " "); System.out.print("]\n"); // putting the value in ByteBuffer // using putInt() at index -1 bb.putInt(-1, 45); } catch (IndexOutOfBoundsException e) { System.out.println("\nindex is negative or not smaller " + "than the buffer's limit"); System.out.println("Exception throws : " + e); } catch (ReadOnlyBufferException e) { System.out.println("Exception throws : " + e); } }} Original ByteBuffer: [ 23 34 27 ] index is negative or not smaller than the buffer's limit Exception throws : java.lang.IndexOutOfBoundsException Example 3: To demonstrate ReadOnlyBufferException. // Java program to demonstrate// putInt() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 12; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // Creating a read-only copy of ByteBuffer // using asReadOnlyBuffer() method ByteBuffer bb1 = bb.asReadOnlyBuffer(); System.out.println("Trying to put the int value" + " in read-only buffer"); // putting the value in readonly ByteBuffer // using putInt() method bb1.putInt(0, 23); } catch (IndexOutOfBoundsException e) { System.out.println("\nindex is negative or not smaller " + "than the buffer's limit"); System.out.println("Exception throws : " + e); } catch (ReadOnlyBufferException e) { System.out.println("Exception throws : " + e); } }} Trying to put the int value in read only buffer Exception throws : java.nio.ReadOnlyBufferException Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#putInt-int- https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#putInt-int-int- Java-ByteBuffer Java-Functions Java-NIO package 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": "\n27 Jun, 2019" }, { "code": null, "e": 257, "s": 28, "text": "The putInt(int value) method of java.nio.ByteBuffer Class is used to write four bytes containing the given int value, in the current byte order, into this buffer at the current position, and then increments the position by four." }, { "code": null, "e": 266, "s": 257, "text": "Syntax :" }, { "code": null, "e": 311, "s": 266, "text": "public abstract ByteBuffer putInt(int value)" }, { "code": null, "e": 387, "s": 311, "text": "Parameters: This method takes the int value to be written as the parameter." }, { "code": null, "e": 438, "s": 387, "text": "Return Value: This method returns this ByteBuffer." }, { "code": null, "e": 494, "s": 438, "text": "Exception: This method throws the following exceptions:" }, { "code": null, "e": 583, "s": 494, "text": "BufferOverflowException- If this buffer’s current position is not smaller than its limit" }, { "code": null, "e": 636, "s": 583, "text": "ReadOnlyBufferException- If this buffer is read-only" }, { "code": null, "e": 703, "s": 636, "text": "Below are the examples to illustrate the putInt(int value) method:" }, { "code": null, "e": 714, "s": 703, "text": "Example 1:" }, { "code": "// Java program to demonstrate// putInt() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 12; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer // using putInt() method bb.putInt(23) .putInt(24) .putInt(30) .rewind(); // print the ByteBuffer System.out.print(\"Original ByteBuffer: [ \"); for (int i = 1; i <= capacity / 4; i++) System.out.print(bb.getInt() + \" \"); System.out.print(\"]\"); } catch (BufferOverflowException e) { System.out.println(\"Exception throws : \" + e); } catch (ReadOnlyBufferException e) { System.out.println(\"Exception throws : \" + e); } }}", "e": 1806, "s": 714, "text": null }, { "code": null, "e": 1841, "s": 1806, "text": "Original ByteBuffer: [ 23 24 30 ]\n" }, { "code": null, "e": 1892, "s": 1841, "text": "Example 2: To demonstrate BufferOverflowException." }, { "code": "// Java program to demonstrate// putInt() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 12; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer // using putInt() method bb.putInt(23) .putInt(24) .putInt(30) .rewind(); // print the ByteBuffer System.out.print(\"Original ByteBuffer: [ \"); for (int i = 1; i <= capacity / 4; i++) System.out.print(bb.getInt() + \" \"); System.out.print(\"]\"); // putting the value in ByteBuffer // using putInt() method bb.putInt(234); } catch (BufferOverflowException e) { System.out.println(\"\\n\\nbuffer's current position \" + \"is not smaller than its limit\"); System.out.println(\"Exception throws : \" + e); } catch (ReadOnlyBufferException e) { System.out.println(\"Exception throws : \" + e); } }}", "e": 3222, "s": 1892, "text": null }, { "code": null, "e": 3366, "s": 3222, "text": "Original ByteBuffer: [ 23 24 30 ]\n\nbuffer's current position is not smaller than its limit\nException throws : java.nio.BufferOverflowException\n" }, { "code": null, "e": 3418, "s": 3366, "text": "Examples 3: To demonstrate ReadOnlyBufferException." }, { "code": "// Java program to demonstrate// putInt() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 12; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer // using putInt() method bb.putInt(23) .putInt(24) .putInt(30) .rewind(); // print the ByteBuffer System.out.print(\"Original ByteBuffer: [ \"); for (int i = 1; i <= capacity / 4; i++) System.out.print(bb.getInt() + \" \"); System.out.print(\"]\"); // Creating a read-only copy of ByteBuffer // using asReadOnlyBuffer() method ByteBuffer bb1 = bb.asReadOnlyBuffer(); System.out.println(\"\\n\\nTrying to put the int value\" + \" in read-only buffer\"); // putting the value in readonly ByteBuffer // using putInt() method bb1.putInt(234); } catch (BufferOverflowException e) { System.out.println(\"Exception throws : \" + e); } catch (ReadOnlyBufferException e) { System.out.println(\"Exception throws : \" + e); } }}", "e": 4907, "s": 3418, "text": null }, { "code": null, "e": 5043, "s": 4907, "text": "Original ByteBuffer: [ 23 24 30 ]\n\nTrying to put the int value in read only buffer\nException throws : java.nio.ReadOnlyBufferException\n" }, { "code": null, "e": 5237, "s": 5043, "text": "The putInt(int index, int value) method of java.nio.ByteBuffer Class is used to write four bytes containing the given four value, in the current byte order, into this buffer at the given index." }, { "code": null, "e": 5245, "s": 5237, "text": "Syntax:" }, { "code": null, "e": 5301, "s": 5245, "text": "public abstract ByteBuffer putInt(int index, int value)" }, { "code": null, "e": 5371, "s": 5301, "text": "Parameters: This method takes the following arguments as a parameter:" }, { "code": null, "e": 5422, "s": 5371, "text": "index: The index at which the byte will be written" }, { "code": null, "e": 5457, "s": 5422, "text": "value: The int value to be written" }, { "code": null, "e": 5508, "s": 5457, "text": "Return Value: This method returns the this buffer." }, { "code": null, "e": 5563, "s": 5508, "text": "Exception: This method throws the following exception:" }, { "code": null, "e": 5650, "s": 5563, "text": "IndexOutOfBoundsException- If index is negative or not smaller than the buffer’s limit" }, { "code": null, "e": 5703, "s": 5650, "text": "ReadOnlyBufferException- If this buffer is read-only" }, { "code": null, "e": 5781, "s": 5703, "text": "Below are the examples to illustrate the putInt(int index, int value) method:" }, { "code": null, "e": 5792, "s": 5781, "text": "Example 1:" }, { "code": "// Java program to demonstrate// putInt() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 12; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer // using putInt() at index 0 bb.putInt(0, 23); // putting the value in ByteBuffer // using putInt() at index 4 bb.putInt(4, 34); // putting the value in ByteBuffer // using putInt() at index 8 bb.putInt(8, 27); // rewinding the ByteBuffer bb.rewind(); // print the ByteBuffer System.out.print(\"Original ByteBuffer: [ \"); for (int i = 1; i <= capacity / 4; i++) System.out.print(bb.getInt() + \" \"); System.out.print(\"]\\n\"); } catch (IndexOutOfBoundsException e) { System.out.println(\"Exception throws : \" + e); } catch (ReadOnlyBufferException e) { System.out.println(\"Exception throws : \" + e); } }}", "e": 7121, "s": 5792, "text": null }, { "code": null, "e": 7159, "s": 7121, "text": "Original ByteBuffer: [ 23 34 27 ]\n" }, { "code": null, "e": 7212, "s": 7159, "text": "Example 2: To demonstrate IndexOutOfBoundsException." }, { "code": "// Java program to demonstrate// putInt() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 12; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer // using putInt() at index 0 bb.putInt(0, 23); // putting the value in ByteBuffer // using putInt() at index 4 bb.putInt(4, 34); // putting the value in ByteBuffer // using putInt() at index 8 bb.putInt(8, 27); // rewinding the ByteBuffer bb.rewind(); // print the ByteBuffer System.out.print(\"Original ByteBuffer: [ \"); for (int i = 1; i <= capacity / 4; i++) System.out.print(bb.getInt() + \" \"); System.out.print(\"]\\n\"); // putting the value in ByteBuffer // using putInt() at index -1 bb.putInt(-1, 45); } catch (IndexOutOfBoundsException e) { System.out.println(\"\\nindex is negative or not smaller \" + \"than the buffer's limit\"); System.out.println(\"Exception throws : \" + e); } catch (ReadOnlyBufferException e) { System.out.println(\"Exception throws : \" + e); } }}", "e": 8787, "s": 7212, "text": null }, { "code": null, "e": 8938, "s": 8787, "text": "Original ByteBuffer: [ 23 34 27 ]\n\nindex is negative or not smaller than the buffer's limit\nException throws : java.lang.IndexOutOfBoundsException\n" }, { "code": null, "e": 8989, "s": 8938, "text": "Example 3: To demonstrate ReadOnlyBufferException." }, { "code": "// Java program to demonstrate// putInt() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 12; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // Creating a read-only copy of ByteBuffer // using asReadOnlyBuffer() method ByteBuffer bb1 = bb.asReadOnlyBuffer(); System.out.println(\"Trying to put the int value\" + \" in read-only buffer\"); // putting the value in readonly ByteBuffer // using putInt() method bb1.putInt(0, 23); } catch (IndexOutOfBoundsException e) { System.out.println(\"\\nindex is negative or not smaller \" + \"than the buffer's limit\"); System.out.println(\"Exception throws : \" + e); } catch (ReadOnlyBufferException e) { System.out.println(\"Exception throws : \" + e); } }}", "e": 10187, "s": 8989, "text": null }, { "code": null, "e": 10288, "s": 10187, "text": "Trying to put the int value in read only buffer\nException throws : java.nio.ReadOnlyBufferException\n" }, { "code": null, "e": 10299, "s": 10288, "text": "Reference:" }, { "code": null, "e": 10378, "s": 10299, "text": "https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#putInt-int-" }, { "code": null, "e": 10461, "s": 10378, "text": "https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#putInt-int-int-" }, { "code": null, "e": 10477, "s": 10461, "text": "Java-ByteBuffer" }, { "code": null, "e": 10492, "s": 10477, "text": "Java-Functions" }, { "code": null, "e": 10509, "s": 10492, "text": "Java-NIO package" }, { "code": null, "e": 10514, "s": 10509, "text": "Java" }, { "code": null, "e": 10519, "s": 10514, "text": "Java" } ]
Working with CSV Files in Julia
17 Jan, 2022 CSV file (Comma-separated values file) is a plain text file that uses commas to separate values and fields. It is majorly used to store data in the form of tables or spreadsheets. Each row of a table or spreadsheet is a record filled with data that belongs to n fields (or Columns). It is used to import or export data and tables very easily and stored with the extension “.csv” in most programming languages. Julia provides various file handling methods to perform operations on CSV files. These methods can be used to create a CSV file, add contents to the file, Update the File, etc. First, you need to Install CSV Package using the following commands on the Julia command line: using pkg pkg.add("Package name") CSV Package is a built-in package with a defined “N” number of methods to perform n operations. Julia # using pkg to install packagesusing Pkg # using pkg to add csv package file to libraryPkg.add("CSV") Install Packages Now you have to Save your data into the CSV file. Created .csv File Here we will use the CSV package and read() method in order to read the contents of the CSV File: Julia # using Installed csv package for working with csv filesusing CSV # reading the csv fileCSV.read("myfile.csv") Reading Data from csv file Here we will learn how to modify the content of an existing file with the help of the write() method in CSV package and DataFrames Package. Julia using CSV # using dataframes package to create a dataframeusing DataFrames # Creating DataFrameab = DataFrame(Name = ["AKANKSHA", "TANYA", "PREETIKA", "VRINDA", "JAHNVI"], Age = [42, 44, 22, 81, 93], Salary = [540000, 650000, 900000, 770000, 850000], RESIDENCE=["DELHI", "DELHI", "UP", "HARYANA", "UP"] ) # modifying the content of myfile.csv using write methodCSV.write("myfile.csv", ab) Creating a new Dataframe Now we will overwrite the existing ‘.csv’ file Using CSV write() method. Write to existing file Here we will create a new file using touch() command and therefore use DataFrames and CSV packages to write the newly created dataframe content to a new file. Julia # new file createdtouch("newfile.csv") # file handling in write modeefg = open("newfile.csv", "w") # Creating a new dataframemn = DataFrame(Name = ["AKANKSHA", "TANYA", "PREETIKA", "VRINDA", "JAHNVI"], Age = [42, 44, 22, 81, 93], Salary = [540000, 650000, 900000, 770000, 850000], RESIDENCE=["DELHI", "DELHI", "UP", "HARYANA", "UP"] ) # writing to the newly created fileCSV.write("newfile.csv", mn) Here we will learn to delete a particular column entry or multiple column entries from a particular table or spreadsheet using the drop command in Julia. Julia # Format# CSV.File(filename;drop=["colulm1", "column2"....., column n]) # dropping "RESIDENCE" column from our file (newfile.csv")CSV.File("newfile.csv"; drop=["RESIDENCE"]) Drop column Residence Here we will learn to query a particular column or set of columns as per demand from the entire table or spreadsheet, and we can even use operators in the query to retrieve a set of rows satisfying the particular condition. Julia # Format for select command# CSV.File(file; select=[column1, column2]) # Select the columns 'Name and Salary'CSV.File("newfile.csv"; select=["Name", "Salary"]) # Selecting columns number wise# selecting column 1 and 3CSV.File("newfile.csv"; select=(i, nm) -> i in (1, 3)) # selecting column 1, 2, 3CSV.File("newfile.csv"; select=(i, nm) -> i in (1, 2, 3)) Hence “N” number of operations can be performed on a CSV file in Julia using built-in CSV packages with a pre-defined “M” number of methods with unique operations. while using CSV.read(“myfile.csv”), if you find error like “”ArgumentError: provide a valid sink argument””use the below command to solve this error: Julia using DataFramesfile = CSV.read("myfile.csv",DataFrames) mohanapranes abhishek0719kadiyan saurabh1990aror julia-FileHandling Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Vectors in Julia String concatenation in Julia String to Number Conversion in Julia Getting rounded value of a number in Julia - round() Method Storing Output on a File in Julia Reshaping array dimensions in Julia | Array reshape() Method Manipulating matrices in Julia Exception handling in Julia Formatting of Strings in Julia Tuples in Julia
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jan, 2022" }, { "code": null, "e": 438, "s": 28, "text": "CSV file (Comma-separated values file) is a plain text file that uses commas to separate values and fields. It is majorly used to store data in the form of tables or spreadsheets. Each row of a table or spreadsheet is a record filled with data that belongs to n fields (or Columns). It is used to import or export data and tables very easily and stored with the extension “.csv” in most programming languages." }, { "code": null, "e": 616, "s": 438, "text": "Julia provides various file handling methods to perform operations on CSV files. These methods can be used to create a CSV file, add contents to the file, Update the File, etc. " }, { "code": null, "e": 711, "s": 616, "text": "First, you need to Install CSV Package using the following commands on the Julia command line:" }, { "code": null, "e": 746, "s": 711, "text": "using pkg \npkg.add(\"Package name\")" }, { "code": null, "e": 842, "s": 746, "text": "CSV Package is a built-in package with a defined “N” number of methods to perform n operations." }, { "code": null, "e": 848, "s": 842, "text": "Julia" }, { "code": "# using pkg to install packagesusing Pkg # using pkg to add csv package file to libraryPkg.add(\"CSV\")", "e": 951, "s": 848, "text": null }, { "code": null, "e": 968, "s": 951, "text": "Install Packages" }, { "code": null, "e": 1018, "s": 968, "text": "Now you have to Save your data into the CSV file." }, { "code": null, "e": 1036, "s": 1018, "text": "Created .csv File" }, { "code": null, "e": 1134, "s": 1036, "text": "Here we will use the CSV package and read() method in order to read the contents of the CSV File:" }, { "code": null, "e": 1140, "s": 1134, "text": "Julia" }, { "code": "# using Installed csv package for working with csv filesusing CSV # reading the csv fileCSV.read(\"myfile.csv\")", "e": 1251, "s": 1140, "text": null }, { "code": null, "e": 1278, "s": 1251, "text": "Reading Data from csv file" }, { "code": null, "e": 1418, "s": 1278, "text": "Here we will learn how to modify the content of an existing file with the help of the write() method in CSV package and DataFrames Package." }, { "code": null, "e": 1424, "s": 1418, "text": "Julia" }, { "code": "using CSV # using dataframes package to create a dataframeusing DataFrames # Creating DataFrameab = DataFrame(Name = [\"AKANKSHA\", \"TANYA\", \"PREETIKA\", \"VRINDA\", \"JAHNVI\"], Age = [42, 44, 22, 81, 93], Salary = [540000, 650000, 900000, 770000, 850000], RESIDENCE=[\"DELHI\", \"DELHI\", \"UP\", \"HARYANA\", \"UP\"] ) # modifying the content of myfile.csv using write methodCSV.write(\"myfile.csv\", ab)", "e": 1864, "s": 1424, "text": null }, { "code": null, "e": 1890, "s": 1864, "text": "Creating a new Dataframe " }, { "code": null, "e": 1963, "s": 1890, "text": "Now we will overwrite the existing ‘.csv’ file Using CSV write() method." }, { "code": null, "e": 1986, "s": 1963, "text": "Write to existing file" }, { "code": null, "e": 2145, "s": 1986, "text": "Here we will create a new file using touch() command and therefore use DataFrames and CSV packages to write the newly created dataframe content to a new file." }, { "code": null, "e": 2151, "s": 2145, "text": "Julia" }, { "code": "# new file createdtouch(\"newfile.csv\") # file handling in write modeefg = open(\"newfile.csv\", \"w\") # Creating a new dataframemn = DataFrame(Name = [\"AKANKSHA\", \"TANYA\", \"PREETIKA\", \"VRINDA\", \"JAHNVI\"], Age = [42, 44, 22, 81, 93], Salary = [540000, 650000, 900000, 770000, 850000], RESIDENCE=[\"DELHI\", \"DELHI\", \"UP\", \"HARYANA\", \"UP\"] ) # writing to the newly created fileCSV.write(\"newfile.csv\", mn)", "e": 2615, "s": 2151, "text": null }, { "code": null, "e": 2769, "s": 2615, "text": "Here we will learn to delete a particular column entry or multiple column entries from a particular table or spreadsheet using the drop command in Julia." }, { "code": null, "e": 2775, "s": 2769, "text": "Julia" }, { "code": "# Format# CSV.File(filename;drop=[\"colulm1\", \"column2\"....., column n]) # dropping \"RESIDENCE\" column from our file (newfile.csv\")CSV.File(\"newfile.csv\"; drop=[\"RESIDENCE\"])", "e": 2949, "s": 2775, "text": null }, { "code": null, "e": 2971, "s": 2949, "text": "Drop column Residence" }, { "code": null, "e": 3195, "s": 2971, "text": "Here we will learn to query a particular column or set of columns as per demand from the entire table or spreadsheet, and we can even use operators in the query to retrieve a set of rows satisfying the particular condition." }, { "code": null, "e": 3201, "s": 3195, "text": "Julia" }, { "code": "# Format for select command# CSV.File(file; select=[column1, column2]) # Select the columns 'Name and Salary'CSV.File(\"newfile.csv\"; select=[\"Name\", \"Salary\"]) # Selecting columns number wise# selecting column 1 and 3CSV.File(\"newfile.csv\"; select=(i, nm) -> i in (1, 3)) # selecting column 1, 2, 3CSV.File(\"newfile.csv\"; select=(i, nm) -> i in (1, 2, 3))", "e": 3557, "s": 3201, "text": null }, { "code": null, "e": 3722, "s": 3557, "text": "Hence “N” number of operations can be performed on a CSV file in Julia using built-in CSV packages with a pre-defined “M” number of methods with unique operations." }, { "code": null, "e": 3872, "s": 3722, "text": "while using CSV.read(“myfile.csv”), if you find error like “”ArgumentError: provide a valid sink argument””use the below command to solve this error:" }, { "code": null, "e": 3878, "s": 3872, "text": "Julia" }, { "code": "using DataFramesfile = CSV.read(\"myfile.csv\",DataFrames)", "e": 3935, "s": 3878, "text": null }, { "code": null, "e": 3948, "s": 3935, "text": "mohanapranes" }, { "code": null, "e": 3968, "s": 3948, "text": "abhishek0719kadiyan" }, { "code": null, "e": 3984, "s": 3968, "text": "saurabh1990aror" }, { "code": null, "e": 4003, "s": 3984, "text": "julia-FileHandling" }, { "code": null, "e": 4009, "s": 4003, "text": "Julia" }, { "code": null, "e": 4107, "s": 4009, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4124, "s": 4107, "text": "Vectors in Julia" }, { "code": null, "e": 4154, "s": 4124, "text": "String concatenation in Julia" }, { "code": null, "e": 4191, "s": 4154, "text": "String to Number Conversion in Julia" }, { "code": null, "e": 4251, "s": 4191, "text": "Getting rounded value of a number in Julia - round() Method" }, { "code": null, "e": 4285, "s": 4251, "text": "Storing Output on a File in Julia" }, { "code": null, "e": 4346, "s": 4285, "text": "Reshaping array dimensions in Julia | Array reshape() Method" }, { "code": null, "e": 4377, "s": 4346, "text": "Manipulating matrices in Julia" }, { "code": null, "e": 4405, "s": 4377, "text": "Exception handling in Julia" }, { "code": null, "e": 4436, "s": 4405, "text": "Formatting of Strings in Julia" } ]
String Alignment in Python f-string
28 Jul, 2020 Text Alignment in Python is useful for printing out clean formatted output. Some times the data to be printed varies in length which makes it look messy when printed. By using String Alignment the output string can be aligned by defining the alignment as left, right or center and also defining space (width) to reserve for the string. Approach : We will be using the f-strings to format the text. The syntax of the alignment of the output string is defined by ‘<‘, ‘>’, ‘^’ and followed by the width number. Example 1 : For Left Alignment output string syntax define ‘<‘ followed by the width number. # here 20 spaces are reserved for the # particular output string. And the string# is printed on the left sideprint(f"{'Left Aligned Text' : <20}") Output : Left Aligned Text Example 2 : For Right Alignment output string syntax define ‘>’ followed by the width number. # here 20 spaces are reserved for the # particular output string. And the string# is printed on the right sideprint(f"{'Right Aligned Text' : >20}") Output : Right Aligned Text Example 3 : For Center Alignment output string syntax define ‘^’ followed by the width number. # here 20 spaces are reserved for the # particular output string. And the string# is printed in the middleprint(f"{'Centered' : ^10}") Output : Centered Example 4 : Printing variables in Aligned format # assigning strings to the variablesleft_alignment = "Left Text"center_alignment = "Centered Text"right_alignment = "Right Text" # printing out aligned textprint(f"{left_alignment : <20}{center_alignment : ^15}{right_alignment : >20}") Left Text Centered Text Right Text Example 5 : Printing out multiple list values in aligned column look. # assigning list values to the variablesnames = ['Raj', 'Shivam', 'Shreeya', 'Kartik']marks = [7, 9, 8, 5]div = ['A', 'A', 'C', 'B']id = [21, 52, 27, 38] # printing Aligned Headerprint(f"{'Name' : <10}{'Marks' : ^10}{'Division' : ^10}{'ID' : >5}") # printing values of variables in Aligned mannerfor i in range(0, 4): print(f"{names[i] : <10}{marks[i] : ^10}{div[i] : ^10}{id[i] : >5}") Name Marks Division ID Raj 7 A 21 Shivam 9 A 52 Shreeya 8 C 27 Kartik 5 B 38 python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jul, 2020" }, { "code": null, "e": 364, "s": 28, "text": "Text Alignment in Python is useful for printing out clean formatted output. Some times the data to be printed varies in length which makes it look messy when printed. By using String Alignment the output string can be aligned by defining the alignment as left, right or center and also defining space (width) to reserve for the string." }, { "code": null, "e": 537, "s": 364, "text": "Approach : We will be using the f-strings to format the text. The syntax of the alignment of the output string is defined by ‘<‘, ‘>’, ‘^’ and followed by the width number." }, { "code": null, "e": 630, "s": 537, "text": "Example 1 : For Left Alignment output string syntax define ‘<‘ followed by the width number." }, { "code": "# here 20 spaces are reserved for the # particular output string. And the string# is printed on the left sideprint(f\"{'Left Aligned Text' : <20}\")", "e": 777, "s": 630, "text": null }, { "code": null, "e": 786, "s": 777, "text": "Output :" }, { "code": null, "e": 804, "s": 786, "text": "Left Aligned Text" }, { "code": null, "e": 898, "s": 804, "text": "Example 2 : For Right Alignment output string syntax define ‘>’ followed by the width number." }, { "code": "# here 20 spaces are reserved for the # particular output string. And the string# is printed on the right sideprint(f\"{'Right Aligned Text' : >20}\")", "e": 1047, "s": 898, "text": null }, { "code": null, "e": 1056, "s": 1047, "text": "Output :" }, { "code": null, "e": 1077, "s": 1056, "text": " Right Aligned Text" }, { "code": null, "e": 1172, "s": 1077, "text": "Example 3 : For Center Alignment output string syntax define ‘^’ followed by the width number." }, { "code": "# here 20 spaces are reserved for the # particular output string. And the string# is printed in the middleprint(f\"{'Centered' : ^10}\")", "e": 1307, "s": 1172, "text": null }, { "code": null, "e": 1316, "s": 1307, "text": "Output :" }, { "code": null, "e": 1327, "s": 1316, "text": " Centered " }, { "code": null, "e": 1376, "s": 1327, "text": "Example 4 : Printing variables in Aligned format" }, { "code": "# assigning strings to the variablesleft_alignment = \"Left Text\"center_alignment = \"Centered Text\"right_alignment = \"Right Text\" # printing out aligned textprint(f\"{left_alignment : <20}{center_alignment : ^15}{right_alignment : >20}\")", "e": 1613, "s": 1376, "text": null }, { "code": null, "e": 1670, "s": 1613, "text": "Left Text Centered Text Right Text\n" }, { "code": null, "e": 1740, "s": 1670, "text": "Example 5 : Printing out multiple list values in aligned column look." }, { "code": "# assigning list values to the variablesnames = ['Raj', 'Shivam', 'Shreeya', 'Kartik']marks = [7, 9, 8, 5]div = ['A', 'A', 'C', 'B']id = [21, 52, 27, 38] # printing Aligned Headerprint(f\"{'Name' : <10}{'Marks' : ^10}{'Division' : ^10}{'ID' : >5}\") # printing values of variables in Aligned mannerfor i in range(0, 4): print(f\"{names[i] : <10}{marks[i] : ^10}{div[i] : ^10}{id[i] : >5}\")", "e": 2132, "s": 1740, "text": null }, { "code": null, "e": 2313, "s": 2132, "text": "Name Marks Division ID\nRaj 7 A 21\nShivam 9 A 52\nShreeya 8 C 27\nKartik 5 B 38\n" }, { "code": null, "e": 2327, "s": 2313, "text": "python-string" }, { "code": null, "e": 2334, "s": 2327, "text": "Python" }, { "code": null, "e": 2432, "s": 2334, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2464, "s": 2432, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2491, "s": 2464, "text": "Python Classes and Objects" }, { "code": null, "e": 2512, "s": 2491, "text": "Python OOPs Concepts" }, { "code": null, "e": 2535, "s": 2512, "text": "Introduction To PYTHON" }, { "code": null, "e": 2591, "s": 2535, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2622, "s": 2591, "text": "Python | os.path.join() method" }, { "code": null, "e": 2664, "s": 2622, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2706, "s": 2664, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2745, "s": 2706, "text": "Python | Get unique values from a list" } ]
Java Program for Maximum circular subarray sum
29 Dec, 2021 Given n numbers (both +ve and -ve), arranged in a circle, find the maximum sum of consecutive numbers. Examples: Input: a[] = {8, -8, 9, -9, 10, -11, 12} Output: 22 (12 + 8 - 8 + 9 - 9 + 10) Input: a[] = {10, -3, -4, 7, 6, 5, -4, -1} Output: 23 (7 + 6 + 5 - 4 -1 + 10) Input: a[] = {-1, 40, -14, 7, 6, 5, -4, -1} Output: 52 (7 + 6 + 5 - 4 - 1 - 1 + 40) Method 1 There can be two cases for the maximum sum: Case 1: The elements that contribute to the maximum sum are arranged such that no wrapping is there. Examples: {-10, 2, -1, 5}, {-2, 4, -1, 4, -1}. In this case, Kadane’s algorithm will produce the result. Case 2: The elements which contribute to the maximum sum are arranged such that wrapping is there. Examples: {10, -12, 11}, {12, -5, 4, -8, 11}. In this case, we change wrapping to non-wrapping. Let us see how. Wrapping of contributing elements implies non-wrapping of non-contributing elements, so find out the sum of non-contributing elements and subtract this sum from the total sum. To find out the sum of non-contributions, invert the sign of each element and then run Kadane’s algorithm. Our array is like a ring and we have to eliminate the maximum continuous negative that implies maximum continuous positive in the inverted arrays. Finally, we compare the sum obtained in both cases and return the maximum of the two sums. The following are implementations of the above method. Java // Java program for maximum contiguous circular sum problemimport java.io.*;import java.util.*; class Solution{ public static int kadane(int a[],int n){ int res = 0; int x = a[0]; for(int i = 0; i < n; i++){ res = Math.max(a[i],res+a[i]); x= Math.max(x,res); } return x; } //lets write a function for calculating max sum in circular manner as discuss above public static int reverseKadane(int a[],int n){ int total = 0; //taking the total sum of the array elements for(int i = 0; i< n; i++){ total +=a[i]; } // inverting the array for(int i = 0; i<n ; i++){ a[i] = -a[i]; } // finding min sum subarray int k = kadane(a,n);// max circular sum int ress = total+k; // to handle the case in which all elements are negative if(total == -k ){ return total; } else{ return ress; } } public static void main(String[] args) { int a[] = {1,4,6,4,-3,8,-1}; int n = 7; if(n==1){ System.out.println("Maximum circular sum is " +a[0]); } else{ System.out.println("Maximum circular sum is " +Integer.max(kadane(a,n), reverseKadane(a,n))); } }} /* This code is contributed by Mohit Kumar*/ Output: Maximum circular sum is 31 Complexity Analysis: Time Complexity: O(n), where n is the number of elements in the input array. As only linear traversal of the array is needed. Auxiliary Space: O(1). As no extra space is required. Note that the above algorithm doesn’t work if all numbers are negative, e.g., {-1, -2, -3}. It returns 0 in this case. This case can be handled by adding a pre-check to see if all the numbers are negative before running the above algorithm. Method 2 Approach: In this method, modify Kadane’s algorithm to find a minimum contiguous subarray sum and the maximum contiguous subarray sum, then check for the maximum value between the max_value and the value left after subtracting min_value from the total sum.Algorithm We will calculate the total sum of the given array.We will declare the variable curr_max, max_so_far, curr_min, min_so_far as the first value of the array.Now we will use Kadane’s Algorithm to find the maximum subarray sum and minimum subarray sum.Check for all the values in the array:- If min_so_far is equaled to sum, i.e. all values are negative, then we return max_so_far.Else, we will calculate the maximum value of max_so_far and (sum – min_so_far) and return it. We will calculate the total sum of the given array. We will declare the variable curr_max, max_so_far, curr_min, min_so_far as the first value of the array. Now we will use Kadane’s Algorithm to find the maximum subarray sum and minimum subarray sum. Check for all the values in the array:- If min_so_far is equaled to sum, i.e. all values are negative, then we return max_so_far.Else, we will calculate the maximum value of max_so_far and (sum – min_so_far) and return it. If min_so_far is equaled to sum, i.e. all values are negative, then we return max_so_far.Else, we will calculate the maximum value of max_so_far and (sum – min_so_far) and return it. If min_so_far is equaled to sum, i.e. all values are negative, then we return max_so_far. Else, we will calculate the maximum value of max_so_far and (sum – min_so_far) and return it. The implementation of the above method is given below. Output: Maximum circular sum is 31 Complexity Analysis: Time Complexity: O(n), where n is the number of elements in the input array. As only linear traversal of the array is needed. Auxiliary Space: O(1). As no extra space is required. Please refer complete article on Maximum circular subarray sum for more details! nnr223442 circular-array subarray subarray-sum Arrays Java Java Programs Arrays 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 Arrays.sort() in Java with examples Reverse a string in Java Split() String method in Java with examples Object Oriented Programming (OOPs) Concept in Java For-each loop in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Dec, 2021" }, { "code": null, "e": 132, "s": 28, "text": "Given n numbers (both +ve and -ve), arranged in a circle, find the maximum sum of consecutive numbers. " }, { "code": null, "e": 143, "s": 132, "text": "Examples: " }, { "code": null, "e": 388, "s": 143, "text": "Input: a[] = {8, -8, 9, -9, 10, -11, 12}\nOutput: 22 (12 + 8 - 8 + 9 - 9 + 10)\n\nInput: a[] = {10, -3, -4, 7, 6, 5, -4, -1} \nOutput: 23 (7 + 6 + 5 - 4 -1 + 10) \n\nInput: a[] = {-1, 40, -14, 7, 6, 5, -4, -1}\nOutput: 52 (7 + 6 + 5 - 4 - 1 - 1 + 40)" }, { "code": null, "e": 443, "s": 388, "text": "Method 1 There can be two cases for the maximum sum: " }, { "code": null, "e": 649, "s": 443, "text": "Case 1: The elements that contribute to the maximum sum are arranged such that no wrapping is there. Examples: {-10, 2, -1, 5}, {-2, 4, -1, 4, -1}. In this case, Kadane’s algorithm will produce the result." }, { "code": null, "e": 1381, "s": 649, "text": "Case 2: The elements which contribute to the maximum sum are arranged such that wrapping is there. Examples: {10, -12, 11}, {12, -5, 4, -8, 11}. In this case, we change wrapping to non-wrapping. Let us see how. Wrapping of contributing elements implies non-wrapping of non-contributing elements, so find out the sum of non-contributing elements and subtract this sum from the total sum. To find out the sum of non-contributions, invert the sign of each element and then run Kadane’s algorithm. Our array is like a ring and we have to eliminate the maximum continuous negative that implies maximum continuous positive in the inverted arrays. Finally, we compare the sum obtained in both cases and return the maximum of the two sums." }, { "code": null, "e": 1437, "s": 1381, "text": "The following are implementations of the above method. " }, { "code": null, "e": 1442, "s": 1437, "text": "Java" }, { "code": "// Java program for maximum contiguous circular sum problemimport java.io.*;import java.util.*; class Solution{ public static int kadane(int a[],int n){ int res = 0; int x = a[0]; for(int i = 0; i < n; i++){ res = Math.max(a[i],res+a[i]); x= Math.max(x,res); } return x; } //lets write a function for calculating max sum in circular manner as discuss above public static int reverseKadane(int a[],int n){ int total = 0; //taking the total sum of the array elements for(int i = 0; i< n; i++){ total +=a[i]; } // inverting the array for(int i = 0; i<n ; i++){ a[i] = -a[i]; } // finding min sum subarray int k = kadane(a,n);// max circular sum int ress = total+k; // to handle the case in which all elements are negative if(total == -k ){ return total; } else{ return ress; } } public static void main(String[] args) { int a[] = {1,4,6,4,-3,8,-1}; int n = 7; if(n==1){ System.out.println(\"Maximum circular sum is \" +a[0]); } else{ System.out.println(\"Maximum circular sum is \" +Integer.max(kadane(a,n), reverseKadane(a,n))); } }} /* This code is contributed by Mohit Kumar*/", "e": 2825, "s": 1442, "text": null }, { "code": null, "e": 2834, "s": 2825, "text": "Output: " }, { "code": null, "e": 2861, "s": 2834, "text": "Maximum circular sum is 31" }, { "code": null, "e": 2884, "s": 2861, "text": "Complexity Analysis: " }, { "code": null, "e": 3010, "s": 2884, "text": "Time Complexity: O(n), where n is the number of elements in the input array. As only linear traversal of the array is needed." }, { "code": null, "e": 3064, "s": 3010, "text": "Auxiliary Space: O(1). As no extra space is required." }, { "code": null, "e": 3305, "s": 3064, "text": "Note that the above algorithm doesn’t work if all numbers are negative, e.g., {-1, -2, -3}. It returns 0 in this case. This case can be handled by adding a pre-check to see if all the numbers are negative before running the above algorithm." }, { "code": null, "e": 3581, "s": 3305, "text": "Method 2 Approach: In this method, modify Kadane’s algorithm to find a minimum contiguous subarray sum and the maximum contiguous subarray sum, then check for the maximum value between the max_value and the value left after subtracting min_value from the total sum.Algorithm " }, { "code": null, "e": 4052, "s": 3581, "text": "We will calculate the total sum of the given array.We will declare the variable curr_max, max_so_far, curr_min, min_so_far as the first value of the array.Now we will use Kadane’s Algorithm to find the maximum subarray sum and minimum subarray sum.Check for all the values in the array:- If min_so_far is equaled to sum, i.e. all values are negative, then we return max_so_far.Else, we will calculate the maximum value of max_so_far and (sum – min_so_far) and return it." }, { "code": null, "e": 4104, "s": 4052, "text": "We will calculate the total sum of the given array." }, { "code": null, "e": 4209, "s": 4104, "text": "We will declare the variable curr_max, max_so_far, curr_min, min_so_far as the first value of the array." }, { "code": null, "e": 4303, "s": 4209, "text": "Now we will use Kadane’s Algorithm to find the maximum subarray sum and minimum subarray sum." }, { "code": null, "e": 4526, "s": 4303, "text": "Check for all the values in the array:- If min_so_far is equaled to sum, i.e. all values are negative, then we return max_so_far.Else, we will calculate the maximum value of max_so_far and (sum – min_so_far) and return it." }, { "code": null, "e": 4709, "s": 4526, "text": "If min_so_far is equaled to sum, i.e. all values are negative, then we return max_so_far.Else, we will calculate the maximum value of max_so_far and (sum – min_so_far) and return it." }, { "code": null, "e": 4799, "s": 4709, "text": "If min_so_far is equaled to sum, i.e. all values are negative, then we return max_so_far." }, { "code": null, "e": 4893, "s": 4799, "text": "Else, we will calculate the maximum value of max_so_far and (sum – min_so_far) and return it." }, { "code": null, "e": 4950, "s": 4893, "text": "The implementation of the above method is given below. " }, { "code": null, "e": 4959, "s": 4950, "text": "Output: " }, { "code": null, "e": 4986, "s": 4959, "text": "Maximum circular sum is 31" }, { "code": null, "e": 5009, "s": 4986, "text": "Complexity Analysis: " }, { "code": null, "e": 5135, "s": 5009, "text": "Time Complexity: O(n), where n is the number of elements in the input array. As only linear traversal of the array is needed." }, { "code": null, "e": 5189, "s": 5135, "text": "Auxiliary Space: O(1). As no extra space is required." }, { "code": null, "e": 5271, "s": 5189, "text": "Please refer complete article on Maximum circular subarray sum for more details! " }, { "code": null, "e": 5281, "s": 5271, "text": "nnr223442" }, { "code": null, "e": 5296, "s": 5281, "text": "circular-array" }, { "code": null, "e": 5305, "s": 5296, "text": "subarray" }, { "code": null, "e": 5318, "s": 5305, "text": "subarray-sum" }, { "code": null, "e": 5325, "s": 5318, "text": "Arrays" }, { "code": null, "e": 5330, "s": 5325, "text": "Java" }, { "code": null, "e": 5344, "s": 5330, "text": "Java Programs" }, { "code": null, "e": 5351, "s": 5344, "text": "Arrays" }, { "code": null, "e": 5356, "s": 5351, "text": "Java" }, { "code": null, "e": 5454, "s": 5356, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5486, "s": 5454, "text": "Introduction to Data Structures" }, { "code": null, "e": 5511, "s": 5486, "text": "Window Sliding Technique" }, { "code": null, "e": 5558, "s": 5511, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 5622, "s": 5558, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 5653, "s": 5622, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 5689, "s": 5653, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 5714, "s": 5689, "text": "Reverse a string in Java" }, { "code": null, "e": 5758, "s": 5714, "text": "Split() String method in Java with examples" }, { "code": null, "e": 5809, "s": 5758, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Chinese Postman or Route Inspection | Set 1 (introduction)
07 Jul, 2022 Chinese Postman Problem is a variation of Eulerian circuit problem for undirected graphs. An Euler Circuit is a closed walk that covers every edge once starting and ending position is same. Chinese Postman problem is defined for connected and undirected graph. The problem is to find shortest path or circuity that visits every edge of the graph at least once. If input graph contains Euler Circuit, then a solution of the problem is Euler Circuit An undirected and connected graph has Eulerian cycle if “all vertices have even degree“. It doesn’t matter whether graph is weighted or unweighted, the Chinese Postman Route is always same as Eulerian Circuit if it exists. In weighted graph the minimum possible weight of Postman tour is sum of all edge weights which we get through Eulerian Circuit. We can’t get a shorter route as we must visit all edges at-least once. If input graph does NOT contain Euler Circuit In this case, the task reduces to following. 1) In unweighted graph, minimum number of edges to duplicate so that the given graph converts to a graph with Eulerian Cycle. 2) In weighted graph, minimum total weight of edges to duplicate so that given graph converts to a graph with Eulerian Cycle. Algorithm to find shortest closed path or optimal Chinese postman route in a weighted graph that may not be Eulerian. step 1 : If graph is Eulerian, return sum of all edge weights.Else do following steps. step 2 : We find all the vertices with odd degree step 3 : List all possible pairings of odd vertices For n odd vertices total number of pairings possible are, (n-1) * (n-3) * (n -5)... * 1 step 4 : For each set of pairings, find the shortest path connecting them. step 5 : Find the pairing with minimum shortest path connecting pairs. step 6 : Modify the graph by adding all the edges that have been found in step 5. step 7 : Weight of Chinese Postman Tour is sum of all edges in the modified graph. step 8 : Print Euler Circuit of the modified graph. This Euler Circuit is Chinese Postman Tour. Illustration : 3 (a)-----------------(b) 1 / | | \1 / | | \ (c) | 5 6| (d) \ | | / 2 \ | 4 | /1 (e)------------------(f) As we see above graph does not contain Eulerian circuit because is has odd degree vertices [a, b, e, f] they all are odd degree vertices . First we make all possible pairs of odd degree vertices [ae, bf], [ab, ef], [af, eb] so pairs with min sum of weight are [ae, bf] : ae = (ac + ce = 3 ), bf = ( bd + df = 2 ) Total : 5 We add edges ac, ce, bd and df to the original graph and create a modified graph. Optimal chinese postman route is of length : 5 + 23 = 28 [ 23 = sum of all edges of modified graph ] Chinese Postman Route : a - b - d - f - d - b - f - e - c - a - c - e - a This route is Euler Circuit of the modified graph. This article is contributed by Nishant Singh . 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. abhijatyagupta amazingahmad56 hardikkoriintern Euler-Circuit Graph Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Dijkstra's shortest path algorithm | Greedy Algo-7 Find if there is a path between two vertices in a directed graph Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Detect Cycle in a Directed Graph Introduction to Data Structures Find if there is a path between two vertices in an undirected graph What is Data Structure: Types, Classifications and Applications Bellman–Ford Algorithm | DP-23 Minimum number of swaps required to sort an array m Coloring Problem | Backtracking-5
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jul, 2022" }, { "code": null, "e": 414, "s": 52, "text": "Chinese Postman Problem is a variation of Eulerian circuit problem for undirected graphs. An Euler Circuit is a closed walk that covers every edge once starting and ending position is same. Chinese Postman problem is defined for connected and undirected graph. The problem is to find shortest path or circuity that visits every edge of the graph at least once. " }, { "code": null, "e": 592, "s": 414, "text": "If input graph contains Euler Circuit, then a solution of the problem is Euler Circuit An undirected and connected graph has Eulerian cycle if “all vertices have even degree“. " }, { "code": null, "e": 926, "s": 592, "text": "It doesn’t matter whether graph is weighted or unweighted, the Chinese Postman Route is always same as Eulerian Circuit if it exists. In weighted graph the minimum possible weight of Postman tour is sum of all edge weights which we get through Eulerian Circuit. We can’t get a shorter route as we must visit all edges at-least once. " }, { "code": null, "e": 975, "s": 926, "text": " If input graph does NOT contain Euler Circuit " }, { "code": null, "e": 1021, "s": 975, "text": "In this case, the task reduces to following. " }, { "code": null, "e": 1148, "s": 1021, "text": "1) In unweighted graph, minimum number of edges to duplicate so that the given graph converts to a graph with Eulerian Cycle. " }, { "code": null, "e": 1274, "s": 1148, "text": "2) In weighted graph, minimum total weight of edges to duplicate so that given graph converts to a graph with Eulerian Cycle." }, { "code": null, "e": 2164, "s": 1274, "text": "Algorithm to find shortest closed path or optimal \nChinese postman route in a weighted graph that may\nnot be Eulerian.\n\nstep 1 : If graph is Eulerian, return sum of all \n edge weights.Else do following steps.\nstep 2 : We find all the vertices with odd degree \nstep 3 : List all possible pairings of odd vertices \n For n odd vertices total number of pairings \n possible are, (n-1) * (n-3) * (n -5)... * 1\nstep 4 : For each set of pairings, find the shortest \n path connecting them.\nstep 5 : Find the pairing with minimum shortest path \n connecting pairs.\nstep 6 : Modify the graph by adding all the edges that \n have been found in step 5.\nstep 7 : Weight of Chinese Postman Tour is sum of all \n edges in the modified graph.\nstep 8 : Print Euler Circuit of the modified graph. \n This Euler Circuit is Chinese Postman Tour. " }, { "code": null, "e": 2180, "s": 2164, "text": "Illustration : " }, { "code": null, "e": 2850, "s": 2180, "text": " 3\n (a)-----------------(b)\n 1 / | | \\1\n / | | \\\n (c) | 5 6| (d)\n \\ | | /\n 2 \\ | 4 | /1\n (e)------------------(f)\nAs we see above graph does not contain Eulerian circuit\nbecause is has odd degree vertices [a, b, e, f]\nthey all are odd degree vertices . \n\nFirst we make all possible pairs of odd degree vertices\n[ae, bf], [ab, ef], [af, eb] \nso pairs with min sum of weight are [ae, bf] :\nae = (ac + ce = 3 ), bf = ( bd + df = 2 ) \nTotal : 5\n\nWe add edges ac, ce, bd and df to the original graph and\ncreate a modified graph." }, { "code": null, "e": 3083, "s": 2850, "text": "Optimal chinese postman route is of length : 5 + 23 = \n28 [ 23 = sum of all edges of modified graph ]\n\nChinese Postman Route : \na - b - d - f - d - b - f - e - c - a - c - e - a \nThis route is Euler Circuit of the modified graph. " }, { "code": null, "e": 3383, "s": 3083, "text": "This article is contributed by Nishant Singh . 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": 3398, "s": 3383, "text": "abhijatyagupta" }, { "code": null, "e": 3413, "s": 3398, "text": "amazingahmad56" }, { "code": null, "e": 3430, "s": 3413, "text": "hardikkoriintern" }, { "code": null, "e": 3444, "s": 3430, "text": "Euler-Circuit" }, { "code": null, "e": 3450, "s": 3444, "text": "Graph" }, { "code": null, "e": 3456, "s": 3450, "text": "Graph" }, { "code": null, "e": 3554, "s": 3456, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3605, "s": 3554, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 3670, "s": 3605, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 3728, "s": 3670, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 3761, "s": 3728, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 3793, "s": 3761, "text": "Introduction to Data Structures" }, { "code": null, "e": 3861, "s": 3793, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 3925, "s": 3861, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 3956, "s": 3925, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 4006, "s": 3956, "text": "Minimum number of swaps required to sort an array" } ]
How to create a nested webpage in HTML ?
25 Aug, 2021 When the content of one completely different webpage is embedded into another webpage, it is called a nested webpage. In simple words, a webpage that is inside another webpage of a completely different domain. In this article, we are going to learn how to create a nested webpage. There are two methods to create a nested webpage. They are as follows. Using <iframe> tagUsing <embed> tag Using <iframe> tag Using <embed> tag 1. Using <iframe> tag: The iframe in HTML stands for Inline Frame. The “iframe” tag defines a rectangular region within the document in which the browser can display a separate document, including scrollbars and borders. An inline frame is used to embed another document within the current HTML document Syntax: <iframe src="URL"></iframe> It can take the height and width of the inline frame as attribute. Example: HTML <!DOCTYPE html><html> <head></head> <body> <h1> Creating a Nested Webpage using 'iframe' Tag: Geeksforgeeks </h1> <iframe src="https://www.geeksforgeeks.org" height="500px" width="1000px"> </iframe> </body></html> Output: 2. Using <embed> tag: The <embed> tag in HTML is used for embedding external applications which are generally multimedia content like audio or video into an HTML document. But another raw HTML content can be embedded using this tag. We can use this feature to create a nested webpage. Syntax: <embed src="URL" type="text/html" /> Example: HTML <!DOCTYPE html><html> <head></head> <body> <h1> Creating a Nested Webpage using 'embed' Tag: Geeksforgeeks </h1> <embed src="https://www.geeksforgeeks.org" type="text/html" /> </body></html> Output: The website can prevent you from embedding their content due to copyright issues. So it is mandatory to have proper permission and authorization before using another webpage as a nested webpage inside your website. HTML-Questions Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Design a web page using HTML and CSS Angular File Upload Installation of Node.js on Linux How to create footer to stay at the bottom of a Web page? How do you run JavaScript script through the Terminal? Node.js fs.readFileSync() Method How to set space between the flexbox ?
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Aug, 2021" }, { "code": null, "e": 238, "s": 28, "text": "When the content of one completely different webpage is embedded into another webpage, it is called a nested webpage. In simple words, a webpage that is inside another webpage of a completely different domain." }, { "code": null, "e": 381, "s": 238, "text": " In this article, we are going to learn how to create a nested webpage. There are two methods to create a nested webpage. They are as follows." }, { "code": null, "e": 417, "s": 381, "text": "Using <iframe> tagUsing <embed> tag" }, { "code": null, "e": 436, "s": 417, "text": "Using <iframe> tag" }, { "code": null, "e": 454, "s": 436, "text": "Using <embed> tag" }, { "code": null, "e": 477, "s": 454, "text": "1. Using <iframe> tag:" }, { "code": null, "e": 758, "s": 477, "text": "The iframe in HTML stands for Inline Frame. The “iframe” tag defines a rectangular region within the document in which the browser can display a separate document, including scrollbars and borders. An inline frame is used to embed another document within the current HTML document" }, { "code": null, "e": 768, "s": 760, "text": "Syntax:" }, { "code": null, "e": 796, "s": 768, "text": "<iframe src=\"URL\"></iframe>" }, { "code": null, "e": 863, "s": 796, "text": "It can take the height and width of the inline frame as attribute." }, { "code": null, "e": 872, "s": 863, "text": "Example:" }, { "code": null, "e": 877, "s": 872, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head></head> <body> <h1> Creating a Nested Webpage using 'iframe' Tag: Geeksforgeeks </h1> <iframe src=\"https://www.geeksforgeeks.org\" height=\"500px\" width=\"1000px\"> </iframe> </body></html>", "e": 1148, "s": 877, "text": null }, { "code": null, "e": 1156, "s": 1148, "text": "Output:" }, { "code": null, "e": 1178, "s": 1156, "text": "2. Using <embed> tag:" }, { "code": null, "e": 1441, "s": 1178, "text": "The <embed> tag in HTML is used for embedding external applications which are generally multimedia content like audio or video into an HTML document. But another raw HTML content can be embedded using this tag. We can use this feature to create a nested webpage." }, { "code": null, "e": 1449, "s": 1441, "text": "Syntax:" }, { "code": null, "e": 1487, "s": 1449, "text": "<embed src=\"URL\" type=\"text/html\" /> " }, { "code": null, "e": 1496, "s": 1487, "text": "Example:" }, { "code": null, "e": 1501, "s": 1496, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head></head> <body> <h1> Creating a Nested Webpage using 'embed' Tag: Geeksforgeeks </h1> <embed src=\"https://www.geeksforgeeks.org\" type=\"text/html\" /> </body></html>", "e": 1739, "s": 1501, "text": null }, { "code": null, "e": 1747, "s": 1739, "text": "Output:" }, { "code": null, "e": 1962, "s": 1747, "text": "The website can prevent you from embedding their content due to copyright issues. So it is mandatory to have proper permission and authorization before using another webpage as a nested webpage inside your website." }, { "code": null, "e": 1977, "s": 1962, "text": "HTML-Questions" }, { "code": null, "e": 1984, "s": 1977, "text": "Picked" }, { "code": null, "e": 1989, "s": 1984, "text": "HTML" }, { "code": null, "e": 2006, "s": 1989, "text": "Web Technologies" }, { "code": null, "e": 2011, "s": 2006, "text": "HTML" }, { "code": null, "e": 2109, "s": 2011, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2133, "s": 2109, "text": "REST API (Introduction)" }, { "code": null, "e": 2172, "s": 2133, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 2211, "s": 2172, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 2248, "s": 2211, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 2268, "s": 2248, "text": "Angular File Upload" }, { "code": null, "e": 2301, "s": 2268, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2359, "s": 2301, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 2414, "s": 2359, "text": "How do you run JavaScript script through the Terminal?" }, { "code": null, "e": 2447, "s": 2414, "text": "Node.js fs.readFileSync() Method" } ]
How to get the Response status code in Golang?
Response status codes are the numbers that we get in response that signify what type of response we received from the server when we asked for something from it. There are different status codes that one gets from the response, and these are mainly divided into five categories. Generally, the status codes are divided into these five classes. 1xx (Informational) 1xx (Informational) 2xx (Successful) 2xx (Successful) 3xx (Redirection) 3xx (Redirection) 4xx (Client Error) 4xx (Client Error) 5xx (Server Error) 5xx (Server Error) In this article, we will try to get two or more of these status codes. Let's start with a basic HTTP request to the google.com URL. Once we do that, we will get the response from the server and that response will contain the status code. Consider the code shown below. package main import ( "fmt" "log" "net/http" ) func main() { resp, err := http.Get("https://www.google.com") if err != nil { log.Fatal(err) } fmt.Println("The status code we got is:", resp.StatusCode) } If we run the command go run main.go on the above code, then we will get the following output in the terminal. The status code we got is: 200 Each status code also holds a StatusText with itself, which we can also print with the statusCode. Consider the code shown below. package main import ( "fmt" "log" "net/http" ) func main() { resp, err := http.Get("https://www.google.com") if err != nil { log.Fatal(err) } fmt.Println("The status code we got is:", resp.StatusCode) fmt.Println("The status code text we got is:", http.StatusText(resp.StatusCode)) } If we run the command go run main.go on the above code, then we will get the following output in the terminal. The status code we got is: 200 The status code text we got is: OK We were able to get the status code 200, as the URL was available at the moment. In case we make a request to a URL which isn't active, we will get a 404 status code. Consider the code shown below. package main import ( "fmt" "log" "net/http" ) func main() { resp, err := http.Get("https://www.google.com/apple") if err != nil { log.Fatal(err) } fmt.Println("The status code we got is:", resp.StatusCode) fmt.Println("The status code text we got is:", http.StatusText(resp.StatusCode)) } If we run the command go run main.go on the above code, then we will get the following output in the terminal. The status code we got is: 404 The status code text we got is: Not Found
[ { "code": null, "e": 1349, "s": 1187, "text": "Response status codes are the numbers that we get in response that signify what type of response we received from the server when we asked for something from it." }, { "code": null, "e": 1466, "s": 1349, "text": "There are different status codes that one gets from the response, and these are mainly divided into five categories." }, { "code": null, "e": 1531, "s": 1466, "text": "Generally, the status codes are divided into these five classes." }, { "code": null, "e": 1551, "s": 1531, "text": "1xx (Informational)" }, { "code": null, "e": 1571, "s": 1551, "text": "1xx (Informational)" }, { "code": null, "e": 1588, "s": 1571, "text": "2xx (Successful)" }, { "code": null, "e": 1605, "s": 1588, "text": "2xx (Successful)" }, { "code": null, "e": 1623, "s": 1605, "text": "3xx (Redirection)" }, { "code": null, "e": 1641, "s": 1623, "text": "3xx (Redirection)" }, { "code": null, "e": 1660, "s": 1641, "text": "4xx (Client Error)" }, { "code": null, "e": 1679, "s": 1660, "text": "4xx (Client Error)" }, { "code": null, "e": 1698, "s": 1679, "text": "5xx (Server Error)" }, { "code": null, "e": 1717, "s": 1698, "text": "5xx (Server Error)" }, { "code": null, "e": 1788, "s": 1717, "text": "In this article, we will try to get two or more of these status codes." }, { "code": null, "e": 1955, "s": 1788, "text": "Let's start with a basic HTTP request to the google.com URL. Once we do that, we will get the response from the server and that response will contain the status code." }, { "code": null, "e": 1986, "s": 1955, "text": "Consider the code shown below." }, { "code": null, "e": 2219, "s": 1986, "text": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"net/http\"\n)\n\nfunc main() {\n resp, err := http.Get(\"https://www.google.com\")\n if err != nil {\n log.Fatal(err)\n }\n\n fmt.Println(\"The status code we got is:\", resp.StatusCode)\n}" }, { "code": null, "e": 2330, "s": 2219, "text": "If we run the command go run main.go on the above code, then we will get the following output in the terminal." }, { "code": null, "e": 2361, "s": 2330, "text": "The status code we got is: 200" }, { "code": null, "e": 2460, "s": 2361, "text": "Each status code also holds a StatusText with itself, which we can also print with the statusCode." }, { "code": null, "e": 2491, "s": 2460, "text": "Consider the code shown below." }, { "code": null, "e": 2808, "s": 2491, "text": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"net/http\"\n)\n\nfunc main() {\n resp, err := http.Get(\"https://www.google.com\")\n if err != nil {\n log.Fatal(err)\n }\n\n fmt.Println(\"The status code we got is:\", resp.StatusCode)\n fmt.Println(\"The status code text we got is:\", http.StatusText(resp.StatusCode))\n}" }, { "code": null, "e": 2919, "s": 2808, "text": "If we run the command go run main.go on the above code, then we will get the following output in the terminal." }, { "code": null, "e": 2985, "s": 2919, "text": "The status code we got is: 200\nThe status code text we got is: OK" }, { "code": null, "e": 3152, "s": 2985, "text": "We were able to get the status code 200, as the URL was available at the moment. In case we make a request to a URL which isn't active, we will get a 404 status code." }, { "code": null, "e": 3183, "s": 3152, "text": "Consider the code shown below." }, { "code": null, "e": 3506, "s": 3183, "text": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"net/http\"\n)\n\nfunc main() {\n resp, err := http.Get(\"https://www.google.com/apple\")\n if err != nil {\n log.Fatal(err)\n }\n\n fmt.Println(\"The status code we got is:\", resp.StatusCode)\n fmt.Println(\"The status code text we got is:\", http.StatusText(resp.StatusCode))\n}" }, { "code": null, "e": 3617, "s": 3506, "text": "If we run the command go run main.go on the above code, then we will get the following output in the terminal." }, { "code": null, "e": 3690, "s": 3617, "text": "The status code we got is: 404\nThe status code text we got is: Not Found" } ]
How to create a multi-page website using React.js ?
06 Jan, 2022 In this article, we will see how to create a simple multipage website using React Js. Prerequisite: npmcreate-react-appreact-router-domstyled components npm create-react-app react-router-dom styled components Approach: We will create a simple website that will have different pages and a navbar. We will create multiple pages Home page, About page, Blog page, Signup page, and Contact page and then we will see how to navigate between those pages. We will be using the following packages and components: react-router-dom: react-router-dom is a reactJS package, It enables you to implement dynamic routing in a web page. BrowserRouter: It uses the HTML5 history API to keep the UI in sync with the URL. Route: Its responsibility is to render UI when its path matches the current URL. Switch: It renders the first child Route or Redirects that matches the location. Styled-components: Styled-component Module allows us to write CSS within JavaScript in a very modular and reusable way in React. Below is the step by step implementation: Step 1: We will start a new project using create-react-app so open your terminal and type: Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English default, selected This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. npx create-react-app react-website Step 2: Now go to your folder by typing the given command in the terminal: cd react-website Step 3: Install the dependencies required in this project by typing the given command in the terminal. npm install react-router-dom npm install --save styled-components Step 4: Now create the components folder in src then go to the components folder and create a new folder name Navbar.In Navbar folder create two files index,js and NavbarElements.js. Create one more folder in src name pages and in pages create files name about.js, blogs.js, index.js, signup.js, contact.js Project Structure: The project structure will look like the following: Step 5: Now we will create the navbar and style it. index.js import React from "react";import { Nav, NavLink, NavMenu } from "./NavbarElements"; const Navbar = () => { return ( <> <Nav> <NavMenu> <NavLink to="/about" activeStyle> About </NavLink> <NavLink to="/contact" activeStyle> Contact Us </NavLink> <NavLink to="/blogs" activeStyle> Blogs </NavLink> <NavLink to="/sign-up" activeStyle> Sign Up </NavLink> </NavMenu> </Nav> </> );}; export default Navbar; NavbarElements.js import { FaBars } from "react-icons/fa";import { NavLink as Link } from "react-router-dom";import styled from "styled-components"; export const Nav = styled.nav` background: #ffb3ff; height: 85px; display: flex; justify-content: space-between; padding: 0.2rem calc((100vw - 1000px) / 2); z-index: 12;`; export const NavLink = styled(Link)` color: #808080; display: flex; align-items: center; text-decoration: none; padding: 0 1rem; height: 100%; cursor: pointer; &.active { color: #4d4dff; }`; export const Bars = styled(FaBars)` display: none; color: #808080; @media screen and (max-width: 768px) { display: block; position: absolute; top: 0; right: 0; transform: translate(-100%, 75%); font-size: 1.8rem; cursor: pointer; }`; export const NavMenu = styled.div` display: flex; align-items: center; margin-right: -24px; /* Second Nav */ /* margin-right: 24px; */ /* Third Nav */ /* width: 100vw;white-space: nowrap; */ @media screen and (max-width: 768px) { display: none; }`; Step 6: Now we will edit various pages in the project in src/pages. about.js import React from "react"; const About = () => { return ( <div> <h1> GeeksforGeeks is a Computer Science portal for geeks. </h1> </div> );}; export default About; blogs.js import React from 'react'; const Blogs = () => { return ( <h1>You can write your blogs!</h1> );}; export default Blogs; index.js import React from 'react'; const Home = () => { return ( <div> <h1>Welcome to GeeksforGeeks</h1> </div> );}; export default Home; signup.js import React from 'react'; const SignUp = () => { return ( <div> <h1>Sign Up Successful</h1> </div> );}; export default SignUp; contact.js import React from 'react'; const Contact = () => { return ( <div> <h1>Mail us on [email protected]</h1> </div> );}; export default Contact; index.js import React from 'react';import ReactDOM from 'react-dom';import App from './App'; ReactDOM.render(<React.StrictMode> <App /></React.StrictMode>,document.getElementById('root')); App.js import React from 'react';import './App.css';import Navbar from './components/Navbar';import { BrowserRouter as Router, Routes, Route} from 'react-router-dom';import Home from './pages';import About from './pages/about';import Blogs from './pages/blogs';import SignUp from './pages/signup';import Contact from './pages/contact'; function App() {return ( <Router> <Navbar /> <Routes> <Route exact path='/' exact element={<Home />} /> <Route path='/about' element={<About/>} /> <Route path='/contact' element={<Contact/>} /> <Route path='/blogs' element={<Blogs/>} /> <Route path='/sign-up' element={<SignUp/>} /> </Routes> </Router>);} export default App; Step to run the application: Now to run the above code open the terminal and type the following command. npm start Output: rkbhola5 React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS setState() How to pass data from one component to other component in ReactJS ? Re-rendering Components in ReactJS ReactJS defaultProps Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Jan, 2022" }, { "code": null, "e": 140, "s": 54, "text": "In this article, we will see how to create a simple multipage website using React Js." }, { "code": null, "e": 154, "s": 140, "text": "Prerequisite:" }, { "code": null, "e": 207, "s": 154, "text": "npmcreate-react-appreact-router-domstyled components" }, { "code": null, "e": 211, "s": 207, "text": "npm" }, { "code": null, "e": 228, "s": 211, "text": "create-react-app" }, { "code": null, "e": 245, "s": 228, "text": "react-router-dom" }, { "code": null, "e": 263, "s": 245, "text": "styled components" }, { "code": null, "e": 558, "s": 263, "text": "Approach: We will create a simple website that will have different pages and a navbar. We will create multiple pages Home page, About page, Blog page, Signup page, and Contact page and then we will see how to navigate between those pages. We will be using the following packages and components:" }, { "code": null, "e": 674, "s": 558, "text": "react-router-dom: react-router-dom is a reactJS package, It enables you to implement dynamic routing in a web page." }, { "code": null, "e": 756, "s": 674, "text": "BrowserRouter: It uses the HTML5 history API to keep the UI in sync with the URL." }, { "code": null, "e": 837, "s": 756, "text": "Route: Its responsibility is to render UI when its path matches the current URL." }, { "code": null, "e": 918, "s": 837, "text": "Switch: It renders the first child Route or Redirects that matches the location." }, { "code": null, "e": 1047, "s": 918, "text": "Styled-components: Styled-component Module allows us to write CSS within JavaScript in a very modular and reusable way in React." }, { "code": null, "e": 1089, "s": 1047, "text": "Below is the step by step implementation:" }, { "code": null, "e": 1180, "s": 1089, "text": "Step 1: We will start a new project using create-react-app so open your terminal and type:" }, { "code": null, "e": 1189, "s": 1180, "text": "Chapters" }, { "code": null, "e": 1216, "s": 1189, "text": "descriptions off, selected" }, { "code": null, "e": 1266, "s": 1216, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1289, "s": 1266, "text": "captions off, selected" }, { "code": null, "e": 1297, "s": 1289, "text": "English" }, { "code": null, "e": 1315, "s": 1297, "text": "default, selected" }, { "code": null, "e": 1339, "s": 1315, "text": "This is a modal window." }, { "code": null, "e": 1408, "s": 1339, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1430, "s": 1408, "text": "End of dialog window." }, { "code": null, "e": 1465, "s": 1430, "text": "npx create-react-app react-website" }, { "code": null, "e": 1540, "s": 1465, "text": "Step 2: Now go to your folder by typing the given command in the terminal:" }, { "code": null, "e": 1557, "s": 1540, "text": "cd react-website" }, { "code": null, "e": 1660, "s": 1557, "text": "Step 3: Install the dependencies required in this project by typing the given command in the terminal." }, { "code": null, "e": 1727, "s": 1660, "text": "npm install react-router-dom \nnpm install --save styled-components" }, { "code": null, "e": 2034, "s": 1727, "text": "Step 4: Now create the components folder in src then go to the components folder and create a new folder name Navbar.In Navbar folder create two files index,js and NavbarElements.js. Create one more folder in src name pages and in pages create files name about.js, blogs.js, index.js, signup.js, contact.js" }, { "code": null, "e": 2105, "s": 2034, "text": "Project Structure: The project structure will look like the following:" }, { "code": null, "e": 2157, "s": 2105, "text": "Step 5: Now we will create the navbar and style it." }, { "code": null, "e": 2166, "s": 2157, "text": "index.js" }, { "code": "import React from \"react\";import { Nav, NavLink, NavMenu } from \"./NavbarElements\"; const Navbar = () => { return ( <> <Nav> <NavMenu> <NavLink to=\"/about\" activeStyle> About </NavLink> <NavLink to=\"/contact\" activeStyle> Contact Us </NavLink> <NavLink to=\"/blogs\" activeStyle> Blogs </NavLink> <NavLink to=\"/sign-up\" activeStyle> Sign Up </NavLink> </NavMenu> </Nav> </> );}; export default Navbar;", "e": 2720, "s": 2166, "text": null }, { "code": null, "e": 2740, "s": 2722, "text": "NavbarElements.js" }, { "code": "import { FaBars } from \"react-icons/fa\";import { NavLink as Link } from \"react-router-dom\";import styled from \"styled-components\"; export const Nav = styled.nav` background: #ffb3ff; height: 85px; display: flex; justify-content: space-between; padding: 0.2rem calc((100vw - 1000px) / 2); z-index: 12;`; export const NavLink = styled(Link)` color: #808080; display: flex; align-items: center; text-decoration: none; padding: 0 1rem; height: 100%; cursor: pointer; &.active { color: #4d4dff; }`; export const Bars = styled(FaBars)` display: none; color: #808080; @media screen and (max-width: 768px) { display: block; position: absolute; top: 0; right: 0; transform: translate(-100%, 75%); font-size: 1.8rem; cursor: pointer; }`; export const NavMenu = styled.div` display: flex; align-items: center; margin-right: -24px; /* Second Nav */ /* margin-right: 24px; */ /* Third Nav */ /* width: 100vw;white-space: nowrap; */ @media screen and (max-width: 768px) { display: none; }`;", "e": 3776, "s": 2740, "text": null }, { "code": null, "e": 3844, "s": 3776, "text": "Step 6: Now we will edit various pages in the project in src/pages." }, { "code": null, "e": 3853, "s": 3844, "text": "about.js" }, { "code": "import React from \"react\"; const About = () => { return ( <div> <h1> GeeksforGeeks is a Computer Science portal for geeks. </h1> </div> );}; export default About;", "e": 4051, "s": 3853, "text": null }, { "code": null, "e": 4060, "s": 4051, "text": "blogs.js" }, { "code": "import React from 'react'; const Blogs = () => { return ( <h1>You can write your blogs!</h1> );}; export default Blogs;", "e": 4187, "s": 4060, "text": null }, { "code": null, "e": 4196, "s": 4187, "text": "index.js" }, { "code": "import React from 'react'; const Home = () => { return ( <div> <h1>Welcome to GeeksforGeeks</h1> </div> );}; export default Home;", "e": 4341, "s": 4196, "text": null }, { "code": null, "e": 4351, "s": 4341, "text": "signup.js" }, { "code": "import React from 'react'; const SignUp = () => { return ( <div> <h1>Sign Up Successful</h1> </div> );}; export default SignUp;", "e": 4494, "s": 4351, "text": null }, { "code": null, "e": 4505, "s": 4494, "text": "contact.js" }, { "code": "import React from 'react'; const Contact = () => { return ( <div> <h1>Mail us on [email protected]</h1> </div> );}; export default Contact;", "e": 4669, "s": 4505, "text": null }, { "code": null, "e": 4678, "s": 4669, "text": "index.js" }, { "code": "import React from 'react';import ReactDOM from 'react-dom';import App from './App'; ReactDOM.render(<React.StrictMode> <App /></React.StrictMode>,document.getElementById('root'));", "e": 4862, "s": 4678, "text": null }, { "code": null, "e": 4869, "s": 4862, "text": "App.js" }, { "code": "import React from 'react';import './App.css';import Navbar from './components/Navbar';import { BrowserRouter as Router, Routes, Route} from 'react-router-dom';import Home from './pages';import About from './pages/about';import Blogs from './pages/blogs';import SignUp from './pages/signup';import Contact from './pages/contact'; function App() {return ( <Router> <Navbar /> <Routes> <Route exact path='/' exact element={<Home />} /> <Route path='/about' element={<About/>} /> <Route path='/contact' element={<Contact/>} /> <Route path='/blogs' element={<Blogs/>} /> <Route path='/sign-up' element={<SignUp/>} /> </Routes> </Router>);} export default App;", "e": 5579, "s": 4869, "text": null }, { "code": null, "e": 5684, "s": 5579, "text": "Step to run the application: Now to run the above code open the terminal and type the following command." }, { "code": null, "e": 5694, "s": 5684, "text": "npm start" }, { "code": null, "e": 5702, "s": 5694, "text": "Output:" }, { "code": null, "e": 5711, "s": 5702, "text": "rkbhola5" }, { "code": null, "e": 5727, "s": 5711, "text": "React-Questions" }, { "code": null, "e": 5735, "s": 5727, "text": "ReactJS" }, { "code": null, "e": 5752, "s": 5735, "text": "Web Technologies" }, { "code": null, "e": 5850, "s": 5752, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5888, "s": 5850, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 5907, "s": 5888, "text": "ReactJS setState()" }, { "code": null, "e": 5975, "s": 5907, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 6010, "s": 5975, "text": "Re-rendering Components in ReactJS" }, { "code": null, "e": 6031, "s": 6010, "text": "ReactJS defaultProps" }, { "code": null, "e": 6093, "s": 6031, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 6126, "s": 6093, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 6187, "s": 6126, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6237, "s": 6187, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Find the number of valid parentheses expressions of given length
03 Nov, 2021 Given a number n find the number of valid parentheses expressions of that length. Examples : Input: 2 Output: 1 There is only possible valid expression of length 2, "()" Input: 4 Output: 2 Possible valid expression of length 4 are "(())" and "()()" Input: 6 Output: 5 Possible valid expressions are ((())), ()(()), ()()(), (())() and (()()) This is mainly an application of Catalan Numbers. Total possible valid expressions for input n is n/2’th Catalan Number if n is even and 0 if n is odd. Below given is the implementation : C++ Java Python3 C# PHP Javascript // C++ program to find valid paranthesisations of length n// The majority of code is taken from method 3 of// https://www.geeksforgeeks.org/program-nth-catalan-number/#include <bits/stdc++.h>using namespace std; // Returns value of Binomial Coefficient C(n, k)unsigned long int binomialCoeff(unsigned int n, unsigned int k){ unsigned long int res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of [n*(n-1)*---*(n-k+1)] / [k*(k-1)*---*1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res;} // A Binomial coefficient based function to// find nth catalan number in O(n) timeunsigned long int catalan(unsigned int n){ // Calculate value of 2nCn unsigned long int c = binomialCoeff(2 * n, n); // return 2nCn/(n+1) return c / (n + 1);} // Function to find possible ways to put balanced// parenthesis in an expression of length nunsigned long int findWays(unsigned n){ // If n is odd, not possible to // create any valid parentheses if (n & 1) return 0; // Otherwise return n/2'th Catalan Number return catalan(n / 2);} // Driver program to test above functionsint main(){ int n = 6; cout << "Total possible expressions of length " << n << " is " << findWays(6); return 0;} // Java program to find valid paranthesisations of length n// The majority of code is taken from method 3 of// https://www.geeksforgeeks.org/program-nth-catalan-number/ class GFG { // Returns value of Binomial Coefficient C(n, k) static long binomialCoeff(int n, int k) { long res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of [n*(n-1)*---*(n-k+1)] / [k*(k-1)*---*1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; } // A Binomial coefficient based function to // find nth catalan number in O(n) time static long catalan(int n) { // Calculate value of 2nCn long c = binomialCoeff(2 * n, n); // return 2nCn/(n+1) return c / (n + 1); } // Function to find possible ways to put balanced // parenthesis in an expression of length n static long findWays(int n) { // If n is odd, not possible to // create any valid parentheses if ((n & 1) != 0) return 0; // Otherwise return n/2'th Catalan Number return catalan(n / 2); } // Driver program to test above functions public static void main(String[] args) { int n = 6; System.out.println("Total possible expressions of length " + n + " is " + findWays(6)); }} // This code is contributed by Smitha Dinesh Semwal # Python3 program to find valid# paranthesisations of length n# The majority of code is taken# from method 3 of# https:#www.geeksforgeeks.org/program-nth-catalan-number/ # Returns value of Binomial# Coefficient C(n, k)def binomialCoeff(n, k): res = 1; # Since C(n, k) = C(n, n-k) if (k > n - k): k = n - k; # Calculate value of [n*(n-1)*--- # *(n-k+1)] / [k*(k-1)*---*1] for i in range(k): res *= (n - i); res /= (i + 1); return int(res); # A Binomial coefficient based# function to find nth catalan # number in O(n) timedef catalan(n): # Calculate value of 2nCn c = binomialCoeff(2 * n, n); # return 2nCn/(n+1) return int(c / (n + 1)); # Function to find possible# ways to put balanced parenthesis# in an expression of length ndef findWays(n): # If n is odd, not possible to # create any valid parentheses if(n & 1): return 0; # Otherwise return n/2'th # Catalan Number return catalan(int(n / 2)); # Driver Coden = 6;print("Total possible expressions of length", n, "is", findWays(6)); # This code is contributed by mits // C# program to find valid paranthesisations// of length n The majority of code is taken// from method 3 of// https://www.geeksforgeeks.org/program-nth-catalan-number/using System; class GFG { // Returns value of Binomial // Coefficient C(n, k) static long binomialCoeff(int n, int k) { long res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of [n*(n-1)*---* // (n-k+1)] / [k*(k-1)*---*1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; } // A Binomial coefficient based function to // find nth catalan number in O(n) time static long catalan(int n) { // Calculate value of 2nCn long c = binomialCoeff(2 * n, n); // return 2nCn/(n+1) return c / (n + 1); } // Function to find possible ways to put // balanced parenthesis in an expression // of length n static long findWays(int n) { // If n is odd, not possible to // create any valid parentheses if ((n & 1) != 0) return 0; // Otherwise return n/2'th // Catalan Number return catalan(n / 2); } // Driver program to test // above functions public static void Main() { int n = 6; Console.Write("Total possible expressions" + "of length " + n + " is " + findWays(6)); }} // This code is contributed by nitin mittal. <?php// PHP program to find valid// paranthesisations of length n// The majority of code is taken// from method 3 of// https://www.geeksforgeeks.org/program-nth-catalan-number/ // Returns value of Binomial// Coefficient C(n, k)function binomialCoeff($n, $k){ $res = 1; // Since C(n, k) = C(n, n-k) if ($k > $n - $k) $k = $n - $k; // Calculate value of [n*(n-1)*--- // *(n-k+1)] / [k*(k-1)*---*1] for ($i = 0; $i < $k; ++$i) { $res *= ($n - $i); $res /= ($i + 1); } return $res;} // A Binomial coefficient// based function to find// nth catalan number in// O(n) timefunction catalan($n){ // Calculate value of 2nCn $c = binomialCoeff(2 * $n, $n); // return 2nCn/(n+1) return $c / ($n + 1);} // Function to find possible// ways to put balanced// parenthesis in an expression// of length nfunction findWays($n){ // If n is odd, not possible to // create any valid parentheses if ($n & 1) return 0; // Otherwise return n/2'th // Catalan Number return catalan($n / 2);} // Driver Code $n = 6; echo "Total possible expressions of length " , $n , " is " , findWays(6); // This code is contributed by nitin mittal?> <script>// Javascript program to find valid// paranthesisations of length n// The majority of code is taken// from method 3 of// https://www.geeksforgeeks.org/program-nth-catalan-number/ // Returns value of Binomial// Coefficient C(n, k)function binomialCoeff(n, k){ let res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of [n*(n-1)*--- // *(n-k+1)] / [k*(k-1)*---*1] for (let i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res;} // A Binomial coefficient// based function to find// nth catalan number in// O(n) timefunction catalan(n){ // Calculate value of 2nCn let c = binomialCoeff(2 * n, n); // return 2nCn/(n+1) return c / (n + 1);} // Function to find possible// ways to put balanced// parenthesis in an expression// of length nfunction findWays(n){ // If n is odd, not possible to // create any valid parentheses if (n & 1) return 0; // Otherwise return n/2'th // Catalan Number return catalan(n / 2);} // Driver Code let n = 6; document.write("Total possible expressions of length " + n + " is " + findWays(6)); // This code is contributed by _saurabh_jaiswal</script> Output: Total possible expressions of length 6 is 5 Time Complexity: O(n) Auxiliary Space: O(1)This article is contributed by Sachin. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Smitha Dinesh Semwal nitin mittal Mithun Kumar _saurabh_jaiswal simmytarika5 rishavmahato348 catalan Parentheses-Problems Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operators in C / C++ Prime Numbers Minimum number of jumps to reach end The Knight's tour problem | Backtracking-1 Algorithm to solve Rubik's Cube Modulo 10^9+7 (1000000007) Modulo Operator (%) in C/C++ with Examples Program for factorial of a number Merge two sorted arrays with O(1) extra space Print all possible combinations of r elements in a given array of size n
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Nov, 2021" }, { "code": null, "e": 149, "s": 54, "text": "Given a number n find the number of valid parentheses expressions of that length. Examples : " }, { "code": null, "e": 402, "s": 149, "text": "Input: 2\nOutput: 1 \nThere is only possible valid expression of length 2, \"()\"\n\nInput: 4\nOutput: 2 \nPossible valid expression of length 4 are \"(())\" and \"()()\" \n\nInput: 6\nOutput: 5\nPossible valid expressions are ((())), ()(()), ()()(), (())() and (()())" }, { "code": null, "e": 556, "s": 402, "text": "This is mainly an application of Catalan Numbers. Total possible valid expressions for input n is n/2’th Catalan Number if n is even and 0 if n is odd. " }, { "code": null, "e": 594, "s": 556, "text": "Below given is the implementation : " }, { "code": null, "e": 598, "s": 594, "text": "C++" }, { "code": null, "e": 603, "s": 598, "text": "Java" }, { "code": null, "e": 611, "s": 603, "text": "Python3" }, { "code": null, "e": 614, "s": 611, "text": "C#" }, { "code": null, "e": 618, "s": 614, "text": "PHP" }, { "code": null, "e": 629, "s": 618, "text": "Javascript" }, { "code": "// C++ program to find valid paranthesisations of length n// The majority of code is taken from method 3 of// https://www.geeksforgeeks.org/program-nth-catalan-number/#include <bits/stdc++.h>using namespace std; // Returns value of Binomial Coefficient C(n, k)unsigned long int binomialCoeff(unsigned int n, unsigned int k){ unsigned long int res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of [n*(n-1)*---*(n-k+1)] / [k*(k-1)*---*1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res;} // A Binomial coefficient based function to// find nth catalan number in O(n) timeunsigned long int catalan(unsigned int n){ // Calculate value of 2nCn unsigned long int c = binomialCoeff(2 * n, n); // return 2nCn/(n+1) return c / (n + 1);} // Function to find possible ways to put balanced// parenthesis in an expression of length nunsigned long int findWays(unsigned n){ // If n is odd, not possible to // create any valid parentheses if (n & 1) return 0; // Otherwise return n/2'th Catalan Number return catalan(n / 2);} // Driver program to test above functionsint main(){ int n = 6; cout << \"Total possible expressions of length \" << n << \" is \" << findWays(6); return 0;}", "e": 1982, "s": 629, "text": null }, { "code": "// Java program to find valid paranthesisations of length n// The majority of code is taken from method 3 of// https://www.geeksforgeeks.org/program-nth-catalan-number/ class GFG { // Returns value of Binomial Coefficient C(n, k) static long binomialCoeff(int n, int k) { long res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of [n*(n-1)*---*(n-k+1)] / [k*(k-1)*---*1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; } // A Binomial coefficient based function to // find nth catalan number in O(n) time static long catalan(int n) { // Calculate value of 2nCn long c = binomialCoeff(2 * n, n); // return 2nCn/(n+1) return c / (n + 1); } // Function to find possible ways to put balanced // parenthesis in an expression of length n static long findWays(int n) { // If n is odd, not possible to // create any valid parentheses if ((n & 1) != 0) return 0; // Otherwise return n/2'th Catalan Number return catalan(n / 2); } // Driver program to test above functions public static void main(String[] args) { int n = 6; System.out.println(\"Total possible expressions of length \" + n + \" is \" + findWays(6)); }} // This code is contributed by Smitha Dinesh Semwal", "e": 3478, "s": 1982, "text": null }, { "code": "# Python3 program to find valid# paranthesisations of length n# The majority of code is taken# from method 3 of# https:#www.geeksforgeeks.org/program-nth-catalan-number/ # Returns value of Binomial# Coefficient C(n, k)def binomialCoeff(n, k): res = 1; # Since C(n, k) = C(n, n-k) if (k > n - k): k = n - k; # Calculate value of [n*(n-1)*--- # *(n-k+1)] / [k*(k-1)*---*1] for i in range(k): res *= (n - i); res /= (i + 1); return int(res); # A Binomial coefficient based# function to find nth catalan # number in O(n) timedef catalan(n): # Calculate value of 2nCn c = binomialCoeff(2 * n, n); # return 2nCn/(n+1) return int(c / (n + 1)); # Function to find possible# ways to put balanced parenthesis# in an expression of length ndef findWays(n): # If n is odd, not possible to # create any valid parentheses if(n & 1): return 0; # Otherwise return n/2'th # Catalan Number return catalan(int(n / 2)); # Driver Coden = 6;print(\"Total possible expressions of length\", n, \"is\", findWays(6)); # This code is contributed by mits", "e": 4620, "s": 3478, "text": null }, { "code": "// C# program to find valid paranthesisations// of length n The majority of code is taken// from method 3 of// https://www.geeksforgeeks.org/program-nth-catalan-number/using System; class GFG { // Returns value of Binomial // Coefficient C(n, k) static long binomialCoeff(int n, int k) { long res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of [n*(n-1)*---* // (n-k+1)] / [k*(k-1)*---*1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; } // A Binomial coefficient based function to // find nth catalan number in O(n) time static long catalan(int n) { // Calculate value of 2nCn long c = binomialCoeff(2 * n, n); // return 2nCn/(n+1) return c / (n + 1); } // Function to find possible ways to put // balanced parenthesis in an expression // of length n static long findWays(int n) { // If n is odd, not possible to // create any valid parentheses if ((n & 1) != 0) return 0; // Otherwise return n/2'th // Catalan Number return catalan(n / 2); } // Driver program to test // above functions public static void Main() { int n = 6; Console.Write(\"Total possible expressions\" + \"of length \" + n + \" is \" + findWays(6)); }} // This code is contributed by nitin mittal.", "e": 6178, "s": 4620, "text": null }, { "code": "<?php// PHP program to find valid// paranthesisations of length n// The majority of code is taken// from method 3 of// https://www.geeksforgeeks.org/program-nth-catalan-number/ // Returns value of Binomial// Coefficient C(n, k)function binomialCoeff($n, $k){ $res = 1; // Since C(n, k) = C(n, n-k) if ($k > $n - $k) $k = $n - $k; // Calculate value of [n*(n-1)*--- // *(n-k+1)] / [k*(k-1)*---*1] for ($i = 0; $i < $k; ++$i) { $res *= ($n - $i); $res /= ($i + 1); } return $res;} // A Binomial coefficient// based function to find// nth catalan number in// O(n) timefunction catalan($n){ // Calculate value of 2nCn $c = binomialCoeff(2 * $n, $n); // return 2nCn/(n+1) return $c / ($n + 1);} // Function to find possible// ways to put balanced// parenthesis in an expression// of length nfunction findWays($n){ // If n is odd, not possible to // create any valid parentheses if ($n & 1) return 0; // Otherwise return n/2'th // Catalan Number return catalan($n / 2);} // Driver Code $n = 6; echo \"Total possible expressions of length \" , $n , \" is \" , findWays(6); // This code is contributed by nitin mittal?>", "e": 7419, "s": 6178, "text": null }, { "code": "<script>// Javascript program to find valid// paranthesisations of length n// The majority of code is taken// from method 3 of// https://www.geeksforgeeks.org/program-nth-catalan-number/ // Returns value of Binomial// Coefficient C(n, k)function binomialCoeff(n, k){ let res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of [n*(n-1)*--- // *(n-k+1)] / [k*(k-1)*---*1] for (let i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res;} // A Binomial coefficient// based function to find// nth catalan number in// O(n) timefunction catalan(n){ // Calculate value of 2nCn let c = binomialCoeff(2 * n, n); // return 2nCn/(n+1) return c / (n + 1);} // Function to find possible// ways to put balanced// parenthesis in an expression// of length nfunction findWays(n){ // If n is odd, not possible to // create any valid parentheses if (n & 1) return 0; // Otherwise return n/2'th // Catalan Number return catalan(n / 2);} // Driver Code let n = 6; document.write(\"Total possible expressions of length \" + n + \" is \" + findWays(6)); // This code is contributed by _saurabh_jaiswal</script>", "e": 8677, "s": 7419, "text": null }, { "code": null, "e": 8686, "s": 8677, "text": "Output: " }, { "code": null, "e": 8730, "s": 8686, "text": "Total possible expressions of length 6 is 5" }, { "code": null, "e": 8752, "s": 8730, "text": "Time Complexity: O(n)" }, { "code": null, "e": 8937, "s": 8752, "text": "Auxiliary Space: O(1)This article is contributed by Sachin. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 8958, "s": 8937, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 8971, "s": 8958, "text": "nitin mittal" }, { "code": null, "e": 8984, "s": 8971, "text": "Mithun Kumar" }, { "code": null, "e": 9001, "s": 8984, "text": "_saurabh_jaiswal" }, { "code": null, "e": 9014, "s": 9001, "text": "simmytarika5" }, { "code": null, "e": 9030, "s": 9014, "text": "rishavmahato348" }, { "code": null, "e": 9038, "s": 9030, "text": "catalan" }, { "code": null, "e": 9059, "s": 9038, "text": "Parentheses-Problems" }, { "code": null, "e": 9072, "s": 9059, "text": "Mathematical" }, { "code": null, "e": 9085, "s": 9072, "text": "Mathematical" }, { "code": null, "e": 9183, "s": 9085, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9204, "s": 9183, "text": "Operators in C / C++" }, { "code": null, "e": 9218, "s": 9204, "text": "Prime Numbers" }, { "code": null, "e": 9255, "s": 9218, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 9298, "s": 9255, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 9330, "s": 9298, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 9357, "s": 9330, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 9400, "s": 9357, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 9434, "s": 9400, "text": "Program for factorial of a number" }, { "code": null, "e": 9480, "s": 9434, "text": "Merge two sorted arrays with O(1) extra space" } ]
PHP | imagepng() Function
29 Oct, 2021 The imagepng() function is an inbuilt function in PHP which is used to display image to browser or file. The main use of this function is to view an image in the browser, convert any other image type to PNG and applying filters to the image. Syntax: bool imagepng( resource $image, int $to, int $quality, int $filters) Parameters: This function accepts three parameters as mentioned above and described below: $image: It specifies the image resource to work on. $to (Optional): It specifies the path to save the file to. $quality (Optional): It specifies the quality of the image. $filters (Optional): It specifies the filters to apply to the image which help in reducing the image size. Return Value: This function returns TRUE on success or FALSE on error. Below examples illustrate the imagepng() function in PHP: Example 1: In this example we will be viewing an image in browser. php <?php // Load an image from PNG URL$im = imagecreatefrompng('https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-13.png'); // View the loaded image in browser using imagepng() functionheader('Content-type: image/png'); imagepng($im);imagedestroy($im);?> Output: Example 2: IN this example we will convert JPEG into PNG. php <?php // Load an image from JPEG URL$im = imagecreatefromjpeg('https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-13.png'); // Convert the image into PNG using imagepng() functionimagepng($im, 'converted.png');imagedestroy($im);?> Output: This will save the PNG version of image in the same folder where your PHP script is. Program 3: In this example we will use filters. php <?php // Create an image instance$im = imagecreatefrompng('https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-13.png'); // Save the image as image1.pngimagepng($im, 'image1.png'); // Save the image as image2.png with all filters to disable size compressionimagepng($im, 'image2.png', null, PNG_ALL_FILTERS); imagedestroy($im);?> Output: This will save the image1.png as compressed and image2.png as uncompressed image Reference: https://www.php.net/manual/en/function.imagepng.php akshaysingh98088 PHP-function PHP-Imagick PHP 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 Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Oct, 2021" }, { "code": null, "e": 270, "s": 28, "text": "The imagepng() function is an inbuilt function in PHP which is used to display image to browser or file. The main use of this function is to view an image in the browser, convert any other image type to PNG and applying filters to the image." }, { "code": null, "e": 278, "s": 270, "text": "Syntax:" }, { "code": null, "e": 347, "s": 278, "text": "bool imagepng( resource $image, int $to, int $quality, int $filters)" }, { "code": null, "e": 438, "s": 347, "text": "Parameters: This function accepts three parameters as mentioned above and described below:" }, { "code": null, "e": 490, "s": 438, "text": "$image: It specifies the image resource to work on." }, { "code": null, "e": 549, "s": 490, "text": "$to (Optional): It specifies the path to save the file to." }, { "code": null, "e": 609, "s": 549, "text": "$quality (Optional): It specifies the quality of the image." }, { "code": null, "e": 716, "s": 609, "text": "$filters (Optional): It specifies the filters to apply to the image which help in reducing the image size." }, { "code": null, "e": 787, "s": 716, "text": "Return Value: This function returns TRUE on success or FALSE on error." }, { "code": null, "e": 845, "s": 787, "text": "Below examples illustrate the imagepng() function in PHP:" }, { "code": null, "e": 912, "s": 845, "text": "Example 1: In this example we will be viewing an image in browser." }, { "code": null, "e": 916, "s": 912, "text": "php" }, { "code": "<?php // Load an image from PNG URL$im = imagecreatefrompng('https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-13.png'); // View the loaded image in browser using imagepng() functionheader('Content-type: image/png'); imagepng($im);imagedestroy($im);?>", "e": 1186, "s": 916, "text": null }, { "code": null, "e": 1194, "s": 1186, "text": "Output:" }, { "code": null, "e": 1252, "s": 1194, "text": "Example 2: IN this example we will convert JPEG into PNG." }, { "code": null, "e": 1256, "s": 1252, "text": "php" }, { "code": "<?php // Load an image from JPEG URL$im = imagecreatefromjpeg('https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-13.png'); // Convert the image into PNG using imagepng() functionimagepng($im, 'converted.png');imagedestroy($im);?>", "e": 1503, "s": 1256, "text": null }, { "code": null, "e": 1511, "s": 1503, "text": "Output:" }, { "code": null, "e": 1596, "s": 1511, "text": "This will save the PNG version of image in the same folder where your PHP script is." }, { "code": null, "e": 1644, "s": 1596, "text": "Program 3: In this example we will use filters." }, { "code": null, "e": 1648, "s": 1644, "text": "php" }, { "code": "<?php // Create an image instance$im = imagecreatefrompng('https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-13.png'); // Save the image as image1.pngimagepng($im, 'image1.png'); // Save the image as image2.png with all filters to disable size compressionimagepng($im, 'image2.png', null, PNG_ALL_FILTERS); imagedestroy($im);?>", "e": 1995, "s": 1648, "text": null }, { "code": null, "e": 2003, "s": 1995, "text": "Output:" }, { "code": null, "e": 2084, "s": 2003, "text": "This will save the image1.png as compressed and image2.png as uncompressed image" }, { "code": null, "e": 2147, "s": 2084, "text": "Reference: https://www.php.net/manual/en/function.imagepng.php" }, { "code": null, "e": 2164, "s": 2147, "text": "akshaysingh98088" }, { "code": null, "e": 2177, "s": 2164, "text": "PHP-function" }, { "code": null, "e": 2189, "s": 2177, "text": "PHP-Imagick" }, { "code": null, "e": 2193, "s": 2189, "text": "PHP" }, { "code": null, "e": 2210, "s": 2193, "text": "Web Technologies" }, { "code": null, "e": 2214, "s": 2210, "text": "PHP" }, { "code": null, "e": 2312, "s": 2214, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2362, "s": 2312, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 2402, "s": 2362, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 2463, "s": 2402, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 2513, "s": 2463, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 2558, "s": 2513, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 2591, "s": 2558, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2653, "s": 2591, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2714, "s": 2653, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2764, "s": 2714, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Spring Framework Annotations
15 Dec, 2021 Spring framework is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. Now talking about Spring Annotation, Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. So in this article, we are going to discuss what are the main types of annotation that are available in the spring framework with some examples. Types of Spring Framework Annotations Basically, there are 6 types of annotation available in the whole spring framework. Spring Core AnnotationsSpring Web AnnotationsSpring Boot AnnotationsSpring Scheduling AnnotationsSpring Data AnnotationsSpring Bean Annotations Spring Core Annotations Spring Web Annotations Spring Boot Annotations Spring Scheduling Annotations Spring Data Annotations Spring Bean Annotations Type 1: Spring Core Annotations Spring annotations present in the org.springframework.beans.factory.annotation and org.springframework.context.annotation packages are commonly known as Spring Core annotations. We can divide them into two categories: DI-Related Annotations@Autowired@Qualifier@Primary@Bean@Lazy@Required@Value@Scope@Lookup, etc. @Autowired @Qualifier @Primary @Bean @Lazy @Required @Value @Scope @Lookup, etc. Context Configuration Annotations@Profile@Import@ImportResource@PropertySource, etc. @Profile @Import @ImportResource @PropertySource, etc. A DI (Dependency Injection) Related Annotations 1.1: @Autowired @Autowired annotation is applied to the fields, setter methods, and constructors. It injects object dependency implicitly. We use @Autowired to mark the dependency that will be injected by the Spring container. 1.2: Field injection Java class Student { @Autowired Address address;} 1.3: Constructor injection Java class Student { Address address; @Autowired Student(Address address) { this.address = address; }} 1.4: Setter injection Java class Student { Address address; @Autowired void setaddress(Address address) { this.address = address; }} B Context Configuration Annotations @Profile: If you want Spring to use a @Component class or a @Bean method only when a specific profile is active then you can mark it with @Profile. @Component @Profile("developer") public class Employee {} Type 2: Spring Web Annotations Spring annotations present in the org.springframework.web.bind.annotation packages are commonly known as Spring Web annotations. Some of the annotations that are available in this category are: @RequestMapping @RequestBody @PathVariable @RequestParam Response Handling Annotations@ResponseBody@ExceptionHandler@ResponseStatus @ResponseBody @ExceptionHandler @ResponseStatus @Controller @RestController @ModelAttribute @CrossOrigin Example: @Controller Spring @Controller annotation is also a specialization of @Component annotation. The @Controller annotation indicates that a particular class serves the role of a controller. Spring Controller annotation is typically used in combination with annotated handler methods based on the @RequestMapping annotation. It can be applied to classes only. It’s used to mark a class as a web request handler. It’s mostly used with Spring MVC applications. This annotation acts as a stereotype for the annotated class, indicating its role. The dispatcher scans such annotated classes for mapped methods and detects @RequestMapping annotations. Java package com.example.demo.controller; import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody; @Controllerpublic class DemoController { @RequestMapping("/hello") @ResponseBody public String helloGFG() { return "Hello GeeksForGeeks"; }} Type 3: Spring Boot Annotations Spring annotations present in the org.springframework.boot.autoconfigure and org.springframework.boot.autoconfigure.condition packages are commonly known as Spring Boot annotations. Some of the annotations that are available in this category are: @SpringBootApplication @EnableAutoConfiguration Auto-Configuration Conditions@ConditionalOnClass, and @ConditionalOnMissingClass@ConditionalOnBean, and @ConditionalOnMissingBean@ConditionalOnProperty@ConditionalOnResource@ConditionalOnWebApplication and @ConditionalOnNotWebApplication@ConditionalExpression@Conditional @ConditionalOnClass, and @ConditionalOnMissingClass @ConditionalOnBean, and @ConditionalOnMissingBean @ConditionalOnProperty @ConditionalOnResource @ConditionalOnWebApplication and @ConditionalOnNotWebApplication @ConditionalExpression @Conditional Example: @SpringBootApplication This annotation is used to mark the main class of a Spring Boot application. It encapsulates @Configuration, @EnableAutoConfiguration, and @ComponentScan annotations with their default attributes. Java @SpringBootApplication // Classpublic class DemoApplication { // Main driver method public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }} Type 4: Spring Scheduling Annotations Spring annotations present in the org.springframework.scheduling.annotation packages are commonly known as Spring Scheduling annotations. Some of the annotations that are available in this category are: @EnableAsync @EnableScheduling @Async @Scheduled @Schedules Example: @EnableAsync This annotation is used to enable asynchronous functionality in Spring. @Configuration @EnableAsync class Config {} Type 5: Spring Data Annotations Spring Data provides an abstraction over data storage technologies. Hence the business logic code can be much more independent of the underlying persistence implementation. Some of the annotations that are available in this category are: Common Spring Data Annotations@Transactional@NoRepositoryBean@Param@Id@Transient@CreatedBy, @LastModifiedBy, @CreatedDate, @LastModifiedDate @Transactional @NoRepositoryBean @Param @Id @Transient @CreatedBy, @LastModifiedBy, @CreatedDate, @LastModifiedDate Spring Data JPA Annotations@Query@Procedure@Lock@Modifying@EnableJpaRepositories @Query @Procedure @Lock @Modifying @EnableJpaRepositories Spring Data Mongo Annotations@Document@Field@Query@EnableMongoRepositories @Document @Field @Query @EnableMongoRepositories Example: A @Transactional When there is a need to configure the transactional behavior of a method, we can do it with @Transactional annotation. @Transactional void payment() {} B @Id: @Id marks a field in a model class as the primary key. Since it’s implementation-independent, it makes a model class easy to use with multiple data store engines. class Student { @Id Long id; // other fields // ........... } Type 6: Spring Bean Annotations There’re several ways to configure beans in a Spring container. You can declare them using XML configuration or you can declare beans using the @Bean annotation in a configuration class or you can mark the class with one of the annotations from the org.springframework.stereotype package and leave the rest to component scanning. Some of the annotations that are available in this category are: @ComponentScan @Configuration Stereotype Annotations@Component@Service@Repository@Controller @Component @Service @Repository @Controller Example: Stereotype Annotations Spring Framework provides us with some special annotations. These annotations are used to create Spring beans automatically in the application context. @Component annotation is the main Stereotype Annotation. There are some Stereotype meta-annotations which is derived from @Component those are @Service@Repository@Controller @Service @Repository @Controller 1: @Service: We specify a class with @Service to indicate that they’re holding the business logic. Besides being used in the service layer, there isn’t any other special use for this annotation. The utility classes can be marked as Service classes. 2: @Repository: We specify a class with @Repository to indicate that they’re dealing with CRUD operations, usually, it’s used with DAO (Data Access Object) or Repository implementations that deal with database tables. 3: @Controller: We specify a class with @Controller to indicate that they’re front controllers and responsible to handle user requests and return the appropriate response. It is mostly used with REST Web Services. So the stereotype annotations in spring are @Component, @Service, @Repository, and @Controller. Java-Spring Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n15 Dec, 2021" }, { "code": null, "e": 823, "s": 53, "text": "Spring framework is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. Now talking about Spring Annotation, Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. So in this article, we are going to discuss what are the main types of annotation that are available in the spring framework with some examples. " }, { "code": null, "e": 861, "s": 823, "text": "Types of Spring Framework Annotations" }, { "code": null, "e": 945, "s": 861, "text": "Basically, there are 6 types of annotation available in the whole spring framework." }, { "code": null, "e": 1089, "s": 945, "text": "Spring Core AnnotationsSpring Web AnnotationsSpring Boot AnnotationsSpring Scheduling AnnotationsSpring Data AnnotationsSpring Bean Annotations" }, { "code": null, "e": 1113, "s": 1089, "text": "Spring Core Annotations" }, { "code": null, "e": 1136, "s": 1113, "text": "Spring Web Annotations" }, { "code": null, "e": 1160, "s": 1136, "text": "Spring Boot Annotations" }, { "code": null, "e": 1190, "s": 1160, "text": "Spring Scheduling Annotations" }, { "code": null, "e": 1214, "s": 1190, "text": "Spring Data Annotations" }, { "code": null, "e": 1238, "s": 1214, "text": "Spring Bean Annotations" }, { "code": null, "e": 1271, "s": 1238, "text": "Type 1: Spring Core Annotations " }, { "code": null, "e": 1489, "s": 1271, "text": "Spring annotations present in the org.springframework.beans.factory.annotation and org.springframework.context.annotation packages are commonly known as Spring Core annotations. We can divide them into two categories:" }, { "code": null, "e": 1584, "s": 1489, "text": "DI-Related Annotations@Autowired@Qualifier@Primary@Bean@Lazy@Required@Value@Scope@Lookup, etc." }, { "code": null, "e": 1595, "s": 1584, "text": "@Autowired" }, { "code": null, "e": 1606, "s": 1595, "text": "@Qualifier" }, { "code": null, "e": 1615, "s": 1606, "text": "@Primary" }, { "code": null, "e": 1621, "s": 1615, "text": "@Bean" }, { "code": null, "e": 1627, "s": 1621, "text": "@Lazy" }, { "code": null, "e": 1637, "s": 1627, "text": "@Required" }, { "code": null, "e": 1644, "s": 1637, "text": "@Value" }, { "code": null, "e": 1651, "s": 1644, "text": "@Scope" }, { "code": null, "e": 1665, "s": 1651, "text": "@Lookup, etc." }, { "code": null, "e": 1750, "s": 1665, "text": "Context Configuration Annotations@Profile@Import@ImportResource@PropertySource, etc." }, { "code": null, "e": 1759, "s": 1750, "text": "@Profile" }, { "code": null, "e": 1767, "s": 1759, "text": "@Import" }, { "code": null, "e": 1783, "s": 1767, "text": "@ImportResource" }, { "code": null, "e": 1805, "s": 1783, "text": "@PropertySource, etc." }, { "code": null, "e": 1853, "s": 1805, "text": "A DI (Dependency Injection) Related Annotations" }, { "code": null, "e": 1869, "s": 1853, "text": "1.1: @Autowired" }, { "code": null, "e": 2080, "s": 1869, "text": "@Autowired annotation is applied to the fields, setter methods, and constructors. It injects object dependency implicitly. We use @Autowired to mark the dependency that will be injected by the Spring container." }, { "code": null, "e": 2101, "s": 2080, "text": "1.2: Field injection" }, { "code": null, "e": 2106, "s": 2101, "text": "Java" }, { "code": "class Student { @Autowired Address address;}", "e": 2157, "s": 2106, "text": null }, { "code": null, "e": 2184, "s": 2157, "text": "1.3: Constructor injection" }, { "code": null, "e": 2189, "s": 2184, "text": "Java" }, { "code": "class Student { Address address; @Autowired Student(Address address) { this.address = address; }}", "e": 2308, "s": 2189, "text": null }, { "code": null, "e": 2330, "s": 2308, "text": "1.4: Setter injection" }, { "code": null, "e": 2335, "s": 2330, "text": "Java" }, { "code": "class Student { Address address; @Autowired void setaddress(Address address) { this.address = address; }}", "e": 2462, "s": 2335, "text": null }, { "code": null, "e": 2499, "s": 2462, "text": "B Context Configuration Annotations " }, { "code": null, "e": 2648, "s": 2499, "text": "@Profile: If you want Spring to use a @Component class or a @Bean method only when a specific profile is active then you can mark it with @Profile. " }, { "code": null, "e": 2706, "s": 2648, "text": "@Component\n@Profile(\"developer\")\npublic class Employee {}" }, { "code": null, "e": 2737, "s": 2706, "text": "Type 2: Spring Web Annotations" }, { "code": null, "e": 2931, "s": 2737, "text": "Spring annotations present in the org.springframework.web.bind.annotation packages are commonly known as Spring Web annotations. Some of the annotations that are available in this category are:" }, { "code": null, "e": 2947, "s": 2931, "text": "@RequestMapping" }, { "code": null, "e": 2960, "s": 2947, "text": "@RequestBody" }, { "code": null, "e": 2974, "s": 2960, "text": "@PathVariable" }, { "code": null, "e": 2988, "s": 2974, "text": "@RequestParam" }, { "code": null, "e": 3063, "s": 2988, "text": "Response Handling Annotations@ResponseBody@ExceptionHandler@ResponseStatus" }, { "code": null, "e": 3077, "s": 3063, "text": "@ResponseBody" }, { "code": null, "e": 3095, "s": 3077, "text": "@ExceptionHandler" }, { "code": null, "e": 3111, "s": 3095, "text": "@ResponseStatus" }, { "code": null, "e": 3123, "s": 3111, "text": "@Controller" }, { "code": null, "e": 3139, "s": 3123, "text": "@RestController" }, { "code": null, "e": 3155, "s": 3139, "text": "@ModelAttribute" }, { "code": null, "e": 3168, "s": 3155, "text": "@CrossOrigin" }, { "code": null, "e": 3189, "s": 3168, "text": "Example: @Controller" }, { "code": null, "e": 3819, "s": 3189, "text": "Spring @Controller annotation is also a specialization of @Component annotation. The @Controller annotation indicates that a particular class serves the role of a controller. Spring Controller annotation is typically used in combination with annotated handler methods based on the @RequestMapping annotation. It can be applied to classes only. It’s used to mark a class as a web request handler. It’s mostly used with Spring MVC applications. This annotation acts as a stereotype for the annotated class, indicating its role. The dispatcher scans such annotated classes for mapped methods and detects @RequestMapping annotations." }, { "code": null, "e": 3824, "s": 3819, "text": "Java" }, { "code": "package com.example.demo.controller; import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody; @Controllerpublic class DemoController { @RequestMapping(\"/hello\") @ResponseBody public String helloGFG() { return \"Hello GeeksForGeeks\"; }}", "e": 4200, "s": 3824, "text": null }, { "code": null, "e": 4232, "s": 4200, "text": "Type 3: Spring Boot Annotations" }, { "code": null, "e": 4479, "s": 4232, "text": "Spring annotations present in the org.springframework.boot.autoconfigure and org.springframework.boot.autoconfigure.condition packages are commonly known as Spring Boot annotations. Some of the annotations that are available in this category are:" }, { "code": null, "e": 4502, "s": 4479, "text": "@SpringBootApplication" }, { "code": null, "e": 4527, "s": 4502, "text": "@EnableAutoConfiguration" }, { "code": null, "e": 4799, "s": 4527, "text": "Auto-Configuration Conditions@ConditionalOnClass, and @ConditionalOnMissingClass@ConditionalOnBean, and @ConditionalOnMissingBean@ConditionalOnProperty@ConditionalOnResource@ConditionalOnWebApplication and @ConditionalOnNotWebApplication@ConditionalExpression@Conditional" }, { "code": null, "e": 4851, "s": 4799, "text": "@ConditionalOnClass, and @ConditionalOnMissingClass" }, { "code": null, "e": 4901, "s": 4851, "text": "@ConditionalOnBean, and @ConditionalOnMissingBean" }, { "code": null, "e": 4924, "s": 4901, "text": "@ConditionalOnProperty" }, { "code": null, "e": 4947, "s": 4924, "text": "@ConditionalOnResource" }, { "code": null, "e": 5012, "s": 4947, "text": "@ConditionalOnWebApplication and @ConditionalOnNotWebApplication" }, { "code": null, "e": 5035, "s": 5012, "text": "@ConditionalExpression" }, { "code": null, "e": 5048, "s": 5035, "text": "@Conditional" }, { "code": null, "e": 5080, "s": 5048, "text": "Example: @SpringBootApplication" }, { "code": null, "e": 5277, "s": 5080, "text": "This annotation is used to mark the main class of a Spring Boot application. It encapsulates @Configuration, @EnableAutoConfiguration, and @ComponentScan annotations with their default attributes." }, { "code": null, "e": 5282, "s": 5277, "text": "Java" }, { "code": "@SpringBootApplication // Classpublic class DemoApplication { // Main driver method public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }}", "e": 5486, "s": 5282, "text": null }, { "code": null, "e": 5524, "s": 5486, "text": "Type 4: Spring Scheduling Annotations" }, { "code": null, "e": 5727, "s": 5524, "text": "Spring annotations present in the org.springframework.scheduling.annotation packages are commonly known as Spring Scheduling annotations. Some of the annotations that are available in this category are:" }, { "code": null, "e": 5740, "s": 5727, "text": "@EnableAsync" }, { "code": null, "e": 5758, "s": 5740, "text": "@EnableScheduling" }, { "code": null, "e": 5765, "s": 5758, "text": "@Async" }, { "code": null, "e": 5776, "s": 5765, "text": "@Scheduled" }, { "code": null, "e": 5787, "s": 5776, "text": "@Schedules" }, { "code": null, "e": 5809, "s": 5787, "text": "Example: @EnableAsync" }, { "code": null, "e": 5881, "s": 5809, "text": "This annotation is used to enable asynchronous functionality in Spring." }, { "code": null, "e": 5925, "s": 5881, "text": "@Configuration\n@EnableAsync\nclass Config {}" }, { "code": null, "e": 5957, "s": 5925, "text": "Type 5: Spring Data Annotations" }, { "code": null, "e": 6195, "s": 5957, "text": "Spring Data provides an abstraction over data storage technologies. Hence the business logic code can be much more independent of the underlying persistence implementation. Some of the annotations that are available in this category are:" }, { "code": null, "e": 6336, "s": 6195, "text": "Common Spring Data Annotations@Transactional@NoRepositoryBean@Param@Id@Transient@CreatedBy, @LastModifiedBy, @CreatedDate, @LastModifiedDate" }, { "code": null, "e": 6351, "s": 6336, "text": "@Transactional" }, { "code": null, "e": 6369, "s": 6351, "text": "@NoRepositoryBean" }, { "code": null, "e": 6376, "s": 6369, "text": "@Param" }, { "code": null, "e": 6380, "s": 6376, "text": "@Id" }, { "code": null, "e": 6391, "s": 6380, "text": "@Transient" }, { "code": null, "e": 6452, "s": 6391, "text": "@CreatedBy, @LastModifiedBy, @CreatedDate, @LastModifiedDate" }, { "code": null, "e": 6533, "s": 6452, "text": "Spring Data JPA Annotations@Query@Procedure@Lock@Modifying@EnableJpaRepositories" }, { "code": null, "e": 6540, "s": 6533, "text": "@Query" }, { "code": null, "e": 6551, "s": 6540, "text": "@Procedure" }, { "code": null, "e": 6557, "s": 6551, "text": "@Lock" }, { "code": null, "e": 6568, "s": 6557, "text": "@Modifying" }, { "code": null, "e": 6591, "s": 6568, "text": "@EnableJpaRepositories" }, { "code": null, "e": 6666, "s": 6591, "text": "Spring Data Mongo Annotations@Document@Field@Query@EnableMongoRepositories" }, { "code": null, "e": 6676, "s": 6666, "text": "@Document" }, { "code": null, "e": 6683, "s": 6676, "text": "@Field" }, { "code": null, "e": 6690, "s": 6683, "text": "@Query" }, { "code": null, "e": 6715, "s": 6690, "text": "@EnableMongoRepositories" }, { "code": null, "e": 6724, "s": 6715, "text": "Example:" }, { "code": null, "e": 6742, "s": 6724, "text": "A @Transactional " }, { "code": null, "e": 6862, "s": 6742, "text": "When there is a need to configure the transactional behavior of a method, we can do it with @Transactional annotation. " }, { "code": null, "e": 6895, "s": 6862, "text": "@Transactional\nvoid payment() {}" }, { "code": null, "e": 7065, "s": 6895, "text": "B @Id: @Id marks a field in a model class as the primary key. Since it’s implementation-independent, it makes a model class easy to use with multiple data store engines." }, { "code": null, "e": 7153, "s": 7065, "text": "class Student {\n\n @Id\n Long id;\n\n // other fields\n // ........... \n \n}" }, { "code": null, "e": 7185, "s": 7153, "text": "Type 6: Spring Bean Annotations" }, { "code": null, "e": 7580, "s": 7185, "text": "There’re several ways to configure beans in a Spring container. You can declare them using XML configuration or you can declare beans using the @Bean annotation in a configuration class or you can mark the class with one of the annotations from the org.springframework.stereotype package and leave the rest to component scanning. Some of the annotations that are available in this category are:" }, { "code": null, "e": 7595, "s": 7580, "text": "@ComponentScan" }, { "code": null, "e": 7610, "s": 7595, "text": "@Configuration" }, { "code": null, "e": 7673, "s": 7610, "text": "Stereotype Annotations@Component@Service@Repository@Controller" }, { "code": null, "e": 7684, "s": 7673, "text": "@Component" }, { "code": null, "e": 7693, "s": 7684, "text": "@Service" }, { "code": null, "e": 7705, "s": 7693, "text": "@Repository" }, { "code": null, "e": 7717, "s": 7705, "text": "@Controller" }, { "code": null, "e": 7749, "s": 7717, "text": "Example: Stereotype Annotations" }, { "code": null, "e": 8044, "s": 7749, "text": "Spring Framework provides us with some special annotations. These annotations are used to create Spring beans automatically in the application context. @Component annotation is the main Stereotype Annotation. There are some Stereotype meta-annotations which is derived from @Component those are" }, { "code": null, "e": 8075, "s": 8044, "text": "@Service@Repository@Controller" }, { "code": null, "e": 8084, "s": 8075, "text": "@Service" }, { "code": null, "e": 8096, "s": 8084, "text": "@Repository" }, { "code": null, "e": 8108, "s": 8096, "text": "@Controller" }, { "code": null, "e": 8357, "s": 8108, "text": "1: @Service: We specify a class with @Service to indicate that they’re holding the business logic. Besides being used in the service layer, there isn’t any other special use for this annotation. The utility classes can be marked as Service classes." }, { "code": null, "e": 8575, "s": 8357, "text": "2: @Repository: We specify a class with @Repository to indicate that they’re dealing with CRUD operations, usually, it’s used with DAO (Data Access Object) or Repository implementations that deal with database tables." }, { "code": null, "e": 8789, "s": 8575, "text": "3: @Controller: We specify a class with @Controller to indicate that they’re front controllers and responsible to handle user requests and return the appropriate response. It is mostly used with REST Web Services." }, { "code": null, "e": 8885, "s": 8789, "text": "So the stereotype annotations in spring are @Component, @Service, @Repository, and @Controller." }, { "code": null, "e": 8897, "s": 8885, "text": "Java-Spring" }, { "code": null, "e": 8902, "s": 8897, "text": "Java" }, { "code": null, "e": 8907, "s": 8902, "text": "Java" } ]
Node.js NPM uuid
08 Apr, 2022 NPM(Node Package Manager) is a package manager of Node.js packages. There is an NPM package called ‘shortid’ used to create short non-sequential url-friendly unique ids. Unique ids are created by Cryptographically-strong random values that’s why it is very secure. It has support for cross-platform like Node, React Native, Chrome, Safari, Firefox, etc. Command to install: npm install uuid Syntax to import the package in local file const {v4 : uuidv4} = require('uuid') Syntax to create unique id const newId = uuidv4() There are some methods defined on shortid modules to create unique ids and customize the ids. some of the methods are illustrates below: Example 1: This example illustrates how to generate and use uuid package to create unique ids. filename-index.js: This file contains all the logic to create unique ids and attach it with user information and save to the database. javascript const express = require('express')const bodyParser = require('body-parser')const {v4 : uuidv4} = require('uuid')const formTemplet = require('./form')const repo = require('./repository') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post('/', (req, res) => { // Fetching user inputs const {name, email} = req.body // Creating new unique id const userId = uuidv4() // Saving record to the database // with attaching userid to each record repo.create({ userId, name, email }) res.send('Information submitted!')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)}) filename – repository.js: This file contain all the logic to create database and interact with it. javascript // Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // Filename where data are going to store if(!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is created // with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll() { return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs){ // Fetch all existing records const records = await this.getAll() // All the existing records with new // record push back to database records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created at runtime// and all the information provided via signup form// store in this file in JSON format.module.exports = new Repository('datastore.json') filename – form.js: This file contain all the logic to render form. javascript module.exports = ({errors}) => { return `<!DOCTYPE html><html> <head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns { margin-top: 100px; } .button { margin-top: 10px } </style></head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/' method='POST'> <div> <div> <label class='label' id='str'>Name </label> </div> <input class='input' type='text' name='name' placeholder='Name' for='name'> </div> <div> <div> <label class='label' id='email'> Email </label> </div> <input class='input' type='email' name='email' placeholder='Email' for='email'> </div> <div> <button class='button is-info'> Submit </button> </div> </form> </div> </div> </div></body> </html> `} Output: Submitting information1 submitting information2 Database: Database after Submitting the informations Example 2: This example illustrates how to use uuid.parse() and uuid.stringify() methods. filename-index.js: This file contains all the logic to create unique ids and attach it with user information and save to the database and also convert id to parsed bytes and parsed bytes to string id. javascript const express = require('express')const bodyParser = require('body-parser')const { v4 : uuidv4, parse:uuidParse, stringify : uuidStringify} = require('uuid') const formTemplet = require('./form')const repo = require('./repository') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post('/', (req, res) => { // Fetching user inputs const {name, email} = req.body // Creating new unique id const userId = uuidv4() const parsedId = uuidParse(userId) const stringfyId = uuidStringify(parsedId) console.log(`parsedId : ${parsedId}\n`) console.log(`StringifyId : ${stringfyId}\n`) // Saving record to the database // with attaching userid to each record repo.create({ userId, name, email }) res.send('Information submitted!')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)}) filename – repository.js: This file contain all the logic to create database and interact with it. javascript // Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // Filename where datas are going to store if(!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is created // with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll() { return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs){ // Fetch all existing records const records = await this.getAll() // All the existing records with new // record push back to database records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created at runtime// and all the information provided via signup form// store in this file in JSON format.module.exports = new Repository('datastore.json') filename – form.js : This file contain all the logic to render form. javascript const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' }}module.exports = ({errors}) => { return `<!DOCTYPE html><html> <head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns { margin-top: 100px; } .button { margin-top: 10px } </style></head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/' method='POST'> <div> <div> <label class='label' id='str'> Name </label> </div> <input class='input' type='text' name='name' placeholder='Name' for='name'> </div> <div> <div> <label class='label' id='email'> Email </label> </div> <input class='input' type='email' name='email' placeholder='Email' for='email'> </div> <div> <button class='button is-info'> Submit </button> </div> </form> </div> </div> </div></body> </html> `} Output: Submitting information Parsed id and stringify id Database: Database after submitting the informations Note: We have used some Bulma classes in form.js file to design our content. rkbhola5 Node.js-Misc Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Apr, 2022" }, { "code": null, "e": 382, "s": 28, "text": "NPM(Node Package Manager) is a package manager of Node.js packages. There is an NPM package called ‘shortid’ used to create short non-sequential url-friendly unique ids. Unique ids are created by Cryptographically-strong random values that’s why it is very secure. It has support for cross-platform like Node, React Native, Chrome, Safari, Firefox, etc." }, { "code": null, "e": 404, "s": 382, "text": "Command to install: " }, { "code": null, "e": 421, "s": 404, "text": "npm install uuid" }, { "code": null, "e": 464, "s": 421, "text": "Syntax to import the package in local file" }, { "code": null, "e": 502, "s": 464, "text": "const {v4 : uuidv4} = require('uuid')" }, { "code": null, "e": 529, "s": 502, "text": "Syntax to create unique id" }, { "code": null, "e": 552, "s": 529, "text": "const newId = uuidv4()" }, { "code": null, "e": 689, "s": 552, "text": "There are some methods defined on shortid modules to create unique ids and customize the ids. some of the methods are illustrates below:" }, { "code": null, "e": 785, "s": 689, "text": "Example 1: This example illustrates how to generate and use uuid package to create unique ids." }, { "code": null, "e": 920, "s": 785, "text": "filename-index.js: This file contains all the logic to create unique ids and attach it with user information and save to the database." }, { "code": null, "e": 931, "s": 920, "text": "javascript" }, { "code": "const express = require('express')const bodyParser = require('body-parser')const {v4 : uuidv4} = require('uuid')const formTemplet = require('./form')const repo = require('./repository') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post('/', (req, res) => { // Fetching user inputs const {name, email} = req.body // Creating new unique id const userId = uuidv4() // Saving record to the database // with attaching userid to each record repo.create({ userId, name, email }) res.send('Information submitted!')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})", "e": 1804, "s": 931, "text": null }, { "code": null, "e": 1903, "s": 1804, "text": "filename – repository.js: This file contain all the logic to create database and interact with it." }, { "code": null, "e": 1914, "s": 1903, "text": "javascript" }, { "code": "// Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // Filename where data are going to store if(!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is created // with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll() { return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs){ // Fetch all existing records const records = await this.getAll() // All the existing records with new // record push back to database records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created at runtime// and all the information provided via signup form// store in this file in JSON format.module.exports = new Repository('datastore.json')", "e": 3048, "s": 1914, "text": null }, { "code": null, "e": 3116, "s": 3048, "text": "filename – form.js: This file contain all the logic to render form." }, { "code": null, "e": 3127, "s": 3116, "text": "javascript" }, { "code": "module.exports = ({errors}) => { return `<!DOCTYPE html><html> <head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns { margin-top: 100px; } .button { margin-top: 10px } </style></head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/' method='POST'> <div> <div> <label class='label' id='str'>Name </label> </div> <input class='input' type='text' name='name' placeholder='Name' for='name'> </div> <div> <div> <label class='label' id='email'> Email </label> </div> <input class='input' type='email' name='email' placeholder='Email' for='email'> </div> <div> <button class='button is-info'> Submit </button> </div> </form> </div> </div> </div></body> </html> `}", "e": 4267, "s": 3127, "text": null }, { "code": null, "e": 4275, "s": 4267, "text": "Output:" }, { "code": null, "e": 4299, "s": 4275, "text": "Submitting information1" }, { "code": null, "e": 4323, "s": 4299, "text": "submitting information2" }, { "code": null, "e": 4333, "s": 4323, "text": "Database:" }, { "code": null, "e": 4376, "s": 4333, "text": "Database after Submitting the informations" }, { "code": null, "e": 4466, "s": 4376, "text": "Example 2: This example illustrates how to use uuid.parse() and uuid.stringify() methods." }, { "code": null, "e": 4667, "s": 4466, "text": "filename-index.js: This file contains all the logic to create unique ids and attach it with user information and save to the database and also convert id to parsed bytes and parsed bytes to string id." }, { "code": null, "e": 4678, "s": 4667, "text": "javascript" }, { "code": "const express = require('express')const bodyParser = require('body-parser')const { v4 : uuidv4, parse:uuidParse, stringify : uuidStringify} = require('uuid') const formTemplet = require('./form')const repo = require('./repository') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post('/', (req, res) => { // Fetching user inputs const {name, email} = req.body // Creating new unique id const userId = uuidv4() const parsedId = uuidParse(userId) const stringfyId = uuidStringify(parsedId) console.log(`parsedId : ${parsedId}\\n`) console.log(`StringifyId : ${stringfyId}\\n`) // Saving record to the database // with attaching userid to each record repo.create({ userId, name, email }) res.send('Information submitted!')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})", "e": 5768, "s": 4678, "text": null }, { "code": null, "e": 5867, "s": 5768, "text": "filename – repository.js: This file contain all the logic to create database and interact with it." }, { "code": null, "e": 5878, "s": 5867, "text": "javascript" }, { "code": "// Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // Filename where datas are going to store if(!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is created // with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll() { return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs){ // Fetch all existing records const records = await this.getAll() // All the existing records with new // record push back to database records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created at runtime// and all the information provided via signup form// store in this file in JSON format.module.exports = new Repository('datastore.json')", "e": 7016, "s": 5878, "text": null }, { "code": null, "e": 7085, "s": 7016, "text": "filename – form.js : This file contain all the logic to render form." }, { "code": null, "e": 7096, "s": 7085, "text": "javascript" }, { "code": "const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' }}module.exports = ({errors}) => { return `<!DOCTYPE html><html> <head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns { margin-top: 100px; } .button { margin-top: 10px } </style></head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/' method='POST'> <div> <div> <label class='label' id='str'> Name </label> </div> <input class='input' type='text' name='name' placeholder='Name' for='name'> </div> <div> <div> <label class='label' id='email'> Email </label> </div> <input class='input' type='email' name='email' placeholder='Email' for='email'> </div> <div> <button class='button is-info'> Submit </button> </div> </form> </div> </div> </div></body> </html> `}", "e": 8351, "s": 7096, "text": null }, { "code": null, "e": 8359, "s": 8351, "text": "Output:" }, { "code": null, "e": 8382, "s": 8359, "text": "Submitting information" }, { "code": null, "e": 8409, "s": 8382, "text": "Parsed id and stringify id" }, { "code": null, "e": 8419, "s": 8409, "text": "Database:" }, { "code": null, "e": 8462, "s": 8419, "text": "Database after submitting the informations" }, { "code": null, "e": 8539, "s": 8462, "text": "Note: We have used some Bulma classes in form.js file to design our content." }, { "code": null, "e": 8548, "s": 8539, "text": "rkbhola5" }, { "code": null, "e": 8561, "s": 8548, "text": "Node.js-Misc" }, { "code": null, "e": 8569, "s": 8561, "text": "Node.js" }, { "code": null, "e": 8586, "s": 8569, "text": "Web Technologies" } ]
HTML <u> Tag
17 Mar, 2022 The <u> tag in HTML stands for underline, and it’s used to underline the text enclosed within the <u> tag. This tag is generally used to underline misspelled words. This tag requires a starting as well as ending tag. Syntax: <u> Contents... </u> Note: This tag is depreciated from HTML 4.1 and redefined in HTML 5 using CSS text-decoration property instead.Below examples illustrates the <u> tag in HTML:Example 1: HTML <html> <body> <h1>GeeksforGeeks</h1> <h2><u> Tag</h2> <p>GeeksforGeeks: A <u>computer science</u> portal for geeks</p> </body> </html> Output: Example 2: Alternate way of <u> tag to underline the text. HTML <html> <head> <title>u Tag</title> <style> body { text-align:center; } .gfg { font-size:40px; font-weight:bold; color:green; } .geeks { font-size:25px; font-weight:bold; } p { font-size:20px; } span { text-decoration:underline; } </style> </head> <body> <div class = "gfg">GeeksforGeeks</div> <div class = "geeks"><u> Tag</div> <p>GeeksforGeeks: A <span>computer science</span> portal for geeks</p> </body> </html> Output: Supported Browsers: Google Chrome Internet Explorer Firefox Opera Safari arorakashish0911 shubhamyadav4 hritikbhatnagar2182 HTML-Tags HTML 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 ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? CSS to put icon inside an input element in a form Types of CSS (Cascading Style Sheet) HTTP headers | Content-Type
[ { "code": null, "e": 53, "s": 25, "text": "\n17 Mar, 2022" }, { "code": null, "e": 270, "s": 53, "text": "The <u> tag in HTML stands for underline, and it’s used to underline the text enclosed within the <u> tag. This tag is generally used to underline misspelled words. This tag requires a starting as well as ending tag." }, { "code": null, "e": 280, "s": 270, "text": "Syntax: " }, { "code": null, "e": 301, "s": 280, "text": "<u> Contents... </u>" }, { "code": null, "e": 471, "s": 301, "text": "Note: This tag is depreciated from HTML 4.1 and redefined in HTML 5 using CSS text-decoration property instead.Below examples illustrates the <u> tag in HTML:Example 1: " }, { "code": null, "e": 476, "s": 471, "text": "HTML" }, { "code": "<html> <body> <h1>GeeksforGeeks</h1> <h2><u> Tag</h2> <p>GeeksforGeeks: A <u>computer science</u> portal for geeks</p> </body> </html> ", "e": 706, "s": 476, "text": null }, { "code": null, "e": 716, "s": 706, "text": "Output: " }, { "code": null, "e": 776, "s": 716, "text": "Example 2: Alternate way of <u> tag to underline the text. " }, { "code": null, "e": 781, "s": 776, "text": "HTML" }, { "code": "<html> <head> <title>u Tag</title> <style> body { text-align:center; } .gfg { font-size:40px; font-weight:bold; color:green; } .geeks { font-size:25px; font-weight:bold; } p { font-size:20px; } span { text-decoration:underline; } </style> </head> <body> <div class = \"gfg\">GeeksforGeeks</div> <div class = \"geeks\"><u> Tag</div> <p>GeeksforGeeks: A <span>computer science</span> portal for geeks</p> </body> </html> ", "e": 1565, "s": 781, "text": null }, { "code": null, "e": 1575, "s": 1565, "text": "Output: " }, { "code": null, "e": 1596, "s": 1575, "text": "Supported Browsers: " }, { "code": null, "e": 1610, "s": 1596, "text": "Google Chrome" }, { "code": null, "e": 1628, "s": 1610, "text": "Internet Explorer" }, { "code": null, "e": 1636, "s": 1628, "text": "Firefox" }, { "code": null, "e": 1642, "s": 1636, "text": "Opera" }, { "code": null, "e": 1649, "s": 1642, "text": "Safari" }, { "code": null, "e": 1668, "s": 1651, "text": "arorakashish0911" }, { "code": null, "e": 1682, "s": 1668, "text": "shubhamyadav4" }, { "code": null, "e": 1702, "s": 1682, "text": "hritikbhatnagar2182" }, { "code": null, "e": 1712, "s": 1702, "text": "HTML-Tags" }, { "code": null, "e": 1717, "s": 1712, "text": "HTML" }, { "code": null, "e": 1722, "s": 1717, "text": "HTML" }, { "code": null, "e": 1820, "s": 1722, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1868, "s": 1820, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 1930, "s": 1868, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1980, "s": 1930, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2004, "s": 1980, "text": "REST API (Introduction)" }, { "code": null, "e": 2057, "s": 2004, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2117, "s": 2057, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 2178, "s": 2117, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 2228, "s": 2178, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 2265, "s": 2228, "text": "Types of CSS (Cascading Style Sheet)" } ]
PostgreSQL – CREATE TABLESPACE
08 Feb, 2021 In PostgreSQL a tablespace is used to map a logical name to a physical location on disk. In the simplest word, we can understand tablespace as a location on the disk where all database objects of PostgreSQL are stored. These objects can be an index or a table etc. PostgreSQL has two default tablespaces: pg_defaulttablespace is used to store user data. pg_globaltablespace is used to store the global data. Tablespaces in general are used to manage and control the disk layout of PostgreSQL. There are two main advantages of using tablespaces: It comes in handy when an initialized cluster in a partition runs out of space. The tablespace can here further be used to create a new tablespace in a different partition altogether until your configuration is adjusted for the lack of space on the previous partition. The database performance can be optimized using tablespaces. Syntax: CREATE TABLESPACE tablespace_name OWNER user_name LOCATION directory_path; It is also important to note that the name of the tablespace must not start with pg_, as these are reserved for the system tablespaces. Example: The following statement uses the CREATE TABLESPACE to create a new tablespace called gfg with the physical location c:\data\gfg. CREATE TABLESPACE gfg LOCATION 'C:\data\gfg'; To list all tablespaces in the current PostgreSQL database server, the following command can be used: \db Output: The below command shows more information such as size and access privileges: \db+ The result will be similar to the image depicted below: postgreSQL-managing-table PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Feb, 2021" }, { "code": null, "e": 293, "s": 28, "text": "In PostgreSQL a tablespace is used to map a logical name to a physical location on disk. In the simplest word, we can understand tablespace as a location on the disk where all database objects of PostgreSQL are stored. These objects can be an index or a table etc." }, { "code": null, "e": 333, "s": 293, "text": "PostgreSQL has two default tablespaces:" }, { "code": null, "e": 382, "s": 333, "text": "pg_defaulttablespace is used to store user data." }, { "code": null, "e": 436, "s": 382, "text": "pg_globaltablespace is used to store the global data." }, { "code": null, "e": 573, "s": 436, "text": "Tablespaces in general are used to manage and control the disk layout of PostgreSQL. There are two main advantages of using tablespaces:" }, { "code": null, "e": 842, "s": 573, "text": "It comes in handy when an initialized cluster in a partition runs out of space. The tablespace can here further be used to create a new tablespace in a different partition altogether until your configuration is adjusted for the lack of space on the previous partition." }, { "code": null, "e": 903, "s": 842, "text": "The database performance can be optimized using tablespaces." }, { "code": null, "e": 987, "s": 903, "text": "Syntax:\nCREATE TABLESPACE tablespace_name\nOWNER user_name\nLOCATION directory_path;\n" }, { "code": null, "e": 1123, "s": 987, "text": "It is also important to note that the name of the tablespace must not start with pg_, as these are reserved for the system tablespaces." }, { "code": null, "e": 1132, "s": 1123, "text": "Example:" }, { "code": null, "e": 1261, "s": 1132, "text": "The following statement uses the CREATE TABLESPACE to create a new tablespace called gfg with the physical location c:\\data\\gfg." }, { "code": null, "e": 1308, "s": 1261, "text": "CREATE TABLESPACE gfg\nLOCATION 'C:\\data\\gfg';\n" }, { "code": null, "e": 1410, "s": 1308, "text": "To list all tablespaces in the current PostgreSQL database server, the following command can be used:" }, { "code": null, "e": 1415, "s": 1410, "text": "\\db\n" }, { "code": null, "e": 1423, "s": 1415, "text": "Output:" }, { "code": null, "e": 1500, "s": 1423, "text": "The below command shows more information such as size and access privileges:" }, { "code": null, "e": 1506, "s": 1500, "text": "\\db+\n" }, { "code": null, "e": 1562, "s": 1506, "text": "The result will be similar to the image depicted below:" }, { "code": null, "e": 1588, "s": 1562, "text": "postgreSQL-managing-table" }, { "code": null, "e": 1599, "s": 1588, "text": "PostgreSQL" } ]
‘this’ reference in Java
27 Jul, 2021 ‘this’ is a reference variable that refers to the current object. Following are the ways to use ‘this’ keyword in java :1. Using ‘this’ keyword to refer current class instance variables Java //Java code for using 'this' keyword to//refer current class instance variablesclass Test{ int a; int b; // Parameterized constructor Test(int a, int b) { this.a = a; this.b = b; } void display() { //Displaying value of variables a and b System.out.println("a = " + a + " b = " + b); } public static void main(String[] args) { Test object = new Test(10, 20); object.display(); }} Output: a = 10 b = 20 2. Using this() to invoke current class constructor Java // Java code for using this() to// invoke current class constructorclass Test{ int a; int b; //Default constructor Test() { this(10, 20); System.out.println("Inside default constructor \n"); } //Parameterized constructor Test(int a, int b) { this.a = a; this.b = b; System.out.println("Inside parameterized constructor"); } public static void main(String[] args) { Test object = new Test(); }} Output: Inside parameterized constructor Inside default constructor 3. Using ‘this’ keyword to return the current class instance Java //Java code for using 'this' keyword//to return the current class instanceclass Test{ int a; int b; //Default constructor Test() { a = 10; b = 20; } //Method that returns current class instance Test get() { return this; } //Displaying value of variables a and b void display() { System.out.println("a = " + a + " b = " + b); } public static void main(String[] args) { Test object = new Test(); object.get().display(); }} Output: a = 10 b = 20 4. Using ‘this’ keyword as method parameter Java // Java code for using 'this'// keyword as method parameterclass Test{ int a; int b; // Default constructor Test() { a = 10; b = 20; } // Method that receives 'this' keyword as parameter void display(Test obj) { System.out.println("a = " +obj.a + " b = " + obj.b); } // Method that returns current class instance void get() { display(this); } public static void main(String[] args) { Test object = new Test(); object.get(); }} Output: a = 10 b = 20 5. Using ‘this’ keyword to invoke current class method Java // Java code for using this to invoke current// class methodclass Test { void display() { // calling function show() this.show(); System.out.println("Inside display function"); } void show() { System.out.println("Inside show function"); } public static void main(String args[]) { Test t1 = new Test(); t1.display(); }} Output: Inside show function Inside display function 6. Using ‘this’ keyword as an argument in the constructor call Java // Java code for using this as an argument in constructor// call// Class with object of Class B as its data memberclass A{ B obj; // Parameterized constructor with object of B // as a parameter A(B obj) { this.obj = obj; // calling display method of class B obj.display(); } } class B{ int x = 5; // Default Constructor that create a object of A // with passing this as an argument in the // constructor B() { A obj = new A(this); } // method to show value of x void display() { System.out.println("Value of x in Class B : " + x); } public static void main(String[] args) { B obj = new B(); }} Output: Value of x in Class B : 5 This article is contributed by Mehak Narang and Amit Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Akanksha_Rai imeenalgrover arorakashish0911 varshagumber28 simmytarika5 java-basics Java School Programming Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java How to iterate any Map in Java Stream In Java Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Inheritance in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Jul, 2021" }, { "code": null, "e": 118, "s": 52, "text": "‘this’ is a reference variable that refers to the current object." }, { "code": null, "e": 238, "s": 118, "text": "Following are the ways to use ‘this’ keyword in java :1. Using ‘this’ keyword to refer current class instance variables" }, { "code": null, "e": 243, "s": 238, "text": "Java" }, { "code": "//Java code for using 'this' keyword to//refer current class instance variablesclass Test{ int a; int b; // Parameterized constructor Test(int a, int b) { this.a = a; this.b = b; } void display() { //Displaying value of variables a and b System.out.println(\"a = \" + a + \" b = \" + b); } public static void main(String[] args) { Test object = new Test(10, 20); object.display(); }}", "e": 709, "s": 243, "text": null }, { "code": null, "e": 717, "s": 709, "text": "Output:" }, { "code": null, "e": 732, "s": 717, "text": "a = 10 b = 20" }, { "code": null, "e": 784, "s": 732, "text": "2. Using this() to invoke current class constructor" }, { "code": null, "e": 789, "s": 784, "text": "Java" }, { "code": "// Java code for using this() to// invoke current class constructorclass Test{ int a; int b; //Default constructor Test() { this(10, 20); System.out.println(\"Inside default constructor \\n\"); } //Parameterized constructor Test(int a, int b) { this.a = a; this.b = b; System.out.println(\"Inside parameterized constructor\"); } public static void main(String[] args) { Test object = new Test(); }}", "e": 1273, "s": 789, "text": null }, { "code": null, "e": 1281, "s": 1273, "text": "Output:" }, { "code": null, "e": 1342, "s": 1281, "text": "Inside parameterized constructor\nInside default constructor" }, { "code": null, "e": 1404, "s": 1342, "text": "3. Using ‘this’ keyword to return the current class instance " }, { "code": null, "e": 1409, "s": 1404, "text": "Java" }, { "code": "//Java code for using 'this' keyword//to return the current class instanceclass Test{ int a; int b; //Default constructor Test() { a = 10; b = 20; } //Method that returns current class instance Test get() { return this; } //Displaying value of variables a and b void display() { System.out.println(\"a = \" + a + \" b = \" + b); } public static void main(String[] args) { Test object = new Test(); object.get().display(); }}", "e": 1936, "s": 1409, "text": null }, { "code": null, "e": 1944, "s": 1936, "text": "Output:" }, { "code": null, "e": 1959, "s": 1944, "text": "a = 10 b = 20" }, { "code": null, "e": 2003, "s": 1959, "text": "4. Using ‘this’ keyword as method parameter" }, { "code": null, "e": 2008, "s": 2003, "text": "Java" }, { "code": "// Java code for using 'this'// keyword as method parameterclass Test{ int a; int b; // Default constructor Test() { a = 10; b = 20; } // Method that receives 'this' keyword as parameter void display(Test obj) { System.out.println(\"a = \" +obj.a + \" b = \" + obj.b); } // Method that returns current class instance void get() { display(this); } public static void main(String[] args) { Test object = new Test(); object.get(); }}", "e": 2542, "s": 2008, "text": null }, { "code": null, "e": 2550, "s": 2542, "text": "Output:" }, { "code": null, "e": 2565, "s": 2550, "text": "a = 10 b = 20" }, { "code": null, "e": 2621, "s": 2565, "text": "5. Using ‘this’ keyword to invoke current class method " }, { "code": null, "e": 2626, "s": 2621, "text": "Java" }, { "code": "// Java code for using this to invoke current// class methodclass Test { void display() { // calling function show() this.show(); System.out.println(\"Inside display function\"); } void show() { System.out.println(\"Inside show function\"); } public static void main(String args[]) { Test t1 = new Test(); t1.display(); }}", "e": 3023, "s": 2626, "text": null }, { "code": null, "e": 3033, "s": 3023, "text": "Output: " }, { "code": null, "e": 3078, "s": 3033, "text": "Inside show function\nInside display function" }, { "code": null, "e": 3141, "s": 3078, "text": "6. Using ‘this’ keyword as an argument in the constructor call" }, { "code": null, "e": 3146, "s": 3141, "text": "Java" }, { "code": "// Java code for using this as an argument in constructor// call// Class with object of Class B as its data memberclass A{ B obj; // Parameterized constructor with object of B // as a parameter A(B obj) { this.obj = obj; // calling display method of class B obj.display(); } } class B{ int x = 5; // Default Constructor that create a object of A // with passing this as an argument in the // constructor B() { A obj = new A(this); } // method to show value of x void display() { System.out.println(\"Value of x in Class B : \" + x); } public static void main(String[] args) { B obj = new B(); }}", "e": 3867, "s": 3146, "text": null }, { "code": null, "e": 3876, "s": 3867, "text": "Output: " }, { "code": null, "e": 3902, "s": 3876, "text": "Value of x in Class B : 5" }, { "code": null, "e": 4089, "s": 3902, "text": "This article is contributed by Mehak Narang and Amit Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 4102, "s": 4089, "text": "Akanksha_Rai" }, { "code": null, "e": 4116, "s": 4102, "text": "imeenalgrover" }, { "code": null, "e": 4133, "s": 4116, "text": "arorakashish0911" }, { "code": null, "e": 4148, "s": 4133, "text": "varshagumber28" }, { "code": null, "e": 4161, "s": 4148, "text": "simmytarika5" }, { "code": null, "e": 4173, "s": 4161, "text": "java-basics" }, { "code": null, "e": 4178, "s": 4173, "text": "Java" }, { "code": null, "e": 4197, "s": 4178, "text": "School Programming" }, { "code": null, "e": 4202, "s": 4197, "text": "Java" }, { "code": null, "e": 4300, "s": 4202, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4344, "s": 4300, "text": "Split() String method in Java with examples" }, { "code": null, "e": 4380, "s": 4344, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 4405, "s": 4380, "text": "Reverse a string in Java" }, { "code": null, "e": 4436, "s": 4405, "text": "How to iterate any Map in Java" }, { "code": null, "e": 4451, "s": 4436, "text": "Stream In Java" }, { "code": null, "e": 4469, "s": 4451, "text": "Python Dictionary" }, { "code": null, "e": 4494, "s": 4469, "text": "Reverse a string in Java" }, { "code": null, "e": 4510, "s": 4494, "text": "Arrays in C/C++" }, { "code": null, "e": 4533, "s": 4510, "text": "Introduction To PYTHON" } ]
How to create array using given columns, rows, and tables in R ?
24 Sep, 2021 In this article, we will discuss how to create an array using given columns, rows, and tables in R Programming Language. The array is created using the array() function. Syntax: Array(vector.., dim=c(row, columns, tables)) Parameter: x: vector dim: values used to create array Example 1: Creating a simple array with 2 rows, 3 columns, 1 table The below example will create an array of 3×3 matrices with 1 table. R vector1 <- c(0,1,2)vector2 <- c(3,4,5) data <- array(c(vector1,vector2),dim = c(2,3,1))print(data) Output: [,1] [,2] [,3] [1,] 0 2 4 [2,] 1 3 5 The above array is created with 2 rows and 3 columns. Example 2: Creating an array using 3 rows, 3 columns, and 2 tables. Here we will create an array with 3 rows, 3 columns, and 2 tables. R vector1 <- c(1:15)vector2 <- c(16:30) data <- array(c(vector1,vector2),dim = c(3,3,2))print(data) Output: sweetyty Picked R-Arrays R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Sep, 2021" }, { "code": null, "e": 198, "s": 28, "text": "In this article, we will discuss how to create an array using given columns, rows, and tables in R Programming Language. The array is created using the array() function." }, { "code": null, "e": 251, "s": 198, "text": "Syntax: Array(vector.., dim=c(row, columns, tables))" }, { "code": null, "e": 262, "s": 251, "text": "Parameter:" }, { "code": null, "e": 272, "s": 262, "text": "x: vector" }, { "code": null, "e": 305, "s": 272, "text": "dim: values used to create array" }, { "code": null, "e": 372, "s": 305, "text": "Example 1: Creating a simple array with 2 rows, 3 columns, 1 table" }, { "code": null, "e": 441, "s": 372, "text": "The below example will create an array of 3×3 matrices with 1 table." }, { "code": null, "e": 443, "s": 441, "text": "R" }, { "code": "vector1 <- c(0,1,2)vector2 <- c(3,4,5) data <- array(c(vector1,vector2),dim = c(2,3,1))print(data)", "e": 542, "s": 443, "text": null }, { "code": null, "e": 551, "s": 542, "text": "Output: " }, { "code": null, "e": 609, "s": 551, "text": " [,1] [,2] [,3]\n[1,] 0 2 4\n[2,] 1 3 5" }, { "code": null, "e": 663, "s": 609, "text": "The above array is created with 2 rows and 3 columns." }, { "code": null, "e": 731, "s": 663, "text": "Example 2: Creating an array using 3 rows, 3 columns, and 2 tables." }, { "code": null, "e": 799, "s": 731, "text": "Here we will create an array with 3 rows, 3 columns, and 2 tables. " }, { "code": null, "e": 801, "s": 799, "text": "R" }, { "code": "vector1 <- c(1:15)vector2 <- c(16:30) data <- array(c(vector1,vector2),dim = c(3,3,2))print(data)", "e": 899, "s": 801, "text": null }, { "code": null, "e": 908, "s": 899, "text": "Output: " }, { "code": null, "e": 919, "s": 910, "text": "sweetyty" }, { "code": null, "e": 926, "s": 919, "text": "Picked" }, { "code": null, "e": 935, "s": 926, "text": "R-Arrays" }, { "code": null, "e": 946, "s": 935, "text": "R Language" }, { "code": null, "e": 957, "s": 946, "text": "R Programs" } ]
Nested Interface in Java
30 Aug, 2018 We can declare interfaces as member of a class or another interface. Such an interface is called as member interface or nested interface. Interface in a classInterfaces (or classes) can have only public and default access specifiers when declared outside any other class (Refer this for details). This interface declared in a class can either be default, public, protected not private. While implementing the interface, we mention the interface as c_name.i_name where c_name is the name of the class in which it is nested and i_name is the name of the interface itself.Let us have a look at the following code:- // Java program to demonstrate working of// interface inside a class.import java.util.*;class Test{ interface Yes { void show(); }} class Testing implements Test.Yes{ public void show() { System.out.println("show method of interface"); }} class A{ public static void main(String[] args) { Test.Yes obj; Testing t = new Testing(); obj=t; obj.show(); }} show method of interface The access specifier in above example is default. We can assign public, protected or private also. Below is an example of protected. In this particular example, if we change access specifier to private, we get compiler error because a derived class tries to access it. // Java program to demonstrate protected // specifier for nested interface.import java.util.*;class Test{ protected interface Yes { void show(); }} class Testing implements Test.Yes{ public void show() { System.out.println("show method of interface"); }} class A{ public static void main(String[] args) { Test.Yes obj; Testing t = new Testing(); obj=t; obj.show(); }} show method of interface Interface in another InterfaceAn interface can be declared inside another interface also. We mention the interface as i_name1.i_name2 where i_name1 is the name of the interface in which it is nested and i_name2 is the name of the interface to be implemented. // Java program to demonstrate working of // interface inside another interface.import java.util.*;interface Test{ interface Yes { void show(); }} class Testing implements Test.Yes{ public void show() { System.out.println("show method of interface"); } } class A{ public static void main(String[] args) { Test.Yes obj; Testing t = new Testing(); obj = t; obj.show(); } } show method of interface Note: In the above example, access specifier is public even if we have not written public. If we try to change access specifier of interface to anything other than public, we get compiler error. Remember, interface members can only be public.. // Java program to demonstrate an interface cannot// have non-public member interface.import java.util.*;interface Test{ protected interface Yes { void show(); }} class Testing implements Test.Yes{ public void show() { System.out.println("show method of interface"); }} class A{ public static void main(String[] args) { Test.Yes obj; Testing t = new Testing(); obj = t; obj.show(); }} illegal combination of modifiers: public and protected protected interface Yes This article is contributed by Twinkle Tyagi. 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 VikramShanbogar java-interfaces Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n30 Aug, 2018" }, { "code": null, "e": 192, "s": 54, "text": "We can declare interfaces as member of a class or another interface. Such an interface is called as member interface or nested interface." }, { "code": null, "e": 666, "s": 192, "text": "Interface in a classInterfaces (or classes) can have only public and default access specifiers when declared outside any other class (Refer this for details). This interface declared in a class can either be default, public, protected not private. While implementing the interface, we mention the interface as c_name.i_name where c_name is the name of the class in which it is nested and i_name is the name of the interface itself.Let us have a look at the following code:-" }, { "code": "// Java program to demonstrate working of// interface inside a class.import java.util.*;class Test{ interface Yes { void show(); }} class Testing implements Test.Yes{ public void show() { System.out.println(\"show method of interface\"); }} class A{ public static void main(String[] args) { Test.Yes obj; Testing t = new Testing(); obj=t; obj.show(); }}", "e": 1089, "s": 666, "text": null }, { "code": null, "e": 1115, "s": 1089, "text": "show method of interface " }, { "code": null, "e": 1384, "s": 1115, "text": "The access specifier in above example is default. We can assign public, protected or private also. Below is an example of protected. In this particular example, if we change access specifier to private, we get compiler error because a derived class tries to access it." }, { "code": "// Java program to demonstrate protected // specifier for nested interface.import java.util.*;class Test{ protected interface Yes { void show(); }} class Testing implements Test.Yes{ public void show() { System.out.println(\"show method of interface\"); }} class A{ public static void main(String[] args) { Test.Yes obj; Testing t = new Testing(); obj=t; obj.show(); }}", "e": 1823, "s": 1384, "text": null }, { "code": null, "e": 1849, "s": 1823, "text": "show method of interface " }, { "code": null, "e": 2110, "s": 1851, "text": "Interface in another InterfaceAn interface can be declared inside another interface also. We mention the interface as i_name1.i_name2 where i_name1 is the name of the interface in which it is nested and i_name2 is the name of the interface to be implemented." }, { "code": "// Java program to demonstrate working of // interface inside another interface.import java.util.*;interface Test{ interface Yes { void show(); }} class Testing implements Test.Yes{ public void show() { System.out.println(\"show method of interface\"); } } class A{ public static void main(String[] args) { Test.Yes obj; Testing t = new Testing(); obj = t; obj.show(); } }", "e": 2532, "s": 2110, "text": null }, { "code": null, "e": 2558, "s": 2532, "text": "show method of interface " }, { "code": null, "e": 2802, "s": 2558, "text": "Note: In the above example, access specifier is public even if we have not written public. If we try to change access specifier of interface to anything other than public, we get compiler error. Remember, interface members can only be public.." }, { "code": "// Java program to demonstrate an interface cannot// have non-public member interface.import java.util.*;interface Test{ protected interface Yes { void show(); }} class Testing implements Test.Yes{ public void show() { System.out.println(\"show method of interface\"); }} class A{ public static void main(String[] args) { Test.Yes obj; Testing t = new Testing(); obj = t; obj.show(); }}", "e": 3258, "s": 2802, "text": null }, { "code": null, "e": 3340, "s": 3258, "text": "illegal combination of modifiers: public and protected\n protected interface Yes" }, { "code": null, "e": 3607, "s": 3340, "text": "This article is contributed by Twinkle Tyagi. 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": 3731, "s": 3607, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 3747, "s": 3731, "text": "VikramShanbogar" }, { "code": null, "e": 3763, "s": 3747, "text": "java-interfaces" }, { "code": null, "e": 3768, "s": 3763, "text": "Java" }, { "code": null, "e": 3773, "s": 3768, "text": "Java" } ]
File Objects in Python
03 Apr, 2017 A file object allows us to use, access and manipulate all the user accessible files. One can read and write any such files.When a file operation fails for an I/O-related reason, the exception IOError is raised. This includes situations where the operation is not defined for some reason, like seek() on a tty device or writing a file opened for reading.Files have the following methods: open(): Opens a file in given access mode. open(file_address, access_mode) Examples of accessing a file: A file can be opened with a built-in function called open(). This function takes in the file’s address and the access_mode and returns a file object.There are different types of access_modes:r: Opens a file for reading only r+: Opens a file for both reading and writing w: Opens a file for writing only w+: Open a file for writing and reading. a: Opens a file for appending a+: Opens a file for both appending and readingWhen you add 'b' to the access modes you can read the file in binary format rather than the default text format. It is used when the file to be accessed is not in text. open(file_address, access_mode) Examples of accessing a file: A file can be opened with a built-in function called open(). This function takes in the file’s address and the access_mode and returns a file object.There are different types of access_modes: r: Opens a file for reading only r+: Opens a file for both reading and writing w: Opens a file for writing only w+: Open a file for writing and reading. a: Opens a file for appending a+: Opens a file for both appending and reading When you add 'b' to the access modes you can read the file in binary format rather than the default text format. It is used when the file to be accessed is not in text. read([size]): It reads the entire file and returns it contents in the form of a string. Reads at most size bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached.# Reading a filef = open(__file__, 'r') #read()text = f.read(10) print(text)f.close() # Reading a filef = open(__file__, 'r') #read()text = f.read(10) print(text)f.close() readline([size]): It reads the first line of the file i.e till a newline character or an EOF in case of a file having a single line and returns a string. If the size argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned. An empty string is returned only when EOF is encountered immediately.# Reading a line in a filef = open(__file__, 'r') #readline()text = f.readline(20)print(text)f.close() # Reading a line in a filef = open(__file__, 'r') #readline()text = f.readline(20)print(text)f.close() readlines([sizehint]): It reads the entire file line by line and updates each line to a list which is returned.Read until EOF using readline() and return a list containing the lines thus read. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read.# Reading a filef = open(__file__, 'r') #readline()text = f.readlines(25)print(text)f.close() # Reading a filef = open(__file__, 'r') #readline()text = f.readlines(25)print(text)f.close() write(string): It writes the contents of string to the file. It has no return value. Due to buffering, the string may not actually show up in the file until the flush() or close() method is called.# Writing a filef = open(__file__, 'w')line = 'Welcome Geeks\n' #write()f.write(line)f.close()More Examples in different modes:# Reading and Writing a filef = open(__file__, 'r+')lines = f.read()f.write(lines)f.close()# Writing and Reading a filef = open(__file__, 'w+')lines = f.read()f.write(lines)f.close()# Appending a filef = open(__file__, 'a')lines = 'Welcome Geeks\n'f.write(lines)f.close()# Appending and reading a filef = open(__file__, 'a+')lines = f.read()f.write(lines)f.close() # Writing a filef = open(__file__, 'w')line = 'Welcome Geeks\n' #write()f.write(line)f.close() More Examples in different modes: # Reading and Writing a filef = open(__file__, 'r+')lines = f.read()f.write(lines)f.close() # Writing and Reading a filef = open(__file__, 'w+')lines = f.read()f.write(lines)f.close() # Appending a filef = open(__file__, 'a')lines = 'Welcome Geeks\n'f.write(lines)f.close() # Appending and reading a filef = open(__file__, 'a+')lines = f.read()f.write(lines)f.close() writelines(sequence): It is a sequence of strings to the file usually a list of strings or any other iterable data type. It has no return value.# Writing a filef = open(__file__, 'a+')lines = f.readlines() #writelines()f.writelines(lines)f.close() # Writing a filef = open(__file__, 'a+')lines = f.readlines() #writelines()f.writelines(lines)f.close() tell(): It returns an integer that tells us the file object’s position from the beginning of the file in the form of bytes# Telling the file object positionf = open(__file__, 'r')lines = f.read(10) #tell()print(f.tell())f.close() # Telling the file object positionf = open(__file__, 'r')lines = f.read(10) #tell()print(f.tell())f.close() seek(offset, from_where): It is used to change the file object’s position. Offset indicates the number of bytes to be moved. from_where indicates from where the bytes are to be moved.# Setting the file object positionf = open(__file__, 'r')lines = f.read(10)print(lines) #seek()print(f.seek(2,2))lines = f.read(10)print(lines)f.close() # Setting the file object positionf = open(__file__, 'r')lines = f.read(10)print(lines) #seek()print(f.seek(2,2))lines = f.read(10)print(lines)f.close() flush(): Flush the internal buffer, like stdio‘s fflush(). It has no return value. close() automatically flushes the data but if you want to flush the data before closing the file then you can use this method.# Clearing the internal buffer before closing the filef = open(__file__, 'r')lines = f.read(10) #flush()f.flush()print(f.read())f.close() # Clearing the internal buffer before closing the filef = open(__file__, 'r')lines = f.read(10) #flush()f.flush()print(f.read())f.close() fileno(): Returns the integer file descriptor that is used by the underlying implementation to request I/O operations from the operating system.# Getting the integer file descriptorf = open(__file__, 'r') #fileno()print(f.fileno())f.close() # Getting the integer file descriptorf = open(__file__, 'r') #fileno()print(f.fileno())f.close() isatty(): Returns True if the file is connected to a tty(-like) device and False if not.# Checks if file is connected to a tty(-like) devicef = open(__file__, 'r') #isatty()print(f.isatty())f.close() # Checks if file is connected to a tty(-like) devicef = open(__file__, 'r') #isatty()print(f.isatty())f.close() next(): It is used when a file is used as an iterator. The method is called repeatedly. This method returns the next input line or raises StopIteration at EOF when the file is open for reading( behaviour is undefined when opened for writing).# Iterates over the filef = open(__file__, 'r') #next()try: while f.next(): print(f.next())except: f.close() # Iterates over the filef = open(__file__, 'r') #next()try: while f.next(): print(f.next())except: f.close() truncate([size]): Truncate the file’s size. If the optional size argument is present, the file is truncated to (at most) that size. The size defaults to the current position. The current file position is not changed. Note that if a specified size exceeds the file’s current size, the result is platform-dependent: possibilities include that the file may remain unchanged, increase to the specified size as if zero-filled, or increase to the specified size with undefined new content.# Truncates the filef = open(__file__, 'w') #truncate()f.truncate(10)f.close() # Truncates the filef = open(__file__, 'w') #truncate()f.truncate(10)f.close() close(): Used to close an open file. A closed file cannot be read or written any more.# Opening and closing a filef = open(__file__, 'r') #close()f.close() # Opening and closing a filef = open(__file__, 'r') #close()f.close() Attributes:closed: returns a boolean indicating the current state of the file object. It returns true if the file is closed and false when the file is open.encoding: The encoding that this file uses. When Unicode strings are written to a file, they will be converted to byte strings using this encoding.mode: The I/O mode for the file. If the file was created using the open() built-in function, this will be the value of the mode parameter.name: If the file object was created using open(), the name of the file.newlines: A file object that has been opened in universal newline mode have this attribute which reflects the newline convention used in the file. The value for this attribute are “\r”, “\n”, “\r\n”, None or a tuple containing all the newline types seen.softspace: It is a boolean that indicates whether a space character needs to be printed before another value when using the print statement.f = open(__file__, 'a+')print(f.closed)print(f.encoding)print(f.mode)print(f.newlines)print(f.softspace) closed: returns a boolean indicating the current state of the file object. It returns true if the file is closed and false when the file is open. encoding: The encoding that this file uses. When Unicode strings are written to a file, they will be converted to byte strings using this encoding. mode: The I/O mode for the file. If the file was created using the open() built-in function, this will be the value of the mode parameter. name: If the file object was created using open(), the name of the file. newlines: A file object that has been opened in universal newline mode have this attribute which reflects the newline convention used in the file. The value for this attribute are “\r”, “\n”, “\r\n”, None or a tuple containing all the newline types seen. softspace: It is a boolean that indicates whether a space character needs to be printed before another value when using the print statement.f = open(__file__, 'a+')print(f.closed)print(f.encoding)print(f.mode)print(f.newlines)print(f.softspace) f = open(__file__, 'a+')print(f.closed)print(f.encoding)print(f.mode)print(f.newlines)print(f.softspace) Related Article :Reading and Writing to text files in Python Reference: https://docs.python.org/2.4/lib/bltin-file-objects.htmlThis article is contributed by Sri Sanketh Uppalapati. 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. Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Apr, 2017" }, { "code": null, "e": 415, "s": 28, "text": "A file object allows us to use, access and manipulate all the user accessible files. One can read and write any such files.When a file operation fails for an I/O-related reason, the exception IOError is raised. This includes situations where the operation is not defined for some reason, like seek() on a tty device or writing a file opened for reading.Files have the following methods:" }, { "code": null, "e": 1110, "s": 415, "text": "open(): Opens a file in given access mode. open(file_address, access_mode) Examples of accessing a file: A file can be opened with a built-in function called open(). This function takes in the file’s address and the access_mode and returns a file object.There are different types of access_modes:r: Opens a file for reading only\nr+: Opens a file for both reading and writing\nw: Opens a file for writing only\nw+: Open a file for writing and reading.\na: Opens a file for appending\na+: Opens a file for both appending and readingWhen you add 'b' to the access modes you can read the file in binary format rather than the default text format. It is used when the file to be accessed is not in text." }, { "code": null, "e": 1144, "s": 1110, "text": " open(file_address, access_mode) " }, { "code": null, "e": 1366, "s": 1144, "text": "Examples of accessing a file: A file can be opened with a built-in function called open(). This function takes in the file’s address and the access_mode and returns a file object.There are different types of access_modes:" }, { "code": null, "e": 1597, "s": 1366, "text": "r: Opens a file for reading only\nr+: Opens a file for both reading and writing\nw: Opens a file for writing only\nw+: Open a file for writing and reading.\na: Opens a file for appending\na+: Opens a file for both appending and reading" }, { "code": null, "e": 1766, "s": 1597, "text": "When you add 'b' to the access modes you can read the file in binary format rather than the default text format. It is used when the file to be accessed is not in text." }, { "code": null, "e": 2118, "s": 1766, "text": "read([size]): It reads the entire file and returns it contents in the form of a string. Reads at most size bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached.# Reading a filef = open(__file__, 'r') #read()text = f.read(10) print(text)f.close()" }, { "code": "# Reading a filef = open(__file__, 'r') #read()text = f.read(10) print(text)f.close()", "e": 2206, "s": 2118, "text": null }, { "code": null, "e": 2683, "s": 2206, "text": "readline([size]): It reads the first line of the file i.e till a newline character or an EOF in case of a file having a single line and returns a string. If the size argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned. An empty string is returned only when EOF is encountered immediately.# Reading a line in a filef = open(__file__, 'r') #readline()text = f.readline(20)print(text)f.close()" }, { "code": "# Reading a line in a filef = open(__file__, 'r') #readline()text = f.readline(20)print(text)f.close()", "e": 2787, "s": 2683, "text": null }, { "code": null, "e": 3267, "s": 2787, "text": "readlines([sizehint]): It reads the entire file line by line and updates each line to a list which is returned.Read until EOF using readline() and return a list containing the lines thus read. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read.# Reading a filef = open(__file__, 'r') #readline()text = f.readlines(25)print(text)f.close()" }, { "code": "# Reading a filef = open(__file__, 'r') #readline()text = f.readlines(25)print(text)f.close()", "e": 3362, "s": 3267, "text": null }, { "code": null, "e": 4052, "s": 3362, "text": "write(string): It writes the contents of string to the file. It has no return value. Due to buffering, the string may not actually show up in the file until the flush() or close() method is called.# Writing a filef = open(__file__, 'w')line = 'Welcome Geeks\\n' #write()f.write(line)f.close()More Examples in different modes:# Reading and Writing a filef = open(__file__, 'r+')lines = f.read()f.write(lines)f.close()# Writing and Reading a filef = open(__file__, 'w+')lines = f.read()f.write(lines)f.close()# Appending a filef = open(__file__, 'a')lines = 'Welcome Geeks\\n'f.write(lines)f.close()# Appending and reading a filef = open(__file__, 'a+')lines = f.read()f.write(lines)f.close()" }, { "code": "# Writing a filef = open(__file__, 'w')line = 'Welcome Geeks\\n' #write()f.write(line)f.close()", "e": 4148, "s": 4052, "text": null }, { "code": null, "e": 4182, "s": 4148, "text": "More Examples in different modes:" }, { "code": "# Reading and Writing a filef = open(__file__, 'r+')lines = f.read()f.write(lines)f.close()", "e": 4274, "s": 4182, "text": null }, { "code": "# Writing and Reading a filef = open(__file__, 'w+')lines = f.read()f.write(lines)f.close()", "e": 4366, "s": 4274, "text": null }, { "code": "# Appending a filef = open(__file__, 'a')lines = 'Welcome Geeks\\n'f.write(lines)f.close()", "e": 4456, "s": 4366, "text": null }, { "code": "# Appending and reading a filef = open(__file__, 'a+')lines = f.read()f.write(lines)f.close()", "e": 4550, "s": 4456, "text": null }, { "code": null, "e": 4799, "s": 4550, "text": "writelines(sequence): It is a sequence of strings to the file usually a list of strings or any other iterable data type. It has no return value.# Writing a filef = open(__file__, 'a+')lines = f.readlines() #writelines()f.writelines(lines)f.close()" }, { "code": "# Writing a filef = open(__file__, 'a+')lines = f.readlines() #writelines()f.writelines(lines)f.close()", "e": 4904, "s": 4799, "text": null }, { "code": null, "e": 5135, "s": 4904, "text": "tell(): It returns an integer that tells us the file object’s position from the beginning of the file in the form of bytes# Telling the file object positionf = open(__file__, 'r')lines = f.read(10) #tell()print(f.tell())f.close()" }, { "code": "# Telling the file object positionf = open(__file__, 'r')lines = f.read(10) #tell()print(f.tell())f.close()", "e": 5244, "s": 5135, "text": null }, { "code": null, "e": 5581, "s": 5244, "text": "seek(offset, from_where): It is used to change the file object’s position. Offset indicates the number of bytes to be moved. from_where indicates from where the bytes are to be moved.# Setting the file object positionf = open(__file__, 'r')lines = f.read(10)print(lines) #seek()print(f.seek(2,2))lines = f.read(10)print(lines)f.close()" }, { "code": "# Setting the file object positionf = open(__file__, 'r')lines = f.read(10)print(lines) #seek()print(f.seek(2,2))lines = f.read(10)print(lines)f.close()", "e": 5735, "s": 5581, "text": null }, { "code": null, "e": 6083, "s": 5735, "text": "flush(): Flush the internal buffer, like stdio‘s fflush(). It has no return value. close() automatically flushes the data but if you want to flush the data before closing the file then you can use this method.# Clearing the internal buffer before closing the filef = open(__file__, 'r')lines = f.read(10) #flush()f.flush()print(f.read())f.close()" }, { "code": "# Clearing the internal buffer before closing the filef = open(__file__, 'r')lines = f.read(10) #flush()f.flush()print(f.read())f.close()", "e": 6222, "s": 6083, "text": null }, { "code": null, "e": 6464, "s": 6222, "text": "fileno(): Returns the integer file descriptor that is used by the underlying implementation to request I/O operations from the operating system.# Getting the integer file descriptorf = open(__file__, 'r') #fileno()print(f.fileno())f.close()" }, { "code": "# Getting the integer file descriptorf = open(__file__, 'r') #fileno()print(f.fileno())f.close()", "e": 6562, "s": 6464, "text": null }, { "code": null, "e": 6763, "s": 6562, "text": "isatty(): Returns True if the file is connected to a tty(-like) device and False if not.# Checks if file is connected to a tty(-like) devicef = open(__file__, 'r') #isatty()print(f.isatty())f.close()" }, { "code": "# Checks if file is connected to a tty(-like) devicef = open(__file__, 'r') #isatty()print(f.isatty())f.close()", "e": 6876, "s": 6763, "text": null }, { "code": null, "e": 7241, "s": 6876, "text": "next(): It is used when a file is used as an iterator. The method is called repeatedly. This method returns the next input line or raises StopIteration at EOF when the file is open for reading( behaviour is undefined when opened for writing).# Iterates over the filef = open(__file__, 'r') #next()try: while f.next(): print(f.next())except: f.close()" }, { "code": "# Iterates over the filef = open(__file__, 'r') #next()try: while f.next(): print(f.next())except: f.close()", "e": 7364, "s": 7241, "text": null }, { "code": null, "e": 7927, "s": 7364, "text": "truncate([size]): Truncate the file’s size. If the optional size argument is present, the file is truncated to (at most) that size. The size defaults to the current position. The current file position is not changed. Note that if a specified size exceeds the file’s current size, the result is platform-dependent: possibilities include that the file may remain unchanged, increase to the specified size as if zero-filled, or increase to the specified size with undefined new content.# Truncates the filef = open(__file__, 'w') #truncate()f.truncate(10)f.close()" }, { "code": "# Truncates the filef = open(__file__, 'w') #truncate()f.truncate(10)f.close()", "e": 8007, "s": 7927, "text": null }, { "code": null, "e": 8164, "s": 8007, "text": "close(): Used to close an open file. A closed file cannot be read or written any more.# Opening and closing a filef = open(__file__, 'r') #close()f.close()" }, { "code": "# Opening and closing a filef = open(__file__, 'r') #close()f.close()", "e": 8235, "s": 8164, "text": null }, { "code": null, "e": 9247, "s": 8235, "text": "Attributes:closed: returns a boolean indicating the current state of the file object. It returns true if the file is closed and false when the file is open.encoding: The encoding that this file uses. When Unicode strings are written to a file, they will be converted to byte strings using this encoding.mode: The I/O mode for the file. If the file was created using the open() built-in function, this will be the value of the mode parameter.name: If the file object was created using open(), the name of the file.newlines: A file object that has been opened in universal newline mode have this attribute which reflects the newline convention used in the file. The value for this attribute are “\\r”, “\\n”, “\\r\\n”, None or a tuple containing all the newline types seen.softspace: It is a boolean that indicates whether a space character needs to be printed before another value when using the print statement.f = open(__file__, 'a+')print(f.closed)print(f.encoding)print(f.mode)print(f.newlines)print(f.softspace)" }, { "code": null, "e": 9393, "s": 9247, "text": "closed: returns a boolean indicating the current state of the file object. It returns true if the file is closed and false when the file is open." }, { "code": null, "e": 9541, "s": 9393, "text": "encoding: The encoding that this file uses. When Unicode strings are written to a file, they will be converted to byte strings using this encoding." }, { "code": null, "e": 9680, "s": 9541, "text": "mode: The I/O mode for the file. If the file was created using the open() built-in function, this will be the value of the mode parameter." }, { "code": null, "e": 9753, "s": 9680, "text": "name: If the file object was created using open(), the name of the file." }, { "code": null, "e": 10008, "s": 9753, "text": "newlines: A file object that has been opened in universal newline mode have this attribute which reflects the newline convention used in the file. The value for this attribute are “\\r”, “\\n”, “\\r\\n”, None or a tuple containing all the newline types seen." }, { "code": null, "e": 10253, "s": 10008, "text": "softspace: It is a boolean that indicates whether a space character needs to be printed before another value when using the print statement.f = open(__file__, 'a+')print(f.closed)print(f.encoding)print(f.mode)print(f.newlines)print(f.softspace)" }, { "code": "f = open(__file__, 'a+')print(f.closed)print(f.encoding)print(f.mode)print(f.newlines)print(f.softspace)", "e": 10358, "s": 10253, "text": null }, { "code": null, "e": 10419, "s": 10358, "text": "Related Article :Reading and Writing to text files in Python" }, { "code": null, "e": 10795, "s": 10419, "text": "Reference: https://docs.python.org/2.4/lib/bltin-file-objects.htmlThis article is contributed by Sri Sanketh Uppalapati. 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." }, { "code": null, "e": 10920, "s": 10795, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 10927, "s": 10920, "text": "Python" } ]
How to change any data type into a String in Python?
24 Jul, 2020 Python defines type conversion functions to directly convert one data type to another which is useful in day to day and competitive programming. A string is a sequence of characters. Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Example : Creating strings in different ways : # creating string using ' 'str1 = 'Welcome to the Geeks for Geeks !'print(str1) # creating string using " "str2 = "Welcome Geek !"print(str2) # creating string using ''' '''str3 = '''Welcome again'''print(str3) Output : Welcome to the Geeks for Geeks! Welcome Geek! Welcome again There are two ways for changing any data type into a String in Python : Using the str() functionUsing the __str__() function Using the str() function Using the __str__() function Method 1 : Using the str() functionAny built-in data type can be converted into its string representation by the str() function. Built-in data type in python include:- int, float, complex, list, tuple, dict etc.Syntax : str(built-in data type) Example : # a is of type inta = 10print("Type before : ", type(a)) # converting the type from int to stra1 = str(a)print("Type after : ", type(a1)) # b is of type floatb = 10.10print("\nType before : ", type(b)) # converting the type from float to strb1 = str(b)print("Type after : ", type(b1)) # type of c is listc = [1, 2, 3]print("\nType before :", type(c)) # converting the type from list to strc1 = str(c)print("Type after : ", type(c1)) # type of d is tupled = (1, 2, 3)print("\nType before:-", type(d)) # converting the type from tuple to strd1 = str(d)print("Type after:-", type(d1)) Output: Type before : <class 'int'> Type after : <class 'str'> Type before : <class 'float'> Type after : <class 'str'> Type before : <class 'list'> Type after : <class 'str'> Type before : <class 'tuple'> Type after : <class 'str'> Method 2 : Defining __str__() function for a user defined class to be converted to string representation. For a user defined class to be converted to string representation, __str__() function needs to be defined in it. Example : # class additionclass addition: def __init__(self): self.a = 10 self.b = 10 # defining __str__() function def __str__(self): return 'value of a = {} value of b = {}'.format(self.a, self.b) # creating object adad = addition()print(str(ad)) # printing the typeprint(type(str(ad))) Output: value of a =10 value of b =10 <class 'str'> python-basics python-string 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": "\n24 Jul, 2020" }, { "code": null, "e": 326, "s": 28, "text": "Python defines type conversion functions to directly convert one data type to another which is useful in day to day and competitive programming. A string is a sequence of characters. Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes." }, { "code": null, "e": 373, "s": 326, "text": "Example : Creating strings in different ways :" }, { "code": "# creating string using ' 'str1 = 'Welcome to the Geeks for Geeks !'print(str1) # creating string using \" \"str2 = \"Welcome Geek !\"print(str2) # creating string using ''' '''str3 = '''Welcome again'''print(str3)", "e": 586, "s": 373, "text": null }, { "code": null, "e": 595, "s": 586, "text": "Output :" }, { "code": null, "e": 655, "s": 595, "text": "Welcome to the Geeks for Geeks!\nWelcome Geek!\nWelcome again" }, { "code": null, "e": 727, "s": 655, "text": "There are two ways for changing any data type into a String in Python :" }, { "code": null, "e": 780, "s": 727, "text": "Using the str() functionUsing the __str__() function" }, { "code": null, "e": 805, "s": 780, "text": "Using the str() function" }, { "code": null, "e": 834, "s": 805, "text": "Using the __str__() function" }, { "code": null, "e": 1054, "s": 834, "text": "Method 1 : Using the str() functionAny built-in data type can be converted into its string representation by the str() function. Built-in data type in python include:- int, float, complex, list, tuple, dict etc.Syntax :" }, { "code": null, "e": 1078, "s": 1054, "text": "str(built-in data type)" }, { "code": null, "e": 1088, "s": 1078, "text": "Example :" }, { "code": "# a is of type inta = 10print(\"Type before : \", type(a)) # converting the type from int to stra1 = str(a)print(\"Type after : \", type(a1)) # b is of type floatb = 10.10print(\"\\nType before : \", type(b)) # converting the type from float to strb1 = str(b)print(\"Type after : \", type(b1)) # type of c is listc = [1, 2, 3]print(\"\\nType before :\", type(c)) # converting the type from list to strc1 = str(c)print(\"Type after : \", type(c1)) # type of d is tupled = (1, 2, 3)print(\"\\nType before:-\", type(d)) # converting the type from tuple to strd1 = str(d)print(\"Type after:-\", type(d1))", "e": 1677, "s": 1088, "text": null }, { "code": null, "e": 1685, "s": 1677, "text": "Output:" }, { "code": null, "e": 1914, "s": 1685, "text": "Type before : <class 'int'>\nType after : <class 'str'>\n\nType before : <class 'float'>\nType after : <class 'str'>\n\nType before : <class 'list'>\nType after : <class 'str'>\n\nType before : <class 'tuple'>\nType after : <class 'str'>\n" }, { "code": null, "e": 2133, "s": 1914, "text": "Method 2 : Defining __str__() function for a user defined class to be converted to string representation. For a user defined class to be converted to string representation, __str__() function needs to be defined in it." }, { "code": null, "e": 2143, "s": 2133, "text": "Example :" }, { "code": "# class additionclass addition: def __init__(self): self.a = 10 self.b = 10 # defining __str__() function def __str__(self): return 'value of a = {} value of b = {}'.format(self.a, self.b) # creating object adad = addition()print(str(ad)) # printing the typeprint(type(str(ad)))", "e": 2456, "s": 2143, "text": null }, { "code": null, "e": 2464, "s": 2456, "text": "Output:" }, { "code": null, "e": 2508, "s": 2464, "text": "value of a =10 value of b =10\n<class 'str'>" }, { "code": null, "e": 2522, "s": 2508, "text": "python-basics" }, { "code": null, "e": 2536, "s": 2522, "text": "python-string" }, { "code": null, "e": 2543, "s": 2536, "text": "Python" }, { "code": null, "e": 2559, "s": 2543, "text": "Python Programs" } ]
How To Fold Legend into Two Rows in ggplot2 in R
14 Sep, 2021 In this article, we are going to see how to draw a ggplot2 legend with two Rows in R Programming Language. If we want to draw ggplot2 Legend 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 the 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 Dataframe in use: Batch Students Class 1 2017 2300 DSA Essential 2 2018 1200 Placement100 3 2019 3500 C++: Expert 4 2020 1400 Web Development Bootcamp 5 2021 120 Android Development Bootcamp To Create an R plot, we use ggplot() function, and to make it a scatter plot we add geom_point() function, assign this whole plot to gplot data object. Let us first create a regular plot so that the difference is apparent. Example: Default legend R library("ggplot2") # Create a DataFramedata <- data.frame(Batch = c(2017, 2018, 2019, 2020, 2021), Students = c(2300, 1200, 3500, 1400, 120), Class = c("DSA Essential", "Placement100", "C++: Expert", "Web Development Bootcamp", "Android DevelopmentBootcamp")) # Create a ggplot2 scatter plotggplot(data, aes(Batch, Students, color = Class)) +geom_point(size = 4) Output: Now to fold the legend, add guides() function with color as guide_legend() together with parameter nrow=2, which folds legend into two-row. Example: Legend folded into 2 rows R library("ggplot2") # Create a DataFramedata <- data.frame(Batch = c(2017, 2018, 2019, 2020, 2021), Students = c(2300, 1200, 3500, 1400, 120), Class = c("DSA Essential", "Placement100", "C++: Expert", "Web Development Bootcamp", "Android Development Bootcamp")) # Create a ggplot2 scatter plotggplot(data, aes(Batch, Students, color = Class)) + geom_point(size = 4) + guides(color = guide_legend(nrow = 2)) Output: 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": "\n14 Sep, 2021" }, { "code": null, "e": 135, "s": 28, "text": "In this article, we are going to see how to draw a ggplot2 legend with two Rows in R Programming Language." }, { "code": null, "e": 374, "s": 135, "text": "If we want to draw ggplot2 Legend 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. " }, { "code": null, "e": 500, "s": 374, "text": "Inside the guide_legend() function, we take an argument called nrow, which has the desired number of rows of legend as value." }, { "code": null, "e": 528, "s": 500, "text": "Syntax : guide_legend(nrow)" }, { "code": null, "e": 542, "s": 528, "text": "Parameter : " }, { "code": null, "e": 587, "s": 542, "text": "nrow : The Desired Number of rows of legend." }, { "code": null, "e": 629, "s": 587, "text": "Return : Legend Guides for various scales" }, { "code": null, "e": 647, "s": 629, "text": "Dataframe in use:" }, { "code": null, "e": 923, "s": 647, "text": " Batch Students Class\n1 2017 2300 DSA Essential\n2 2018 1200 Placement100\n3 2019 3500 C++: Expert\n4 2020 1400 Web Development Bootcamp\n5 2021 120 Android Development Bootcamp" }, { "code": null, "e": 1146, "s": 923, "text": "To Create an R plot, we use ggplot() function, and to make it a scatter plot we add geom_point() function, assign this whole plot to gplot data object. Let us first create a regular plot so that the difference is apparent." }, { "code": null, "e": 1170, "s": 1146, "text": "Example: Default legend" }, { "code": null, "e": 1172, "s": 1170, "text": "R" }, { "code": "library(\"ggplot2\") # Create a DataFramedata <- data.frame(Batch = c(2017, 2018, 2019, 2020, 2021), Students = c(2300, 1200, 3500, 1400, 120), Class = c(\"DSA Essential\", \"Placement100\", \"C++: Expert\", \"Web Development Bootcamp\", \"Android DevelopmentBootcamp\")) # Create a ggplot2 scatter plotggplot(data, aes(Batch, Students, color = Class)) +geom_point(size = 4)", "e": 1631, "s": 1172, "text": null }, { "code": null, "e": 1639, "s": 1631, "text": "Output:" }, { "code": null, "e": 1779, "s": 1639, "text": "Now to fold the legend, add guides() function with color as guide_legend() together with parameter nrow=2, which folds legend into two-row." }, { "code": null, "e": 1814, "s": 1779, "text": "Example: Legend folded into 2 rows" }, { "code": null, "e": 1816, "s": 1814, "text": "R" }, { "code": "library(\"ggplot2\") # Create a DataFramedata <- data.frame(Batch = c(2017, 2018, 2019, 2020, 2021), Students = c(2300, 1200, 3500, 1400, 120), Class = c(\"DSA Essential\", \"Placement100\", \"C++: Expert\", \"Web Development Bootcamp\", \"Android Development Bootcamp\")) # Create a ggplot2 scatter plotggplot(data, aes(Batch, Students, color = Class)) + geom_point(size = 4) + guides(color = guide_legend(nrow = 2))", "e": 2320, "s": 1816, "text": null }, { "code": null, "e": 2328, "s": 2320, "text": "Output:" }, { "code": null, "e": 2335, "s": 2328, "text": "Picked" }, { "code": null, "e": 2344, "s": 2335, "text": "R-ggplot" }, { "code": null, "e": 2355, "s": 2344, "text": "R Language" } ]
Working with the Python Debugger
22 Jun, 2020 Python Debugger may be a new word for the beginner developers . In this post , we will try to explain the meaning of Debugging and Debugging with Python . Debugging means the complete control over the program execution. Developers use debugging to overcome program from any bad issues. So debugging is a healthier process for the program and keeps the diseases bugs far away. Python also allows developers to debug the programs using pdb module that comes with standard Python by default. We just need to import pdb module in the Python script. Using pdb module, we can set breakpoints in the program to check the current status. We can Change the flow of execution by using jump, continue statements . Let’s understand debugging with a Python program. Example: Python3 # Program to print Multiplication # table of a Numbern=5for x in range(1,11) : print( n , '*' , x , '=' , n*x ) Output: 5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25 5 * 6 = 30 5 * 7 = 35 5 * 8 = 40 5 * 9 = 45 5 * 10 = 50 This program simply print multiplication table but now we need to debug the loop steps using set_trace() function call to pdb module . Example: Python3 # Python Program to print Multiplication Table# We want to debug the for loop so we use# set_trace() call to pdb module import pdb # It means , the Start of Debugging Modepdb.set_trace() n=5for x in range(1,11) : print( n , '*' , x , '=' , n*x ) Output: list command to see entire program . list command list 3 , 6 to see the program lines from 3 to 5 only . list lines command in pdb debugger break command to stop the program execution at particular line . break command in pdb debugger continue command to see the next step in the loop . continue command in pdb debugger jump command allows us to go on any particular line in the program . jump command in pdb debugger pp command to see variable value at the current position in the program . pp command in pdb debugger disable command to disable the current line output and we can use continue command to skip this line in program. We use quit or exit command to come outside the debugging mode . Debugging helps developers to analyze programs line by line. Developers see the every interpreted line by using debugging mode in programs. Python comes with by default debugger that is easy to import and use. So it is good to start with debugger when confused about execution of large loops, current variable values and all . python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jun, 2020" }, { "code": null, "e": 208, "s": 52, "text": "Python Debugger may be a new word for the beginner developers . In this post , we will try to explain the meaning of Debugging and Debugging with Python . " }, { "code": null, "e": 808, "s": 208, "text": "Debugging means the complete control over the program execution. Developers use debugging to overcome program from any bad issues. So debugging is a healthier process for the program and keeps the diseases bugs far away. Python also allows developers to debug the programs using pdb module that comes with standard Python by default. We just need to import pdb module in the Python script. Using pdb module, we can set breakpoints in the program to check the current status. We can Change the flow of execution by using jump, continue statements . Let’s understand debugging with a Python program." }, { "code": null, "e": 817, "s": 808, "text": "Example:" }, { "code": null, "e": 825, "s": 817, "text": "Python3" }, { "code": "# Program to print Multiplication # table of a Numbern=5for x in range(1,11) : print( n , '*' , x , '=' , n*x )", "e": 938, "s": 825, "text": null }, { "code": null, "e": 946, "s": 938, "text": "Output:" }, { "code": null, "e": 1056, "s": 946, "text": "5 * 1 = 5\n5 * 2 = 10\n5 * 3 = 15\n5 * 4 = 20\n5 * 5 = 25\n5 * 6 = 30\n5 * 7 = 35\n5 * 8 = 40\n5 * 9 = 45\n5 * 10 = 50" }, { "code": null, "e": 1191, "s": 1056, "text": "This program simply print multiplication table but now we need to debug the loop steps using set_trace() function call to pdb module ." }, { "code": null, "e": 1200, "s": 1191, "text": "Example:" }, { "code": null, "e": 1208, "s": 1200, "text": "Python3" }, { "code": "# Python Program to print Multiplication Table# We want to debug the for loop so we use# set_trace() call to pdb module import pdb # It means , the Start of Debugging Modepdb.set_trace() n=5for x in range(1,11) : print( n , '*' , x , '=' , n*x )", "e": 1460, "s": 1208, "text": null }, { "code": null, "e": 1468, "s": 1460, "text": "Output:" }, { "code": null, "e": 1506, "s": 1468, "text": " list command to see entire program ." }, { "code": null, "e": 1519, "s": 1506, "text": "list command" }, { "code": null, "e": 1576, "s": 1519, "text": " list 3 , 6 to see the program lines from 3 to 5 only ." }, { "code": null, "e": 1611, "s": 1576, "text": "list lines command in pdb debugger" }, { "code": null, "e": 1679, "s": 1613, "text": " break command to stop the program execution at particular line ." }, { "code": null, "e": 1709, "s": 1679, "text": "break command in pdb debugger" }, { "code": null, "e": 1762, "s": 1709, "text": " continue command to see the next step in the loop ." }, { "code": null, "e": 1795, "s": 1762, "text": "continue command in pdb debugger" }, { "code": null, "e": 1864, "s": 1795, "text": "jump command allows us to go on any particular line in the program ." }, { "code": null, "e": 1893, "s": 1864, "text": "jump command in pdb debugger" }, { "code": null, "e": 1968, "s": 1893, "text": " pp command to see variable value at the current position in the program ." }, { "code": null, "e": 1995, "s": 1968, "text": "pp command in pdb debugger" }, { "code": null, "e": 2175, "s": 1995, "text": "disable command to disable the current line output and we can use continue command to skip this line in program. We use quit or exit command to come outside the debugging mode ." }, { "code": null, "e": 2503, "s": 2175, "text": "Debugging helps developers to analyze programs line by line. Developers see the every interpreted line by using debugging mode in programs. Python comes with by default debugger that is easy to import and use. So it is good to start with debugger when confused about execution of large loops, current variable values and all . " }, { "code": null, "e": 2518, "s": 2503, "text": "python-utility" }, { "code": null, "e": 2525, "s": 2518, "text": "Python" }, { "code": null, "e": 2623, "s": 2525, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2655, "s": 2623, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2682, "s": 2655, "text": "Python Classes and Objects" }, { "code": null, "e": 2703, "s": 2682, "text": "Python OOPs Concepts" }, { "code": null, "e": 2726, "s": 2703, "text": "Introduction To PYTHON" }, { "code": null, "e": 2757, "s": 2726, "text": "Python | os.path.join() method" }, { "code": null, "e": 2813, "s": 2757, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2855, "s": 2813, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2897, "s": 2855, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2936, "s": 2897, "text": "Python | Get unique values from a list" } ]
How to Generate Barcode in Python?
05 Sep, 2020 In this article, we are going to write a short script to generate barcodes using Python. We’ll be using the python-barcode module which is a fork of the pyBarcode module. This module provides us the functionality to generate barcodes in SVG format. Pillow is required to generate barcodes in image formats (such as png or jpg). python-barcode: This module is used to create bar codes as SVG objects. It provides us the power to create different standard types of barcodes such as EAN-8, EAN-13, EAN-14, UPC-A, JAN, ISBN-10, ISBN-13, and many more. To install this module type the below command in the terminal. pip install python-barcode Pillow: This is used to create the barcodes in the image format. To install this module type the below command in the terminal. pip install pillow Here, we are going to generate a barcode in the EAN-13 format. First, let’s generate it as an SVG file. Python3 # import EAN13 from barcode modulefrom barcode import EAN13 # Make sure to pass the number as stringnumber = '5901234123457' # Now, let's create an object of EAN13# class and pass the numbermy_code = EAN13(number) # Our barcode is ready. Let's save it.my_code.save("new_code") Output: Generated barcode as SVG file Now, let’s generate the same barcode in PNG format. Python3 # import EAN13 from barcode modulefrom barcode import EAN13 # import ImageWriter to generate an image filefrom barcode.writer import ImageWriter # Make sure to pass the number as stringnumber = '5901234123457' # Now, let's create an object of EAN13 class and # pass the number with the ImageWriter() as the # writermy_code = EAN13(number, writer=ImageWriter()) # Our barcode is ready. Let's save it.my_code.save("new_code1") Output: Generated barcode as PNG file python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n05 Sep, 2020" }, { "code": null, "e": 381, "s": 53, "text": "In this article, we are going to write a short script to generate barcodes using Python. We’ll be using the python-barcode module which is a fork of the pyBarcode module. This module provides us the functionality to generate barcodes in SVG format. Pillow is required to generate barcodes in image formats (such as png or jpg)." }, { "code": null, "e": 664, "s": 381, "text": "python-barcode: This module is used to create bar codes as SVG objects. It provides us the power to create different standard types of barcodes such as EAN-8, EAN-13, EAN-14, UPC-A, JAN, ISBN-10, ISBN-13, and many more. To install this module type the below command in the terminal." }, { "code": null, "e": 692, "s": 664, "text": "pip install python-barcode " }, { "code": null, "e": 820, "s": 692, "text": "Pillow: This is used to create the barcodes in the image format. To install this module type the below command in the terminal." }, { "code": null, "e": 840, "s": 820, "text": "pip install pillow\n" }, { "code": null, "e": 944, "s": 840, "text": "Here, we are going to generate a barcode in the EAN-13 format. First, let’s generate it as an SVG file." }, { "code": null, "e": 952, "s": 944, "text": "Python3" }, { "code": "# import EAN13 from barcode modulefrom barcode import EAN13 # Make sure to pass the number as stringnumber = '5901234123457' # Now, let's create an object of EAN13# class and pass the numbermy_code = EAN13(number) # Our barcode is ready. Let's save it.my_code.save(\"new_code\")", "e": 1232, "s": 952, "text": null }, { "code": null, "e": 1240, "s": 1232, "text": "Output:" }, { "code": null, "e": 1270, "s": 1240, "text": "Generated barcode as SVG file" }, { "code": null, "e": 1322, "s": 1270, "text": "Now, let’s generate the same barcode in PNG format." }, { "code": null, "e": 1330, "s": 1322, "text": "Python3" }, { "code": "# import EAN13 from barcode modulefrom barcode import EAN13 # import ImageWriter to generate an image filefrom barcode.writer import ImageWriter # Make sure to pass the number as stringnumber = '5901234123457' # Now, let's create an object of EAN13 class and # pass the number with the ImageWriter() as the # writermy_code = EAN13(number, writer=ImageWriter()) # Our barcode is ready. Let's save it.my_code.save(\"new_code1\")", "e": 1759, "s": 1330, "text": null }, { "code": null, "e": 1767, "s": 1759, "text": "Output:" }, { "code": null, "e": 1797, "s": 1767, "text": "Generated barcode as PNG file" }, { "code": null, "e": 1812, "s": 1797, "text": "python-utility" }, { "code": null, "e": 1819, "s": 1812, "text": "Python" } ]
Select Subset of DataTable Columns in R
23 Sep, 2021 In this article, we will discuss how to select a subset of data table columns in R programming language. Let’s create a data table using a matrix. First, we need to load data.table package in the working space. Installation install.packages(“data.table”) Loading library(“data.table”) Dataset in use: We can select a subset of datatable columns by index operator – [] Syntax: datatable[ , c(columns), with = FALSE] Where, datatable is the input data table columns are the columns in the datatable to be selected with =FALSE is an optional parameter Example: R program to select subset of columns from the data table R # load data.table packagelibrary("data.table") # create data table with matrix with 20 elements# 4 rows and 5 columnsdata= data.table(matrix(1:20, nrow=4,ncol = 5)) # display the subset that include v1 and v3 columnsprint(data[ , c("V1", "V3"), with = FALSE]) # display the subset that include v1 , v2 and v3 columnsprint(data[ , c("V1","V2", "V3"), with = FALSE]) # display the subset that include v2,v3,v4 and v5 columnsprint(data[ , c("V2", "V3","V4","V5"), with = FALSE]) Output: Using ! operator before columns can be enough to get the job done by this approach. Here we are not including the subset that is selected from the data table Syntax: datatable[ , !c(columns), with = FALSE] where, datatable is the input data table columns are the columns in the datatable to be selected Example: R program to select columns from datatable R # load data.table packagelibrary("data.table") # create data table with matrix with 20 elements# 4 rows and 5 columnsdata= data.table(matrix(1:20, nrow=4,ncol = 5)) # display the subset that exclude v1 and v3 columnsprint(data[ , !c("V1", "V3"), with = FALSE]) # display the subset that exclude v1 , v2 and v3 columnsprint(data[ , !c("V1","V2", "V3"), with = FALSE]) # display the subset that exclude v2,v3,v4 and v5 columnsprint(data[ , !c("V2", "V3","V4","V5"), with = FALSE]) Output: Picked R DataTable 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 Sep, 2021" }, { "code": null, "e": 133, "s": 28, "text": "In this article, we will discuss how to select a subset of data table columns in R programming language." }, { "code": null, "e": 239, "s": 133, "text": "Let’s create a data table using a matrix. First, we need to load data.table package in the working space." }, { "code": null, "e": 252, "s": 239, "text": "Installation" }, { "code": null, "e": 308, "s": 252, "text": "install.packages(“data.table”) " }, { "code": null, "e": 316, "s": 308, "text": "Loading" }, { "code": null, "e": 339, "s": 316, "text": "library(“data.table”) " }, { "code": null, "e": 355, "s": 339, "text": "Dataset in use:" }, { "code": null, "e": 422, "s": 355, "text": "We can select a subset of datatable columns by index operator – []" }, { "code": null, "e": 430, "s": 422, "text": "Syntax:" }, { "code": null, "e": 470, "s": 430, "text": "datatable[ , c(columns), with = FALSE]" }, { "code": null, "e": 477, "s": 470, "text": "Where," }, { "code": null, "e": 511, "s": 477, "text": "datatable is the input data table" }, { "code": null, "e": 567, "s": 511, "text": "columns are the columns in the datatable to be selected" }, { "code": null, "e": 604, "s": 567, "text": "with =FALSE is an optional parameter" }, { "code": null, "e": 671, "s": 604, "text": "Example: R program to select subset of columns from the data table" }, { "code": null, "e": 673, "s": 671, "text": "R" }, { "code": "# load data.table packagelibrary(\"data.table\") # create data table with matrix with 20 elements# 4 rows and 5 columnsdata= data.table(matrix(1:20, nrow=4,ncol = 5)) # display the subset that include v1 and v3 columnsprint(data[ , c(\"V1\", \"V3\"), with = FALSE]) # display the subset that include v1 , v2 and v3 columnsprint(data[ , c(\"V1\",\"V2\", \"V3\"), with = FALSE]) # display the subset that include v2,v3,v4 and v5 columnsprint(data[ , c(\"V2\", \"V3\",\"V4\",\"V5\"), with = FALSE])", "e": 1169, "s": 673, "text": null }, { "code": null, "e": 1177, "s": 1169, "text": "Output:" }, { "code": null, "e": 1335, "s": 1177, "text": "Using ! operator before columns can be enough to get the job done by this approach. Here we are not including the subset that is selected from the data table" }, { "code": null, "e": 1343, "s": 1335, "text": "Syntax:" }, { "code": null, "e": 1384, "s": 1343, "text": "datatable[ , !c(columns), with = FALSE]" }, { "code": null, "e": 1391, "s": 1384, "text": "where," }, { "code": null, "e": 1425, "s": 1391, "text": "datatable is the input data table" }, { "code": null, "e": 1481, "s": 1425, "text": "columns are the columns in the datatable to be selected" }, { "code": null, "e": 1533, "s": 1481, "text": "Example: R program to select columns from datatable" }, { "code": null, "e": 1535, "s": 1533, "text": "R" }, { "code": "# load data.table packagelibrary(\"data.table\") # create data table with matrix with 20 elements# 4 rows and 5 columnsdata= data.table(matrix(1:20, nrow=4,ncol = 5)) # display the subset that exclude v1 and v3 columnsprint(data[ , !c(\"V1\", \"V3\"), with = FALSE]) # display the subset that exclude v1 , v2 and v3 columnsprint(data[ , !c(\"V1\",\"V2\", \"V3\"), with = FALSE]) # display the subset that exclude v2,v3,v4 and v5 columnsprint(data[ , !c(\"V2\", \"V3\",\"V4\",\"V5\"), with = FALSE])", "e": 2035, "s": 1535, "text": null }, { "code": null, "e": 2043, "s": 2035, "text": "Output:" }, { "code": null, "e": 2050, "s": 2043, "text": "Picked" }, { "code": null, "e": 2062, "s": 2050, "text": "R DataTable" }, { "code": null, "e": 2073, "s": 2062, "text": "R Language" } ]
jQuery UI Button disable() Method
21 Dec, 2021 jQuery UI consists of GUI widgets, visual effects, and themes implemented using HTML, CSS, and jQuery. jQuery UI is great for building UI interfaces for the webpages. The jQuery UI Button disable() method is used to disable the button widget. It does not accept any parameter. Syntax: $(".selector").button("disable"); CDN Link: First, add jQuery UI scripts needed for your project. <link rel=”stylesheet” href=”//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css”><script src=”//code.jquery.com/jquery-1.12.4.js”></script><script src=”//code.jquery.com/ui/1.12.1/jquery-ui.js”></script> Example: This example describes the uses of jQuery UI Button disable() method. HTML <!doctype html><html lang="en"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.12.4.js"></script> <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script></head> <body> <center> <h1 style="color: green;"> GeeksforGeeks </h1> <h3>jQuery UI Button disable() Method</h3> <button>GFG Button</button> <br><br> <input type="button" id="GFG" style="padding: 5px 15px;" value="Disable the Button Widget"> </center> <script> $(document).ready(function () { $("button").button(); $("#GFG").on('click', function () { $("button").button("disable"); }); }); </script></body> </html> Output: Reference: https://api.jqueryui.com/button/#method-disable jQuery-UI jQuery-UI-Button JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Dec, 2021" }, { "code": null, "e": 305, "s": 28, "text": "jQuery UI consists of GUI widgets, visual effects, and themes implemented using HTML, CSS, and jQuery. jQuery UI is great for building UI interfaces for the webpages. The jQuery UI Button disable() method is used to disable the button widget. It does not accept any parameter." }, { "code": null, "e": 313, "s": 305, "text": "Syntax:" }, { "code": null, "e": 347, "s": 313, "text": "$(\".selector\").button(\"disable\");" }, { "code": null, "e": 411, "s": 347, "text": "CDN Link: First, add jQuery UI scripts needed for your project." }, { "code": null, "e": 624, "s": 411, "text": "<link rel=”stylesheet” href=”//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css”><script src=”//code.jquery.com/jquery-1.12.4.js”></script><script src=”//code.jquery.com/ui/1.12.1/jquery-ui.js”></script>" }, { "code": null, "e": 705, "s": 626, "text": "Example: This example describes the uses of jQuery UI Button disable() method." }, { "code": null, "e": 710, "s": 705, "text": "HTML" }, { "code": "<!doctype html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css\"> <script src=\"//code.jquery.com/jquery-1.12.4.js\"></script> <script src=\"//code.jquery.com/ui/1.12.1/jquery-ui.js\"></script></head> <body> <center> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h3>jQuery UI Button disable() Method</h3> <button>GFG Button</button> <br><br> <input type=\"button\" id=\"GFG\" style=\"padding: 5px 15px;\" value=\"Disable the Button Widget\"> </center> <script> $(document).ready(function () { $(\"button\").button(); $(\"#GFG\").on('click', function () { $(\"button\").button(\"disable\"); }); }); </script></body> </html>", "e": 1578, "s": 710, "text": null }, { "code": null, "e": 1586, "s": 1578, "text": "Output:" }, { "code": null, "e": 1645, "s": 1586, "text": "Reference: https://api.jqueryui.com/button/#method-disable" }, { "code": null, "e": 1655, "s": 1645, "text": "jQuery-UI" }, { "code": null, "e": 1672, "s": 1655, "text": "jQuery-UI-Button" }, { "code": null, "e": 1679, "s": 1672, "text": "JQuery" }, { "code": null, "e": 1696, "s": 1679, "text": "Web Technologies" } ]
Neo4j Create Index
06 Jun, 2021 In neo4j you can create index for both property and nodes. Indexing is data structure that helps faster performance on retrieval operation on database. There is special features in neo4j indexing once you create indexing that index will manage itself and keep it up to date whenever changes made on the database. Similarly CREATE INDEX ON statement will provide the indexing. Example: In the below example we create index on the Tag property of all nodes with the GeeksforGeeks label. $ CREATE INDEX ON:GeeksforGeeks(Tag) Output: Note: When you create an index, neo4j will create the index in background. If your database is large it will take some time. Note: When you create an index, neo4j will create the index in background. If your database is large it will take some time. View Index: Index and Constraint is the part of the database schema. To view the indexes you have to use :schema command, like below example. :schema Output: Index hints: If the indexing is exist on your database then it will be helpful when you trigger similar type of queries, it improves the performance. You can create an index hint by including USING INDEX ... in your query. $ MATCH (a:GeeksforGeeks {Tag: "A Computer Science Portal"}) USING INDEX a:GeeksforGeeks(Tag) RETURN a Output: Note: You can also provide multiple hints. Simply add a new USING INDEX for each index you’d like to enforce. Note: You can also provide multiple hints. Simply add a new USING INDEX for each index you’d like to enforce. skyridetim ruhelaa48 DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jun, 2021" }, { "code": null, "e": 405, "s": 28, "text": "In neo4j you can create index for both property and nodes. Indexing is data structure that helps faster performance on retrieval operation on database. There is special features in neo4j indexing once you create indexing that index will manage itself and keep it up to date whenever changes made on the database. Similarly CREATE INDEX ON statement will provide the indexing. " }, { "code": null, "e": 516, "s": 405, "text": "Example: In the below example we create index on the Tag property of all nodes with the GeeksforGeeks label. " }, { "code": null, "e": 553, "s": 516, "text": "$ CREATE INDEX ON:GeeksforGeeks(Tag)" }, { "code": null, "e": 563, "s": 553, "text": "Output: " }, { "code": null, "e": 690, "s": 563, "text": "Note: When you create an index, neo4j will create the index in background. If your database is large it will take some time. " }, { "code": null, "e": 817, "s": 690, "text": "Note: When you create an index, neo4j will create the index in background. If your database is large it will take some time. " }, { "code": null, "e": 961, "s": 817, "text": "View Index: Index and Constraint is the part of the database schema. To view the indexes you have to use :schema command, like below example. " }, { "code": null, "e": 969, "s": 961, "text": ":schema" }, { "code": null, "e": 979, "s": 969, "text": "Output: " }, { "code": null, "e": 1206, "s": 981, "text": "Index hints: If the indexing is exist on your database then it will be helpful when you trigger similar type of queries, it improves the performance. You can create an index hint by including USING INDEX ... in your query. " }, { "code": null, "e": 1312, "s": 1206, "text": "$ MATCH (a:GeeksforGeeks {Tag: \"A Computer Science Portal\"}) \nUSING INDEX a:GeeksforGeeks(Tag) \nRETURN a " }, { "code": null, "e": 1430, "s": 1312, "text": "Output: Note: You can also provide multiple hints. Simply add a new USING INDEX for each index you’d like to enforce." }, { "code": null, "e": 1540, "s": 1430, "text": "Note: You can also provide multiple hints. Simply add a new USING INDEX for each index you’d like to enforce." }, { "code": null, "e": 1553, "s": 1542, "text": "skyridetim" }, { "code": null, "e": 1563, "s": 1553, "text": "ruhelaa48" }, { "code": null, "e": 1568, "s": 1563, "text": "DBMS" }, { "code": null, "e": 1573, "s": 1568, "text": "DBMS" } ]
Rotation of colorbar tick labels in Matplotlib
24 Jan, 2021 Colorbar is an axis that indicates the mapping of data values to the colors used in plot. The colorbar() function in pyplot module of matplotlib adds a colorbar to a plot indicating the color scale. Typical Colorbar Sometimes it is desirable to rotate the ticklabels for better visualization and understanding. To change the rotation of colorbar ticklabels desired angle of rotation is provided in: cbar.ax.set_xticklabels, if colorbar orientation is horizontal cbar.ax.set_yticklabels, if colorbar orientation is vertical Positive value of angle corresponds to counterclockwise rotation, while negative value corresponds to clockwise rotation. Also, we can use “vertical” and “horizontal” values for rotation instead of numeric value of angle. These are equivalent to 0° and +90° respectively. Plot a figurePlot corresponding colorbarProvide ticks and ticklabelsSet rotation of ticklabels to desired angle Plot a figure Plot corresponding colorbar Provide ticks and ticklabels Set rotation of ticklabels to desired angle Example 1: Following program demonstrates horizontal color bar with 45 degrees rotation of colorbar ticklabels. Python3 # Import librariesimport matplotlib.pyplot as pltimport numpy as np # Plot imagea = np.random.random((10, 10))plt.imshow(a, cmap='gray') # Plot horizontal colorbarcbar = plt.colorbar( orientation="horizontal", fraction=0.050) # Set ticklabelslabels = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]cbar.set_ticks(labels) # Rotate colorbar ticklabels by 45 degrees# anticlockwisecbar.ax.set_xticklabels(labels, rotation=45) plt.show() Output: Example 2: Following program demonstrates horizontal color bar with -45 degrees rotation of colorbar ticklabels. Python3 # Import librariesimport matplotlib.pyplot as pltimport numpy as np # Plot imagea = np.random.random((10, 10))plt.imshow(a, cmap='gray') # Plot horizontal colorbarcbar = plt.colorbar( orientation="horizontal", fraction=0.050) # Set ticklabelslabels = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]cbar.set_ticks(labels) # Rotate colorbar ticklabels by 45 degrees clockwisecbar.ax.set_xticklabels(labels, rotation=-45) plt.show() Output: Example 3: Following program demonstrates vertical color bar with 30 degrees rotation of colorbar ticklabels. Python3 # Import librariesimport matplotlib.pyplot as pltimport numpy as np # Plot imagea = np.random.random((10, 10))plt.imshow(a, cmap='gray') # Plot vertical colorbarcbar = plt.colorbar( orientation="vertical", fraction=0.050) # Set ticklabelslabels = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]cbar.set_ticks(labels) # Rotate colorbar ticklabels by 30 degrees# anticlockwisecbar.ax.set_yticklabels(labels, rotation=30) plt.show() Output: Example 4: Following program demonstrates vertical color bar with -30 degrees rotation of colorbar ticklabels. Python3 # Import librariesimport matplotlib.pyplot as pltimport numpy as np # Plot imagea = np.random.random((10, 10))plt.imshow(a, cmap='gray') # Plot vertical colorbarcbar = plt.colorbar( orientation="vertical", fraction=0.050) # Set ticklabelslabels = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]cbar.set_ticks(labels) # Rotate colorbar ticklabels by 30 degrees clockwisecbar.ax.set_yticklabels(labels, rotation=-30) plt.show() Output: Example 5: Following program demonstrates horizontal color bar with vertical rotation of colorbar ticklabels. Python3 # Import librariesimport matplotlib.pyplot as pltimport numpy as np # Plot imagea = np.random.random((10, 10))plt.imshow(a, cmap='gray') # Plot horizontal colorbarcbar = plt.colorbar( orientation="horizontal", fraction=0.050) # Set ticklabelslabels = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]cbar.set_ticks(labels) # Rotate colorbar ticklabels by 90 degrees# anticlockwise using "vertical" valuecbar.ax.set_xticklabels(labels, rotation="vertical") plt.show() Output: Example 6: Following program demonstrates vertical color bar with 270 degrees rotation of colorbar ticklabels. Python3 # Import librariesimport matplotlib.pyplot as pltimport numpy as np # Plot imagea = np.random.random((10, 10))plt.imshow(a, cmap='gray') # Plot vertical colorbarcbar = plt.colorbar( orientation="vertical", fraction=0.050) # Set ticklabelslabels = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]cbar.set_ticks(labels) # Rotate colorbar ticklabels by 270 degrees# anticlockwisecbar.ax.set_yticklabels(labels, rotation=270)plt.show() Output: Picked Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jan, 2021" }, { "code": null, "e": 227, "s": 28, "text": "Colorbar is an axis that indicates the mapping of data values to the colors used in plot. The colorbar() function in pyplot module of matplotlib adds a colorbar to a plot indicating the color scale." }, { "code": null, "e": 244, "s": 227, "text": "Typical Colorbar" }, { "code": null, "e": 427, "s": 244, "text": "Sometimes it is desirable to rotate the ticklabels for better visualization and understanding. To change the rotation of colorbar ticklabels desired angle of rotation is provided in:" }, { "code": null, "e": 490, "s": 427, "text": "cbar.ax.set_xticklabels, if colorbar orientation is horizontal" }, { "code": null, "e": 551, "s": 490, "text": "cbar.ax.set_yticklabels, if colorbar orientation is vertical" }, { "code": null, "e": 824, "s": 551, "text": "Positive value of angle corresponds to counterclockwise rotation, while negative value corresponds to clockwise rotation. Also, we can use “vertical” and “horizontal” values for rotation instead of numeric value of angle. These are equivalent to 0° and +90° respectively." }, { "code": null, "e": 936, "s": 824, "text": "Plot a figurePlot corresponding colorbarProvide ticks and ticklabelsSet rotation of ticklabels to desired angle" }, { "code": null, "e": 950, "s": 936, "text": "Plot a figure" }, { "code": null, "e": 978, "s": 950, "text": "Plot corresponding colorbar" }, { "code": null, "e": 1007, "s": 978, "text": "Provide ticks and ticklabels" }, { "code": null, "e": 1051, "s": 1007, "text": "Set rotation of ticklabels to desired angle" }, { "code": null, "e": 1163, "s": 1051, "text": "Example 1: Following program demonstrates horizontal color bar with 45 degrees rotation of colorbar ticklabels." }, { "code": null, "e": 1171, "s": 1163, "text": "Python3" }, { "code": "# Import librariesimport matplotlib.pyplot as pltimport numpy as np # Plot imagea = np.random.random((10, 10))plt.imshow(a, cmap='gray') # Plot horizontal colorbarcbar = plt.colorbar( orientation=\"horizontal\", fraction=0.050) # Set ticklabelslabels = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]cbar.set_ticks(labels) # Rotate colorbar ticklabels by 45 degrees# anticlockwisecbar.ax.set_xticklabels(labels, rotation=45) plt.show()", "e": 1626, "s": 1171, "text": null }, { "code": null, "e": 1634, "s": 1626, "text": "Output:" }, { "code": null, "e": 1747, "s": 1634, "text": "Example 2: Following program demonstrates horizontal color bar with -45 degrees rotation of colorbar ticklabels." }, { "code": null, "e": 1755, "s": 1747, "text": "Python3" }, { "code": "# Import librariesimport matplotlib.pyplot as pltimport numpy as np # Plot imagea = np.random.random((10, 10))plt.imshow(a, cmap='gray') # Plot horizontal colorbarcbar = plt.colorbar( orientation=\"horizontal\", fraction=0.050) # Set ticklabelslabels = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]cbar.set_ticks(labels) # Rotate colorbar ticklabels by 45 degrees clockwisecbar.ax.set_xticklabels(labels, rotation=-45) plt.show()", "e": 2206, "s": 1755, "text": null }, { "code": null, "e": 2214, "s": 2206, "text": "Output:" }, { "code": null, "e": 2324, "s": 2214, "text": "Example 3: Following program demonstrates vertical color bar with 30 degrees rotation of colorbar ticklabels." }, { "code": null, "e": 2332, "s": 2324, "text": "Python3" }, { "code": "# Import librariesimport matplotlib.pyplot as pltimport numpy as np # Plot imagea = np.random.random((10, 10))plt.imshow(a, cmap='gray') # Plot vertical colorbarcbar = plt.colorbar( orientation=\"vertical\", fraction=0.050) # Set ticklabelslabels = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]cbar.set_ticks(labels) # Rotate colorbar ticklabels by 30 degrees# anticlockwisecbar.ax.set_yticklabels(labels, rotation=30) plt.show()", "e": 2783, "s": 2332, "text": null }, { "code": null, "e": 2791, "s": 2783, "text": "Output:" }, { "code": null, "e": 2902, "s": 2791, "text": "Example 4: Following program demonstrates vertical color bar with -30 degrees rotation of colorbar ticklabels." }, { "code": null, "e": 2910, "s": 2902, "text": "Python3" }, { "code": "# Import librariesimport matplotlib.pyplot as pltimport numpy as np # Plot imagea = np.random.random((10, 10))plt.imshow(a, cmap='gray') # Plot vertical colorbarcbar = plt.colorbar( orientation=\"vertical\", fraction=0.050) # Set ticklabelslabels = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]cbar.set_ticks(labels) # Rotate colorbar ticklabels by 30 degrees clockwisecbar.ax.set_yticklabels(labels, rotation=-30) plt.show()", "e": 3357, "s": 2910, "text": null }, { "code": null, "e": 3365, "s": 3357, "text": "Output:" }, { "code": null, "e": 3475, "s": 3365, "text": "Example 5: Following program demonstrates horizontal color bar with vertical rotation of colorbar ticklabels." }, { "code": null, "e": 3483, "s": 3475, "text": "Python3" }, { "code": "# Import librariesimport matplotlib.pyplot as pltimport numpy as np # Plot imagea = np.random.random((10, 10))plt.imshow(a, cmap='gray') # Plot horizontal colorbarcbar = plt.colorbar( orientation=\"horizontal\", fraction=0.050) # Set ticklabelslabels = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]cbar.set_ticks(labels) # Rotate colorbar ticklabels by 90 degrees# anticlockwise using \"vertical\" valuecbar.ax.set_xticklabels(labels, rotation=\"vertical\") plt.show()", "e": 3992, "s": 3483, "text": null }, { "code": null, "e": 4000, "s": 3992, "text": "Output:" }, { "code": null, "e": 4111, "s": 4000, "text": "Example 6: Following program demonstrates vertical color bar with 270 degrees rotation of colorbar ticklabels." }, { "code": null, "e": 4119, "s": 4111, "text": "Python3" }, { "code": "# Import librariesimport matplotlib.pyplot as pltimport numpy as np # Plot imagea = np.random.random((10, 10))plt.imshow(a, cmap='gray') # Plot vertical colorbarcbar = plt.colorbar( orientation=\"vertical\", fraction=0.050) # Set ticklabelslabels = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]cbar.set_ticks(labels) # Rotate colorbar ticklabels by 270 degrees# anticlockwisecbar.ax.set_yticklabels(labels, rotation=270)plt.show()", "e": 4570, "s": 4119, "text": null }, { "code": null, "e": 4578, "s": 4570, "text": "Output:" }, { "code": null, "e": 4585, "s": 4578, "text": "Picked" }, { "code": null, "e": 4603, "s": 4585, "text": "Python-matplotlib" }, { "code": null, "e": 4610, "s": 4603, "text": "Python" } ]
Ruby | Hash fetch function
07 Jan, 2020 Hash#fetch() is a Hash class method which returns a value from the hash for the given key. With no other arguments, it will raise a KeyError exception. Syntax: Hash.fetch() Parameter: Hash values Return: value from the hash for the given key Example #1 : # Ruby code for Hash.fetch() method # declaring Hash valuea = { "a" => 100, "b" => 200 } # declaring Hash valueb = {"a" => 100} # declaring Hash valuec = {"a" => 100, "c" => 300, "b" => 200} # Handling no key argument# fetch? Valueputs "Hash a fetch form : #{a.fetch("x"){|el| "Not present, #{el}"}}\n\n" Output : Hash a fetch form : Not present, x Example #2 : # Ruby code for Hash.fetch() method # declaring Hash valuea = { "a" => 100, "b" => 200 } # declaring Hash valueb = {"a" => 100} # declaring Hash valuec = {"a" => 100, "c" => 300, "b" => 200} # fetch Valueputs "Hash a fetch form : #{a.fetch("a")}\n\n" puts "Hash b fetch form : #{b.fetch("a")}\n\n" puts "Hash c fetch form : #{c.fetch("b")}\n\n" Output : Hash a fetch form : 100 Hash b fetch form : 100 Hash c fetch form : 200 Ruby Hash-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jan, 2020" }, { "code": null, "e": 180, "s": 28, "text": "Hash#fetch() is a Hash class method which returns a value from the hash for the given key. With no other arguments, it will raise a KeyError exception." }, { "code": null, "e": 201, "s": 180, "text": "Syntax: Hash.fetch()" }, { "code": null, "e": 224, "s": 201, "text": "Parameter: Hash values" }, { "code": null, "e": 270, "s": 224, "text": "Return: value from the hash for the given key" }, { "code": null, "e": 283, "s": 270, "text": "Example #1 :" }, { "code": "# Ruby code for Hash.fetch() method # declaring Hash valuea = { \"a\" => 100, \"b\" => 200 } # declaring Hash valueb = {\"a\" => 100} # declaring Hash valuec = {\"a\" => 100, \"c\" => 300, \"b\" => 200} # Handling no key argument# fetch? Valueputs \"Hash a fetch form : #{a.fetch(\"x\"){|el| \"Not present, #{el}\"}}\\n\\n\"", "e": 592, "s": 283, "text": null }, { "code": null, "e": 601, "s": 592, "text": "Output :" }, { "code": null, "e": 638, "s": 601, "text": "Hash a fetch form : Not present, x\n\n" }, { "code": null, "e": 651, "s": 638, "text": "Example #2 :" }, { "code": "# Ruby code for Hash.fetch() method # declaring Hash valuea = { \"a\" => 100, \"b\" => 200 } # declaring Hash valueb = {\"a\" => 100} # declaring Hash valuec = {\"a\" => 100, \"c\" => 300, \"b\" => 200} # fetch Valueputs \"Hash a fetch form : #{a.fetch(\"a\")}\\n\\n\" puts \"Hash b fetch form : #{b.fetch(\"a\")}\\n\\n\" puts \"Hash c fetch form : #{c.fetch(\"b\")}\\n\\n\"", "e": 1002, "s": 651, "text": null }, { "code": null, "e": 1011, "s": 1002, "text": "Output :" }, { "code": null, "e": 1087, "s": 1011, "text": "Hash a fetch form : 100\n\nHash b fetch form : 100\n\nHash c fetch form : 200\n\n" }, { "code": null, "e": 1103, "s": 1087, "text": "Ruby Hash-class" }, { "code": null, "e": 1116, "s": 1103, "text": "Ruby-Methods" }, { "code": null, "e": 1121, "s": 1116, "text": "Ruby" } ]
10 Useful Jupyter Notebook Extensions for a Data Scientist in 2021 | Towards Data Science
Every Data Scientist spends most of his time in data visualization, preprocessing and model tuning based on the results. These are the toughest situations for every Data Scientist because you will get a good model when you perform all these three steps precisely. There are 10 very helpful jupyter notebook extensions to help in these circumstances. Qgrid is a Jupyter notebook widget which uses SlickGrid to render pandas DataFrames within a Jupyter notebook. This allows you to explore your DataFrames with intuitive scrolling, sorting and filtering controls, as well as edit your DataFrames by double-clicking cells. pip install qgrid #Installing with pipconda install qgrid #Installing with conda ITables turns pandas DataFrames and Series into interactive data tables in both your notebooks and their HTML representation. ITables uses basic Javascript, and because of this, it will only work in Jupyter Notebook, not in JupyterLab. pip install itables Activate the interactive mode for all series and dataframes with from itables import init_notebook_modeinit_notebook_mode(all_interactive=True)import world_bank_data as wbdf = wb.get_countries()df Data scientists and in fact many developers work with dataframe on daily basis to interpret data to process them. The common workflow is to display the dataframe, take a look at the data schema and then produce multiple plots to check the distribution of the data to have a clearer picture, perhaps search some data in the table, etc... What if those distribution plots were part of the standard DataFrame and we had the ability to quickly search through the table with minimal effort? What if it was the default representation? The jupyter-datatables uses jupyter-require to draw the table. pip install jupyter-datatables from jupyter_datatables import init_datatables_modeinit_datatables_mode() ipyvolume helps in 3d plotting for Python in the Jupyter notebook based on IPython widgets using WebGL. Ipyvolume currently can Do (multi) volume rendering. Create scatter plots (up to ~1 million glyphs). Create quiver plots (like scatter, but with an arrow pointing in a particular direction). Do lasso mouse selections. Render in stereo, for virtual reality with Google Cardboard. Animate in d3 style, for instance, if the x coordinates or colour of a scatter plots changes. Animations / sequences, all scatter/quiver plot properties can be a list of arrays, which can represent time snapshots etc. $ pip install ipyvolume #Installing with pip$ conda install -c conda-forge ipyvolume #Installing with conda bqplot is a 2-D visualization system for Jupyter, based on the constructs of the Grammar of Graphics. provide a unified framework for 2-D visualizations with a pythonic API. provide a sensible API for adding user interactions (panning, zooming, selection, etc) Two APIs are provided Users can build custom visualizations using the internal object model, which is inspired by the constructs of the Grammar of Graphics (figure, marks, axes, scales), and enrich their visualization with our Interaction Layer. Or they can use the context-based API similar to Matplotlib’s pyplot, which provides sensible default choices for most parameters. $ pip install bqplot #Installing with pip$ conda install -c conda-forge bqplot #Installing with conda Don’t train deep learning models blindfolded! Be impatient and look at each epoch of your training! livelossplot provides a live training loss plot in Jupyter Notebook for Keras, PyTorch and other frameworks. pip install livelossplot from livelossplot import PlotLossesKerasmodel.fit(X_train, Y_train, epochs=10, validation_data=(X_test, Y_test), callbacks=[PlotLossesKeras()], verbose=0) TensorWatch is a debugging and visualization tool designed for data science, deep learning and reinforcement learning from Microsoft Research. It works in Jupyter Notebook to show real-time visualizations of your machine learning training and perform several other key analysis tasks for your models and data. pip install tensorwatch Polyaxon is a platform for building, training, and monitoring large scale deep learning applications. We are making a system to solve reproducibility, automation, and scalability for machine learning applications. Polyaxon deploys into any data center, cloud provider, or can be hosted and managed by Polyaxon, and it supports all the major deep learning frameworks such as Tensorflow, MXNet, Caffe, Torch, etc. $ pip install -U polyaxon handcalcs is a library to render Python calculation code automatically in Latex, but in a manner that mimics how one might format their calculation if it were written with a pencil: write the symbolic formula, followed by numeric substitutions, and then the result. pip install handcalcs jupyternotify provides a Jupyter notebook cell magic %%notify that notifies the user upon completion of a potentially long-running cell via a browser push notification. Use cases include long-running machine learning models, grid searches, or Spark computations. This magic allows you to navigate away to other work and still get a notification when your cell completes. pip install jupyternotify Any feedback and comments are, greatly appreciated!
[ { "code": null, "e": 522, "s": 172, "text": "Every Data Scientist spends most of his time in data visualization, preprocessing and model tuning based on the results. These are the toughest situations for every Data Scientist because you will get a good model when you perform all these three steps precisely. There are 10 very helpful jupyter notebook extensions to help in these circumstances." }, { "code": null, "e": 792, "s": 522, "text": "Qgrid is a Jupyter notebook widget which uses SlickGrid to render pandas DataFrames within a Jupyter notebook. This allows you to explore your DataFrames with intuitive scrolling, sorting and filtering controls, as well as edit your DataFrames by double-clicking cells." }, { "code": null, "e": 875, "s": 792, "text": "pip install qgrid #Installing with pipconda install qgrid #Installing with conda" }, { "code": null, "e": 1111, "s": 875, "text": "ITables turns pandas DataFrames and Series into interactive data tables in both your notebooks and their HTML representation. ITables uses basic Javascript, and because of this, it will only work in Jupyter Notebook, not in JupyterLab." }, { "code": null, "e": 1131, "s": 1111, "text": "pip install itables" }, { "code": null, "e": 1196, "s": 1131, "text": "Activate the interactive mode for all series and dataframes with" }, { "code": null, "e": 1328, "s": 1196, "text": "from itables import init_notebook_modeinit_notebook_mode(all_interactive=True)import world_bank_data as wbdf = wb.get_countries()df" }, { "code": null, "e": 1665, "s": 1328, "text": "Data scientists and in fact many developers work with dataframe on daily basis to interpret data to process them. The common workflow is to display the dataframe, take a look at the data schema and then produce multiple plots to check the distribution of the data to have a clearer picture, perhaps search some data in the table, etc..." }, { "code": null, "e": 1857, "s": 1665, "text": "What if those distribution plots were part of the standard DataFrame and we had the ability to quickly search through the table with minimal effort? What if it was the default representation?" }, { "code": null, "e": 1920, "s": 1857, "text": "The jupyter-datatables uses jupyter-require to draw the table." }, { "code": null, "e": 1951, "s": 1920, "text": "pip install jupyter-datatables" }, { "code": null, "e": 2025, "s": 1951, "text": "from jupyter_datatables import init_datatables_modeinit_datatables_mode()" }, { "code": null, "e": 2129, "s": 2025, "text": "ipyvolume helps in 3d plotting for Python in the Jupyter notebook based on IPython widgets using WebGL." }, { "code": null, "e": 2153, "s": 2129, "text": "Ipyvolume currently can" }, { "code": null, "e": 2182, "s": 2153, "text": "Do (multi) volume rendering." }, { "code": null, "e": 2230, "s": 2182, "text": "Create scatter plots (up to ~1 million glyphs)." }, { "code": null, "e": 2320, "s": 2230, "text": "Create quiver plots (like scatter, but with an arrow pointing in a particular direction)." }, { "code": null, "e": 2347, "s": 2320, "text": "Do lasso mouse selections." }, { "code": null, "e": 2408, "s": 2347, "text": "Render in stereo, for virtual reality with Google Cardboard." }, { "code": null, "e": 2502, "s": 2408, "text": "Animate in d3 style, for instance, if the x coordinates or colour of a scatter plots changes." }, { "code": null, "e": 2626, "s": 2502, "text": "Animations / sequences, all scatter/quiver plot properties can be a list of arrays, which can represent time snapshots etc." }, { "code": null, "e": 2735, "s": 2626, "text": "$ pip install ipyvolume #Installing with pip$ conda install -c conda-forge ipyvolume #Installing with conda" }, { "code": null, "e": 2837, "s": 2735, "text": "bqplot is a 2-D visualization system for Jupyter, based on the constructs of the Grammar of Graphics." }, { "code": null, "e": 2909, "s": 2837, "text": "provide a unified framework for 2-D visualizations with a pythonic API." }, { "code": null, "e": 2996, "s": 2909, "text": "provide a sensible API for adding user interactions (panning, zooming, selection, etc)" }, { "code": null, "e": 3018, "s": 2996, "text": "Two APIs are provided" }, { "code": null, "e": 3242, "s": 3018, "text": "Users can build custom visualizations using the internal object model, which is inspired by the constructs of the Grammar of Graphics (figure, marks, axes, scales), and enrich their visualization with our Interaction Layer." }, { "code": null, "e": 3373, "s": 3242, "text": "Or they can use the context-based API similar to Matplotlib’s pyplot, which provides sensible default choices for most parameters." }, { "code": null, "e": 3476, "s": 3373, "text": "$ pip install bqplot #Installing with pip$ conda install -c conda-forge bqplot #Installing with conda" }, { "code": null, "e": 3576, "s": 3476, "text": "Don’t train deep learning models blindfolded! Be impatient and look at each epoch of your training!" }, { "code": null, "e": 3685, "s": 3576, "text": "livelossplot provides a live training loss plot in Jupyter Notebook for Keras, PyTorch and other frameworks." }, { "code": null, "e": 3710, "s": 3685, "text": "pip install livelossplot" }, { "code": null, "e": 3901, "s": 3710, "text": "from livelossplot import PlotLossesKerasmodel.fit(X_train, Y_train, epochs=10, validation_data=(X_test, Y_test), callbacks=[PlotLossesKeras()], verbose=0)" }, { "code": null, "e": 4211, "s": 3901, "text": "TensorWatch is a debugging and visualization tool designed for data science, deep learning and reinforcement learning from Microsoft Research. It works in Jupyter Notebook to show real-time visualizations of your machine learning training and perform several other key analysis tasks for your models and data." }, { "code": null, "e": 4235, "s": 4211, "text": "pip install tensorwatch" }, { "code": null, "e": 4647, "s": 4235, "text": "Polyaxon is a platform for building, training, and monitoring large scale deep learning applications. We are making a system to solve reproducibility, automation, and scalability for machine learning applications. Polyaxon deploys into any data center, cloud provider, or can be hosted and managed by Polyaxon, and it supports all the major deep learning frameworks such as Tensorflow, MXNet, Caffe, Torch, etc." }, { "code": null, "e": 4673, "s": 4647, "text": "$ pip install -U polyaxon" }, { "code": null, "e": 4939, "s": 4673, "text": "handcalcs is a library to render Python calculation code automatically in Latex, but in a manner that mimics how one might format their calculation if it were written with a pencil: write the symbolic formula, followed by numeric substitutions, and then the result." }, { "code": null, "e": 4961, "s": 4939, "text": "pip install handcalcs" }, { "code": null, "e": 5332, "s": 4961, "text": "jupyternotify provides a Jupyter notebook cell magic %%notify that notifies the user upon completion of a potentially long-running cell via a browser push notification. Use cases include long-running machine learning models, grid searches, or Spark computations. This magic allows you to navigate away to other work and still get a notification when your cell completes." }, { "code": null, "e": 5358, "s": 5332, "text": "pip install jupyternotify" } ]
Python Program to Flatten a Nested List using Recursion - GeeksforGeeks
14 Aug, 2021 Given a nested list, the task is to write a python program to flatten a nested list using recursion. Examples: Input: [[8, 9], [10, 11, ‘geeks’], [13]] Output: [8, 9, 10, 11, ‘geeks’, 13] Input: [[‘A’, ‘B’, ‘C’], [‘D’, ‘E’, ‘F’]] Output: [‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’] Step-by-step Approach: Firstly, we try to initialize a variable into the linked list. Then, our next task is to pass our list as an argument to a recursive function for flattening the list. In that recursive function, if we find the list as empty then we return the list. Else, we call the function in recursive form along with its sublists as parameters until the list gets flattened. Then finally, we will print the flattened list as output. Below are some python programs based on the above approach: Example 1: Python3 # Python program to flatten a nested list # explicit function to flatten a# nested listdef flattenList(nestedList): # check if list is empty if not(bool(nestedList)): return nestedList # to check instance of list is empty or not if isinstance(nestedList[0], list): # call function with sublist as argument return flattenList(*nestedList[:1]) + flattenList(nestedList[1:]) # call function with sublist as argument return nestedList[:1] + flattenList(nestedList[1:]) # Driver CodenestedList = [[8, 9], [10, 11, 'geeks'], [13]]print('Nested List:\n', nestedList) print("Flattened List:\n", flattenList(nestedList)) Output: Nested List: [[8, 9], [10, 11, 'geeks'], [13]] Flattened List: [8, 9, 10, 11, 'geeks', 13] Example 2: Python3 # Python program to flatten a nested list # explicit function to flatten a# nested listdef flattenList(nestedList): # check if list is empty if not(bool(nestedList)): return nestedList # to check instance of list is empty or not if isinstance(nestedList[0], list): # call function with sublist as argument return flattenList(*nestedList[:1]) + flattenList(nestedList[1:]) # call function with sublist as argument return nestedList[:1] + flattenList(nestedList[1:]) # Driver CodenestedList = [['A', 'B', 'C'], ['D', 'E', 'F']]print('Nested List:\n', nestedList) print("Flattened List:\n", flattenList(nestedList)) Output: Nested List: [['A', 'B', 'C'], ['D', 'E', 'F']] Flattened List: ['A', 'B', 'C', 'D', 'E', 'F'] Example 3: Python3 # Python program to flatten a nested list # explicit function to flatten a# nested listdef flattenList(nestedList): # check if list is empty if not(bool(nestedList)): return nestedList # to check instance of list is empty or not if isinstance(nestedList[0], list): # call function with sublist as argument return flattenList(*nestedList[:1]) + flattenList(nestedList[1:]) # call function with sublist as argument return nestedList[:1] + flattenList(nestedList[1:]) # Driver CodenestedList = [[1], [2], [3], [4], [5]]print('Nested List:\n', nestedList) print("Flattened List:\n", flattenList(nestedList)) Output: Nested List: [[1], [2], [3], [4], [5]] Flattened List: [1, 2, 3, 4, 5] ruhelaa48 Picked Python list-programs Technical Scripter 2020 Python Python Programs Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python OOPs Concepts How to Install PIP on Windows ? Bar Plot in Matplotlib Defaultdict in Python Python Classes and Objects Defaultdict in Python Python | Split string into list of characters Python program to check whether a number is Prime or not Python | Get dictionary keys as a list Python | Convert a list to dictionary
[ { "code": null, "e": 24236, "s": 24208, "text": "\n14 Aug, 2021" }, { "code": null, "e": 24337, "s": 24236, "text": "Given a nested list, the task is to write a python program to flatten a nested list using recursion." }, { "code": null, "e": 24347, "s": 24337, "text": "Examples:" }, { "code": null, "e": 24388, "s": 24347, "text": "Input: [[8, 9], [10, 11, ‘geeks’], [13]]" }, { "code": null, "e": 24424, "s": 24388, "text": "Output: [8, 9, 10, 11, ‘geeks’, 13]" }, { "code": null, "e": 24466, "s": 24424, "text": "Input: [[‘A’, ‘B’, ‘C’], [‘D’, ‘E’, ‘F’]]" }, { "code": null, "e": 24505, "s": 24466, "text": "Output: [‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’]" }, { "code": null, "e": 24528, "s": 24505, "text": "Step-by-step Approach:" }, { "code": null, "e": 24591, "s": 24528, "text": "Firstly, we try to initialize a variable into the linked list." }, { "code": null, "e": 24695, "s": 24591, "text": "Then, our next task is to pass our list as an argument to a recursive function for flattening the list." }, { "code": null, "e": 24777, "s": 24695, "text": "In that recursive function, if we find the list as empty then we return the list." }, { "code": null, "e": 24891, "s": 24777, "text": "Else, we call the function in recursive form along with its sublists as parameters until the list gets flattened." }, { "code": null, "e": 24949, "s": 24891, "text": "Then finally, we will print the flattened list as output." }, { "code": null, "e": 25009, "s": 24949, "text": "Below are some python programs based on the above approach:" }, { "code": null, "e": 25020, "s": 25009, "text": "Example 1:" }, { "code": null, "e": 25028, "s": 25020, "text": "Python3" }, { "code": "# Python program to flatten a nested list # explicit function to flatten a# nested listdef flattenList(nestedList): # check if list is empty if not(bool(nestedList)): return nestedList # to check instance of list is empty or not if isinstance(nestedList[0], list): # call function with sublist as argument return flattenList(*nestedList[:1]) + flattenList(nestedList[1:]) # call function with sublist as argument return nestedList[:1] + flattenList(nestedList[1:]) # Driver CodenestedList = [[8, 9], [10, 11, 'geeks'], [13]]print('Nested List:\\n', nestedList) print(\"Flattened List:\\n\", flattenList(nestedList))", "e": 25685, "s": 25028, "text": null }, { "code": null, "e": 25693, "s": 25685, "text": "Output:" }, { "code": null, "e": 25786, "s": 25693, "text": "Nested List:\n [[8, 9], [10, 11, 'geeks'], [13]]\nFlattened List:\n [8, 9, 10, 11, 'geeks', 13]" }, { "code": null, "e": 25797, "s": 25786, "text": "Example 2:" }, { "code": null, "e": 25805, "s": 25797, "text": "Python3" }, { "code": "# Python program to flatten a nested list # explicit function to flatten a# nested listdef flattenList(nestedList): # check if list is empty if not(bool(nestedList)): return nestedList # to check instance of list is empty or not if isinstance(nestedList[0], list): # call function with sublist as argument return flattenList(*nestedList[:1]) + flattenList(nestedList[1:]) # call function with sublist as argument return nestedList[:1] + flattenList(nestedList[1:]) # Driver CodenestedList = [['A', 'B', 'C'], ['D', 'E', 'F']]print('Nested List:\\n', nestedList) print(\"Flattened List:\\n\", flattenList(nestedList))", "e": 26463, "s": 25805, "text": null }, { "code": null, "e": 26471, "s": 26463, "text": "Output:" }, { "code": null, "e": 26568, "s": 26471, "text": "Nested List:\n [['A', 'B', 'C'], ['D', 'E', 'F']]\nFlattened List:\n ['A', 'B', 'C', 'D', 'E', 'F']" }, { "code": null, "e": 26579, "s": 26568, "text": "Example 3:" }, { "code": null, "e": 26587, "s": 26579, "text": "Python3" }, { "code": "# Python program to flatten a nested list # explicit function to flatten a# nested listdef flattenList(nestedList): # check if list is empty if not(bool(nestedList)): return nestedList # to check instance of list is empty or not if isinstance(nestedList[0], list): # call function with sublist as argument return flattenList(*nestedList[:1]) + flattenList(nestedList[1:]) # call function with sublist as argument return nestedList[:1] + flattenList(nestedList[1:]) # Driver CodenestedList = [[1], [2], [3], [4], [5]]print('Nested List:\\n', nestedList) print(\"Flattened List:\\n\", flattenList(nestedList))", "e": 27236, "s": 26587, "text": null }, { "code": null, "e": 27244, "s": 27236, "text": "Output:" }, { "code": null, "e": 27317, "s": 27244, "text": "Nested List:\n [[1], [2], [3], [4], [5]]\nFlattened List:\n [1, 2, 3, 4, 5]" }, { "code": null, "e": 27327, "s": 27317, "text": "ruhelaa48" }, { "code": null, "e": 27334, "s": 27327, "text": "Picked" }, { "code": null, "e": 27355, "s": 27334, "text": "Python list-programs" }, { "code": null, "e": 27379, "s": 27355, "text": "Technical Scripter 2020" }, { "code": null, "e": 27386, "s": 27379, "text": "Python" }, { "code": null, "e": 27402, "s": 27386, "text": "Python Programs" }, { "code": null, "e": 27421, "s": 27402, "text": "Technical Scripter" }, { "code": null, "e": 27519, "s": 27421, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27528, "s": 27519, "text": "Comments" }, { "code": null, "e": 27541, "s": 27528, "text": "Old Comments" }, { "code": null, "e": 27562, "s": 27541, "text": "Python OOPs Concepts" }, { "code": null, "e": 27594, "s": 27562, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27617, "s": 27594, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 27639, "s": 27617, "text": "Defaultdict in Python" }, { "code": null, "e": 27666, "s": 27639, "text": "Python Classes and Objects" }, { "code": null, "e": 27688, "s": 27666, "text": "Defaultdict in Python" }, { "code": null, "e": 27734, "s": 27688, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27791, "s": 27734, "text": "Python program to check whether a number is Prime or not" }, { "code": null, "e": 27830, "s": 27791, "text": "Python | Get dictionary keys as a list" } ]
A Really Simple Way to Edit Row by Row in a Pandas DataFrame | by Byron Dolon | Towards Data Science
Have you ever needed to edit each row in a table based on some conditions? It’s a common task for data analysis projects. I used to search StackOverflow for a solution every time I needed to do this. Finally, I read the Pandas documentation and created a template that works every time I need to edit data row by row. Here’s a look at how you can use the pandas .loc method to select a subset of your data and edit it if it meets a condition. Note, before trying any of the code below, don’t forget to import pandas. import pandas as pd The Pandas documentation has this description for “.loc[]”: Access a group of rows and columns (in a .DataFrame) by label(s) or a boolean array. For our case, we’re going to use the method like this: df.loc[row_indexer,column_indexer] Here are some sample data and an illustration to what the row_indexer and column_indexer are referring to. (For an explanation of how to get that sample data, check out my other piece on easily getting tables from websites.) df = pd.read_html('https://finance.yahoo.com/quote/TSLA/profile?p=TSLA')[0] To set a row_indexer , you need to select one of the values in blue. These numbers in the leftmost column are the “row indexes”, which are used to identify each row. a column_indexer , you need to select one of the values in red, which are the column names of the DataFrame. If we wanted to select the text “Mr. Elon R. Musk”, we would need to do the following: df.loc[0,'Name'] This gives us our desired output: Now that we’ve got the basics down, we’re ready to start editing our tables! Now, say we wanted to edit the “Title” value for some of the people in the table. Let’s change Elon Musk to “The Boss Man”, Zachary Kirkhorn to “The Money Man” and everyone else to “Another Dude”. We need to go through each row in the table and check what the “Name” value is, then edit the “Title” value based on the change we specified. To go through the data row by row, we’re going to use df.index, which selects the “row indexes” from the DataFrame. To see how that works, we can print the index from our sample table in a basic “for” loop: for index in df.index: print(index) This gives us the same values you can see on the leftmost column in the first screenshot. To search and edit the right subset of data for every row in the DataFrame, we use the following code: for index in df.index: if df.loc[index,'Name']=='Mr. Elon R. Musk': df.loc[index,'Title'] = 'The Boss Man' elif df.loc[index,'Name']=='Mr. Zachary J. Kirkhorn': df.loc[index,'Title'] = 'The Money Man' else: df.loc[index,'Title'] = 'Another Dude' This loop will go through every row of the DataFrame, check what the “Name” is, and then edit the “Title” based on which condition it meets. Our conditions are whether the “Name” of value each row is with “Mr. Elon R. Musk”, “Mr. Zachary J. Kirkhorn” and everyone else. In this case, because the first row has “Mr. Elon R. Musk” as the “Name”, the script will change this first row’s “Title” value to “The Boss Man”. It knows which row to perform this change because we specified the row index using df.loc[]. The resulting DataFrame looks like this: We have successfully changed the “Title” values of each row based on the conditions we specified earlier! I hope you find this useful the next time you have to comb through thousands of rows and edit values based on some conditions. You should check out the df.loc[] documentation for more information on how to use the method. You can also look at the Pandas User Guide for more tips on indexing and selecting data.
[ { "code": null, "e": 247, "s": 172, "text": "Have you ever needed to edit each row in a table based on some conditions?" }, { "code": null, "e": 490, "s": 247, "text": "It’s a common task for data analysis projects. I used to search StackOverflow for a solution every time I needed to do this. Finally, I read the Pandas documentation and created a template that works every time I need to edit data row by row." }, { "code": null, "e": 615, "s": 490, "text": "Here’s a look at how you can use the pandas .loc method to select a subset of your data and edit it if it meets a condition." }, { "code": null, "e": 689, "s": 615, "text": "Note, before trying any of the code below, don’t forget to import pandas." }, { "code": null, "e": 709, "s": 689, "text": "import pandas as pd" }, { "code": null, "e": 769, "s": 709, "text": "The Pandas documentation has this description for “.loc[]”:" }, { "code": null, "e": 854, "s": 769, "text": "Access a group of rows and columns (in a .DataFrame) by label(s) or a boolean array." }, { "code": null, "e": 909, "s": 854, "text": "For our case, we’re going to use the method like this:" }, { "code": null, "e": 944, "s": 909, "text": "df.loc[row_indexer,column_indexer]" }, { "code": null, "e": 1169, "s": 944, "text": "Here are some sample data and an illustration to what the row_indexer and column_indexer are referring to. (For an explanation of how to get that sample data, check out my other piece on easily getting tables from websites.)" }, { "code": null, "e": 1245, "s": 1169, "text": "df = pd.read_html('https://finance.yahoo.com/quote/TSLA/profile?p=TSLA')[0]" }, { "code": null, "e": 1520, "s": 1245, "text": "To set a row_indexer , you need to select one of the values in blue. These numbers in the leftmost column are the “row indexes”, which are used to identify each row. a column_indexer , you need to select one of the values in red, which are the column names of the DataFrame." }, { "code": null, "e": 1607, "s": 1520, "text": "If we wanted to select the text “Mr. Elon R. Musk”, we would need to do the following:" }, { "code": null, "e": 1624, "s": 1607, "text": "df.loc[0,'Name']" }, { "code": null, "e": 1658, "s": 1624, "text": "This gives us our desired output:" }, { "code": null, "e": 1735, "s": 1658, "text": "Now that we’ve got the basics down, we’re ready to start editing our tables!" }, { "code": null, "e": 1932, "s": 1735, "text": "Now, say we wanted to edit the “Title” value for some of the people in the table. Let’s change Elon Musk to “The Boss Man”, Zachary Kirkhorn to “The Money Man” and everyone else to “Another Dude”." }, { "code": null, "e": 2074, "s": 1932, "text": "We need to go through each row in the table and check what the “Name” value is, then edit the “Title” value based on the change we specified." }, { "code": null, "e": 2281, "s": 2074, "text": "To go through the data row by row, we’re going to use df.index, which selects the “row indexes” from the DataFrame. To see how that works, we can print the index from our sample table in a basic “for” loop:" }, { "code": null, "e": 2320, "s": 2281, "text": "for index in df.index: print(index)" }, { "code": null, "e": 2410, "s": 2320, "text": "This gives us the same values you can see on the leftmost column in the first screenshot." }, { "code": null, "e": 2513, "s": 2410, "text": "To search and edit the right subset of data for every row in the DataFrame, we use the following code:" }, { "code": null, "e": 2789, "s": 2513, "text": "for index in df.index: if df.loc[index,'Name']=='Mr. Elon R. Musk': df.loc[index,'Title'] = 'The Boss Man' elif df.loc[index,'Name']=='Mr. Zachary J. Kirkhorn': df.loc[index,'Title'] = 'The Money Man' else: df.loc[index,'Title'] = 'Another Dude'" }, { "code": null, "e": 3059, "s": 2789, "text": "This loop will go through every row of the DataFrame, check what the “Name” is, and then edit the “Title” based on which condition it meets. Our conditions are whether the “Name” of value each row is with “Mr. Elon R. Musk”, “Mr. Zachary J. Kirkhorn” and everyone else." }, { "code": null, "e": 3299, "s": 3059, "text": "In this case, because the first row has “Mr. Elon R. Musk” as the “Name”, the script will change this first row’s “Title” value to “The Boss Man”. It knows which row to perform this change because we specified the row index using df.loc[]." }, { "code": null, "e": 3340, "s": 3299, "text": "The resulting DataFrame looks like this:" }, { "code": null, "e": 3446, "s": 3340, "text": "We have successfully changed the “Title” values of each row based on the conditions we specified earlier!" }, { "code": null, "e": 3573, "s": 3446, "text": "I hope you find this useful the next time you have to comb through thousands of rows and edit values based on some conditions." } ]
How to copy files of the specific extension using PowerShell?
To copy the files using the specific files extension using PowerShell, we can use the Copy-Item command. The below command will copy only the .ps1 files from the source to the destination. For example, PS C:\> Copy-Item -Path C:\Temp -Recurse -Filter *.ps1 -Destination C:\Temp1\ -Verbose If the C:\Temp1 doesn't exist, it will create the destination folder and then copy the content of the file but the problem with this command is it copies the subfolders as well which doesn’t have the .ps1 file. So to copy the with the same folder structure without empty directories and the specific file extension we can write the code to check the size of the directory after copy and delete if the folder is empty but this would be a lengthy process. We can use the xCopy or the RoboCopy command to overcome the above problem. PS C:\> robocopy c:\temp c:\temp1 "*.ps1" /s The above command will copy files with extension .ps1 from the C:\temp to the C:\temp1 without the empty folders.
[ { "code": null, "e": 1167, "s": 1062, "text": "To copy the files using the specific files extension using PowerShell, we can use the Copy-Item command." }, { "code": null, "e": 1251, "s": 1167, "text": "The below command will copy only the .ps1 files from the source to the destination." }, { "code": null, "e": 1264, "s": 1251, "text": "For example," }, { "code": null, "e": 1351, "s": 1264, "text": "PS C:\\> Copy-Item -Path C:\\Temp -Recurse -Filter *.ps1 -Destination C:\\Temp1\\ -Verbose" }, { "code": null, "e": 1562, "s": 1351, "text": "If the C:\\Temp1 doesn't exist, it will create the destination folder and then copy the content of the file but the problem with this command is it copies the subfolders as well which doesn’t have the .ps1 file." }, { "code": null, "e": 1805, "s": 1562, "text": "So to copy the with the same folder structure without empty directories and the specific file extension we can write the code to check the size of the directory after copy and delete if the folder is empty but this would be a lengthy process." }, { "code": null, "e": 1881, "s": 1805, "text": "We can use the xCopy or the RoboCopy command to overcome the above problem." }, { "code": null, "e": 1926, "s": 1881, "text": "PS C:\\> robocopy c:\\temp c:\\temp1 \"*.ps1\" /s" }, { "code": null, "e": 2040, "s": 1926, "text": "The above command will copy files with extension .ps1 from the C:\\temp to the C:\\temp1 without the empty folders." } ]
C | String | Question 9 - GeeksforGeeks
28 Jun, 2021 Consider the following C program segment: char p[20]; char *s = "string"; int length = strlen(s); int i; for (i = 0; i < length; i++) p[i] = s[length — i]; printf("%s", p); The output of the program is? (GATE CS 2004)(A) gnirts(B) gnirt(C) string(D) no output is printedAnswer: (D)Explanation: Let us consider below line inside the for loopp[i] = s[length — i];For i = 0, p[i] will be s[6 — 0] and s[6] is ‘\0′So p[0] becomes ‘\0’. It doesn’t matter what comes in p[1], p[2]..... as P[0] will not change for i >0. Nothing is printed if we print a string with first character ‘\0′Quiz of this Question C-String C-String-Question C Language C Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Command line arguments in C/C++ fork() in C Different methods to reverse a string in C/C++ Function Pointer in C Substring in C++ Compiling a C program:- Behind the Scenes Operator Precedence and Associativity in C C | Structure & Union | Question 4 C | File Handling | Question 5 C | Dynamic Memory Allocation | Question 5
[ { "code": null, "e": 24058, "s": 24030, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24100, "s": 24058, "text": "Consider the following C program segment:" }, { "code": "char p[20]; char *s = \"string\"; int length = strlen(s); int i; for (i = 0; i < length; i++) p[i] = s[length — i]; printf(\"%s\", p);", "e": 24235, "s": 24100, "text": null }, { "code": null, "e": 24663, "s": 24235, "text": "The output of the program is? (GATE CS 2004)(A) gnirts(B) gnirt(C) string(D) no output is printedAnswer: (D)Explanation: Let us consider below line inside the for loopp[i] = s[length — i];For i = 0, p[i] will be s[6 — 0] and s[6] is ‘\\0′So p[0] becomes ‘\\0’. It doesn’t matter what comes in p[1], p[2]..... as P[0] will not change for i >0. Nothing is printed if we print a string with first character ‘\\0′Quiz of this Question" }, { "code": null, "e": 24672, "s": 24663, "text": "C-String" }, { "code": null, "e": 24690, "s": 24672, "text": "C-String-Question" }, { "code": null, "e": 24701, "s": 24690, "text": "C Language" }, { "code": null, "e": 24708, "s": 24701, "text": "C Quiz" }, { "code": null, "e": 24806, "s": 24708, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24815, "s": 24806, "text": "Comments" }, { "code": null, "e": 24828, "s": 24815, "text": "Old Comments" }, { "code": null, "e": 24860, "s": 24828, "text": "Command line arguments in C/C++" }, { "code": null, "e": 24872, "s": 24860, "text": "fork() in C" }, { "code": null, "e": 24919, "s": 24872, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 24941, "s": 24919, "text": "Function Pointer in C" }, { "code": null, "e": 24958, "s": 24941, "text": "Substring in C++" }, { "code": null, "e": 25000, "s": 24958, "text": "Compiling a C program:- Behind the Scenes" }, { "code": null, "e": 25043, "s": 25000, "text": "Operator Precedence and Associativity in C" }, { "code": null, "e": 25078, "s": 25043, "text": "C | Structure & Union | Question 4" }, { "code": null, "e": 25109, "s": 25078, "text": "C | File Handling | Question 5" } ]
UDDI - Data Model
UDDI includes an XML Schema that describes the following data structures − businessEntity businessService bindingTemplate tModel publisherAssertion The business entity structure represents the provider of web services. Within the UDDI registry, this structure contains information about the company itself, including contact information, industry categories, business identifiers, and a list of services provided. Here is an example of a fictitious business's UDDI registry entry − <businessEntity businessKey = "uuid:C0E6D5A8-C446-4f01-99DA-70E212685A40" operator = "http://www.ibm.com" authorizedName = "John Doe"> <name>Acme Company</name> <description> We create cool Web services </description> <contacts> <contact useType = "general info"> <description>General Information</description> <personName>John Doe</personName> <phone>(123) 123-1234</phone> <email>[email protected]</email> </contact> </contacts> <businessServices> ... </businessServices> <identifierBag> <keyedReference tModelKey = "UUID:8609C81E-EE1F-4D5A-B202-3EB13AD01823" name = "D-U-N-S" value = "123456789" /> </identifierBag> <categoryBag> <keyedReference tModelKey = "UUID:C0B9FE13-179F-413D-8A5B-5004DB8E5BB2" name = "NAICS" value = "111336" /> </categoryBag> </businessEntity> The business service structure represents an individual web service provided by the business entity. Its description includes information on how to bind to the web service, what type of web service it is, and what taxonomical categories it belongs to. Here is an example of a business service structure for the Hello World web service. <businessService serviceKey = "uuid:D6F1B765-BDB3-4837-828D-8284301E5A2A" businessKey = "uuid:C0E6D5A8-C446-4f01-99DA-70E212685A40"> <name>Hello World Web Service</name> <description>A friendly Web service</description> <bindingTemplates> ... </bindingTemplates> <categoryBag /> </businessService> Notice the use of the Universally Unique Identifiers (UUIDs) in the businessKey and serviceKey attributes. Every business entity and business service is uniquely identified in all the UDDI registries through the UUID assigned by the registry when the information is first entered. Binding templates are the technical descriptions of the web services represented by the business service structure. A single business service may have multiple binding templates. The binding template represents the actual implementation of the web service. Here is an example of a binding template for Hello World. <bindingTemplate serviceKey = "uuid:D6F1B765-BDB3-4837-828D-8284301E5A2A" bindingKey = "uuid:C0E6D5A8-C446-4f01-99DA-70E212685A40"> <description>Hello World SOAP Binding</description> <accessPoint URLType = "http">http://localhost:8080</accessPoint> <tModelInstanceDetails> <tModelInstanceInfo tModelKey = "uuid:EB1B645F-CF2F-491f-811A-4868705F5904"> <instanceDetails> <overviewDoc> <description> references the description of the WSDL service definition </description> <overviewURL> http://localhost/helloworld.wsdl </overviewURL> </overviewDoc> </instanceDetails> </tModelInstanceInfo> </tModelInstanceDetails> </bindingTemplate> As a business service may have multiple binding templates, the service may specify different implementations of the same service, each bound to a different set of protocols or a different network address. tModel is the last core data type, but potentially the most difficult to grasp. tModel stands for technical model. tModel is a way of describing the various business, service, and template structures stored within the UDDI registry. Any abstract concept can be registered within the UDDI as a tModel. For instance, if you define a new WSDL port type, you can define a tModel that represents that port type within the UDDI. Then, you can specify that a given business service implements that port type by associating the tModel with one of that business service's binding templates. Here is an example of a tModel representing the Hello World Interface port type. <tModel tModelKey = "uuid:xyz987..." operator = "http://www.ibm.com" authorizedName = "John Doe"> <name>HelloWorldInterface Port Type</name> <description> An interface for a friendly Web service </description> <overviewDoc> <overviewURL> http://localhost/helloworld.wsdl </overviewURL> </overviewDoc> </tModel> This is a relationship structure putting into association two or more businessEntity structures according to a specific type of relationship, such as subsidiary or department. The publisherAssertion structure consists of the three elements: fromKey (the first businessKey), toKey (the second businessKey), and keyedReference. The keyedReference designates the asserted relationship type in terms of a keyName keyValue pair within a tModel, uniquely referenced by a tModelKey. <element name = "publisherAssertion" type = "uddi:publisherAssertion" /> <complexType name = "publisherAssertion"> <sequence> <element ref = "uddi:fromKey" /> <element ref = "uddi:toKey" /> <element ref = "uddi:keyedReference" />
[ { "code": null, "e": 2014, "s": 1939, "text": "UDDI includes an XML Schema that describes the following data structures −" }, { "code": null, "e": 2029, "s": 2014, "text": "businessEntity" }, { "code": null, "e": 2045, "s": 2029, "text": "businessService" }, { "code": null, "e": 2061, "s": 2045, "text": "bindingTemplate" }, { "code": null, "e": 2068, "s": 2061, "text": "tModel" }, { "code": null, "e": 2087, "s": 2068, "text": "publisherAssertion" }, { "code": null, "e": 2353, "s": 2087, "text": "The business entity structure represents the provider of web services. Within the UDDI registry, this structure contains information about the company itself, including contact information, industry categories, business identifiers, and a list of services provided." }, { "code": null, "e": 2421, "s": 2353, "text": "Here is an example of a fictitious business's UDDI registry entry −" }, { "code": null, "e": 3334, "s": 2421, "text": "<businessEntity businessKey = \"uuid:C0E6D5A8-C446-4f01-99DA-70E212685A40\"\n operator = \"http://www.ibm.com\" authorizedName = \"John Doe\">\n <name>Acme Company</name>\n <description>\n We create cool Web services\n </description>\n\t\n <contacts>\t\n <contact useType = \"general info\">\n <description>General Information</description>\n <personName>John Doe</personName>\n <phone>(123) 123-1234</phone>\n <email>[email protected]</email>\n </contact>\t\t\n </contacts>\n\t\n <businessServices>\n ...\n </businessServices>\n <identifierBag>\t\n <keyedReference tModelKey = \"UUID:8609C81E-EE1F-4D5A-B202-3EB13AD01823\" \n name = \"D-U-N-S\" value = \"123456789\" />\n </identifierBag>\n\t\n <categoryBag>\t\n <keyedReference tModelKey = \"UUID:C0B9FE13-179F-413D-8A5B-5004DB8E5BB2\" \n name = \"NAICS\" value = \"111336\" />\t\t\t\n </categoryBag>\t\t\n</businessEntity>" }, { "code": null, "e": 3586, "s": 3334, "text": "The business service structure represents an individual web service provided by the business entity. Its description includes information on how to bind to the web service, what type of web service it is, and what taxonomical categories it belongs to." }, { "code": null, "e": 3670, "s": 3586, "text": "Here is an example of a business service structure for the Hello World web service." }, { "code": null, "e": 3992, "s": 3670, "text": "<businessService serviceKey = \"uuid:D6F1B765-BDB3-4837-828D-8284301E5A2A\"\n businessKey = \"uuid:C0E6D5A8-C446-4f01-99DA-70E212685A40\">\n <name>Hello World Web Service</name>\n <description>A friendly Web service</description>\n <bindingTemplates>\n ...\n </bindingTemplates>\n <categoryBag />\n</businessService>" }, { "code": null, "e": 4273, "s": 3992, "text": "Notice the use of the Universally Unique Identifiers (UUIDs) in the businessKey and serviceKey attributes. Every business entity and business service is uniquely identified in all the UDDI registries through the UUID assigned by the registry when the information is first entered." }, { "code": null, "e": 4530, "s": 4273, "text": "Binding templates are the technical descriptions of the web services represented by the business service structure. A single business service may have multiple binding templates. The binding template represents the actual implementation of the web service." }, { "code": null, "e": 4588, "s": 4530, "text": "Here is an example of a binding template for Hello World." }, { "code": null, "e": 5405, "s": 4588, "text": "<bindingTemplate serviceKey = \"uuid:D6F1B765-BDB3-4837-828D-8284301E5A2A\"\n bindingKey = \"uuid:C0E6D5A8-C446-4f01-99DA-70E212685A40\">\n <description>Hello World SOAP Binding</description>\n <accessPoint URLType = \"http\">http://localhost:8080</accessPoint>\n \n <tModelInstanceDetails>\n <tModelInstanceInfo tModelKey = \"uuid:EB1B645F-CF2F-491f-811A-4868705F5904\">\n <instanceDetails>\n <overviewDoc>\n <description>\n references the description of the WSDL service definition\n </description>\n \n <overviewURL>\n http://localhost/helloworld.wsdl\n </overviewURL>\n </overviewDoc>\n </instanceDetails>\n </tModelInstanceInfo>\n </tModelInstanceDetails>\n</bindingTemplate>" }, { "code": null, "e": 5610, "s": 5405, "text": "As a business service may have multiple binding templates, the service may specify different implementations of the same service, each bound to a different set of protocols or a different network address." }, { "code": null, "e": 5725, "s": 5610, "text": "tModel is the last core data type, but potentially the most difficult to grasp. tModel stands for technical model." }, { "code": null, "e": 6192, "s": 5725, "text": "tModel is a way of describing the various business, service, and template structures stored within the UDDI registry. Any abstract concept can be registered within the UDDI as a tModel. For instance, if you define a new WSDL port type, you can define a tModel that represents that port type within the UDDI. Then, you can specify that a given business service implements that port type by associating the tModel with one of that business service's binding templates." }, { "code": null, "e": 6273, "s": 6192, "text": "Here is an example of a tModel representing the Hello World Interface port type." }, { "code": null, "e": 6632, "s": 6273, "text": "<tModel tModelKey = \"uuid:xyz987...\" operator = \"http://www.ibm.com\" \n authorizedName = \"John Doe\">\n <name>HelloWorldInterface Port Type</name>\n <description>\n An interface for a friendly Web service\n </description>\n\t\n <overviewDoc>\n <overviewURL>\n http://localhost/helloworld.wsdl\n </overviewURL>\n </overviewDoc>\n</tModel>" }, { "code": null, "e": 6808, "s": 6632, "text": "This is a relationship structure putting into association two or more businessEntity structures according to a specific type of relationship, such as subsidiary or department." }, { "code": null, "e": 6958, "s": 6808, "text": "The publisherAssertion structure consists of the three elements: fromKey (the first businessKey), toKey (the second businessKey), and keyedReference." }, { "code": null, "e": 7108, "s": 6958, "text": "The keyedReference designates the asserted relationship type in terms of a keyName keyValue pair within a tModel, uniquely referenced by a tModelKey." } ]
Sum and Product of digits in a number that divide the number
22 Apr, 2021 Given a positive integer N. The task is to find sum and product of digits of the number which evenly divides the number n.Examples: Input: N = 12 Output: Sum = 3, product = 2 1 and 2 divide 12. So, their sum is 3 and product is 2. Input: N = 1012 Output: Sum = 4, product = 2 1, 1 and 2 divide 1012. Approach: The idea is to find the each digit of the number n by modulus 10 and then check whether it divides n or not. Accordingly, add it to the sum and multiply it with the product. Notice that the digit can be 0, so take care of that case.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Print the sum and product of digits// that divides the number.void countDigit(int n){ int temp = n, sum = 0, product = 1; while (temp != 0) { // Fetching each digit of the number int d = temp % 10; temp /= 10; // Checking if digit is greater than 0 // and can divides n. if (d > 0 && n % d == 0) { sum += d; product *= d; } } cout << "Sum = " << sum; cout << "\nProduct = " << product;} // Driver codeint main(){ int n = 1012; countDigit(n); return 0;} // Java implementation of the// above approachimport java.lang.*;import java.util.*; class GFG{// Print the sum and product of// digits that divides the number.static void countDigit(int n){ int temp = n, sum = 0, product = 1; while (temp != 0) { // Fetching each digit of // the number int d = temp % 10; temp /= 10; // Checking if digit is greater // than 0 and can divides n. if (d > 0 && n % d == 0) { sum += d; product *= d; } } System.out.print("Sum = " + sum); System.out.print("\nProduct = " + product);} // Driver codepublic static void main(String args[]){ int n = 1012; countDigit(n);}} // This code is contributed// by Akanksha Rai(Abby_akku) # Python3 implementation of the above approach # Print the sum and product of digits# that divides the number.def countDigit(n): temp = n sum = 0 product = 1 while(temp != 0): # Fetching each digit of the number d = temp % 10 temp //= 10 # Checking if digit is greater # than 0 and can divides n. if(d > 0 and n % d == 0): sum += d product *= d print("Sum =", sum) print("Product =", product) # Driver codeif __name__=='__main__': n = 1012 countDigit(n) # This code is contributed# by Kirti_Mangal // C# implementation of the// above approachusing System; class GFG{// Print the sum and product of// digits that divides the number.static void countDigit(int n){ int temp = n, sum = 0, product = 1; while (temp != 0) { // Fetching each digit of // the number int d = temp % 10; temp /= 10; // Checking if digit is greater // than 0 and can divides n. if (d > 0 && n % d == 0) { sum += d; product *= d; } } Console.Write("Sum = " + sum); Console.Write("\nProduct = " + product);} // Driver codepublic static void Main(){ int n = 1012; countDigit(n);}} // This code is contributed// by Akanksha Rai(Abby_akku) <?php// PHP implementation of the above approach // Print the sum and product of digits// that divides the number.function countDigit($n){ $temp = $n; $sum = 0; $product = 1; while ($temp != 0) { // Fetching each digit of the number $d = $temp % 10; $temp =(int)($temp/10); // Checking if digit is greater than 0 // and can divides n. if ($d > 0 && $n % $d == 0) { $sum += $d; $product *= $d; } } echo "Sum = ".$sum; echo "\nProduct = ".$product;} // Driver code $n = 1012; countDigit($n); // This code is contributed by mits?> <script>// java script implementation of the above approach // Print the sum and product of digits// that divides the number.function countDigit(n){ let temp = n; let sum = 0; let product = 1; while (temp != 0) { // Fetching each digit of the number let d = temp % 10; temp =parseInt(temp/10); // Checking if digit is greater than 0 // and can divides n. if (d > 0 && n % d == 0) { sum += d; product *= d; } } document.write( "Sum = "+sum); document.write( "<br>Product = "+product);} // Driver code let n = 1012; countDigit(n); // This code is contributed by Gottumukkala Bobby</script> Sum = 4 Product = 2 Kirti_Mangal Akanksha_Rai Mithun Kumar gottumukkalabobby Number Divisibility number-digits Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Merge two sorted arrays with O(1) extra space Program to print prime numbers from 1 to N. Find next greater number with same set of digits Segment Tree | Set 1 (Sum of given range) Check if a number is Palindrome Count ways to reach the n'th stair Fizz Buzz Implementation Count all possible paths from top left to bottom right of a mXn matrix Product of Array except itself
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2021" }, { "code": null, "e": 162, "s": 28, "text": "Given a positive integer N. The task is to find sum and product of digits of the number which evenly divides the number n.Examples: " }, { "code": null, "e": 331, "s": 162, "text": "Input: N = 12\nOutput: Sum = 3, product = 2\n1 and 2 divide 12. So, their sum is 3 and product is 2.\n\nInput: N = 1012\nOutput: Sum = 4, product = 2\n1, 1 and 2 divide 1012." }, { "code": null, "e": 628, "s": 333, "text": "Approach: The idea is to find the each digit of the number n by modulus 10 and then check whether it divides n or not. Accordingly, add it to the sum and multiply it with the product. Notice that the digit can be 0, so take care of that case.Below is the implementation of the above approach: " }, { "code": null, "e": 632, "s": 628, "text": "C++" }, { "code": null, "e": 637, "s": 632, "text": "Java" }, { "code": null, "e": 645, "s": 637, "text": "Python3" }, { "code": null, "e": 648, "s": 645, "text": "C#" }, { "code": null, "e": 652, "s": 648, "text": "PHP" }, { "code": null, "e": 663, "s": 652, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Print the sum and product of digits// that divides the number.void countDigit(int n){ int temp = n, sum = 0, product = 1; while (temp != 0) { // Fetching each digit of the number int d = temp % 10; temp /= 10; // Checking if digit is greater than 0 // and can divides n. if (d > 0 && n % d == 0) { sum += d; product *= d; } } cout << \"Sum = \" << sum; cout << \"\\nProduct = \" << product;} // Driver codeint main(){ int n = 1012; countDigit(n); return 0;}", "e": 1307, "s": 663, "text": null }, { "code": "// Java implementation of the// above approachimport java.lang.*;import java.util.*; class GFG{// Print the sum and product of// digits that divides the number.static void countDigit(int n){ int temp = n, sum = 0, product = 1; while (temp != 0) { // Fetching each digit of // the number int d = temp % 10; temp /= 10; // Checking if digit is greater // than 0 and can divides n. if (d > 0 && n % d == 0) { sum += d; product *= d; } } System.out.print(\"Sum = \" + sum); System.out.print(\"\\nProduct = \" + product);} // Driver codepublic static void main(String args[]){ int n = 1012; countDigit(n);}} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 2075, "s": 1307, "text": null }, { "code": "# Python3 implementation of the above approach # Print the sum and product of digits# that divides the number.def countDigit(n): temp = n sum = 0 product = 1 while(temp != 0): # Fetching each digit of the number d = temp % 10 temp //= 10 # Checking if digit is greater # than 0 and can divides n. if(d > 0 and n % d == 0): sum += d product *= d print(\"Sum =\", sum) print(\"Product =\", product) # Driver codeif __name__=='__main__': n = 1012 countDigit(n) # This code is contributed# by Kirti_Mangal ", "e": 2701, "s": 2075, "text": null }, { "code": "// C# implementation of the// above approachusing System; class GFG{// Print the sum and product of// digits that divides the number.static void countDigit(int n){ int temp = n, sum = 0, product = 1; while (temp != 0) { // Fetching each digit of // the number int d = temp % 10; temp /= 10; // Checking if digit is greater // than 0 and can divides n. if (d > 0 && n % d == 0) { sum += d; product *= d; } } Console.Write(\"Sum = \" + sum); Console.Write(\"\\nProduct = \" + product);} // Driver codepublic static void Main(){ int n = 1012; countDigit(n);}} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 3423, "s": 2701, "text": null }, { "code": "<?php// PHP implementation of the above approach // Print the sum and product of digits// that divides the number.function countDigit($n){ $temp = $n; $sum = 0; $product = 1; while ($temp != 0) { // Fetching each digit of the number $d = $temp % 10; $temp =(int)($temp/10); // Checking if digit is greater than 0 // and can divides n. if ($d > 0 && $n % $d == 0) { $sum += $d; $product *= $d; } } echo \"Sum = \".$sum; echo \"\\nProduct = \".$product;} // Driver code $n = 1012; countDigit($n); // This code is contributed by mits?>", "e": 4058, "s": 3423, "text": null }, { "code": "<script>// java script implementation of the above approach // Print the sum and product of digits// that divides the number.function countDigit(n){ let temp = n; let sum = 0; let product = 1; while (temp != 0) { // Fetching each digit of the number let d = temp % 10; temp =parseInt(temp/10); // Checking if digit is greater than 0 // and can divides n. if (d > 0 && n % d == 0) { sum += d; product *= d; } } document.write( \"Sum = \"+sum); document.write( \"<br>Product = \"+product);} // Driver code let n = 1012; countDigit(n); // This code is contributed by Gottumukkala Bobby</script>", "e": 4754, "s": 4058, "text": null }, { "code": null, "e": 4774, "s": 4754, "text": "Sum = 4\nProduct = 2" }, { "code": null, "e": 4789, "s": 4776, "text": "Kirti_Mangal" }, { "code": null, "e": 4802, "s": 4789, "text": "Akanksha_Rai" }, { "code": null, "e": 4815, "s": 4802, "text": "Mithun Kumar" }, { "code": null, "e": 4833, "s": 4815, "text": "gottumukkalabobby" }, { "code": null, "e": 4853, "s": 4833, "text": "Number Divisibility" }, { "code": null, "e": 4867, "s": 4853, "text": "number-digits" }, { "code": null, "e": 4880, "s": 4867, "text": "Mathematical" }, { "code": null, "e": 4893, "s": 4880, "text": "Mathematical" }, { "code": null, "e": 4991, "s": 4893, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5023, "s": 4991, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 5069, "s": 5023, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 5113, "s": 5069, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 5162, "s": 5113, "text": "Find next greater number with same set of digits" }, { "code": null, "e": 5204, "s": 5162, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 5236, "s": 5204, "text": "Check if a number is Palindrome" }, { "code": null, "e": 5271, "s": 5236, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 5296, "s": 5271, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 5367, "s": 5296, "text": "Count all possible paths from top left to bottom right of a mXn matrix" } ]
Print given sentence into its equivalent ASCII form
07 Jul, 2022 Given a string containing words forming a sentence(belonging to english language). The task is to output the equivalent ASCII sentence of the input sentence. ASCII form of a sentence is the conversion of each of the character of the input string and aligning them in position of characters present in the stringExamples: Input : hello, world! Output : ASCII Sentence: 104101108108111443211911111410810033 Input : GeeksforGeeks Output : ASCII Sentence: 7110110110711510211111471101101107115 Explanation:To complete the task, we need to convert each character into it’s equivalent ASCII value. We perform the following steps to achieve the equivalent ASCII form of the given sentence- Iterate over the length of the complete sentence/string Take each character of the sentence at a time, subtract NULL character to it and explicitly typecast the result Print the result Following the above steps, we can achieve the equivalent ASCII form of a given sentence/string. C++ Java Python3 C# PHP Javascript // C++ implementation for converting// a string into it's ASCII equivalent sentence#include <bits/stdc++.h>using namespace std; // Function to compute the ASCII value of each// character one by onevoid ASCIISentence(std::string str){ int l = str.length(); int convert; for (int i = 0; i < l; i++) { convert = str[i] - NULL; cout << convert; }} // Driver functionint main(){ string str = "GeeksforGeeks"; cout << "ASCII Sentence:" << std::endl; ASCIISentence(str); return 0;} // Java implementation for converting// a string into it's ASCII equivalent sentenceimport java.util.*;import java.lang.*; class GeeksforGeeks { // Function to compute the ASCII value of each // character one by one static void ASCIISentence(String str) { int l = str.length(); int convert; for (int i = 0; i < l; i++) { convert = str.charAt(i); System.out.print(convert); } } // Driver function public static void main(String args[]) { String str = "GeeksforGeeks"; System.out.println("ASCII Sentence:"); ASCIISentence(str); }} # Python3 implementation for# converting a string into it's# ASCII equivalent sentence # Function to compute the ASCII# value of each character one by onedef ASCIISentence( str ): for i in str: print(ord(i), end = '') print('\n', end = '') # Driver codestr = "GeeksforGeeks"print("ASCII Sentence:")ASCIISentence(str) # This code is contributed by "Sharad_Bhardwaj". // C# implementation for converting// a string into it's ASCII equivalent sentenceusing System; class GeeksforGeeks { // Function to compute the ASCII value // of each character one by one static void ASCIISentence(string str) { int l = str.Length; int convert; for (int i = 0; i < l; i++) { convert = str[i]; Console.Write(convert); } } // Driver function public static void Main() { string str = "GeeksforGeeks"; Console.WriteLine("ASCII Sentence:"); ASCIISentence(str); }} // This code is contributed by vt_m. <?php // PHP implementation for converting a // string into it's ASCII equivalent sentence // Function to compute the ASCII// value of each character one by onefunction ASCIISentence($str){ for ($i = 0; $i< strlen($str); $i++) echo ord($str[$i]);} // Driver code$str = "GeeksforGeeks";echo "ASCII Sentence:"."\n";ASCIISentence($str); // This code is contributed // by ChitraNayal?> <script>// Javascript implementation for converting// a string into it's ASCII equivalent sentence // Function to compute the ASCII value of each // character one by one function ASCIISentence(str) { let l = str.length; let convert; for (let i = 0; i < l; i++) { convert = str[i].charCodeAt(0); document.write(convert); } } // Driver function let str = "GeeksforGeeks"; document.write("ASCII Sentence:<br>"); ASCIISentence(str); // This code is contributed by rag2127</script> 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. ASCII Sentence: 7110110110711510211111471101101107115 Time Complexity: O(N), as we are using a loop to traverse N times. Where N is the length of the string. Auxiliary Space: O(N), as we are using extra space for convert string.Application: Sentence in english language could be encoded/decoded into this form e.g. convert a sentence into it’s equivalent ASCII form and add 5 to each digit and send it from encoder’s side. Later, decoder can subtract 5 from each digit and decode it into it’s original form. This way only the sender and the receiver would be able to decode the sentence. ASCII form is also used to transfer data from one computer to another. ukasp rag2127 simmytarika5 rohitsingh57 ASCII Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 String Coding Problems for Interviews What is Data Structure: Types, Classifications and Applications Print all the duplicates in the input string Print all subsequences of a string A Program to check if strings are rotations of each other or not String class in Java | Set 1 Find if a string is interleaved of two other strings | DP-33 Remove first and last character of a string in Java Check if an URL is valid or not using Regular Expression Find the smallest window in a string containing all characters of another string
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jul, 2022" }, { "code": null, "e": 351, "s": 28, "text": "Given a string containing words forming a sentence(belonging to english language). The task is to output the equivalent ASCII sentence of the input sentence. ASCII form of a sentence is the conversion of each of the character of the input string and aligning them in position of characters present in the stringExamples: " }, { "code": null, "e": 539, "s": 351, "text": "Input : hello, world!\nOutput : ASCII Sentence:\n 104101108108111443211911111410810033\n\nInput : GeeksforGeeks\nOutput : ASCII Sentence:\n 7110110110711510211111471101101107115" }, { "code": null, "e": 736, "s": 541, "text": "Explanation:To complete the task, we need to convert each character into it’s equivalent ASCII value. We perform the following steps to achieve the equivalent ASCII form of the given sentence- " }, { "code": null, "e": 792, "s": 736, "text": "Iterate over the length of the complete sentence/string" }, { "code": null, "e": 904, "s": 792, "text": "Take each character of the sentence at a time, subtract NULL character to it and explicitly typecast the result" }, { "code": null, "e": 921, "s": 904, "text": "Print the result" }, { "code": null, "e": 1018, "s": 921, "text": "Following the above steps, we can achieve the equivalent ASCII form of a given sentence/string. " }, { "code": null, "e": 1022, "s": 1018, "text": "C++" }, { "code": null, "e": 1027, "s": 1022, "text": "Java" }, { "code": null, "e": 1035, "s": 1027, "text": "Python3" }, { "code": null, "e": 1038, "s": 1035, "text": "C#" }, { "code": null, "e": 1042, "s": 1038, "text": "PHP" }, { "code": null, "e": 1053, "s": 1042, "text": "Javascript" }, { "code": "// C++ implementation for converting// a string into it's ASCII equivalent sentence#include <bits/stdc++.h>using namespace std; // Function to compute the ASCII value of each// character one by onevoid ASCIISentence(std::string str){ int l = str.length(); int convert; for (int i = 0; i < l; i++) { convert = str[i] - NULL; cout << convert; }} // Driver functionint main(){ string str = \"GeeksforGeeks\"; cout << \"ASCII Sentence:\" << std::endl; ASCIISentence(str); return 0;}", "e": 1568, "s": 1053, "text": null }, { "code": "// Java implementation for converting// a string into it's ASCII equivalent sentenceimport java.util.*;import java.lang.*; class GeeksforGeeks { // Function to compute the ASCII value of each // character one by one static void ASCIISentence(String str) { int l = str.length(); int convert; for (int i = 0; i < l; i++) { convert = str.charAt(i); System.out.print(convert); } } // Driver function public static void main(String args[]) { String str = \"GeeksforGeeks\"; System.out.println(\"ASCII Sentence:\"); ASCIISentence(str); }}", "e": 2200, "s": 1568, "text": null }, { "code": "# Python3 implementation for# converting a string into it's# ASCII equivalent sentence # Function to compute the ASCII# value of each character one by onedef ASCIISentence( str ): for i in str: print(ord(i), end = '') print('\\n', end = '') # Driver codestr = \"GeeksforGeeks\"print(\"ASCII Sentence:\")ASCIISentence(str) # This code is contributed by \"Sharad_Bhardwaj\".", "e": 2592, "s": 2200, "text": null }, { "code": "// C# implementation for converting// a string into it's ASCII equivalent sentenceusing System; class GeeksforGeeks { // Function to compute the ASCII value // of each character one by one static void ASCIISentence(string str) { int l = str.Length; int convert; for (int i = 0; i < l; i++) { convert = str[i]; Console.Write(convert); } } // Driver function public static void Main() { string str = \"GeeksforGeeks\"; Console.WriteLine(\"ASCII Sentence:\"); ASCIISentence(str); }} // This code is contributed by vt_m.", "e": 3217, "s": 2592, "text": null }, { "code": "<?php // PHP implementation for converting a // string into it's ASCII equivalent sentence // Function to compute the ASCII// value of each character one by onefunction ASCIISentence($str){ for ($i = 0; $i< strlen($str); $i++) echo ord($str[$i]);} // Driver code$str = \"GeeksforGeeks\";echo \"ASCII Sentence:\".\"\\n\";ASCIISentence($str); // This code is contributed // by ChitraNayal?>", "e": 3616, "s": 3217, "text": null }, { "code": "<script>// Javascript implementation for converting// a string into it's ASCII equivalent sentence // Function to compute the ASCII value of each // character one by one function ASCIISentence(str) { let l = str.length; let convert; for (let i = 0; i < l; i++) { convert = str[i].charCodeAt(0); document.write(convert); } } // Driver function let str = \"GeeksforGeeks\"; document.write(\"ASCII Sentence:<br>\"); ASCIISentence(str); // This code is contributed by rag2127</script>", "e": 4195, "s": 3616, "text": null }, { "code": null, "e": 4205, "s": 4195, "text": "Output: " }, { "code": null, "e": 4214, "s": 4205, "text": "Chapters" }, { "code": null, "e": 4241, "s": 4214, "text": "descriptions off, selected" }, { "code": null, "e": 4291, "s": 4241, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 4314, "s": 4291, "text": "captions off, selected" }, { "code": null, "e": 4322, "s": 4314, "text": "English" }, { "code": null, "e": 4346, "s": 4322, "text": "This is a modal window." }, { "code": null, "e": 4415, "s": 4346, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 4437, "s": 4415, "text": "End of dialog window." }, { "code": null, "e": 4491, "s": 4437, "text": "ASCII Sentence:\n7110110110711510211111471101101107115" }, { "code": null, "e": 4595, "s": 4491, "text": "Time Complexity: O(N), as we are using a loop to traverse N times. Where N is the length of the string." }, { "code": null, "e": 4679, "s": 4595, "text": "Auxiliary Space: O(N), as we are using extra space for convert string.Application: " }, { "code": null, "e": 5026, "s": 4679, "text": "Sentence in english language could be encoded/decoded into this form e.g. convert a sentence into it’s equivalent ASCII form and add 5 to each digit and send it from encoder’s side. Later, decoder can subtract 5 from each digit and decode it into it’s original form. This way only the sender and the receiver would be able to decode the sentence." }, { "code": null, "e": 5097, "s": 5026, "text": "ASCII form is also used to transfer data from one computer to another." }, { "code": null, "e": 5105, "s": 5099, "text": "ukasp" }, { "code": null, "e": 5113, "s": 5105, "text": "rag2127" }, { "code": null, "e": 5126, "s": 5113, "text": "simmytarika5" }, { "code": null, "e": 5139, "s": 5126, "text": "rohitsingh57" }, { "code": null, "e": 5145, "s": 5139, "text": "ASCII" }, { "code": null, "e": 5153, "s": 5145, "text": "Strings" }, { "code": null, "e": 5161, "s": 5153, "text": "Strings" }, { "code": null, "e": 5259, "s": 5161, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5304, "s": 5259, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 5368, "s": 5304, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 5413, "s": 5368, "text": "Print all the duplicates in the input string" }, { "code": null, "e": 5448, "s": 5413, "text": "Print all subsequences of a string" }, { "code": null, "e": 5513, "s": 5448, "text": "A Program to check if strings are rotations of each other or not" }, { "code": null, "e": 5542, "s": 5513, "text": "String class in Java | Set 1" }, { "code": null, "e": 5603, "s": 5542, "text": "Find if a string is interleaved of two other strings | DP-33" }, { "code": null, "e": 5655, "s": 5603, "text": "Remove first and last character of a string in Java" }, { "code": null, "e": 5712, "s": 5655, "text": "Check if an URL is valid or not using Regular Expression" } ]
HTML | DOM onsubmit Event
08 Mar, 2022 The onsubmit event in HTML DOM occurs after submission of a form. The form tag supports this event.Supported HTML Tags: <form> Syntax: In HTML: <element onsubmit="Script"> In JavaScript: object.onsubmit = function(){myScript}; In JavaScript, using the addEventListener() method: object.addEventListener("submit", myScript); Example: Using JavaScript html <!DOCTYPE html><html> <head> <title> HTML DOM onsubmit Event </title></head> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <h2>HTML DOM onsubmit Event</h2> <form id="formID" action="#"> Enter name: <input type="text" name="fname"> <input type="submit" value="Submit"> </form> </center> <script> document.getElementById("formID").onsubmit = function() {GFGfun()}; function GFGfun() { alert("form submitted"); } </script> </body> </html> Output: Before: After: Example: Using the addEventListener() method html <!DOCTYPE html><html> <head> <title> HTML DOM onsubmit Event </title></head> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <h2>HTML DOM onsubmit Event</h2> <form id="formID" action="#"> Enter name: <input type="text" name="fname"> <input type="submit" value="Submit"> </form> </center> <script> document.getElementById( "FormID").addEventListener("submit", GFGfun); function GFGfun() { alert("form submitted"); } </script> </body> </html> Output: Before: After: Supported Browsers: The browsers supported by HTML DOM onsubmit Event are listed below: Google Chrome Internet Explorer Firefox Apple Safari Opera ManasChhabra2 chhabradhanvi HTML-DOM 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 Design a Tribute Page using HTML & CSS Types of CSS (Cascading Style Sheet) 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": "\n08 Mar, 2022" }, { "code": null, "e": 149, "s": 28, "text": "The onsubmit event in HTML DOM occurs after submission of a form. The form tag supports this event.Supported HTML Tags: " }, { "code": null, "e": 156, "s": 149, "text": "<form>" }, { "code": null, "e": 166, "s": 156, "text": "Syntax: " }, { "code": null, "e": 177, "s": 166, "text": "In HTML: " }, { "code": null, "e": 205, "s": 177, "text": "<element onsubmit=\"Script\">" }, { "code": null, "e": 222, "s": 205, "text": "In JavaScript: " }, { "code": null, "e": 262, "s": 222, "text": "object.onsubmit = function(){myScript};" }, { "code": null, "e": 316, "s": 262, "text": "In JavaScript, using the addEventListener() method: " }, { "code": null, "e": 361, "s": 316, "text": "object.addEventListener(\"submit\", myScript);" }, { "code": null, "e": 389, "s": 361, "text": "Example: Using JavaScript " }, { "code": null, "e": 394, "s": 389, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML DOM onsubmit Event </title></head> <body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>HTML DOM onsubmit Event</h2> <form id=\"formID\" action=\"#\"> Enter name: <input type=\"text\" name=\"fname\"> <input type=\"submit\" value=\"Submit\"> </form> </center> <script> document.getElementById(\"formID\").onsubmit = function() {GFGfun()}; function GFGfun() { alert(\"form submitted\"); } </script> </body> </html>", "e": 972, "s": 394, "text": null }, { "code": null, "e": 990, "s": 972, "text": "Output: Before: " }, { "code": null, "e": 999, "s": 990, "text": "After: " }, { "code": null, "e": 1046, "s": 999, "text": "Example: Using the addEventListener() method " }, { "code": null, "e": 1051, "s": 1046, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML DOM onsubmit Event </title></head> <body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>HTML DOM onsubmit Event</h2> <form id=\"formID\" action=\"#\"> Enter name: <input type=\"text\" name=\"fname\"> <input type=\"submit\" value=\"Submit\"> </form> </center> <script> document.getElementById( \"FormID\").addEventListener(\"submit\", GFGfun); function GFGfun() { alert(\"form submitted\"); } </script> </body> </html>", "e": 1630, "s": 1051, "text": null }, { "code": null, "e": 1648, "s": 1630, "text": "Output: Before: " }, { "code": null, "e": 1657, "s": 1648, "text": "After: " }, { "code": null, "e": 1747, "s": 1657, "text": "Supported Browsers: The browsers supported by HTML DOM onsubmit Event are listed below: " }, { "code": null, "e": 1761, "s": 1747, "text": "Google Chrome" }, { "code": null, "e": 1779, "s": 1761, "text": "Internet Explorer" }, { "code": null, "e": 1787, "s": 1779, "text": "Firefox" }, { "code": null, "e": 1800, "s": 1787, "text": "Apple Safari" }, { "code": null, "e": 1806, "s": 1800, "text": "Opera" }, { "code": null, "e": 1822, "s": 1808, "text": "ManasChhabra2" }, { "code": null, "e": 1836, "s": 1822, "text": "chhabradhanvi" }, { "code": null, "e": 1845, "s": 1836, "text": "HTML-DOM" }, { "code": null, "e": 1850, "s": 1845, "text": "HTML" }, { "code": null, "e": 1867, "s": 1850, "text": "Web Technologies" }, { "code": null, "e": 1872, "s": 1867, "text": "HTML" }, { "code": null, "e": 1970, "s": 1872, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2018, "s": 1970, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 2042, "s": 2018, "text": "REST API (Introduction)" }, { "code": null, "e": 2092, "s": 2042, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 2131, "s": 2092, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 2168, "s": 2131, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 2201, "s": 2168, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2262, "s": 2201, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2305, "s": 2262, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2377, "s": 2305, "text": "Differences between Functional Components and Class Components in React" } ]
How to instantiate Struct Pointer Address Operator in Golang?
20 Aug, 2021 As pointers are the special variables that are used to store the memory address of another variable whereas, the struct is user-defined data type that consists of different types. A struct is mainly a holder for all other data types. By using a pointer to a struct we can easily manipulate/access the data assigned to a struct. To use pointer to a struct we use “&” i.e, address operator. In Go lang, by using pointers to a struct we can access the fields of a struct without de-referencing them explicitly. Example: Here we have defined one struct names as “shape” and we are passing the values to the field of this struct. Also, we are printing the value of the struct using pointers. Go // Golang program to show how to instantiate// Struct Pointer Address Operatorpackage main import "fmt" type shape struct { length int breadth int color string} func main() { // Passing all the parameters var shape1 = &shape{10, 20, "Green"} // Printing the value struct is holding fmt.Println(shape1) // Passing only length and color value var shape2 = &shape{} shape2.length = 10 shape2.color = "Red" // Printing the value struct is holding fmt.Println(shape2) // Printing the length stored in the struct fmt.Println(shape2.length) // Printing the color stored in the struct fmt.Println(shape2.color) // Passing only address of the struct var shape3 = &shape{} // Passing the value through a pointer // in breadth field of the variable // holding the struct address (*shape3).breadth = 10 // Passing the value through a pointer // in color field of the variable // holding the struct address (*shape3).color = "Blue" // Printing the values stored // in the struct using pointer fmt.Println(shape3)} Output: &{10 20 Green} &{10 0 Red} 10 Red &{0 10 Blue} singghakshay Golang-Pointers Golang-Program Picked Go Language Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Aug, 2021" }, { "code": null, "e": 536, "s": 28, "text": "As pointers are the special variables that are used to store the memory address of another variable whereas, the struct is user-defined data type that consists of different types. A struct is mainly a holder for all other data types. By using a pointer to a struct we can easily manipulate/access the data assigned to a struct. To use pointer to a struct we use “&” i.e, address operator. In Go lang, by using pointers to a struct we can access the fields of a struct without de-referencing them explicitly." }, { "code": null, "e": 715, "s": 536, "text": "Example: Here we have defined one struct names as “shape” and we are passing the values to the field of this struct. Also, we are printing the value of the struct using pointers." }, { "code": null, "e": 718, "s": 715, "text": "Go" }, { "code": "// Golang program to show how to instantiate// Struct Pointer Address Operatorpackage main import \"fmt\" type shape struct { length int breadth int color string} func main() { // Passing all the parameters var shape1 = &shape{10, 20, \"Green\"} // Printing the value struct is holding fmt.Println(shape1) // Passing only length and color value var shape2 = &shape{} shape2.length = 10 shape2.color = \"Red\" // Printing the value struct is holding fmt.Println(shape2) // Printing the length stored in the struct fmt.Println(shape2.length) // Printing the color stored in the struct fmt.Println(shape2.color) // Passing only address of the struct var shape3 = &shape{} // Passing the value through a pointer // in breadth field of the variable // holding the struct address (*shape3).breadth = 10 // Passing the value through a pointer // in color field of the variable // holding the struct address (*shape3).color = \"Blue\" // Printing the values stored // in the struct using pointer fmt.Println(shape3)}", "e": 1822, "s": 718, "text": null }, { "code": null, "e": 1830, "s": 1822, "text": "Output:" }, { "code": null, "e": 1877, "s": 1830, "text": "&{10 20 Green}\n&{10 0 Red}\n10\nRed\n&{0 10 Blue}" }, { "code": null, "e": 1892, "s": 1879, "text": "singghakshay" }, { "code": null, "e": 1908, "s": 1892, "text": "Golang-Pointers" }, { "code": null, "e": 1923, "s": 1908, "text": "Golang-Program" }, { "code": null, "e": 1930, "s": 1923, "text": "Picked" }, { "code": null, "e": 1942, "s": 1930, "text": "Go Language" }, { "code": null, "e": 1958, "s": 1942, "text": "Write From Home" } ]
What is global installation of dependencies in Node.js ?
29 Jul, 2021 The global installation of dependencies in Node.js is putting global packages in a single place in the system exactly where it depends on your setup, regardless of where you run the command npm install -g <package-name> to install dependencies. Installing the local dependencies means the module will be available only for a project you installed in the same directory. Global installing dependencies puts the module into your Node. js path, which is Operating System dependent) and will be accessible from any project without the need to install it separately for each project while doing the setup. They allow us to use the packaging as a tool anywhere on the local computer. Prerequisites: Node JS: Node.js is an open-source and cross-platform runtime environment built on Chrome’s V8 JavaScript engine for executing JavaScript code outside of a browser. You need to recollect that NodeJS isn’t a framework, and it’s not a programming language. React JS: React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It’s ‘V’ in MVC. ReactJS is an open-source, component-based front-end library responsible only for the view layer of the application. Syntax: run npm install -g <package-name> Where g denotes a global mode of a variable. Application: It is used to install packages globally in the system while making Node projects. Path of Global Packages in the system: Global modules are installed in the standard system in root location in the system directory /usr/local/lib/node_modules project directory. Command to print the location on your system where all the global modules are installed. npm root -g Output: C:\Users\Pallavi\AppData\Roaming\npm\node_modules Example to illustrate how to install the package globally in the system. Write this command in the console. npm install -g mit-license-generator Output: How to check which packages are installed globally in the system. npm list -g The output will be: Advantages: We do not need to install a module every time when installed globally. It takes less memory as only one copy is installed. We can make .js scripts and run them anywhere without having a node_modules folder in the same directory when packages are installed globally. Disadvantages: when we are running a Node app other than a local machine, then it will give an error because it needs packages in package.json that i.e, local packages. Globally deployed packages cannot be imported using require() in Node application directly. rajeev0719singh singghakshay Node.js-Basics NodeJS-Questions Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. JWT Authentication with Node.js Installation of Node.js on Windows 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": 54, "s": 26, "text": "\n29 Jul, 2021" }, { "code": null, "e": 299, "s": 54, "text": "The global installation of dependencies in Node.js is putting global packages in a single place in the system exactly where it depends on your setup, regardless of where you run the command npm install -g <package-name> to install dependencies." }, { "code": null, "e": 424, "s": 299, "text": "Installing the local dependencies means the module will be available only for a project you installed in the same directory." }, { "code": null, "e": 655, "s": 424, "text": "Global installing dependencies puts the module into your Node. js path, which is Operating System dependent) and will be accessible from any project without the need to install it separately for each project while doing the setup." }, { "code": null, "e": 732, "s": 655, "text": "They allow us to use the packaging as a tool anywhere on the local computer." }, { "code": null, "e": 747, "s": 732, "text": "Prerequisites:" }, { "code": null, "e": 1002, "s": 747, "text": "Node JS: Node.js is an open-source and cross-platform runtime environment built on Chrome’s V8 JavaScript engine for executing JavaScript code outside of a browser. You need to recollect that NodeJS isn’t a framework, and it’s not a programming language." }, { "code": null, "e": 1243, "s": 1002, "text": "React JS: React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It’s ‘V’ in MVC. ReactJS is an open-source, component-based front-end library responsible only for the view layer of the application." }, { "code": null, "e": 1253, "s": 1243, "text": " Syntax:" }, { "code": null, "e": 1287, "s": 1253, "text": "run npm install -g <package-name>" }, { "code": null, "e": 1332, "s": 1287, "text": "Where g denotes a global mode of a variable." }, { "code": null, "e": 1427, "s": 1332, "text": "Application: It is used to install packages globally in the system while making Node projects." }, { "code": null, "e": 1607, "s": 1427, "text": "Path of Global Packages in the system: Global modules are installed in the standard system in root location in the system directory /usr/local/lib/node_modules project directory." }, { "code": null, "e": 1697, "s": 1607, "text": "Command to print the location on your system where all the global modules are installed. " }, { "code": null, "e": 1709, "s": 1697, "text": "npm root -g" }, { "code": null, "e": 1718, "s": 1709, "text": "Output: " }, { "code": null, "e": 1768, "s": 1718, "text": "C:\\Users\\Pallavi\\AppData\\Roaming\\npm\\node_modules" }, { "code": null, "e": 1841, "s": 1768, "text": "Example to illustrate how to install the package globally in the system." }, { "code": null, "e": 1877, "s": 1841, "text": "Write this command in the console. " }, { "code": null, "e": 1914, "s": 1877, "text": "npm install -g mit-license-generator" }, { "code": null, "e": 1923, "s": 1914, "text": "Output: " }, { "code": null, "e": 1990, "s": 1923, "text": "How to check which packages are installed globally in the system. " }, { "code": null, "e": 2002, "s": 1990, "text": "npm list -g" }, { "code": null, "e": 2023, "s": 2002, "text": "The output will be: " }, { "code": null, "e": 2035, "s": 2023, "text": "Advantages:" }, { "code": null, "e": 2106, "s": 2035, "text": "We do not need to install a module every time when installed globally." }, { "code": null, "e": 2158, "s": 2106, "text": "It takes less memory as only one copy is installed." }, { "code": null, "e": 2301, "s": 2158, "text": "We can make .js scripts and run them anywhere without having a node_modules folder in the same directory when packages are installed globally." }, { "code": null, "e": 2316, "s": 2301, "text": "Disadvantages:" }, { "code": null, "e": 2470, "s": 2316, "text": "when we are running a Node app other than a local machine, then it will give an error because it needs packages in package.json that i.e, local packages." }, { "code": null, "e": 2562, "s": 2470, "text": "Globally deployed packages cannot be imported using require() in Node application directly." }, { "code": null, "e": 2580, "s": 2564, "text": "rajeev0719singh" }, { "code": null, "e": 2593, "s": 2580, "text": "singghakshay" }, { "code": null, "e": 2608, "s": 2593, "text": "Node.js-Basics" }, { "code": null, "e": 2625, "s": 2608, "text": "NodeJS-Questions" }, { "code": null, "e": 2632, "s": 2625, "text": "Picked" }, { "code": null, "e": 2640, "s": 2632, "text": "Node.js" }, { "code": null, "e": 2657, "s": 2640, "text": "Web Technologies" }, { "code": null, "e": 2755, "s": 2657, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2787, "s": 2755, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 2822, "s": 2787, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 2892, "s": 2822, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 2919, "s": 2892, "text": "Mongoose Populate() Method" }, { "code": null, "e": 2944, "s": 2919, "text": "Mongoose find() Function" }, { "code": null, "e": 3006, "s": 2944, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3067, "s": 3006, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3117, "s": 3067, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3160, "s": 3117, "text": "How to fetch data from an API in ReactJS ?" } ]
Rexx - substr String
This method gets a sub string from a particular string. substr(string1,index,count) string1 − The source string. string1 − The source string. index − The starting index position for the sub string. index − The starting index position for the sub string. count − The number of characters for the sub string. count − The number of characters for the sub string. Returns the sub-string. /* Main program */ a = "Hello World" say substr(a,2,3) When we run the above program, we will get the following result.
[ { "code": null, "e": 2529, "s": 2473, "text": "This method gets a sub string from a particular string." }, { "code": null, "e": 2559, "s": 2529, "text": "substr(string1,index,count) \n" }, { "code": null, "e": 2588, "s": 2559, "text": "string1 − The source string." }, { "code": null, "e": 2617, "s": 2588, "text": "string1 − The source string." }, { "code": null, "e": 2673, "s": 2617, "text": "index − The starting index position for the sub string." }, { "code": null, "e": 2729, "s": 2673, "text": "index − The starting index position for the sub string." }, { "code": null, "e": 2782, "s": 2729, "text": "count − The number of characters for the sub string." }, { "code": null, "e": 2835, "s": 2782, "text": "count − The number of characters for the sub string." }, { "code": null, "e": 2859, "s": 2835, "text": "Returns the sub-string." }, { "code": null, "e": 2917, "s": 2859, "text": "/* Main program */ \na = \"Hello World\" \nsay substr(a,2,3) " } ]
Python Program to Print matrix in antispiral form
06 Jan, 2022 Given a 2D array, the task is to print matrix in anti spiral form:Examples: Output: 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 Input : arr[][4] = {1, 2, 3, 4 5, 6, 7, 8 9, 10, 11, 12 13, 14, 15, 16}; Output : 10 11 7 6 5 9 13 14 15 16 12 8 4 3 2 1 Input :arr[][6] = {1, 2, 3, 4, 5, 6 7, 8, 9, 10, 11, 12 13, 14, 15, 16, 17, 18}; Output : 11 10 9 8 7 13 14 15 16 17 18 12 6 5 4 3 2 1 The idea is simple, we traverse matrix in spiral form and put all traversed elements in a stack. Finally one by one elements from stack and print them. Python 3 # Python 3 program to print# matrix in anti-spiral formR = 4C = 5 def antiSpiralTraversal(m, n, a): k = 0 l = 0 # k - starting row index # m - ending row index # l - starting column index # n - ending column index # i - iterator stk = [] while (k <= m and l <= n): # Print the first row # from the remaining rows for i in range(l, n + 1): stk.append(a[k][i]) k += 1 # Print the last column # from the remaining columns for i in range(k, m + 1): stk.append(a[i][n]) n -= 1 # Print the last row # from the remaining rows if ( k <= m): for i in range(n, l - 1, -1): stk.append(a[m][i]) m -= 1 # Print the first column # from the remaining columns if (l <= n): for i in range(m, k - 1, -1): stk.append(a[i][l]) l += 1 while len(stk) != 0: print(str(stk[-1]), end = " ") stk.pop() # Driver Codemat = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]; antiSpiralTraversal(R - 1, C - 1, mat) # This code is contributed# by ChitraNayal Output: 12 13 14 9 8 7 6 11 16 17 18 19 20 15 10 5 4 3 2 1 Please refer complete article on Print matrix in antispiral form for more details! Matrix Python Python Programs School Programming Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jan, 2022" }, { "code": null, "e": 106, "s": 28, "text": "Given a 2D array, the task is to print matrix in anti spiral form:Examples: " }, { "code": null, "e": 154, "s": 106, "text": "Output: 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 " }, { "code": null, "e": 507, "s": 154, "text": "Input : arr[][4] = {1, 2, 3, 4\n 5, 6, 7, 8\n 9, 10, 11, 12\n 13, 14, 15, 16};\nOutput : 10 11 7 6 5 9 13 14 15 16 12 8 4 3 2 1\n\nInput :arr[][6] = {1, 2, 3, 4, 5, 6\n 7, 8, 9, 10, 11, 12\n 13, 14, 15, 16, 17, 18};\nOutput : 11 10 9 8 7 13 14 15 16 17 18 12 6 5 4 3 2 1" }, { "code": null, "e": 663, "s": 509, "text": "The idea is simple, we traverse matrix in spiral form and put all traversed elements in a stack. Finally one by one elements from stack and print them. " }, { "code": null, "e": 672, "s": 663, "text": "Python 3" }, { "code": "# Python 3 program to print# matrix in anti-spiral formR = 4C = 5 def antiSpiralTraversal(m, n, a): k = 0 l = 0 # k - starting row index # m - ending row index # l - starting column index # n - ending column index # i - iterator stk = [] while (k <= m and l <= n): # Print the first row # from the remaining rows for i in range(l, n + 1): stk.append(a[k][i]) k += 1 # Print the last column # from the remaining columns for i in range(k, m + 1): stk.append(a[i][n]) n -= 1 # Print the last row # from the remaining rows if ( k <= m): for i in range(n, l - 1, -1): stk.append(a[m][i]) m -= 1 # Print the first column # from the remaining columns if (l <= n): for i in range(m, k - 1, -1): stk.append(a[i][l]) l += 1 while len(stk) != 0: print(str(stk[-1]), end = \" \") stk.pop() # Driver Codemat = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]; antiSpiralTraversal(R - 1, C - 1, mat) # This code is contributed# by ChitraNayal", "e": 1928, "s": 672, "text": null }, { "code": null, "e": 1938, "s": 1928, "text": "Output: " }, { "code": null, "e": 1990, "s": 1938, "text": "12 13 14 9 8 7 6 11 16 17 18 19 20 15 10 5 4 3 2 1 " }, { "code": null, "e": 2073, "s": 1990, "text": "Please refer complete article on Print matrix in antispiral form for more details!" }, { "code": null, "e": 2080, "s": 2073, "text": "Matrix" }, { "code": null, "e": 2087, "s": 2080, "text": "Python" }, { "code": null, "e": 2103, "s": 2087, "text": "Python Programs" }, { "code": null, "e": 2122, "s": 2103, "text": "School Programming" }, { "code": null, "e": 2129, "s": 2122, "text": "Matrix" } ]
PyQt5 – How to auto resize Label | adjustSize QLabel
26 Mar, 2020 During the designing of the GUI (Graphical User Interface) application there is a need to display plain text as information where label is used, but sometimes information text could be large or much smaller and it is difficult to use resize() method so have to auto adjust the size of the label according to the text, in order to do so adjustSize() method can be used. adjustSize() method will change the size of label according to the length of the text, if the length is less it will decrease the length and height of the widget and vice versa. Syntax : label.adjustSize() Argument : It takes no argument. Code : # importing the required libraries from PyQt5.QtWidgets import * from PyQt5 import QtCorefrom PyQt5.QtGui import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Label") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating a label widget self.label_1 = QLabel("== Normal Label ====", self) # moving position self.label_1.move(100, 100) # setting up border self.label_1.setStyleSheet("border: 1px solid black;") # creating a label widget self.label_2 = QLabel("====== Adjusted label =====", self) # moving position self.label_2.move(100, 150) # setting up border self.label_2.setStyleSheet("border: 1px solid black;") # adjusting the size of label self.label_2.adjustSize() # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Mar, 2020" }, { "code": null, "e": 397, "s": 28, "text": "During the designing of the GUI (Graphical User Interface) application there is a need to display plain text as information where label is used, but sometimes information text could be large or much smaller and it is difficult to use resize() method so have to auto adjust the size of the label according to the text, in order to do so adjustSize() method can be used." }, { "code": null, "e": 575, "s": 397, "text": "adjustSize() method will change the size of label according to the length of the text, if the length is less it will decrease the length and height of the widget and vice versa." }, { "code": null, "e": 603, "s": 575, "text": "Syntax : label.adjustSize()" }, { "code": null, "e": 636, "s": 603, "text": "Argument : It takes no argument." }, { "code": null, "e": 643, "s": 636, "text": "Code :" }, { "code": "# importing the required libraries from PyQt5.QtWidgets import * from PyQt5 import QtCorefrom PyQt5.QtGui import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Label\") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating a label widget self.label_1 = QLabel(\"== Normal Label ====\", self) # moving position self.label_1.move(100, 100) # setting up border self.label_1.setStyleSheet(\"border: 1px solid black;\") # creating a label widget self.label_2 = QLabel(\"====== Adjusted label =====\", self) # moving position self.label_2.move(100, 150) # setting up border self.label_2.setStyleSheet(\"border: 1px solid black;\") # adjusting the size of label self.label_2.adjustSize() # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 1760, "s": 643, "text": null }, { "code": null, "e": 1769, "s": 1760, "text": "Output :" }, { "code": null, "e": 1780, "s": 1769, "text": "Python-gui" }, { "code": null, "e": 1792, "s": 1780, "text": "Python-PyQt" }, { "code": null, "e": 1799, "s": 1792, "text": "Python" } ]
How to set FlowLayout for JFrame in Java?
To set FlowLayout for a frame, use the Container. At first, set a JFrame − JFrame frame = new JFrame(); Now, use Container and set the layout as FlowLayout− Container container container = frame.getContentPane(); container.setLayout(new FlowLayout()); The following is an example to set FlowLayout for JFrame − package my; import java.awt.Container; import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; public class SwingDemo { public static void main(String[] val) { JFrame frame = new JFrame(); Container container; JButton btn; frame.setBounds(20, 20, 15, 15); container = frame.getContentPane(); container.setLayout(new FlowLayout()); btn = new JButton("Submit"); JCheckBox checkBox1 = new JCheckBox("Graduate"); JCheckBox checkBox2 = new JCheckBox("Post-Graduate"); container.add(btn); container.add(checkBox1); container.add(checkBox2); frame.setVisible(true); frame.setSize(550, 400); frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE); } }
[ { "code": null, "e": 1262, "s": 1187, "text": "To set FlowLayout for a frame, use the Container. At first, set a JFrame −" }, { "code": null, "e": 1291, "s": 1262, "text": "JFrame frame = new JFrame();" }, { "code": null, "e": 1344, "s": 1291, "text": "Now, use Container and set the layout as FlowLayout−" }, { "code": null, "e": 1439, "s": 1344, "text": "Container container\ncontainer = frame.getContentPane();\ncontainer.setLayout(new FlowLayout());" }, { "code": null, "e": 1498, "s": 1439, "text": "The following is an example to set FlowLayout for JFrame −" }, { "code": null, "e": 2292, "s": 1498, "text": "package my;\nimport java.awt.Container;\nimport java.awt.FlowLayout;\nimport javax.swing.JButton;\nimport javax.swing.JCheckBox;\nimport javax.swing.JFrame;\npublic class SwingDemo {\n public static void main(String[] val) {\n JFrame frame = new JFrame();\n Container container;\n JButton btn;\n frame.setBounds(20, 20, 15, 15);\n container = frame.getContentPane();\n container.setLayout(new FlowLayout());\n btn = new JButton(\"Submit\");\n JCheckBox checkBox1 = new JCheckBox(\"Graduate\");\n JCheckBox checkBox2 = new JCheckBox(\"Post-Graduate\");\n container.add(btn);\n container.add(checkBox1);\n container.add(checkBox2);\n frame.setVisible(true);\n frame.setSize(550, 400);\n frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);\n }\n}" } ]
How to check if the PyMongo Cursor is Empty?
10 Jul, 2020 MongoDB is an open source NOSQL database, and is implemented in C++. It is a document oriented database implementation that stores data in structures called Collections (group of MongoDB documents). PyMongo is a famous open source library that is used for embedded MongoDB queries. PyMongo is widely used for interacting with a MongoDB database as python is powerful language for data analysis and data science. When a given collection is queried using pymongo using the .find() method, the return value is an object of type PyMongo.cursor.Cursor Class and it contains the documents matching the query. PyMongo cursor would be empty in the case the query made returns no result. If you want to get the individual documents you need to use the .find_one() method. To check is the cursor object is empty or not several approaches can be followed – Approach 1: The cursor returned is an iterable, thus we can convert it into a list. If the length of the list is zero (i.e. List is empty), this implies the cursor is empty as well. Sample Database: Example: Python3 import pymongo connection = pymongo.MongoClient()db = connection.GFGcol = db.lecture # This is a cursor instancecur = col.find() results = list(cur) # Checking the cursor is empty# or notif len(results)==0: print("Empty Cursor")else: print("Cursor is Not Empty") print("Do Stuff Here") Output: Cursor is Not Empty Do Stuff Here Approach 2: Another way is to use the .count() method that returns the number of matching documents for the query. if the return value for .count() is 0, then the cursor is empty Example: Python3 import pymongo connection = pymongo.MongoClient()db = connection.GFGcol = db.lecture # This is a cursor instancecur = col.find() if cur.count()==0: print("Empty Cursor")else: print("Cursor is Not Empty") print("Do Stuff Here") Output: Cursor is Not Empty Do Stuff Here Python-mongoDB Python 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 Deque in Python Stack in Python Queue in Python Read a file line by line in Python Defaultdict in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jul, 2020" }, { "code": null, "e": 440, "s": 28, "text": "MongoDB is an open source NOSQL database, and is implemented in C++. It is a document oriented database implementation that stores data in structures called Collections (group of MongoDB documents). PyMongo is a famous open source library that is used for embedded MongoDB queries. PyMongo is widely used for interacting with a MongoDB database as python is powerful language for data analysis and data science." }, { "code": null, "e": 875, "s": 440, "text": "When a given collection is queried using pymongo using the .find() method, the return value is an object of type PyMongo.cursor.Cursor Class and it contains the documents matching the query. PyMongo cursor would be empty in the case the query made returns no result. If you want to get the individual documents you need to use the .find_one() method. To check is the cursor object is empty or not several approaches can be followed – " }, { "code": null, "e": 1057, "s": 875, "text": "Approach 1: The cursor returned is an iterable, thus we can convert it into a list. If the length of the list is zero (i.e. List is empty), this implies the cursor is empty as well." }, { "code": null, "e": 1074, "s": 1057, "text": "Sample Database:" }, { "code": null, "e": 1084, "s": 1074, "text": "Example: " }, { "code": null, "e": 1092, "s": 1084, "text": "Python3" }, { "code": "import pymongo connection = pymongo.MongoClient()db = connection.GFGcol = db.lecture # This is a cursor instancecur = col.find() results = list(cur) # Checking the cursor is empty# or notif len(results)==0: print(\"Empty Cursor\")else: print(\"Cursor is Not Empty\") print(\"Do Stuff Here\")", "e": 1394, "s": 1092, "text": null }, { "code": null, "e": 1402, "s": 1394, "text": "Output:" }, { "code": null, "e": 1436, "s": 1402, "text": "Cursor is Not Empty\nDo Stuff Here" }, { "code": null, "e": 1615, "s": 1436, "text": "Approach 2: Another way is to use the .count() method that returns the number of matching documents for the query. if the return value for .count() is 0, then the cursor is empty" }, { "code": null, "e": 1624, "s": 1615, "text": "Example:" }, { "code": null, "e": 1632, "s": 1624, "text": "Python3" }, { "code": "import pymongo connection = pymongo.MongoClient()db = connection.GFGcol = db.lecture # This is a cursor instancecur = col.find() if cur.count()==0: print(\"Empty Cursor\")else: print(\"Cursor is Not Empty\") print(\"Do Stuff Here\")", "e": 1873, "s": 1632, "text": null }, { "code": null, "e": 1881, "s": 1873, "text": "Output:" }, { "code": null, "e": 1915, "s": 1881, "text": "Cursor is Not Empty\nDo Stuff Here" }, { "code": null, "e": 1930, "s": 1915, "text": "Python-mongoDB" }, { "code": null, "e": 1937, "s": 1930, "text": "Python" }, { "code": null, "e": 2035, "s": 1937, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2065, "s": 2035, "text": "Iterate over a list in Python" }, { "code": null, "e": 2110, "s": 2065, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 2132, "s": 2110, "text": "Enumerate() in Python" }, { "code": null, "e": 2182, "s": 2132, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 2200, "s": 2182, "text": "Python Dictionary" }, { "code": null, "e": 2216, "s": 2200, "text": "Deque in Python" }, { "code": null, "e": 2232, "s": 2216, "text": "Stack in Python" }, { "code": null, "e": 2248, "s": 2232, "text": "Queue in Python" }, { "code": null, "e": 2283, "s": 2248, "text": "Read a file line by line in Python" } ]
Reading and Writing Data to Excel File in Java using Apache POI
03 Jul, 2022 In Java, reading an Excel file is not similar to reading a Word file because of cells in an Excel file. JDK does not provide a direct API to read data from Excel files for which we have to toggle to a third-party library that is Apache POI. Apache POI is an open-source java library designed for reading and writing Microsoft documents in order to create and manipulate various file formats based on Microsoft Office. Using POI, one should be able to perform create, modify and display/read operations on the following file formats. For Example, Java doesn’t provide built-in support for working with excel files, so we need to look for open-source APIs for the job. Apache POI provides Java API for manipulating various file formats based on the Office Open XML (OOXML) standard and OLE2 standard from Microsoft. Apache POI releases are available under the Apache License (V2.0). Earlier we introduced Apache POI- a Java API useful for interacting with Microsoft Office documents. Now we’ll see how can we read and write to an excel file using the API. Procedure: Writing a file using POI is very simple and involve the following steps: Create a workbookCreate a sheet in the workbookCreate a row in the sheetAdd cells in the sheetRepeat steps 3 and 4 to write more data.Close the output stream. Create a workbook Create a sheet in the workbook Create a row in the sheet Add cells in the sheet Repeat steps 3 and 4 to write more data. Close the output stream. Example: Java // Java Program to Illustrate Writing // Data to Excel File using Apache POI // Import statementsimport java.io.FileOutputStream;import java.io.IOException;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.Row;import org.apache.poi.xssf.usermodel.XSSFSheet;import org.apache.poi.xssf.usermodel.XSSFWorkbook; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Blank workbook XSSFWorkbook workbook = new XSSFWorkbook(); // Creating a blank Excel sheet XSSFSheet sheet = workbook.createSheet("student Details"); // Creating an empty TreeMap of string and Object][] // type Map<String, Object[]> data = new TreeMap<String, Object[]>(); // Writing data to Object[] // using put() method data.put("1", new Object[] { "ID", "NAME", "LASTNAME" }); data.put("2", new Object[] { 1, "Pankaj", "Kumar" }); data.put("3", new Object[] { 2, "Prakashni", "Yadav" }); data.put("4", new Object[] { 3, "Ayan", "Mondal" }); data.put("5", new Object[] { 4, "Virat", "kohli" }); // Iterating over data and writing it to sheet Set<String> keyset = data.keySet(); int rownum = 0; for (String key : keyset) { // Creating a new row in the sheet Row row = sheet.createRow(rownum++); Object[] objArr = data.get(key); int cellnum = 0; for (Object obj : objArr) { // This line creates a cell in the next // column of that row Cell cell = row.createCell(cellnum++); if (obj instanceof String) cell.setCellValue((String)obj); else if (obj instanceof Integer) cell.setCellValue((Integer)obj); } } // Try block to check for exceptions try { // Writing the workbook FileOutputStream out = new FileOutputStream( new File("gfgcontribute.xlsx")); workbook.write(out); // Closing file output connections out.close(); // Console message for successful execution of // program System.out.println( "gfgcontribute.xlsx written successfully on disk."); } // Catch block to handle exceptions catch (Exception e) { // Display exceptions along with line number // using printStackTrace() method e.printStackTrace(); } }} Procedure: Reading an excel file is also very simple if we divide this into steps. Create workbook instance from excel sheetGet to the desired sheetIncrement row numberiterate over all cells in a rowrepeat steps 3 and 4 until all data is read.Close the output stream. Create workbook instance from excel sheet Get to the desired sheet Increment row number iterate over all cells in a row repeat steps 3 and 4 until all data is read. Close the output stream. Example: Java // Java Program to Illustrate Reading// Data to Excel File Using Apache POI // Import statementsimport java.io.File;import java.io.FileInputStream;import java.io.IOException;import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.FormulaEvaluator;import org.apache.poi.ss.usermodel.Row; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Reading file from local directory FileInputStream file = new FileInputStream( new File("gfgcontribute.xlsx")); // Create Workbook instance holding reference to // .xlsx file XSSFWorkbook workbook = new XSSFWorkbook(file); // Get first/desired sheet from the workbook XSSFSheet sheet = workbook.getSheetAt(0); // Iterate through each rows one by one Iterator<Row> rowIterator = sheet.iterator(); // Till there is an element condition holds true while (rowIterator.hasNext()) { Row row = rowIterator.next(); // For each row, iterate through all the // columns Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); // Checking the cell type and format // accordingly switch (cell.getCellType()) { // Case 1 case Cell.CELL_TYPE_NUMERIC: System.out.print( cell.getNumericCellValue() + "t"); break; // Case 2 case Cell.CELL_TYPE_STRING: System.out.print( cell.getStringCellValue() + "t"); break; } } System.out.println(""); } // Closing file output streams file.close(); } // Catch block to handle exceptions catch (Exception e) { // Display the exception along with line number // using printStackTrace() method e.printStackTrace(); } }} Output: Geeks, now you must be wondering what if we need to read a file at a different location, so the below example explains it all. Example 1-A: // Java Program to Read a File From Different Location // Getting file from local directory private static final String FILE_NAME = "C:\\Users\\pankaj\\Desktop\\projectOutput\\mobilitymodel.xlsx"; // Method public static void write() throws IOException, InvalidFormatException { InputStream inp = new FileInputStream(FILE_NAME); Workbook wb = WorkbookFactory.create(inp); Sheet sheet = wb.getSheetAt(0); ........ } Example 1-B: // Reading and Writing data to excel file using Apache POI // Via Appending to the Existing File // Getting the path from the local directory private static final String FILE_NAME = "C:\\Users\\pankaj\\Desktop\\projectOutput\\blo.xlsx"; // Method public static void write() throws IOException, InvalidFormatException { InputStream inp = new FileInputStream(FILE_NAME); Workbook wb = WorkbookFactory.create(inp); Sheet sheet = wb.getSheetAt(0); int num = sheet.getLastRowNum(); Row row = sheet.createRow(++num); row.createCell(0).setCellValue("xyz"); ..... .. // Now it will write the output to a file FileOutputStream fileOut = new FileOutputStream(FILE_NAME); wb.write(fileOut); // Closing the file connections fileOut.close(); } This article is contributed by Pankaj Kumar. 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. solankimayank surinderdawra388 Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of CSS (Cascading Style Sheet) How to set space between the flexbox ? How do you run JavaScript script through the Terminal? Remove elements from a JavaScript Array HTML Introduction How to execute PHP code using command line ? How to Open URL in New Tab using JavaScript ? How to Insert Form Data into Database using PHP ? DOM (Document Object Model) How to pop an alert message box using PHP ?
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Jul, 2022" }, { "code": null, "e": 910, "s": 28, "text": "In Java, reading an Excel file is not similar to reading a Word file because of cells in an Excel file. JDK does not provide a direct API to read data from Excel files for which we have to toggle to a third-party library that is Apache POI. Apache POI is an open-source java library designed for reading and writing Microsoft documents in order to create and manipulate various file formats based on Microsoft Office. Using POI, one should be able to perform create, modify and display/read operations on the following file formats. For Example, Java doesn’t provide built-in support for working with excel files, so we need to look for open-source APIs for the job. Apache POI provides Java API for manipulating various file formats based on the Office Open XML (OOXML) standard and OLE2 standard from Microsoft. Apache POI releases are available under the Apache License (V2.0). " }, { "code": null, "e": 1083, "s": 910, "text": "Earlier we introduced Apache POI- a Java API useful for interacting with Microsoft Office documents. Now we’ll see how can we read and write to an excel file using the API." }, { "code": null, "e": 1167, "s": 1083, "text": "Procedure: Writing a file using POI is very simple and involve the following steps:" }, { "code": null, "e": 1326, "s": 1167, "text": "Create a workbookCreate a sheet in the workbookCreate a row in the sheetAdd cells in the sheetRepeat steps 3 and 4 to write more data.Close the output stream." }, { "code": null, "e": 1344, "s": 1326, "text": "Create a workbook" }, { "code": null, "e": 1375, "s": 1344, "text": "Create a sheet in the workbook" }, { "code": null, "e": 1401, "s": 1375, "text": "Create a row in the sheet" }, { "code": null, "e": 1424, "s": 1401, "text": "Add cells in the sheet" }, { "code": null, "e": 1465, "s": 1424, "text": "Repeat steps 3 and 4 to write more data." }, { "code": null, "e": 1490, "s": 1465, "text": "Close the output stream." }, { "code": null, "e": 1499, "s": 1490, "text": "Example:" }, { "code": null, "e": 1504, "s": 1499, "text": "Java" }, { "code": "// Java Program to Illustrate Writing // Data to Excel File using Apache POI // Import statementsimport java.io.FileOutputStream;import java.io.IOException;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.Row;import org.apache.poi.xssf.usermodel.XSSFSheet;import org.apache.poi.xssf.usermodel.XSSFWorkbook; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Blank workbook XSSFWorkbook workbook = new XSSFWorkbook(); // Creating a blank Excel sheet XSSFSheet sheet = workbook.createSheet(\"student Details\"); // Creating an empty TreeMap of string and Object][] // type Map<String, Object[]> data = new TreeMap<String, Object[]>(); // Writing data to Object[] // using put() method data.put(\"1\", new Object[] { \"ID\", \"NAME\", \"LASTNAME\" }); data.put(\"2\", new Object[] { 1, \"Pankaj\", \"Kumar\" }); data.put(\"3\", new Object[] { 2, \"Prakashni\", \"Yadav\" }); data.put(\"4\", new Object[] { 3, \"Ayan\", \"Mondal\" }); data.put(\"5\", new Object[] { 4, \"Virat\", \"kohli\" }); // Iterating over data and writing it to sheet Set<String> keyset = data.keySet(); int rownum = 0; for (String key : keyset) { // Creating a new row in the sheet Row row = sheet.createRow(rownum++); Object[] objArr = data.get(key); int cellnum = 0; for (Object obj : objArr) { // This line creates a cell in the next // column of that row Cell cell = row.createCell(cellnum++); if (obj instanceof String) cell.setCellValue((String)obj); else if (obj instanceof Integer) cell.setCellValue((Integer)obj); } } // Try block to check for exceptions try { // Writing the workbook FileOutputStream out = new FileOutputStream( new File(\"gfgcontribute.xlsx\")); workbook.write(out); // Closing file output connections out.close(); // Console message for successful execution of // program System.out.println( \"gfgcontribute.xlsx written successfully on disk.\"); } // Catch block to handle exceptions catch (Exception e) { // Display exceptions along with line number // using printStackTrace() method e.printStackTrace(); } }}", "e": 4182, "s": 1504, "text": null }, { "code": null, "e": 4265, "s": 4182, "text": "Procedure: Reading an excel file is also very simple if we divide this into steps." }, { "code": null, "e": 4450, "s": 4265, "text": "Create workbook instance from excel sheetGet to the desired sheetIncrement row numberiterate over all cells in a rowrepeat steps 3 and 4 until all data is read.Close the output stream." }, { "code": null, "e": 4492, "s": 4450, "text": "Create workbook instance from excel sheet" }, { "code": null, "e": 4517, "s": 4492, "text": "Get to the desired sheet" }, { "code": null, "e": 4538, "s": 4517, "text": "Increment row number" }, { "code": null, "e": 4570, "s": 4538, "text": "iterate over all cells in a row" }, { "code": null, "e": 4615, "s": 4570, "text": "repeat steps 3 and 4 until all data is read." }, { "code": null, "e": 4640, "s": 4615, "text": "Close the output stream." }, { "code": null, "e": 4649, "s": 4640, "text": "Example:" }, { "code": null, "e": 4654, "s": 4649, "text": "Java" }, { "code": "// Java Program to Illustrate Reading// Data to Excel File Using Apache POI // Import statementsimport java.io.File;import java.io.FileInputStream;import java.io.IOException;import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.FormulaEvaluator;import org.apache.poi.ss.usermodel.Row; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Reading file from local directory FileInputStream file = new FileInputStream( new File(\"gfgcontribute.xlsx\")); // Create Workbook instance holding reference to // .xlsx file XSSFWorkbook workbook = new XSSFWorkbook(file); // Get first/desired sheet from the workbook XSSFSheet sheet = workbook.getSheetAt(0); // Iterate through each rows one by one Iterator<Row> rowIterator = sheet.iterator(); // Till there is an element condition holds true while (rowIterator.hasNext()) { Row row = rowIterator.next(); // For each row, iterate through all the // columns Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); // Checking the cell type and format // accordingly switch (cell.getCellType()) { // Case 1 case Cell.CELL_TYPE_NUMERIC: System.out.print( cell.getNumericCellValue() + \"t\"); break; // Case 2 case Cell.CELL_TYPE_STRING: System.out.print( cell.getStringCellValue() + \"t\"); break; } } System.out.println(\"\"); } // Closing file output streams file.close(); } // Catch block to handle exceptions catch (Exception e) { // Display the exception along with line number // using printStackTrace() method e.printStackTrace(); } }}", "e": 7182, "s": 4654, "text": null }, { "code": null, "e": 7192, "s": 7182, "text": "Output: " }, { "code": null, "e": 7319, "s": 7192, "text": "Geeks, now you must be wondering what if we need to read a file at a different location, so the below example explains it all." }, { "code": null, "e": 7332, "s": 7319, "text": "Example 1-A:" }, { "code": null, "e": 7771, "s": 7332, "text": "// Java Program to Read a File From Different Location\n\n// Getting file from local directory\nprivate static final String FILE_NAME\n = \"C:\\\\Users\\\\pankaj\\\\Desktop\\\\projectOutput\\\\mobilitymodel.xlsx\";\n\n// Method\npublic static void write() throws IOException, InvalidFormatException \n{\n\n InputStream inp = new FileInputStream(FILE_NAME);\n Workbook wb = WorkbookFactory.create(inp);\n Sheet sheet = wb.getSheetAt(0);\n ........\n}" }, { "code": null, "e": 7784, "s": 7771, "text": "Example 1-B:" }, { "code": null, "e": 8578, "s": 7784, "text": "// Reading and Writing data to excel file using Apache POI\n// Via Appending to the Existing File\n\n// Getting the path from the local directory\nprivate static final String FILE_NAME\n = \"C:\\\\Users\\\\pankaj\\\\Desktop\\\\projectOutput\\\\blo.xlsx\";\n\n// Method\npublic static void write() throws IOException, InvalidFormatException \n{\n\n InputStream inp = new FileInputStream(FILE_NAME);\n Workbook wb = WorkbookFactory.create(inp);\n Sheet sheet = wb.getSheetAt(0);\n\n int num = sheet.getLastRowNum();\n Row row = sheet.createRow(++num);\n row.createCell(0).setCellValue(\"xyz\");\n .....\n ..\n\n // Now it will write the output to a file\n FileOutputStream fileOut = new FileOutputStream(FILE_NAME);\n wb.write(fileOut);\n\n // Closing the file connections\n fileOut.close();\n}" }, { "code": null, "e": 8999, "s": 8578, "text": "This article is contributed by Pankaj Kumar. 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": 9013, "s": 8999, "text": "solankimayank" }, { "code": null, "e": 9030, "s": 9013, "text": "surinderdawra388" }, { "code": null, "e": 9057, "s": 9030, "text": "Web technologies Questions" }, { "code": null, "e": 9155, "s": 9057, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9192, "s": 9155, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 9231, "s": 9192, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 9286, "s": 9231, "text": "How do you run JavaScript script through the Terminal?" }, { "code": null, "e": 9326, "s": 9286, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 9344, "s": 9326, "text": "HTML Introduction" }, { "code": null, "e": 9389, "s": 9344, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 9435, "s": 9389, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 9485, "s": 9435, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 9513, "s": 9485, "text": "DOM (Document Object Model)" } ]
JavaFX | TitledPane Class
26 Sep, 2018 TitledPane class is a part of JavaFX. TitledPane class creates a panel with a title which can be opened or closed. TitledPane class extends the Labeled class. Constructor of the class: TitledPane(): Creates a new TitledPane object. TitledPane(String t, Node n): Creates a new TitledPane object with specified content and title. Commonly Used Methods: Below programs illustrate the use of TitlePane Class: Java program to create a TitledPane and add a label to it:In this program, we will create a TitledPane and add a label to it.The Label will contain a picture which is imported using the fileInputStream.Add this picture to the label.Add the label to the titled_pane.Now add the titled_pane to the scene and add the scene to the stage.Call the show() function to display the final results.// Java program to create a TitledPane// and add a label to it.import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.scene.layout.*;import javafx.scene.paint.*;import javafx.scene.text.*;import javafx.geometry.*;import javafx.scene.layout.*;import javafx.scene.shape.*;import javafx.scene.paint.*;import javafx.scene.*;import java.io.*;import javafx.scene.image.*; public class TitledPane_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("Titled Pane"); // create a input stream FileInputStream input = new FileInputStream("D:\\GFG.png"); // create a image Image image = new Image(input); // create a image View ImageView imageview = new ImageView(image); // create Label Label label = new Label("", imageview); // create TiledPane TitledPane titled_pane = new TitledPane("Titled Pane", label); // create a scene Scene scene = new Scene(titled_pane, 500, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/TitledPane.mp400:0000:0000:09Use Up/Down Arrow keys to increase or decrease volume.Java program to create a TitledPane, state whether it is animated or not, collapsible or not and add a label to it:In this program, we will create a TitledPane and add a label to it.The Label will contain a picture which is imported using the fileInputStream.Add this picture to the label and add the label to the titled_pane.Add the titled_pane to the scene and add the scene to the stage.Call the show() function to display the final results.Set the animated to false using setAnimated() function and set the collapsable to false using setCollapsable() function.// Java program to create a TitledPane, state // whether it is animated or not, collapsible// or not and add a label to itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.scene.layout.*;import javafx.scene.paint.*;import javafx.scene.text.*;import javafx.geometry.*;import javafx.scene.layout.*;import javafx.scene.shape.*;import javafx.scene.paint.*;import javafx.scene.*;import java.io.*;import javafx.scene.image.*; public class TitledPane_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("Titled Pane"); // create a input stream FileInputStream input = new FileInputStream("D:\\GFG.png"); // create a image Image image = new Image(input); // create a image View ImageView imageview = new ImageView(image); // create Label Label label = new Label("", imageview); // create TiledPane TitledPane titled_pane = new TitledPane("Titled Pane", label); // set Animated titled_pane.setAnimated(false); // set collapsible titled_pane.setCollapsible(false); // create a scene Scene scene = new Scene(titled_pane, 500, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output: Java program to create a TitledPane and add a label to it:In this program, we will create a TitledPane and add a label to it.The Label will contain a picture which is imported using the fileInputStream.Add this picture to the label.Add the label to the titled_pane.Now add the titled_pane to the scene and add the scene to the stage.Call the show() function to display the final results.// Java program to create a TitledPane// and add a label to it.import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.scene.layout.*;import javafx.scene.paint.*;import javafx.scene.text.*;import javafx.geometry.*;import javafx.scene.layout.*;import javafx.scene.shape.*;import javafx.scene.paint.*;import javafx.scene.*;import java.io.*;import javafx.scene.image.*; public class TitledPane_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("Titled Pane"); // create a input stream FileInputStream input = new FileInputStream("D:\\GFG.png"); // create a image Image image = new Image(input); // create a image View ImageView imageview = new ImageView(image); // create Label Label label = new Label("", imageview); // create TiledPane TitledPane titled_pane = new TitledPane("Titled Pane", label); // create a scene Scene scene = new Scene(titled_pane, 500, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/TitledPane.mp400:0000:0000:09Use Up/Down Arrow keys to increase or decrease volume. In this program, we will create a TitledPane and add a label to it. The Label will contain a picture which is imported using the fileInputStream. Add this picture to the label. Add the label to the titled_pane. Now add the titled_pane to the scene and add the scene to the stage. Call the show() function to display the final results. // Java program to create a TitledPane// and add a label to it.import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.scene.layout.*;import javafx.scene.paint.*;import javafx.scene.text.*;import javafx.geometry.*;import javafx.scene.layout.*;import javafx.scene.shape.*;import javafx.scene.paint.*;import javafx.scene.*;import java.io.*;import javafx.scene.image.*; public class TitledPane_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("Titled Pane"); // create a input stream FileInputStream input = new FileInputStream("D:\\GFG.png"); // create a image Image image = new Image(input); // create a image View ImageView imageview = new ImageView(image); // create Label Label label = new Label("", imageview); // create TiledPane TitledPane titled_pane = new TitledPane("Titled Pane", label); // create a scene Scene scene = new Scene(titled_pane, 500, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }} Output: Java program to create a TitledPane, state whether it is animated or not, collapsible or not and add a label to it:In this program, we will create a TitledPane and add a label to it.The Label will contain a picture which is imported using the fileInputStream.Add this picture to the label and add the label to the titled_pane.Add the titled_pane to the scene and add the scene to the stage.Call the show() function to display the final results.Set the animated to false using setAnimated() function and set the collapsable to false using setCollapsable() function.// Java program to create a TitledPane, state // whether it is animated or not, collapsible// or not and add a label to itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.scene.layout.*;import javafx.scene.paint.*;import javafx.scene.text.*;import javafx.geometry.*;import javafx.scene.layout.*;import javafx.scene.shape.*;import javafx.scene.paint.*;import javafx.scene.*;import java.io.*;import javafx.scene.image.*; public class TitledPane_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("Titled Pane"); // create a input stream FileInputStream input = new FileInputStream("D:\\GFG.png"); // create a image Image image = new Image(input); // create a image View ImageView imageview = new ImageView(image); // create Label Label label = new Label("", imageview); // create TiledPane TitledPane titled_pane = new TitledPane("Titled Pane", label); // set Animated titled_pane.setAnimated(false); // set collapsible titled_pane.setCollapsible(false); // create a scene Scene scene = new Scene(titled_pane, 500, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output: In this program, we will create a TitledPane and add a label to it. The Label will contain a picture which is imported using the fileInputStream. Add this picture to the label and add the label to the titled_pane. Add the titled_pane to the scene and add the scene to the stage. Call the show() function to display the final results. Set the animated to false using setAnimated() function and set the collapsable to false using setCollapsable() function. // Java program to create a TitledPane, state // whether it is animated or not, collapsible// or not and add a label to itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.scene.layout.*;import javafx.scene.paint.*;import javafx.scene.text.*;import javafx.geometry.*;import javafx.scene.layout.*;import javafx.scene.shape.*;import javafx.scene.paint.*;import javafx.scene.*;import java.io.*;import javafx.scene.image.*; public class TitledPane_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("Titled Pane"); // create a input stream FileInputStream input = new FileInputStream("D:\\GFG.png"); // create a image Image image = new Image(input); // create a image View ImageView imageview = new ImageView(image); // create Label Label label = new Label("", imageview); // create TiledPane TitledPane titled_pane = new TitledPane("Titled Pane", label); // set Animated titled_pane.setAnimated(false); // set collapsible titled_pane.setCollapsible(false); // create a scene Scene scene = new Scene(titled_pane, 500, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }} Output: Note: The above programs might not run in an online IDE please use an offline compiler. Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/TitledPane.html JavaFX Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java Stack Class in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Sep, 2018" }, { "code": null, "e": 187, "s": 28, "text": "TitledPane class is a part of JavaFX. TitledPane class creates a panel with a title which can be opened or closed. TitledPane class extends the Labeled class." }, { "code": null, "e": 213, "s": 187, "text": "Constructor of the class:" }, { "code": null, "e": 260, "s": 213, "text": "TitledPane(): Creates a new TitledPane object." }, { "code": null, "e": 356, "s": 260, "text": "TitledPane(String t, Node n): Creates a new TitledPane object with specified content and title." }, { "code": null, "e": 379, "s": 356, "text": "Commonly Used Methods:" }, { "code": null, "e": 433, "s": 379, "text": "Below programs illustrate the use of TitlePane Class:" }, { "code": null, "e": 4896, "s": 433, "text": "Java program to create a TitledPane and add a label to it:In this program, we will create a TitledPane and add a label to it.The Label will contain a picture which is imported using the fileInputStream.Add this picture to the label.Add the label to the titled_pane.Now add the titled_pane to the scene and add the scene to the stage.Call the show() function to display the final results.// Java program to create a TitledPane// and add a label to it.import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.scene.layout.*;import javafx.scene.paint.*;import javafx.scene.text.*;import javafx.geometry.*;import javafx.scene.layout.*;import javafx.scene.shape.*;import javafx.scene.paint.*;import javafx.scene.*;import java.io.*;import javafx.scene.image.*; public class TitledPane_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"Titled Pane\"); // create a input stream FileInputStream input = new FileInputStream(\"D:\\\\GFG.png\"); // create a image Image image = new Image(input); // create a image View ImageView imageview = new ImageView(image); // create Label Label label = new Label(\"\", imageview); // create TiledPane TitledPane titled_pane = new TitledPane(\"Titled Pane\", label); // create a scene Scene scene = new Scene(titled_pane, 500, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/TitledPane.mp400:0000:0000:09Use Up/Down Arrow keys to increase or decrease volume.Java program to create a TitledPane, state whether it is animated or not, collapsible or not and add a label to it:In this program, we will create a TitledPane and add a label to it.The Label will contain a picture which is imported using the fileInputStream.Add this picture to the label and add the label to the titled_pane.Add the titled_pane to the scene and add the scene to the stage.Call the show() function to display the final results.Set the animated to false using setAnimated() function and set the collapsable to false using setCollapsable() function.// Java program to create a TitledPane, state // whether it is animated or not, collapsible// or not and add a label to itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.scene.layout.*;import javafx.scene.paint.*;import javafx.scene.text.*;import javafx.geometry.*;import javafx.scene.layout.*;import javafx.scene.shape.*;import javafx.scene.paint.*;import javafx.scene.*;import java.io.*;import javafx.scene.image.*; public class TitledPane_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"Titled Pane\"); // create a input stream FileInputStream input = new FileInputStream(\"D:\\\\GFG.png\"); // create a image Image image = new Image(input); // create a image View ImageView imageview = new ImageView(image); // create Label Label label = new Label(\"\", imageview); // create TiledPane TitledPane titled_pane = new TitledPane(\"Titled Pane\", label); // set Animated titled_pane.setAnimated(false); // set collapsible titled_pane.setCollapsible(false); // create a scene Scene scene = new Scene(titled_pane, 500, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:" }, { "code": null, "e": 7016, "s": 4896, "text": "Java program to create a TitledPane and add a label to it:In this program, we will create a TitledPane and add a label to it.The Label will contain a picture which is imported using the fileInputStream.Add this picture to the label.Add the label to the titled_pane.Now add the titled_pane to the scene and add the scene to the stage.Call the show() function to display the final results.// Java program to create a TitledPane// and add a label to it.import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.scene.layout.*;import javafx.scene.paint.*;import javafx.scene.text.*;import javafx.geometry.*;import javafx.scene.layout.*;import javafx.scene.shape.*;import javafx.scene.paint.*;import javafx.scene.*;import java.io.*;import javafx.scene.image.*; public class TitledPane_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"Titled Pane\"); // create a input stream FileInputStream input = new FileInputStream(\"D:\\\\GFG.png\"); // create a image Image image = new Image(input); // create a image View ImageView imageview = new ImageView(image); // create Label Label label = new Label(\"\", imageview); // create TiledPane TitledPane titled_pane = new TitledPane(\"Titled Pane\", label); // create a scene Scene scene = new Scene(titled_pane, 500, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/TitledPane.mp400:0000:0000:09Use Up/Down Arrow keys to increase or decrease volume." }, { "code": null, "e": 7084, "s": 7016, "text": "In this program, we will create a TitledPane and add a label to it." }, { "code": null, "e": 7162, "s": 7084, "text": "The Label will contain a picture which is imported using the fileInputStream." }, { "code": null, "e": 7193, "s": 7162, "text": "Add this picture to the label." }, { "code": null, "e": 7227, "s": 7193, "text": "Add the label to the titled_pane." }, { "code": null, "e": 7296, "s": 7227, "text": "Now add the titled_pane to the scene and add the scene to the stage." }, { "code": null, "e": 7351, "s": 7296, "text": "Call the show() function to display the final results." }, { "code": "// Java program to create a TitledPane// and add a label to it.import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.scene.layout.*;import javafx.scene.paint.*;import javafx.scene.text.*;import javafx.geometry.*;import javafx.scene.layout.*;import javafx.scene.shape.*;import javafx.scene.paint.*;import javafx.scene.*;import java.io.*;import javafx.scene.image.*; public class TitledPane_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"Titled Pane\"); // create a input stream FileInputStream input = new FileInputStream(\"D:\\\\GFG.png\"); // create a image Image image = new Image(input); // create a image View ImageView imageview = new ImageView(image); // create Label Label label = new Label(\"\", imageview); // create TiledPane TitledPane titled_pane = new TitledPane(\"Titled Pane\", label); // create a scene Scene scene = new Scene(titled_pane, 500, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}", "e": 8931, "s": 7351, "text": null }, { "code": null, "e": 8939, "s": 8931, "text": "Output:" }, { "code": null, "e": 11283, "s": 8939, "text": "Java program to create a TitledPane, state whether it is animated or not, collapsible or not and add a label to it:In this program, we will create a TitledPane and add a label to it.The Label will contain a picture which is imported using the fileInputStream.Add this picture to the label and add the label to the titled_pane.Add the titled_pane to the scene and add the scene to the stage.Call the show() function to display the final results.Set the animated to false using setAnimated() function and set the collapsable to false using setCollapsable() function.// Java program to create a TitledPane, state // whether it is animated or not, collapsible// or not and add a label to itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.scene.layout.*;import javafx.scene.paint.*;import javafx.scene.text.*;import javafx.geometry.*;import javafx.scene.layout.*;import javafx.scene.shape.*;import javafx.scene.paint.*;import javafx.scene.*;import java.io.*;import javafx.scene.image.*; public class TitledPane_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"Titled Pane\"); // create a input stream FileInputStream input = new FileInputStream(\"D:\\\\GFG.png\"); // create a image Image image = new Image(input); // create a image View ImageView imageview = new ImageView(image); // create Label Label label = new Label(\"\", imageview); // create TiledPane TitledPane titled_pane = new TitledPane(\"Titled Pane\", label); // set Animated titled_pane.setAnimated(false); // set collapsible titled_pane.setCollapsible(false); // create a scene Scene scene = new Scene(titled_pane, 500, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:" }, { "code": null, "e": 11351, "s": 11283, "text": "In this program, we will create a TitledPane and add a label to it." }, { "code": null, "e": 11429, "s": 11351, "text": "The Label will contain a picture which is imported using the fileInputStream." }, { "code": null, "e": 11497, "s": 11429, "text": "Add this picture to the label and add the label to the titled_pane." }, { "code": null, "e": 11562, "s": 11497, "text": "Add the titled_pane to the scene and add the scene to the stage." }, { "code": null, "e": 11617, "s": 11562, "text": "Call the show() function to display the final results." }, { "code": null, "e": 11738, "s": 11617, "text": "Set the animated to false using setAnimated() function and set the collapsable to false using setCollapsable() function." }, { "code": "// Java program to create a TitledPane, state // whether it is animated or not, collapsible// or not and add a label to itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.scene.layout.*;import javafx.scene.paint.*;import javafx.scene.text.*;import javafx.geometry.*;import javafx.scene.layout.*;import javafx.scene.shape.*;import javafx.scene.paint.*;import javafx.scene.*;import java.io.*;import javafx.scene.image.*; public class TitledPane_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"Titled Pane\"); // create a input stream FileInputStream input = new FileInputStream(\"D:\\\\GFG.png\"); // create a image Image image = new Image(input); // create a image View ImageView imageview = new ImageView(image); // create Label Label label = new Label(\"\", imageview); // create TiledPane TitledPane titled_pane = new TitledPane(\"Titled Pane\", label); // set Animated titled_pane.setAnimated(false); // set collapsible titled_pane.setCollapsible(false); // create a scene Scene scene = new Scene(titled_pane, 500, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}", "e": 13511, "s": 11738, "text": null }, { "code": null, "e": 13519, "s": 13511, "text": "Output:" }, { "code": null, "e": 13607, "s": 13519, "text": "Note: The above programs might not run in an online IDE please use an offline compiler." }, { "code": null, "e": 13699, "s": 13607, "text": "Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/TitledPane.html" }, { "code": null, "e": 13706, "s": 13699, "text": "JavaFX" }, { "code": null, "e": 13711, "s": 13706, "text": "Java" }, { "code": null, "e": 13716, "s": 13711, "text": "Java" }, { "code": null, "e": 13814, "s": 13716, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13865, "s": 13814, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 13896, "s": 13865, "text": "How to iterate any Map in Java" }, { "code": null, "e": 13915, "s": 13896, "text": "Interfaces in Java" }, { "code": null, "e": 13945, "s": 13915, "text": "HashMap in Java with Examples" }, { "code": null, "e": 13960, "s": 13945, "text": "Stream In Java" }, { "code": null, "e": 13980, "s": 13960, "text": "Collections in Java" }, { "code": null, "e": 14004, "s": 13980, "text": "Singleton Class in Java" }, { "code": null, "e": 14036, "s": 14004, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 14048, "s": 14036, "text": "Set in Java" } ]
Recoverability in DBMS
28 Jun, 2021 Prerequisite: Introduction to Concurrency Control Types of Schedules As discussed, a transaction may not execute completely due to hardware failure, system crash or software issues. In that case, we have to roll back the failed transaction. But some other transaction may also have used values produced by the failed transaction. So we have to roll back those transactions as well. Recoverable Schedules: Schedules in which transactions commit only after all transactions whose changes they read commit are called recoverable schedules. In other words, if some transaction Tj is reading value updated or written by some other transaction Ti, then the commit of Tj must occur after the commit of Ti.Example 1:S1: R1(x), W1(x), R2(x), R1(y), R2(y), W2(x), W1(y), C1, C2; Given schedule follows order of Ti->Tj => C1->C2. Transaction T1 is executed before T2 hence there is no chances of conflict occur. R1(x) appears before W1(x) and transaction T1 is committed before T2 i.e. completion of first transaction performed first update on data item x, hence given schedule is recoverable.Example 2: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)R(A)commitcommitThis is a recoverable schedule since T1 commits before T2, that makes the value read by T2 correct. S1: R1(x), W1(x), R2(x), R1(y), R2(y), W2(x), W1(y), C1, C2; Given schedule follows order of Ti->Tj => C1->C2. Transaction T1 is executed before T2 hence there is no chances of conflict occur. R1(x) appears before W1(x) and transaction T1 is committed before T2 i.e. completion of first transaction performed first update on data item x, hence given schedule is recoverable. Example 2: Consider the following schedule involving two transactions T1 and T2. This is a recoverable schedule since T1 commits before T2, that makes the value read by T2 correct. Irrecoverable Schedule: The table below shows a schedule with two transactions, T1 reads and writes A and that value is read and written by T2. T2 commits. But later on, T1 fails. So we have to rollback T1. Since T2 has read the value written by T1, it should also be rollbacked. But we have already committed that. So this schedule is irrecoverable schedule. When Tj is reading the value updated by Ti and Tj is committed before committing of Ti, the schedule will be irrecoverable. Recoverable with Cascading Rollback: The table below shows a schedule with two transactions, T1 reads and writes A and that value is read and written by T2. But later on, T1 fails. So we have to rollback T1. Since T2 has read the value written by T1, it should also be rollbacked. As it has not committed, we can rollback T2 as well. So it is recoverable with cascading rollback. Therefore, if Tj is reading value updated by Ti and commit of Tj is delayed till commit of Ti, the schedule is called recoverable with cascading rollback. Cascadeless Recoverable Rollback: The table below shows a schedule with two transactions, T1 reads and writes A and commits and that value is read by T2. But if T1 fails before commit, no other transaction has read its value, so there is no need to rollback other transaction. So this is a Cascadeless recoverable schedule. So, if Tj reads value updated by Ti only after Ti is committed, the schedule will be cascadeless recoverable. Question: Which of the following scenarios may lead to an irrecoverable error in a database system? A transaction writes a data item after it is read by an uncommitted transaction.A transaction reads a data item after it is read by an uncommitted transaction.A transaction reads a data item after it is written by a committed transaction.A transaction reads a data item after it is written by an uncommitted transaction. A transaction writes a data item after it is read by an uncommitted transaction. A transaction reads a data item after it is read by an uncommitted transaction. A transaction reads a data item after it is written by a committed transaction. A transaction reads a data item after it is written by an uncommitted transaction. Answer: See the example discussed in Table 1, a transaction is reading a data item after it is written by an uncommitted transaction, the schedule will be irrecoverable.Related Post:Conflict Serializability This article is contributed by Sonal Tuteja. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above DBMS-Transactions and Concurrency Control DBMS DBMS 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": 66, "s": 52, "text": "Prerequisite:" }, { "code": null, "e": 102, "s": 66, "text": "Introduction to Concurrency Control" }, { "code": null, "e": 121, "s": 102, "text": "Types of Schedules" }, { "code": null, "e": 434, "s": 121, "text": "As discussed, a transaction may not execute completely due to hardware failure, system crash or software issues. In that case, we have to roll back the failed transaction. But some other transaction may also have used values produced by the failed transaction. So we have to roll back those transactions as well." }, { "code": null, "e": 457, "s": 434, "text": "Recoverable Schedules:" }, { "code": null, "e": 1356, "s": 457, "text": "Schedules in which transactions commit only after all transactions whose changes they read commit are called recoverable schedules. In other words, if some transaction Tj is reading value updated or written by some other transaction Ti, then the commit of Tj must occur after the commit of Ti.Example 1:S1: R1(x), W1(x), R2(x), R1(y), R2(y), \n W2(x), W1(y), C1, C2; Given schedule follows order of Ti->Tj => C1->C2. Transaction T1 is executed before T2 hence there is no chances of conflict occur. R1(x) appears before W1(x) and transaction T1 is committed before T2 i.e. completion of first transaction performed first update on data item x, hence given schedule is recoverable.Example 2: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)R(A)commitcommitThis is a recoverable schedule since T1 commits before T2, that makes the value read by T2 correct." }, { "code": null, "e": 1428, "s": 1356, "text": "S1: R1(x), W1(x), R2(x), R1(y), R2(y), \n W2(x), W1(y), C1, C2; " }, { "code": null, "e": 1742, "s": 1428, "text": "Given schedule follows order of Ti->Tj => C1->C2. Transaction T1 is executed before T2 hence there is no chances of conflict occur. R1(x) appears before W1(x) and transaction T1 is committed before T2 i.e. completion of first transaction performed first update on data item x, hence given schedule is recoverable." }, { "code": null, "e": 1823, "s": 1742, "text": "Example 2: Consider the following schedule involving two transactions T1 and T2." }, { "code": null, "e": 1923, "s": 1823, "text": "This is a recoverable schedule since T1 commits before T2, that makes the value read by T2 correct." }, { "code": null, "e": 1947, "s": 1923, "text": "Irrecoverable Schedule:" }, { "code": null, "e": 2407, "s": 1947, "text": "The table below shows a schedule with two transactions, T1 reads and writes A and that value is read and written by T2. T2 commits. But later on, T1 fails. So we have to rollback T1. Since T2 has read the value written by T1, it should also be rollbacked. But we have already committed that. So this schedule is irrecoverable schedule. When Tj is reading the value updated by Ti and Tj is committed before committing of Ti, the schedule will be irrecoverable." }, { "code": null, "e": 2444, "s": 2407, "text": "Recoverable with Cascading Rollback:" }, { "code": null, "e": 2942, "s": 2444, "text": "The table below shows a schedule with two transactions, T1 reads and writes A and that value is read and written by T2. But later on, T1 fails. So we have to rollback T1. Since T2 has read the value written by T1, it should also be rollbacked. As it has not committed, we can rollback T2 as well. So it is recoverable with cascading rollback. Therefore, if Tj is reading value updated by Ti and commit of Tj is delayed till commit of Ti, the schedule is called recoverable with cascading rollback." }, { "code": null, "e": 2976, "s": 2942, "text": "Cascadeless Recoverable Rollback:" }, { "code": null, "e": 3376, "s": 2976, "text": "The table below shows a schedule with two transactions, T1 reads and writes A and commits and that value is read by T2. But if T1 fails before commit, no other transaction has read its value, so there is no need to rollback other transaction. So this is a Cascadeless recoverable schedule. So, if Tj reads value updated by Ti only after Ti is committed, the schedule will be cascadeless recoverable." }, { "code": null, "e": 3476, "s": 3376, "text": "Question: Which of the following scenarios may lead to an irrecoverable error in a database system?" }, { "code": null, "e": 3797, "s": 3476, "text": "A transaction writes a data item after it is read by an uncommitted transaction.A transaction reads a data item after it is read by an uncommitted transaction.A transaction reads a data item after it is written by a committed transaction.A transaction reads a data item after it is written by an uncommitted transaction." }, { "code": null, "e": 3878, "s": 3797, "text": "A transaction writes a data item after it is read by an uncommitted transaction." }, { "code": null, "e": 3958, "s": 3878, "text": "A transaction reads a data item after it is read by an uncommitted transaction." }, { "code": null, "e": 4038, "s": 3958, "text": "A transaction reads a data item after it is written by a committed transaction." }, { "code": null, "e": 4121, "s": 4038, "text": "A transaction reads a data item after it is written by an uncommitted transaction." }, { "code": null, "e": 4328, "s": 4121, "text": "Answer: See the example discussed in Table 1, a transaction is reading a data item after it is written by an uncommitted transaction, the schedule will be irrecoverable.Related Post:Conflict Serializability" }, { "code": null, "e": 4497, "s": 4328, "text": "This article is contributed by Sonal Tuteja. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 4539, "s": 4497, "text": "DBMS-Transactions and Concurrency Control" }, { "code": null, "e": 4544, "s": 4539, "text": "DBMS" }, { "code": null, "e": 4549, "s": 4544, "text": "DBMS" } ]
Validate the size of input=file in HTML5?
You can try to run the following code to validate the size of input type file: <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head> <body> <form > <input type="file" id="myfile" data-max-size="32154" /> <input type="submit"/> </form> <script> $(function(){ $('form').submit(function(){ var val = true; $('input[type=file][data-max-size]').each(function(){ if(typeof this.files[0] !== 'undefined'){ var max = parseInt($(this).attr('max-size'),10), mySize = this.files[0].size; val = max > mySize; return val; } }); return val; }); }); </script> </body> </html>
[ { "code": null, "e": 1266, "s": 1187, "text": "You can try to run the following code to validate the size of input type file:" }, { "code": null, "e": 2148, "s": 1266, "text": "<!DOCTYPE html>\n <html>\n <head>\n <script src=\"http://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n </head>\n <body>\n <form >\n <input type=\"file\" id=\"myfile\" data-max-size=\"32154\" />\n <input type=\"submit\"/>\n </form>\n <script>\n $(function(){\n $('form').submit(function(){\n var val = true;\n \n $('input[type=file][data-max-size]').each(function(){\n if(typeof this.files[0] !== 'undefined'){\n var max = parseInt($(this).attr('max-size'),10),\n mySize = this.files[0].size;\n val = max > mySize;\n return val;\n }\n });\n return val;\n });\n });\n </script>\n </body>\n</html>" } ]
Optional filter() method in Java with examples
30 Jul, 2019 The filter() method of java.util.Optional class in Java is used to filter the value of this Optional instance by matching it with the given Predicate, and then return the filtered Optional instance. If there is no value present in this Optional instance, then this method returns an empty Optional instance. Syntax: public Optional<T> filter(Predicale<T> predicate) Parameters: This method accepts predicate as parameter of type Predicate to filter an Optional instance with this. Return value: This method returns the filtered Optional instance. If there is no value present in this Optional instance, then this method returns an empty Optional instance. Exception: This method throws NullPointerException if the specified predicate is null. Below programs illustrate filter() method:Program 1: // Java program to demonstrate// Optional.filter() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.of(9456); // print value System.out.println("Optional: " + op); // filter the value System.out.println("Filtered value " + "for odd or even: " + op .filter(num -> num % 2 == 0)); }} Optional: Optional[9456] Filtered value for odd or even: Optional[9456] Program 2: // Java program to demonstrate// Optional.filter() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.empty(); // print value System.out.println("Optional: " + op); try { // filter the value System.out.println("Filtered value " + "for odd or even: " + op .filter(num -> num % 2 == 0)); } catch (Exception e) { System.out.println(e); } }} Optional: Optional.empty Filtered value for odd or even: Optional.empty Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#filter-java.util.function.Predicate- Java - util package Java-Functions Java-Optional 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": "\n30 Jul, 2019" }, { "code": null, "e": 336, "s": 28, "text": "The filter() method of java.util.Optional class in Java is used to filter the value of this Optional instance by matching it with the given Predicate, and then return the filtered Optional instance. If there is no value present in this Optional instance, then this method returns an empty Optional instance." }, { "code": null, "e": 344, "s": 336, "text": "Syntax:" }, { "code": null, "e": 398, "s": 344, "text": "public Optional<T> \n filter(Predicale<T> predicate)\n" }, { "code": null, "e": 513, "s": 398, "text": "Parameters: This method accepts predicate as parameter of type Predicate to filter an Optional instance with this." }, { "code": null, "e": 688, "s": 513, "text": "Return value: This method returns the filtered Optional instance. If there is no value present in this Optional instance, then this method returns an empty Optional instance." }, { "code": null, "e": 775, "s": 688, "text": "Exception: This method throws NullPointerException if the specified predicate is null." }, { "code": null, "e": 828, "s": 775, "text": "Below programs illustrate filter() method:Program 1:" }, { "code": "// Java program to demonstrate// Optional.filter() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.of(9456); // print value System.out.println(\"Optional: \" + op); // filter the value System.out.println(\"Filtered value \" + \"for odd or even: \" + op .filter(num -> num % 2 == 0)); }}", "e": 1423, "s": 828, "text": null }, { "code": null, "e": 1496, "s": 1423, "text": "Optional: Optional[9456]\nFiltered value for odd or even: Optional[9456]\n" }, { "code": null, "e": 1507, "s": 1496, "text": "Program 2:" }, { "code": "// Java program to demonstrate// Optional.filter() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.empty(); // print value System.out.println(\"Optional: \" + op); try { // filter the value System.out.println(\"Filtered value \" + \"for odd or even: \" + op .filter(num -> num % 2 == 0)); } catch (Exception e) { System.out.println(e); } }}", "e": 2221, "s": 1507, "text": null }, { "code": null, "e": 2294, "s": 2221, "text": "Optional: Optional.empty\nFiltered value for odd or even: Optional.empty\n" }, { "code": null, "e": 2408, "s": 2294, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#filter-java.util.function.Predicate-" }, { "code": null, "e": 2428, "s": 2408, "text": "Java - util package" }, { "code": null, "e": 2443, "s": 2428, "text": "Java-Functions" }, { "code": null, "e": 2457, "s": 2443, "text": "Java-Optional" }, { "code": null, "e": 2462, "s": 2457, "text": "Java" }, { "code": null, "e": 2467, "s": 2462, "text": "Java" } ]
Internationalization(I18N) in Java
17 Dec, 2021 Internationalization(I18N) is the process of designing web applications in such a way that which provides support for various countries, various languages, and various currencies automatically without performing any change in the application is called Internationalization(I18N). It is known as I18N because between I and N; there are 18 characters; that’s why I18N. Internationalization is one of the powerful concepts of java if you are developing an application and want to display messages, currencies, dates, time, etc., according to the specific region or language. Example: We all know about the Amazon website. It is worldwide available. We Indians also access the website, and any other country person also accesses the website. If any request is coming from an Indian person, then the response from the amazon website should be in the form understandable by Indian People, like Currency should be in INR, etc. But at the same time, if US people access the website, then the response/information given by the website should be in some form which is understandable by US people like here currency should be in $. The above process is known as Internationalization(I18N). We can implement Internationalization by using the following three classes: Locale NumberFormat DateFormat Java // Java Program to illustrate Program// without Internationalization public class InternationalizationDemo{ public static void main(String[] args) { System.out.println("Hello"); System.out.println("Geeks"); System.out.println("How are you?"); }} Hello Geeks How are you? Explanation: If we want this program to display these same messages for people living in ITALY and SPAIN. Unfortunately, Our programming staff is not multilingual, and then we have to translate the above message in ITALY and SPAIN. Suppose we don’t know the languages of ITALY and SPAIN. Then our program will not word for ITALY and SPAIN people. It looks like the program needs to be internationalized. Java // Java Program to illustrate Program with// Internationalization import java.text.*;import java.util.*; class NumberFormatDemo { public static void main(String[] args) { // Here we get the below number // representation in various countries double d = 123456.789; NumberFormat nf = NumberFormat.getInstance(Locale.ITALY); NumberFormat nf1 = NumberFormat.getInstance(Locale.US); NumberFormat nf2 = NumberFormat.getInstance(Locale.CHINA); System.out.println("ITALY representation of " + d + " : " + nf.format(d)); System.out.println("US representation of " + d + " : " + nf1.format(d)); System.out.println("CHINA representation of " + d + " : " + nf2.format(d)); }} ITALY representation of 123456.789 : 123.456,789 US representation of 123456.789 : 123,456.789 CHINA representation of 123456.789 : 123,456.789 nishkarshgandhi Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Dec, 2021" }, { "code": null, "e": 419, "s": 52, "text": "Internationalization(I18N) is the process of designing web applications in such a way that which provides support for various countries, various languages, and various currencies automatically without performing any change in the application is called Internationalization(I18N). It is known as I18N because between I and N; there are 18 characters; that’s why I18N." }, { "code": null, "e": 624, "s": 419, "text": "Internationalization is one of the powerful concepts of java if you are developing an application and want to display messages, currencies, dates, time, etc., according to the specific region or language." }, { "code": null, "e": 1231, "s": 624, "text": "Example: We all know about the Amazon website. It is worldwide available. We Indians also access the website, and any other country person also accesses the website. If any request is coming from an Indian person, then the response from the amazon website should be in the form understandable by Indian People, like Currency should be in INR, etc. But at the same time, if US people access the website, then the response/information given by the website should be in some form which is understandable by US people like here currency should be in $. The above process is known as Internationalization(I18N)." }, { "code": null, "e": 1308, "s": 1231, "text": "We can implement Internationalization by using the following three classes: " }, { "code": null, "e": 1315, "s": 1308, "text": "Locale" }, { "code": null, "e": 1328, "s": 1315, "text": "NumberFormat" }, { "code": null, "e": 1339, "s": 1328, "text": "DateFormat" }, { "code": null, "e": 1344, "s": 1339, "text": "Java" }, { "code": "// Java Program to illustrate Program// without Internationalization public class InternationalizationDemo{ public static void main(String[] args) { System.out.println(\"Hello\"); System.out.println(\"Geeks\"); System.out.println(\"How are you?\"); }}", "e": 1621, "s": 1344, "text": null }, { "code": null, "e": 1646, "s": 1621, "text": "Hello\nGeeks\nHow are you?" }, { "code": null, "e": 2050, "s": 1646, "text": "Explanation: If we want this program to display these same messages for people living in ITALY and SPAIN. Unfortunately, Our programming staff is not multilingual, and then we have to translate the above message in ITALY and SPAIN. Suppose we don’t know the languages of ITALY and SPAIN. Then our program will not word for ITALY and SPAIN people. It looks like the program needs to be internationalized." }, { "code": null, "e": 2055, "s": 2050, "text": "Java" }, { "code": "// Java Program to illustrate Program with// Internationalization import java.text.*;import java.util.*; class NumberFormatDemo { public static void main(String[] args) { // Here we get the below number // representation in various countries double d = 123456.789; NumberFormat nf = NumberFormat.getInstance(Locale.ITALY); NumberFormat nf1 = NumberFormat.getInstance(Locale.US); NumberFormat nf2 = NumberFormat.getInstance(Locale.CHINA); System.out.println(\"ITALY representation of \" + d + \" : \" + nf.format(d)); System.out.println(\"US representation of \" + d + \" : \" + nf1.format(d)); System.out.println(\"CHINA representation of \" + d + \" : \" + nf2.format(d)); }}", "e": 2911, "s": 2055, "text": null }, { "code": null, "e": 3055, "s": 2911, "text": "ITALY representation of 123456.789 : 123.456,789\nUS representation of 123456.789 : 123,456.789\nCHINA representation of 123456.789 : 123,456.789" }, { "code": null, "e": 3071, "s": 3055, "text": "nishkarshgandhi" }, { "code": null, "e": 3076, "s": 3071, "text": "Java" }, { "code": null, "e": 3081, "s": 3076, "text": "Java" }, { "code": null, "e": 3179, "s": 3081, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3194, "s": 3179, "text": "Stream In Java" }, { "code": null, "e": 3215, "s": 3194, "text": "Introduction to Java" }, { "code": null, "e": 3236, "s": 3215, "text": "Constructors in Java" }, { "code": null, "e": 3255, "s": 3236, "text": "Exceptions in Java" }, { "code": null, "e": 3272, "s": 3255, "text": "Generics in Java" }, { "code": null, "e": 3302, "s": 3272, "text": "Functional Interfaces in Java" }, { "code": null, "e": 3328, "s": 3302, "text": "Java Programming Examples" }, { "code": null, "e": 3344, "s": 3328, "text": "Strings in Java" }, { "code": null, "e": 3381, "s": 3344, "text": "Differences between JDK, JRE and JVM" } ]
How to use getters/setters in TypeScript ?
26 Jul, 2021 In TypeScript, there are two supported methods getter and setter to access and set the class members. In this very short article, I’m going to show you Typescript Accessor which includes getters/setters method. Actually, getters and setters are nothing but a way for you to provide access to the properties of an object. Unlike other OOP’s languages like Java, C++, etc. where you can only access variables via the getter or setter method, but things work differently in Typescript where you can access variables directly (Given in the below example). This is called TypeScript Accessor. Methods of the Typescript accessor property: getter: This method comes when you want to access any property of an object. A getter is also called an accessor. setter: This method comes when you want to change any property of an object. A setter is also known as a mutator. Below given code is a Student class with 3 properties: name, semester and course. class Student { public name: string; public semester: number; public course: string; } To access any property of the Student class: let student = new Student(); // You can access Student class variables directly Student.name = "Aman Rathod"; Getter Method: Note: For extracting the value of a variable, getter accessor property is the conventional method. It is denoted by get keyword, in an object literal. A getter can be public, protected, private. Syntax: get accessName() { // getter, the code executed on // getting obj.accessName } Example: Javascript class Student { private _name: string = "Aman Rathod"; private _semester: number; private _course: string; // Getter method to return name of // Student class public get name() { return this._name; } } // Access any property of the Student classlet student = new Student(); // Getter calllet value = student.name; console.log(value); Output: Aman Rathod From the above example you can observe that when we invoke the getter method (student.name), we didn’t include the open and close parentheses as we would with a regular function. Thus you access variables directly. Setter Method: For updating the value of a variable the setter accessor property is the conventional method which is used. They are denoted by a set keyword in an object literal. Syntax: set accessName(value) { // The code executed on setting // obj.accessName = value, from setter } Example: Javascript class Student { private _name: string = "Aman Rathod"; private _semester: number; private _course: string; // Getter method to return name // of Student class public get name() { return this._name; } // Setter method to set the semester number public set semester(thesem: number) { this._semester = thesem; } // Setter method public set course(thecourse: string) { this._course = thecourse; }} // Access any property of the Student classlet student = new Student(); // Setter callstudent.semester = 5;student.course = "Web Development"; From the above example, also you can notice that call to the setter method doesn’t have parentheses like a regular method. When you call student.semester or student.course, the semester or course setter method is invoked and value is assigned. Handle Error: You can also add a condition in the setter method and if the condition is invalid then it throws an error. Let’s understand through the below example. Javascript class Student { private _name: string = "Aman Rathod"; private _semester: number; private _course: string; // Suppose the only 1st to 8th-semester students // are allowed to purchase the courses. public set semester( thesem: number ) { if( thesem < 1 || thesem > 8 ){ throw new Error('Sorry, this course is valid for students from 1st to 8th semester'); } this._semester = thesem; }} // Access any property of the Student classlet student = new Student(); // setter callstudent.semester = 9; Output: Constructor: Now let’s discuss Getter and Setter Method using Constructor. Actually, there is no difference in using or not using constructor in a class to access getter or setter method, but we just want to give overlook of constructor in TypeScript. Example: Javascript class Student { name: string; semester: number; course: string; constructor(nm: string, sm: number, cs: string) { this.name = nm; this.semester = sm; this.course = cs; } // Getter method public get courses() { return this.course; } public set courses( thecourse: string) { this.course = thecourse; }} // Access any property of the Student class, let student = new Student("Aman Rathod", 4, "Web Development" ); // Setter callstudent.course = "Data structure"; // Getter callconsole.log("Course purchased is " + student.courses); Output: JavaScript-Questions Picked TypeScript JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n26 Jul, 2021" }, { "code": null, "e": 264, "s": 53, "text": "In TypeScript, there are two supported methods getter and setter to access and set the class members. In this very short article, I’m going to show you Typescript Accessor which includes getters/setters method." }, { "code": null, "e": 641, "s": 264, "text": "Actually, getters and setters are nothing but a way for you to provide access to the properties of an object. Unlike other OOP’s languages like Java, C++, etc. where you can only access variables via the getter or setter method, but things work differently in Typescript where you can access variables directly (Given in the below example). This is called TypeScript Accessor." }, { "code": null, "e": 687, "s": 641, "text": "Methods of the Typescript accessor property: " }, { "code": null, "e": 801, "s": 687, "text": "getter: This method comes when you want to access any property of an object. A getter is also called an accessor." }, { "code": null, "e": 915, "s": 801, "text": "setter: This method comes when you want to change any property of an object. A setter is also known as a mutator." }, { "code": null, "e": 997, "s": 915, "text": "Below given code is a Student class with 3 properties: name, semester and course." }, { "code": null, "e": 1096, "s": 997, "text": "class Student {\n public name: string;\n public semester: number;\n public course: string;\n}" }, { "code": null, "e": 1143, "s": 1098, "text": "To access any property of the Student class:" }, { "code": null, "e": 1254, "s": 1143, "text": "let student = new Student();\n\n// You can access Student class variables directly\nStudent.name = \"Aman Rathod\";" }, { "code": null, "e": 1269, "s": 1254, "text": "Getter Method:" }, { "code": null, "e": 1464, "s": 1269, "text": "Note: For extracting the value of a variable, getter accessor property is the conventional method. It is denoted by get keyword, in an object literal. A getter can be public, protected, private." }, { "code": null, "e": 1472, "s": 1464, "text": "Syntax:" }, { "code": null, "e": 1564, "s": 1472, "text": "get accessName() { \n // getter, the code executed on \n // getting obj.accessName \n}" }, { "code": null, "e": 1573, "s": 1564, "text": "Example:" }, { "code": null, "e": 1584, "s": 1573, "text": "Javascript" }, { "code": "class Student { private _name: string = \"Aman Rathod\"; private _semester: number; private _course: string; // Getter method to return name of // Student class public get name() { return this._name; } } // Access any property of the Student classlet student = new Student(); // Getter calllet value = student.name; console.log(value);", "e": 1954, "s": 1584, "text": null }, { "code": null, "e": 1962, "s": 1954, "text": "Output:" }, { "code": null, "e": 1974, "s": 1962, "text": "Aman Rathod" }, { "code": null, "e": 2189, "s": 1974, "text": "From the above example you can observe that when we invoke the getter method (student.name), we didn’t include the open and close parentheses as we would with a regular function. Thus you access variables directly." }, { "code": null, "e": 2368, "s": 2189, "text": "Setter Method: For updating the value of a variable the setter accessor property is the conventional method which is used. They are denoted by a set keyword in an object literal." }, { "code": null, "e": 2376, "s": 2368, "text": "Syntax:" }, { "code": null, "e": 2489, "s": 2376, "text": "set accessName(value) { \n\n // The code executed on setting \n // obj.accessName = value, from setter \n} " }, { "code": null, "e": 2498, "s": 2489, "text": "Example:" }, { "code": null, "e": 2509, "s": 2498, "text": "Javascript" }, { "code": "class Student { private _name: string = \"Aman Rathod\"; private _semester: number; private _course: string; // Getter method to return name // of Student class public get name() { return this._name; } // Setter method to set the semester number public set semester(thesem: number) { this._semester = thesem; } // Setter method public set course(thecourse: string) { this._course = thecourse; }} // Access any property of the Student classlet student = new Student(); // Setter callstudent.semester = 5;student.course = \"Web Development\";", "e": 3116, "s": 2509, "text": null }, { "code": null, "e": 3361, "s": 3116, "text": "From the above example, also you can notice that call to the setter method doesn’t have parentheses like a regular method. When you call student.semester or student.course, the semester or course setter method is invoked and value is assigned. " }, { "code": null, "e": 3526, "s": 3361, "text": "Handle Error: You can also add a condition in the setter method and if the condition is invalid then it throws an error. Let’s understand through the below example." }, { "code": null, "e": 3537, "s": 3526, "text": "Javascript" }, { "code": "class Student { private _name: string = \"Aman Rathod\"; private _semester: number; private _course: string; // Suppose the only 1st to 8th-semester students // are allowed to purchase the courses. public set semester( thesem: number ) { if( thesem < 1 || thesem > 8 ){ throw new Error('Sorry, this course is valid for students from 1st to 8th semester'); } this._semester = thesem; }} // Access any property of the Student classlet student = new Student(); // setter callstudent.semester = 9;", "e": 4118, "s": 3537, "text": null }, { "code": null, "e": 4126, "s": 4118, "text": "Output:" }, { "code": null, "e": 4378, "s": 4126, "text": "Constructor: Now let’s discuss Getter and Setter Method using Constructor. Actually, there is no difference in using or not using constructor in a class to access getter or setter method, but we just want to give overlook of constructor in TypeScript." }, { "code": null, "e": 4387, "s": 4378, "text": "Example:" }, { "code": null, "e": 4398, "s": 4387, "text": "Javascript" }, { "code": "class Student { name: string; semester: number; course: string; constructor(nm: string, sm: number, cs: string) { this.name = nm; this.semester = sm; this.course = cs; } // Getter method public get courses() { return this.course; } public set courses( thecourse: string) { this.course = thecourse; }} // Access any property of the Student class, let student = new Student(\"Aman Rathod\", 4, \"Web Development\" ); // Setter callstudent.course = \"Data structure\"; // Getter callconsole.log(\"Course purchased is \" + student.courses);", "e": 5015, "s": 4398, "text": null }, { "code": null, "e": 5023, "s": 5015, "text": "Output:" }, { "code": null, "e": 5044, "s": 5023, "text": "JavaScript-Questions" }, { "code": null, "e": 5051, "s": 5044, "text": "Picked" }, { "code": null, "e": 5062, "s": 5051, "text": "TypeScript" }, { "code": null, "e": 5073, "s": 5062, "text": "JavaScript" }, { "code": null, "e": 5090, "s": 5073, "text": "Web Technologies" } ]
How to disable a form control in Angular ?
24 May, 2021 In this article, we are going to see how to disable a form control in Angular 10. We will use AbstractControl disabled property to disable a form control element. Syntax: <formelement disabled></formelement> Return Value: boolean: returns boolean stating whether the element is disabled or not. Approach: Create the Angular app to be used In app.component.html make a form using ngForm directive. Now disable the form control element using AbstractControl disabled property Serve the angular app using ng serve to see the output. Example 1: In this example, we have disabled the input element using this property. app.module.ts import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ]})export class AppModule { } app.component.html <br><form #gfg = "ngForm"> Name: <input type="text" name = 'name' ngModel disabled></form> Output: Example 2: In this example, we have disabled the checkbox element using this property. app.module.ts import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ]})export class AppModule { } app.component.html <br><form #gfg = "ngForm"> Checked: <input type="checkbox" name = 'Check' ngModel disabled></form> Output: Example 3: In this example, we have disabled the button element using this property. app.module.ts import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ]})export class AppModule { } app.component.html app.component.html <br><form #gfg = "ngForm"> <button disabled>Disabled Button</button></form> Output: Reference: https://angular.io/api/forms/AbstractControlDirective#disabled Angular10 AngularJS-Basics AngularJS-Questions AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Routing in Angular 9/10 Angular PrimeNG Dropdown Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? How to create module with Routing in Angular 9 ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n24 May, 2021" }, { "code": null, "e": 191, "s": 28, "text": "In this article, we are going to see how to disable a form control in Angular 10. We will use AbstractControl disabled property to disable a form control element." }, { "code": null, "e": 199, "s": 191, "text": "Syntax:" }, { "code": null, "e": 236, "s": 199, "text": "<formelement disabled></formelement>" }, { "code": null, "e": 250, "s": 236, "text": "Return Value:" }, { "code": null, "e": 323, "s": 250, "text": "boolean: returns boolean stating whether the element is disabled or not." }, { "code": null, "e": 334, "s": 323, "text": "Approach: " }, { "code": null, "e": 368, "s": 334, "text": "Create the Angular app to be used" }, { "code": null, "e": 426, "s": 368, "text": "In app.component.html make a form using ngForm directive." }, { "code": null, "e": 503, "s": 426, "text": "Now disable the form control element using AbstractControl disabled property" }, { "code": null, "e": 559, "s": 503, "text": "Serve the angular app using ng serve to see the output." }, { "code": null, "e": 643, "s": 559, "text": "Example 1: In this example, we have disabled the input element using this property." }, { "code": null, "e": 657, "s": 643, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ]})export class AppModule { }", "e": 1159, "s": 657, "text": null }, { "code": null, "e": 1178, "s": 1159, "text": "app.component.html" }, { "code": "<br><form #gfg = \"ngForm\"> Name: <input type=\"text\" name = 'name' ngModel disabled></form>", "e": 1272, "s": 1178, "text": null }, { "code": null, "e": 1280, "s": 1272, "text": "Output:" }, { "code": null, "e": 1367, "s": 1280, "text": "Example 2: In this example, we have disabled the checkbox element using this property." }, { "code": null, "e": 1381, "s": 1367, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ]})export class AppModule { }", "e": 1883, "s": 1381, "text": null }, { "code": null, "e": 1902, "s": 1883, "text": "app.component.html" }, { "code": "<br><form #gfg = \"ngForm\"> Checked: <input type=\"checkbox\" name = 'Check' ngModel disabled></form>", "e": 2004, "s": 1902, "text": null }, { "code": null, "e": 2012, "s": 2004, "text": "Output:" }, { "code": null, "e": 2097, "s": 2012, "text": "Example 3: In this example, we have disabled the button element using this property." }, { "code": null, "e": 2111, "s": 2097, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ]})export class AppModule { }", "e": 2613, "s": 2111, "text": null }, { "code": null, "e": 2632, "s": 2613, "text": "app.component.html" }, { "code": null, "e": 2651, "s": 2632, "text": "app.component.html" }, { "code": "<br><form #gfg = \"ngForm\"> <button disabled>Disabled Button</button></form>", "e": 2730, "s": 2651, "text": null }, { "code": null, "e": 2738, "s": 2730, "text": "Output:" }, { "code": null, "e": 2812, "s": 2738, "text": "Reference: https://angular.io/api/forms/AbstractControlDirective#disabled" }, { "code": null, "e": 2822, "s": 2812, "text": "Angular10" }, { "code": null, "e": 2839, "s": 2822, "text": "AngularJS-Basics" }, { "code": null, "e": 2859, "s": 2839, "text": "AngularJS-Questions" }, { "code": null, "e": 2869, "s": 2859, "text": "AngularJS" }, { "code": null, "e": 2886, "s": 2869, "text": "Web Technologies" }, { "code": null, "e": 2984, "s": 2886, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3008, "s": 2984, "text": "Routing in Angular 9/10" }, { "code": null, "e": 3043, "s": 3008, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 3067, "s": 3043, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 3120, "s": 3067, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 3169, "s": 3120, "text": "How to create module with Routing in Angular 9 ?" }, { "code": null, "e": 3202, "s": 3169, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3264, "s": 3202, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3325, "s": 3264, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3375, "s": 3325, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Difference between friend function and member function in C++
12 Jun, 2022 Friend Function: It is basically a function that is used to access all private and protected members of classes. It is considered as a non-member function of class and is declared by the class that is granting access. This function is prefixed using the friend keyword in the declaration as shown below: Class definition using friend function: C++ class freetrial {private: { public: { friend void check(); } void check(); }} C++ // Example: Find the largest of two numbers using Friend Function #include<iostream>using namespace std; class Largest{ int a,b,m; public: void set_data(); friend void find_max(Largest); }; void Largest::set_data(){ cout<<"Enter the First No:"; cin>>a; cout<<"Enter the Second No:"; cin>>b;} void find_max(Largest t){ if(t.a>t.b) t.m=t.a; else t.m=t.b; cout<<"Maximum Number is\t"<<t.m;} main(){ Largest l; l.set_data(); find_max(l); return 0;} Output Enter the First No:25 Enter the Second No:96 Maximum Number is 96 Member Function: It is basically a function that can be declared as members of a class. It is usually declared inside the class definition and works on data members of the same class. It can have access to private, public, and protected data members of the same class. This function is declared as shown below: Class definition using member function: C++ class freetrial {private: { public: { void check(); } trial::void check(); }} C++ // Example: defining member function without argument inside class #include<iostream>using namespace std; class Item{ int itemId,quantity; double price; public: void setValue() { cout<<"Enter the Item Id:"; cin>>itemId; cout<<"Enter the Item Price:"; cin>>price; cout<<"Enter the Quantity:"; cin>>quantity; } void display() { cout<<endl<<itemId<<"\t"<<price<<"\t"<<quantity; } }; main(){ Item _item; _item.setValue(); _item.display(); return 0;} Output Enter the Item Id: 123 123 Enter the Item Price:25 Enter the Quantity:3 123 25 3 C++ // Example: defining member function without argument outside class #include<iostream>using namespace std; class Item{ int itemId,quantity; double price; public: void setValue(); void display();}; void Item::setValue(){ cout<<"Enter the Item Id:"; cin>>itemId; cout<<"Enter the Item Price:"; cin>>price; cout<<"Enter the Quantity:"; cin>>quantity;} void Item::display(){ cout<<endl<<itemId<<"\t"<<price<<"\t"<<quantity;} main(){ Item _item; _item.setValue(); _item.display(); return 0;} Output Enter the Item Id:1234 Enter the Item Price:25 Enter the Quantity:4 Tabular Difference between the friend function and member function: Friend Function Member Function chinmaychougaonkar aditiyadav20102001 Friend function and class Difference Between Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Synchronous and Asynchronous Transmission Difference Between Method Overloading and Method Overriding in Java Difference Between Go-Back-N and Selective Repeat Protocol Time complexities of different data structures Difference between Compile-time and Run-time Polymorphism in Java Differences and Applications of List, Tuple, Set and Dictionary in Python Difference between HTTP GET and POST Methods Difference between Top down parsing and Bottom up parsing Difference between Prim's and Kruskal's algorithm for MST Difference Between Paging and Segmentation
[ { "code": null, "e": 54, "s": 26, "text": "\n12 Jun, 2022" }, { "code": null, "e": 358, "s": 54, "text": "Friend Function: It is basically a function that is used to access all private and protected members of classes. It is considered as a non-member function of class and is declared by the class that is granting access. This function is prefixed using the friend keyword in the declaration as shown below:" }, { "code": null, "e": 398, "s": 358, "text": "Class definition using friend function:" }, { "code": null, "e": 402, "s": 398, "text": "C++" }, { "code": "class freetrial {private: { public: { friend void check(); } void check(); }}", "e": 521, "s": 402, "text": null }, { "code": null, "e": 525, "s": 521, "text": "C++" }, { "code": "// Example: Find the largest of two numbers using Friend Function #include<iostream>using namespace std; class Largest{ int a,b,m; public: void set_data(); friend void find_max(Largest); }; void Largest::set_data(){ cout<<\"Enter the First No:\"; cin>>a; cout<<\"Enter the Second No:\"; cin>>b;} void find_max(Largest t){ if(t.a>t.b) t.m=t.a; else t.m=t.b; cout<<\"Maximum Number is\\t\"<<t.m;} main(){ Largest l; l.set_data(); find_max(l); return 0;}", "e": 1056, "s": 525, "text": null }, { "code": null, "e": 1063, "s": 1056, "text": "Output" }, { "code": null, "e": 1132, "s": 1063, "text": "Enter the First No:25\nEnter the Second No:96\nMaximum Number is 96" }, { "code": null, "e": 1443, "s": 1132, "text": "Member Function: It is basically a function that can be declared as members of a class. It is usually declared inside the class definition and works on data members of the same class. It can have access to private, public, and protected data members of the same class. This function is declared as shown below:" }, { "code": null, "e": 1483, "s": 1443, "text": "Class definition using member function:" }, { "code": null, "e": 1487, "s": 1483, "text": "C++" }, { "code": "class freetrial {private: { public: { void check(); } trial::void check(); }}", "e": 1606, "s": 1487, "text": null }, { "code": null, "e": 1610, "s": 1606, "text": "C++" }, { "code": "// Example: defining member function without argument inside class #include<iostream>using namespace std; class Item{ int itemId,quantity; double price; public: void setValue() { cout<<\"Enter the Item Id:\"; cin>>itemId; cout<<\"Enter the Item Price:\"; cin>>price; cout<<\"Enter the Quantity:\"; cin>>quantity; } void display() { cout<<endl<<itemId<<\"\\t\"<<price<<\"\\t\"<<quantity; } }; main(){ Item _item; _item.setValue(); _item.display(); return 0;}", "e": 2205, "s": 1610, "text": null }, { "code": null, "e": 2212, "s": 2205, "text": "Output" }, { "code": null, "e": 2299, "s": 2212, "text": "Enter the Item Id: 123\n123\nEnter the Item Price:25\nEnter the Quantity:3\n123 25 3" }, { "code": null, "e": 2303, "s": 2299, "text": "C++" }, { "code": "// Example: defining member function without argument outside class #include<iostream>using namespace std; class Item{ int itemId,quantity; double price; public: void setValue(); void display();}; void Item::setValue(){ cout<<\"Enter the Item Id:\"; cin>>itemId; cout<<\"Enter the Item Price:\"; cin>>price; cout<<\"Enter the Quantity:\"; cin>>quantity;} void Item::display(){ cout<<endl<<itemId<<\"\\t\"<<price<<\"\\t\"<<quantity;} main(){ Item _item; _item.setValue(); _item.display(); return 0;}", "e": 2855, "s": 2303, "text": null }, { "code": null, "e": 2862, "s": 2855, "text": "Output" }, { "code": null, "e": 2930, "s": 2862, "text": "Enter the Item Id:1234\nEnter the Item Price:25\nEnter the Quantity:4" }, { "code": null, "e": 2998, "s": 2930, "text": "Tabular Difference between the friend function and member function:" }, { "code": null, "e": 3014, "s": 2998, "text": "Friend Function" }, { "code": null, "e": 3030, "s": 3014, "text": "Member Function" }, { "code": null, "e": 3049, "s": 3030, "text": "chinmaychougaonkar" }, { "code": null, "e": 3068, "s": 3049, "text": "aditiyadav20102001" }, { "code": null, "e": 3094, "s": 3068, "text": "Friend function and class" }, { "code": null, "e": 3113, "s": 3094, "text": "Difference Between" }, { "code": null, "e": 3211, "s": 3113, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3272, "s": 3211, "text": "Difference between Synchronous and Asynchronous Transmission" }, { "code": null, "e": 3340, "s": 3272, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 3399, "s": 3340, "text": "Difference Between Go-Back-N and Selective Repeat Protocol" }, { "code": null, "e": 3446, "s": 3399, "text": "Time complexities of different data structures" }, { "code": null, "e": 3512, "s": 3446, "text": "Difference between Compile-time and Run-time Polymorphism in Java" }, { "code": null, "e": 3586, "s": 3512, "text": "Differences and Applications of List, Tuple, Set and Dictionary in Python" }, { "code": null, "e": 3631, "s": 3586, "text": "Difference between HTTP GET and POST Methods" }, { "code": null, "e": 3689, "s": 3631, "text": "Difference between Top down parsing and Bottom up parsing" }, { "code": null, "e": 3747, "s": 3689, "text": "Difference between Prim's and Kruskal's algorithm for MST" } ]