title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
CSS - border-collapse
|
border-collapse determines the border model used in the rendering of a table.
collapse − Borders are collapsed to make a single border. Two adjacent cells will share a border.
collapse − Borders are collapsed to make a single border. Two adjacent cells will share a border.
separate − Borders are separated. Every cell has its own border, and none of these borders are shared with other cells in the table.
separate − Borders are separated. Every cell has its own border, and none of these borders are shared with other cells in the table.
Elements with a display of table or inline-table.
object.style.borderCollapse = "Any of the two values";
Following is the example to show both values −
<html>
<head>
<style type = "text/css">
table.one {border-collapse:collapse;}
table.two {border-collapse:separate;}
td.a {
border-style:dotted;
border-width:3px;
border-color:#000000;
padding: 10px;
}
td.b {
border-style:solid;
border-width:3px;
border-color:#333333;
padding:10px;
}
</style>
</head>
<body>
<table class = "one">
<caption>Collapse Border Example</caption>
<tr><td class = "a"> Cell A Collapse Example</td></tr>
<tr><td class = "b"> Cell B Collapse Example</td></tr>
</table>
<br />
<table class = "two">
<caption>Separate Border Example</caption>
<tr><td class = "a"> Cell A Separate Example</td></tr>
<tr><td class = "b"> Cell B Separate Example</td></tr>
</table>
</body>
</html>
This will produce following result −
33 Lectures
2.5 hours
Anadi Sharma
26 Lectures
2.5 hours
Frahaan Hussain
44 Lectures
4.5 hours
DigiFisk (Programming Is Fun)
21 Lectures
2.5 hours
DigiFisk (Programming Is Fun)
51 Lectures
7.5 hours
DigiFisk (Programming Is Fun)
52 Lectures
4 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2704,
"s": 2626,
"text": "border-collapse determines the border model used in the rendering of a table."
},
{
"code": null,
"e": 2802,
"s": 2704,
"text": "collapse − Borders are collapsed to make a single border. Two adjacent cells will share a border."
},
{
"code": null,
"e": 2900,
"s": 2802,
"text": "collapse − Borders are collapsed to make a single border. Two adjacent cells will share a border."
},
{
"code": null,
"e": 3033,
"s": 2900,
"text": "separate − Borders are separated. Every cell has its own border, and none of these borders are shared with other cells in the table."
},
{
"code": null,
"e": 3166,
"s": 3033,
"text": "separate − Borders are separated. Every cell has its own border, and none of these borders are shared with other cells in the table."
},
{
"code": null,
"e": 3216,
"s": 3166,
"text": "Elements with a display of table or inline-table."
},
{
"code": null,
"e": 3272,
"s": 3216,
"text": "object.style.borderCollapse = \"Any of the two values\";\n"
},
{
"code": null,
"e": 3319,
"s": 3272,
"text": "Following is the example to show both values −"
},
{
"code": null,
"e": 4311,
"s": 3319,
"text": "<html>\n <head>\n <style type = \"text/css\">\n table.one {border-collapse:collapse;}\n table.two {border-collapse:separate;}\n \n td.a {\n border-style:dotted; \n border-width:3px; \n border-color:#000000; \n padding: 10px;\n }\n td.b {\n border-style:solid; \n border-width:3px; \n border-color:#333333; \n padding:10px;\n }\n </style>\n </head>\n\n <body>\n \n <table class = \"one\">\n <caption>Collapse Border Example</caption>\n <tr><td class = \"a\"> Cell A Collapse Example</td></tr>\n <tr><td class = \"b\"> Cell B Collapse Example</td></tr>\n </table>\n <br />\n \n <table class = \"two\">\n <caption>Separate Border Example</caption>\n <tr><td class = \"a\"> Cell A Separate Example</td></tr>\n <tr><td class = \"b\"> Cell B Separate Example</td></tr>\n </table>\n \n </body>\n</html>"
},
{
"code": null,
"e": 4348,
"s": 4311,
"text": "This will produce following result −"
},
{
"code": null,
"e": 4383,
"s": 4348,
"text": "\n 33 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4397,
"s": 4383,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4432,
"s": 4397,
"text": "\n 26 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4449,
"s": 4432,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4484,
"s": 4449,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4515,
"s": 4484,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4550,
"s": 4515,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4581,
"s": 4550,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4616,
"s": 4581,
"text": "\n 51 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 4647,
"s": 4616,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4680,
"s": 4647,
"text": "\n 52 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4711,
"s": 4680,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4718,
"s": 4711,
"text": " Print"
},
{
"code": null,
"e": 4729,
"s": 4718,
"text": " Add Notes"
}
] |
Node.js Puppeteer - GeeksforGeeks
|
08 Oct, 2021
Puppeteer is an open-source library for Node.js that helps in automating and simplifying development by providing control over the Developers tools. It allows developers to write and maintain simple and automated tests. Most of the things that were done in the browser manually can be done by using puppeteer. Features of Puppeteer are –
It can work as a Web Scrawler.
It can Generates Screenshots of pages.
It can make PDFs of Web Pages.
It can automate the process of testing and form submission.
It can be used for testing Chrome extensions.
It creates an updated and automated environment for testing so that tests can be run directly in the browser(Google Chrome).
It creates its own browser user profile which is cleaned whenever this library is made to run.
Installation: For the first step, initialize the application with package.json file. Therefore, run the following command –
npm init
For installing the library, write the following command –
npm install puppeteer --save
After installing, our package.json file will look like –
{
"name": "day37",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Pranjal Srivastava",
"license": "ISC",
"dependencies": {
"puppeteer": "^3.1.0"
}
}
Implementation: Puppeteer basically creates an instance of the browser and then manipulate the pages of the browser. Let us see an implementation of puppeteer for navigating to a web-page –
const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://www.geeksforgeeks.org/'); await browser.close();})();
Firstly, we are creating an instance of the browser and allowing the puppeteer library to launch. Here,browser.newPage() is used to create a new page and then navigate to the URL provided in page.goto() as a parameter. And, finally browser.close() is used to close the whole running process. The name of our javascript file is index.js, therefore, to run the application just type the following command in the terminal –
node index.js
The above code will launch the default Web Browser in your system and navigate to https://www.geeksforgeeks.org/
Take a screenshot of the web-page: For taking the screenshot of a web-page, write the following code –
const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://www.geeksforgeeks.org/'); await page.screenshot({ path: 'GFG.png' }); await browser.close();})();
Here, page.screenshot method will take the screenshot of the page and save it with the filename GFG.png. The above code will firstly open the page and then take the screenshot of the page.
Run the application with the command –
node index.js
The output for the above code will be –
To create a PDF for the given Website: For creating PDF of a website, write the following code –
const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://www.geeksforgeeks.org/'); await page.pdf({ path: 'gfg.pdf' }); await browser.close();})();
Here, page.pdf() will create the PDF of the given website and save it with the name gfg.pdf. Run the application with the command –
node index.js
The above code will generate a PDF of the page.Output for above code will be –
For getting the dimensions of web-page opened: For getting the dimensions of a page, write the following code –
const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://www.geeksforgeeks.org/'); const getDimensions = await page.evaluate(() => { return { width: document.documentElement.clientWidth, height: document.documentElement.clientHeight }; }); console.log(getDimensions); await browser.close();})();
Here, getDimensions will first evaluate the page and then return the width and height of the page. The properties clientWidth and clientHeight are used to fetch the width and height of the page respectively. Run the application with the command –
node index.js
The output for the above code will be –
{
width: 1366px,
height: 695px
}
Default Settings:
It runs in Headless Mode: The headless mode of a browser provides automated testing and server environments. It is a way of running the browser without its full GUI. The advantage of using the browser in headless mode is that it continuously runs the javascript tests. The default setting for a headless browser is true in puppeteer. To make it false, write the following code –const browser = await puppeteer.launch({ headless: false })
const browser = await puppeteer.launch({ headless: false })
It runs the specific version of Chrome: By default, puppeteer uses the specific version of Chrome. If you want to run some other version of code, then write the following –const browser = await puppeteer.launch({ executablePath:
'/path/to/your/version/of/Chrome' });Here, executablePath property lets you to specify the path to your version of Chrome.
const browser = await puppeteer.launch({ executablePath:
'/path/to/your/version/of/Chrome' });
Here, executablePath property lets you to specify the path to your version of Chrome.
Conclusion: In this article, we learned about the pupeteer library of Node.js. We also learned about the various features of this library. We have seen its implementations and the default settings used by this library.
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect Node.js with React.js ?
Node.js Export Module
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Remove elements from a JavaScript Array
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
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26267,
"s": 26239,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 26605,
"s": 26267,
"text": "Puppeteer is an open-source library for Node.js that helps in automating and simplifying development by providing control over the Developers tools. It allows developers to write and maintain simple and automated tests. Most of the things that were done in the browser manually can be done by using puppeteer. Features of Puppeteer are –"
},
{
"code": null,
"e": 26636,
"s": 26605,
"text": "It can work as a Web Scrawler."
},
{
"code": null,
"e": 26675,
"s": 26636,
"text": "It can Generates Screenshots of pages."
},
{
"code": null,
"e": 26706,
"s": 26675,
"text": "It can make PDFs of Web Pages."
},
{
"code": null,
"e": 26766,
"s": 26706,
"text": "It can automate the process of testing and form submission."
},
{
"code": null,
"e": 26812,
"s": 26766,
"text": "It can be used for testing Chrome extensions."
},
{
"code": null,
"e": 26937,
"s": 26812,
"text": "It creates an updated and automated environment for testing so that tests can be run directly in the browser(Google Chrome)."
},
{
"code": null,
"e": 27032,
"s": 26937,
"text": "It creates its own browser user profile which is cleaned whenever this library is made to run."
},
{
"code": null,
"e": 27156,
"s": 27032,
"text": "Installation: For the first step, initialize the application with package.json file. Therefore, run the following command –"
},
{
"code": null,
"e": 27165,
"s": 27156,
"text": "npm init"
},
{
"code": null,
"e": 27223,
"s": 27165,
"text": "For installing the library, write the following command –"
},
{
"code": null,
"e": 27252,
"s": 27223,
"text": "npm install puppeteer --save"
},
{
"code": null,
"e": 27309,
"s": 27252,
"text": "After installing, our package.json file will look like –"
},
{
"code": null,
"e": 27580,
"s": 27309,
"text": "{\n \"name\": \"day37\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n },\n \"author\": \"Pranjal Srivastava\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"puppeteer\": \"^3.1.0\"\n }\n}\n"
},
{
"code": null,
"e": 27770,
"s": 27580,
"text": "Implementation: Puppeteer basically creates an instance of the browser and then manipulate the pages of the browser. Let us see an implementation of puppeteer for navigating to a web-page –"
},
{
"code": "const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://www.geeksforgeeks.org/'); await browser.close();})();",
"e": 28001,
"s": 27770,
"text": null
},
{
"code": null,
"e": 28422,
"s": 28001,
"text": "Firstly, we are creating an instance of the browser and allowing the puppeteer library to launch. Here,browser.newPage() is used to create a new page and then navigate to the URL provided in page.goto() as a parameter. And, finally browser.close() is used to close the whole running process. The name of our javascript file is index.js, therefore, to run the application just type the following command in the terminal –"
},
{
"code": null,
"e": 28436,
"s": 28422,
"text": "node index.js"
},
{
"code": null,
"e": 28549,
"s": 28436,
"text": "The above code will launch the default Web Browser in your system and navigate to https://www.geeksforgeeks.org/"
},
{
"code": null,
"e": 28652,
"s": 28549,
"text": "Take a screenshot of the web-page: For taking the screenshot of a web-page, write the following code –"
},
{
"code": "const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://www.geeksforgeeks.org/'); await page.screenshot({ path: 'GFG.png' }); await browser.close();})();",
"e": 28926,
"s": 28652,
"text": null
},
{
"code": null,
"e": 29115,
"s": 28926,
"text": "Here, page.screenshot method will take the screenshot of the page and save it with the filename GFG.png. The above code will firstly open the page and then take the screenshot of the page."
},
{
"code": null,
"e": 29154,
"s": 29115,
"text": "Run the application with the command –"
},
{
"code": null,
"e": 29168,
"s": 29154,
"text": "node index.js"
},
{
"code": null,
"e": 29208,
"s": 29168,
"text": "The output for the above code will be –"
},
{
"code": null,
"e": 29305,
"s": 29208,
"text": "To create a PDF for the given Website: For creating PDF of a website, write the following code –"
},
{
"code": "const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://www.geeksforgeeks.org/'); await page.pdf({ path: 'gfg.pdf' }); await browser.close();})();",
"e": 29574,
"s": 29305,
"text": null
},
{
"code": null,
"e": 29706,
"s": 29574,
"text": "Here, page.pdf() will create the PDF of the given website and save it with the name gfg.pdf. Run the application with the command –"
},
{
"code": null,
"e": 29720,
"s": 29706,
"text": "node index.js"
},
{
"code": null,
"e": 29799,
"s": 29720,
"text": "The above code will generate a PDF of the page.Output for above code will be –"
},
{
"code": null,
"e": 29911,
"s": 29799,
"text": "For getting the dimensions of web-page opened: For getting the dimensions of a page, write the following code –"
},
{
"code": "const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://www.geeksforgeeks.org/'); const getDimensions = await page.evaluate(() => { return { width: document.documentElement.clientWidth, height: document.documentElement.clientHeight }; }); console.log(getDimensions); await browser.close();})();",
"e": 30340,
"s": 29911,
"text": null
},
{
"code": null,
"e": 30587,
"s": 30340,
"text": "Here, getDimensions will first evaluate the page and then return the width and height of the page. The properties clientWidth and clientHeight are used to fetch the width and height of the page respectively. Run the application with the command –"
},
{
"code": null,
"e": 30601,
"s": 30587,
"text": "node index.js"
},
{
"code": null,
"e": 30641,
"s": 30601,
"text": "The output for the above code will be –"
},
{
"code": null,
"e": 30675,
"s": 30641,
"text": "{\nwidth: 1366px,\nheight: 695px\n}\n"
},
{
"code": null,
"e": 30693,
"s": 30675,
"text": "Default Settings:"
},
{
"code": null,
"e": 31131,
"s": 30693,
"text": "It runs in Headless Mode: The headless mode of a browser provides automated testing and server environments. It is a way of running the browser without its full GUI. The advantage of using the browser in headless mode is that it continuously runs the javascript tests. The default setting for a headless browser is true in puppeteer. To make it false, write the following code –const browser = await puppeteer.launch({ headless: false })"
},
{
"code": null,
"e": 31191,
"s": 31131,
"text": "const browser = await puppeteer.launch({ headless: false })"
},
{
"code": null,
"e": 31556,
"s": 31191,
"text": "It runs the specific version of Chrome: By default, puppeteer uses the specific version of Chrome. If you want to run some other version of code, then write the following –const browser = await puppeteer.launch({ executablePath:\n '/path/to/your/version/of/Chrome' });Here, executablePath property lets you to specify the path to your version of Chrome."
},
{
"code": null,
"e": 31664,
"s": 31556,
"text": "const browser = await puppeteer.launch({ executablePath:\n '/path/to/your/version/of/Chrome' });"
},
{
"code": null,
"e": 31750,
"s": 31664,
"text": "Here, executablePath property lets you to specify the path to your version of Chrome."
},
{
"code": null,
"e": 31969,
"s": 31750,
"text": "Conclusion: In this article, we learned about the pupeteer library of Node.js. We also learned about the various features of this library. We have seen its implementations and the default settings used by this library."
},
{
"code": null,
"e": 31982,
"s": 31969,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 31990,
"s": 31982,
"text": "Node.js"
},
{
"code": null,
"e": 32007,
"s": 31990,
"text": "Web Technologies"
},
{
"code": null,
"e": 32105,
"s": 32007,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32144,
"s": 32105,
"text": "How to connect Node.js with React.js ?"
},
{
"code": null,
"e": 32166,
"s": 32144,
"text": "Node.js Export Module"
},
{
"code": null,
"e": 32236,
"s": 32166,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 32263,
"s": 32236,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 32288,
"s": 32263,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 32328,
"s": 32288,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32373,
"s": 32328,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 32416,
"s": 32373,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 32478,
"s": 32416,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Cloning Table in MySQL - GeeksforGeeks
|
26 Jul, 2020
There may be a number of occasions where you need to create an exact copy of an already defined (or created) table. MySQL enables you to perform this operation. Because we may need such duplicate tables for testing over the data without having any impact over the original table and the data stored in it.
Original_table –
Steps to replicate (Clone) an existing table schema (structure) and it’s content –
Step 1 : To clone a table, use the query below. Using this query an empty schema (structure) of the table gets created with the same attributes of original table :
CREATE TABLE Contact List(Clone_1) LIKE Original_table;
Output : Contact List (Clone_1)
Step 2 : If you want to create a table which is bedecked with all the content of your original table, use this MySQL query :
CREATE TABLE Contact List(Clone_1) AS SELECT *
FROM Original_table;
OR
INSERT INTO Contact List(Clone_1) SELECT *
FROM original_table;
Output : Contact List (Clone_1)
SQLmysql
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Deadlock in DBMS
Types of Functional dependencies in DBMS
KDD Process in Data Mining
Conflict Serializability in DBMS
Introduction of Relational Algebra in DBMS
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL?
MySQL | Group_CONCAT() Function
|
[
{
"code": null,
"e": 25549,
"s": 25521,
"text": "\n26 Jul, 2020"
},
{
"code": null,
"e": 25855,
"s": 25549,
"text": "There may be a number of occasions where you need to create an exact copy of an already defined (or created) table. MySQL enables you to perform this operation. Because we may need such duplicate tables for testing over the data without having any impact over the original table and the data stored in it."
},
{
"code": null,
"e": 25872,
"s": 25855,
"text": "Original_table –"
},
{
"code": null,
"e": 25955,
"s": 25872,
"text": "Steps to replicate (Clone) an existing table schema (structure) and it’s content –"
},
{
"code": null,
"e": 26119,
"s": 25955,
"text": "Step 1 : To clone a table, use the query below. Using this query an empty schema (structure) of the table gets created with the same attributes of original table :"
},
{
"code": null,
"e": 26175,
"s": 26119,
"text": "CREATE TABLE Contact List(Clone_1) LIKE Original_table;"
},
{
"code": null,
"e": 26207,
"s": 26175,
"text": "Output : Contact List (Clone_1)"
},
{
"code": null,
"e": 26332,
"s": 26207,
"text": "Step 2 : If you want to create a table which is bedecked with all the content of your original table, use this MySQL query :"
},
{
"code": null,
"e": 26487,
"s": 26332,
"text": "CREATE TABLE Contact List(Clone_1) AS SELECT * \nFROM Original_table; \n OR\nINSERT INTO Contact List(Clone_1) SELECT * \nFROM original_table;"
},
{
"code": null,
"e": 26519,
"s": 26487,
"text": "Output : Contact List (Clone_1)"
},
{
"code": null,
"e": 26528,
"s": 26519,
"text": "SQLmysql"
},
{
"code": null,
"e": 26533,
"s": 26528,
"text": "DBMS"
},
{
"code": null,
"e": 26537,
"s": 26533,
"text": "SQL"
},
{
"code": null,
"e": 26542,
"s": 26537,
"text": "DBMS"
},
{
"code": null,
"e": 26546,
"s": 26542,
"text": "SQL"
},
{
"code": null,
"e": 26644,
"s": 26546,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26661,
"s": 26644,
"text": "Deadlock in DBMS"
},
{
"code": null,
"e": 26702,
"s": 26661,
"text": "Types of Functional dependencies in DBMS"
},
{
"code": null,
"e": 26729,
"s": 26702,
"text": "KDD Process in Data Mining"
},
{
"code": null,
"e": 26762,
"s": 26729,
"text": "Conflict Serializability in DBMS"
},
{
"code": null,
"e": 26805,
"s": 26762,
"text": "Introduction of Relational Algebra in DBMS"
},
{
"code": null,
"e": 26847,
"s": 26805,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 26891,
"s": 26847,
"text": "How to find Nth highest salary from a table"
},
{
"code": null,
"e": 26912,
"s": 26891,
"text": "SQL | ALTER (RENAME)"
},
{
"code": null,
"e": 26978,
"s": 26912,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
}
] |
Python unittest - assertFalse() function - GeeksforGeeks
|
29 Aug, 2020
assertFalse() in Python is a unittest library function that is used in unit testing to compare test value with false. This function will take two parameters as input and return a boolean value depending upon the assert condition. If test value is false then assertFalse() will return true else return false.
Syntax: assertFalse(testValue, message)
Parameters: assertFalse() accepts two parameters which are listed below with explanation:
testValue: variable of a boolean type which is used in the comparison by function
message: a string sentence as a message which got displayed when the test case got failed.
Listed below are two different examples illustrating the positive and negative test case for given assert function:
Example 1: Negative Test case
Python3
# unit test caseimport unittest class TestStringMethods(unittest.TestCase): # test function def test_negative(self): testValue = True # error message in case if test case got failed message = "Test value is not false." # assetFalse() to check test value as false self.assertFalse( testValue, message) if __name__ == '__main__': unittest.main()
Output:
F
======================================================================
FAIL: test_negative (__main__.TestStringMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
File "p1.py", line 11, in test_negative
self.assertFalse( testValue, message)
AssertionError: True is not false : Test value is not false.
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (failures=1)
Example 2: Positive Test case
Python3
# unit test caseimport unittest class TestStringMethods(unittest.TestCase): # test function def test_positive(self): testValue = False # error message in case if test case got failed message = "Test value is not false." # assertFalse() to check test value as false self.assertFalse( testValue, message) if __name__ == '__main__': unittest.main()
Output:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
Reference: https://docs.python.org/3/library/unittest.html
Python unittest-library
Python
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
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 25845,
"s": 25537,
"text": "assertFalse() in Python is a unittest library function that is used in unit testing to compare test value with false. This function will take two parameters as input and return a boolean value depending upon the assert condition. If test value is false then assertFalse() will return true else return false."
},
{
"code": null,
"e": 25885,
"s": 25845,
"text": "Syntax: assertFalse(testValue, message)"
},
{
"code": null,
"e": 25975,
"s": 25885,
"text": "Parameters: assertFalse() accepts two parameters which are listed below with explanation:"
},
{
"code": null,
"e": 26058,
"s": 25975,
"text": "testValue: variable of a boolean type which is used in the comparison by function"
},
{
"code": null,
"e": 26149,
"s": 26058,
"text": "message: a string sentence as a message which got displayed when the test case got failed."
},
{
"code": null,
"e": 26265,
"s": 26149,
"text": "Listed below are two different examples illustrating the positive and negative test case for given assert function:"
},
{
"code": null,
"e": 26295,
"s": 26265,
"text": "Example 1: Negative Test case"
},
{
"code": null,
"e": 26303,
"s": 26295,
"text": "Python3"
},
{
"code": "# unit test caseimport unittest class TestStringMethods(unittest.TestCase): # test function def test_negative(self): testValue = True # error message in case if test case got failed message = \"Test value is not false.\" # assetFalse() to check test value as false self.assertFalse( testValue, message) if __name__ == '__main__': unittest.main()",
"e": 26694,
"s": 26303,
"text": null
},
{
"code": null,
"e": 26702,
"s": 26694,
"text": "Output:"
},
{
"code": null,
"e": 27192,
"s": 26702,
"text": "F\n======================================================================\nFAIL: test_negative (__main__.TestStringMethods)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"p1.py\", line 11, in test_negative\n self.assertFalse( testValue, message)\nAssertionError: True is not false : Test value is not false.\n\n----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nFAILED (failures=1)\n\n\n"
},
{
"code": null,
"e": 27222,
"s": 27192,
"text": "Example 2: Positive Test case"
},
{
"code": null,
"e": 27230,
"s": 27222,
"text": "Python3"
},
{
"code": "# unit test caseimport unittest class TestStringMethods(unittest.TestCase): # test function def test_positive(self): testValue = False # error message in case if test case got failed message = \"Test value is not false.\" # assertFalse() to check test value as false self.assertFalse( testValue, message) if __name__ == '__main__': unittest.main()",
"e": 27623,
"s": 27230,
"text": null
},
{
"code": null,
"e": 27631,
"s": 27623,
"text": "Output:"
},
{
"code": null,
"e": 27733,
"s": 27631,
"text": ".\n----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nOK\n\n\n\n"
},
{
"code": null,
"e": 27792,
"s": 27733,
"text": "Reference: https://docs.python.org/3/library/unittest.html"
},
{
"code": null,
"e": 27816,
"s": 27792,
"text": "Python unittest-library"
},
{
"code": null,
"e": 27823,
"s": 27816,
"text": "Python"
},
{
"code": null,
"e": 27921,
"s": 27823,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27953,
"s": 27921,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27995,
"s": 27953,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28037,
"s": 27995,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28064,
"s": 28037,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28120,
"s": 28064,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28159,
"s": 28120,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28181,
"s": 28159,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28212,
"s": 28181,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28241,
"s": 28212,
"text": "Create a directory in Python"
}
] |
Is JavaScript's eval() evil? - GeeksforGeeks
|
22 Jun, 2020
The eval() is an in-built JS function that evaluates arguments that are expressions and executes one or more statements given to it as arguments.
Reason eval() consider evil: There are several problems possessed by the use of eval() and out of all performance and code injection are considered the most problematic. Performance- since script compiler cannot pre-compile eval(), it runs the compiler even when the code is compiled during run-time. Even though not much but this still degrades the performance.
It is Complicated- most cases in which eval() is used don’t even require it that badly. So, in cases like these an alternative approach is preferred more than eval(). Code injection- eval() runs string as a code and it is way more easier for hackers to get into privileged information just by the use of eval(). This is a big security threat when a program takes input from the user and is running on the client-side. This in-turn can go on to manipulate the original program itself.
Harder to debug- while debugging it requires double work.
Example:
HTML
<!DOCTYPE html><html><head> <title></title></head><body> <script type="text/javascript"> var a=eval("4+3"); document.write(a); </script></body></html>
Output:
7
When eval() not evil: For cases where you are running the program on your browser. Also, you need to be very careful not to pass any information that can give rise to code injection and manipulate the program in any way possible. It is generally preferred to use an alternate function in place of eval() if there is any function that can give out the same result as eval(). Closures, object-oriented techniques, functional techniques generally are capable of replacing eval(). For cases where this can’t be done and using eval() is the only way possible it is preferred to the passcode that will not manipulate the DOM in any way.eval() is evil if running on the server using input submitted by a client that was not created by the developer or that was not sanitized by the developer. eval() is not evil if running on the client, even if using unsanitized input crafted by the client. Obviously you should always sanitize the input, as to have some control over what your code consumes.
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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 append HTML code to a div using 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 ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25389,
"s": 25361,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 25536,
"s": 25389,
"text": "The eval() is an in-built JS function that evaluates arguments that are expressions and executes one or more statements given to it as arguments. "
},
{
"code": null,
"e": 25899,
"s": 25536,
"text": "Reason eval() consider evil: There are several problems possessed by the use of eval() and out of all performance and code injection are considered the most problematic. Performance- since script compiler cannot pre-compile eval(), it runs the compiler even when the code is compiled during run-time. Even though not much but this still degrades the performance."
},
{
"code": null,
"e": 26383,
"s": 25899,
"text": "It is Complicated- most cases in which eval() is used don’t even require it that badly. So, in cases like these an alternative approach is preferred more than eval(). Code injection- eval() runs string as a code and it is way more easier for hackers to get into privileged information just by the use of eval(). This is a big security threat when a program takes input from the user and is running on the client-side. This in-turn can go on to manipulate the original program itself."
},
{
"code": null,
"e": 26441,
"s": 26383,
"text": "Harder to debug- while debugging it requires double work."
},
{
"code": null,
"e": 26450,
"s": 26441,
"text": "Example:"
},
{
"code": null,
"e": 26455,
"s": 26450,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title></title></head><body> <script type=\"text/javascript\"> var a=eval(\"4+3\"); document.write(a); </script></body></html>",
"e": 26629,
"s": 26455,
"text": null
},
{
"code": null,
"e": 26637,
"s": 26629,
"text": "Output:"
},
{
"code": null,
"e": 26639,
"s": 26637,
"text": "7"
},
{
"code": null,
"e": 27628,
"s": 26639,
"text": "When eval() not evil: For cases where you are running the program on your browser. Also, you need to be very careful not to pass any information that can give rise to code injection and manipulate the program in any way possible. It is generally preferred to use an alternate function in place of eval() if there is any function that can give out the same result as eval(). Closures, object-oriented techniques, functional techniques generally are capable of replacing eval(). For cases where this can’t be done and using eval() is the only way possible it is preferred to the passcode that will not manipulate the DOM in any way.eval() is evil if running on the server using input submitted by a client that was not created by the developer or that was not sanitized by the developer. eval() is not evil if running on the client, even if using unsanitized input crafted by the client. Obviously you should always sanitize the input, as to have some control over what your code consumes."
},
{
"code": null,
"e": 27644,
"s": 27628,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 27651,
"s": 27644,
"text": "Picked"
},
{
"code": null,
"e": 27662,
"s": 27651,
"text": "JavaScript"
},
{
"code": null,
"e": 27679,
"s": 27662,
"text": "Web Technologies"
},
{
"code": null,
"e": 27706,
"s": 27679,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 27804,
"s": 27706,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27844,
"s": 27804,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27889,
"s": 27844,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27950,
"s": 27889,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28022,
"s": 27950,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28074,
"s": 28022,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 28114,
"s": 28074,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28147,
"s": 28114,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28192,
"s": 28147,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28235,
"s": 28192,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
CSS | resize Property - GeeksforGeeks
|
09 Aug, 2019
The resize property in CSS is used to resize the element according to user requirement. It does not apply to inline elements or to block elements where overflow is visible.
Syntax:
resize: none|both|horizontal|vertical|initial;
Property value:
none
both
horizontal
vertical
initialnone: The user is not able to resize the element. It is a default value.Example:<!DOCTYPE html><html> <head> <title>resize property</title> <style> .gfg{ border: 2px solid green; padding: 25px; width: 300px; resize: none; overflow: auto; } h1, h2 { color: green; } </style> </head> <body> <center> <h1>GeeksForGeeks</h1> <h2>resize: none;</h2> <div class="gfg"> <h2 style="color:red;">Sudo Placement</h2> <h3>Course Overview</h3> <p> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> <p> The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> </center> </body></html> Output:both: The element should be resized on both sides i.e. height and width.Example:<!DOCTYPE html><html> <head> <title>resize property</title> <style> .gfg{ border: 2px solid green; padding: 25px; width: 300px; resize: both; overflow: auto; } h1, h2 { color: green; } </style> </head> <body> <center> <h1>GeeksForGeeks</h1> <h2>resize:both;</h2> <div class="gfg"> <h2 style="color:red;">Sudo Placement</h2> <h3>Course Overview</h3> <p> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> <p> The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> </center> </body></html> Output:horizontal: It is used to resize only the width of the element by the user.Example:<!DOCTYPE html><html> <head> <title>tesize property</title> <style> .gfg{ border: 2px solid green; padding: 25px; width: 300px; resize: horizontal; overflow: auto; } h1, h2 { color: green; } </style> </head> <body> <center> <h1>GeeksForGeeks</h1> <h2>resize:horizontal;</h2> <div class="gfg"> <h2 style="color:red;">Sudo Placement</h2> <h3>Course Overview</h3> <p> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> <p> The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> </center> </body></html> Output:vertical: It is only used to resize the height of the element according to the requirement of user.Example:<!DOCTYPE html><html> <head> <title>resize property</title> <style> .gfg{ border: 2px solid green; padding: 25px; width: 300px; resize: vertical; overflow: auto; } h1, h2 { color: green; } </style> </head> <body> <center> <h1 style="color:green;">GeeksForGeeks</h1> <h2 style="color:green;">resize:vertical;</h2> <div class="gfg"> <h2 style="color:red;">Sudo Placement</h2> <h3>Course Overview</h3> <p> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> <p> The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> </center> </body></html> Output:initial: It sets the Property to its default value.It is same as none property.Example;<!DOCTYPE html><html> <head> <title>resize property</title> <style> .gfg{ border: 2px solid green; padding: 25px; width: 300px; resize: initial; overflow: auto; } h1, h2 { color:green; } </style> </head> <body> <center> <h1>GeeksForGeeks</h1> <h2>resize:initial;</h2> <div class="gfg"> <h2 style="color:red;">Sudo Placement</h2> <h3>Course Overview</h3> <p> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> <p> The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> </center> </body></html> Output:Supported Browsers: the browsers supported by resize Property are listed below:Google ChromeInternet ExplorerFirefoxOperaSafariAttention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes
arrow_drop_upSave
none: The user is not able to resize the element. It is a default value.
Example:
<!DOCTYPE html><html> <head> <title>resize property</title> <style> .gfg{ border: 2px solid green; padding: 25px; width: 300px; resize: none; overflow: auto; } h1, h2 { color: green; } </style> </head> <body> <center> <h1>GeeksForGeeks</h1> <h2>resize: none;</h2> <div class="gfg"> <h2 style="color:red;">Sudo Placement</h2> <h3>Course Overview</h3> <p> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> <p> The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> </center> </body></html>
Output:
both: The element should be resized on both sides i.e. height and width.
Example:
<!DOCTYPE html><html> <head> <title>resize property</title> <style> .gfg{ border: 2px solid green; padding: 25px; width: 300px; resize: both; overflow: auto; } h1, h2 { color: green; } </style> </head> <body> <center> <h1>GeeksForGeeks</h1> <h2>resize:both;</h2> <div class="gfg"> <h2 style="color:red;">Sudo Placement</h2> <h3>Course Overview</h3> <p> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> <p> The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> </center> </body></html>
Output:
horizontal: It is used to resize only the width of the element by the user.
Example:
<!DOCTYPE html><html> <head> <title>tesize property</title> <style> .gfg{ border: 2px solid green; padding: 25px; width: 300px; resize: horizontal; overflow: auto; } h1, h2 { color: green; } </style> </head> <body> <center> <h1>GeeksForGeeks</h1> <h2>resize:horizontal;</h2> <div class="gfg"> <h2 style="color:red;">Sudo Placement</h2> <h3>Course Overview</h3> <p> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> <p> The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> </center> </body></html>
Output:
vertical: It is only used to resize the height of the element according to the requirement of user.
Example:
<!DOCTYPE html><html> <head> <title>resize property</title> <style> .gfg{ border: 2px solid green; padding: 25px; width: 300px; resize: vertical; overflow: auto; } h1, h2 { color: green; } </style> </head> <body> <center> <h1 style="color:green;">GeeksForGeeks</h1> <h2 style="color:green;">resize:vertical;</h2> <div class="gfg"> <h2 style="color:red;">Sudo Placement</h2> <h3>Course Overview</h3> <p> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> <p> The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> </center> </body></html>
Output:
initial: It sets the Property to its default value.It is same as none property.
Example;
<!DOCTYPE html><html> <head> <title>resize property</title> <style> .gfg{ border: 2px solid green; padding: 25px; width: 300px; resize: initial; overflow: auto; } h1, h2 { color:green; } </style> </head> <body> <center> <h1>GeeksForGeeks</h1> <h2>resize:initial;</h2> <div class="gfg"> <h2 style="color:red;">Sudo Placement</h2> <h3>Course Overview</h3> <p> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> <p> The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> </center> </body></html>
Output:
Supported Browsers: the browsers supported by resize Property are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Properties
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
|
[
{
"code": null,
"e": 24905,
"s": 24877,
"text": "\n09 Aug, 2019"
},
{
"code": null,
"e": 25078,
"s": 24905,
"text": "The resize property in CSS is used to resize the element according to user requirement. It does not apply to inline elements or to block elements where overflow is visible."
},
{
"code": null,
"e": 25086,
"s": 25078,
"text": "Syntax:"
},
{
"code": null,
"e": 25133,
"s": 25086,
"text": "resize: none|both|horizontal|vertical|initial;"
},
{
"code": null,
"e": 25149,
"s": 25133,
"text": "Property value:"
},
{
"code": null,
"e": 25154,
"s": 25149,
"text": "none"
},
{
"code": null,
"e": 25159,
"s": 25154,
"text": "both"
},
{
"code": null,
"e": 25170,
"s": 25159,
"text": "horizontal"
},
{
"code": null,
"e": 25179,
"s": 25170,
"text": "vertical"
},
{
"code": null,
"e": 31819,
"s": 25179,
"text": "initialnone: The user is not able to resize the element. It is a default value.Example:<!DOCTYPE html><html> <head> <title>resize property</title> <style> .gfg{ border: 2px solid green; padding: 25px; width: 300px; resize: none; overflow: auto; } h1, h2 { color: green; } </style> </head> <body> <center> <h1>GeeksForGeeks</h1> <h2>resize: none;</h2> <div class=\"gfg\"> <h2 style=\"color:red;\">Sudo Placement</h2> <h3>Course Overview</h3> <p> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> <p> The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> </center> </body></html> Output:both: The element should be resized on both sides i.e. height and width.Example:<!DOCTYPE html><html> <head> <title>resize property</title> <style> .gfg{ border: 2px solid green; padding: 25px; width: 300px; resize: both; overflow: auto; } h1, h2 { color: green; } </style> </head> <body> <center> <h1>GeeksForGeeks</h1> <h2>resize:both;</h2> <div class=\"gfg\"> <h2 style=\"color:red;\">Sudo Placement</h2> <h3>Course Overview</h3> <p> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> <p> The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> </center> </body></html> Output:horizontal: It is used to resize only the width of the element by the user.Example:<!DOCTYPE html><html> <head> <title>tesize property</title> <style> .gfg{ border: 2px solid green; padding: 25px; width: 300px; resize: horizontal; overflow: auto; } h1, h2 { color: green; } </style> </head> <body> <center> <h1>GeeksForGeeks</h1> <h2>resize:horizontal;</h2> <div class=\"gfg\"> <h2 style=\"color:red;\">Sudo Placement</h2> <h3>Course Overview</h3> <p> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> <p> The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> </center> </body></html> Output:vertical: It is only used to resize the height of the element according to the requirement of user.Example:<!DOCTYPE html><html> <head> <title>resize property</title> <style> .gfg{ border: 2px solid green; padding: 25px; width: 300px; resize: vertical; overflow: auto; } h1, h2 { color: green; } </style> </head> <body> <center> <h1 style=\"color:green;\">GeeksForGeeks</h1> <h2 style=\"color:green;\">resize:vertical;</h2> <div class=\"gfg\"> <h2 style=\"color:red;\">Sudo Placement</h2> <h3>Course Overview</h3> <p> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> <p> The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> </center> </body></html> Output:initial: It sets the Property to its default value.It is same as none property.Example;<!DOCTYPE html><html> <head> <title>resize property</title> <style> .gfg{ border: 2px solid green; padding: 25px; width: 300px; resize: initial; overflow: auto; } h1, h2 { color:green; } </style> </head> <body> <center> <h1>GeeksForGeeks</h1> <h2>resize:initial;</h2> <div class=\"gfg\"> <h2 style=\"color:red;\">Sudo Placement</h2> <h3>Course Overview</h3> <p> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> <p> The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> </center> </body></html> Output:Supported Browsers: the browsers supported by resize Property are listed below:Google ChromeInternet ExplorerFirefoxOperaSafariAttention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 31892,
"s": 31819,
"text": "none: The user is not able to resize the element. It is a default value."
},
{
"code": null,
"e": 31901,
"s": 31892,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>resize property</title> <style> .gfg{ border: 2px solid green; padding: 25px; width: 300px; resize: none; overflow: auto; } h1, h2 { color: green; } </style> </head> <body> <center> <h1>GeeksForGeeks</h1> <h2>resize: none;</h2> <div class=\"gfg\"> <h2 style=\"color:red;\">Sudo Placement</h2> <h3>Course Overview</h3> <p> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> <p> The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> </center> </body></html> ",
"e": 33061,
"s": 31901,
"text": null
},
{
"code": null,
"e": 33069,
"s": 33061,
"text": "Output:"
},
{
"code": null,
"e": 33142,
"s": 33069,
"text": "both: The element should be resized on both sides i.e. height and width."
},
{
"code": null,
"e": 33151,
"s": 33142,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>resize property</title> <style> .gfg{ border: 2px solid green; padding: 25px; width: 300px; resize: both; overflow: auto; } h1, h2 { color: green; } </style> </head> <body> <center> <h1>GeeksForGeeks</h1> <h2>resize:both;</h2> <div class=\"gfg\"> <h2 style=\"color:red;\">Sudo Placement</h2> <h3>Course Overview</h3> <p> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> <p> The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> </center> </body></html> ",
"e": 34311,
"s": 33151,
"text": null
},
{
"code": null,
"e": 34319,
"s": 34311,
"text": "Output:"
},
{
"code": null,
"e": 34395,
"s": 34319,
"text": "horizontal: It is used to resize only the width of the element by the user."
},
{
"code": null,
"e": 34404,
"s": 34395,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>tesize property</title> <style> .gfg{ border: 2px solid green; padding: 25px; width: 300px; resize: horizontal; overflow: auto; } h1, h2 { color: green; } </style> </head> <body> <center> <h1>GeeksForGeeks</h1> <h2>resize:horizontal;</h2> <div class=\"gfg\"> <h2 style=\"color:red;\">Sudo Placement</h2> <h3>Course Overview</h3> <p> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> <p> The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> </center> </body></html> ",
"e": 35576,
"s": 34404,
"text": null
},
{
"code": null,
"e": 35584,
"s": 35576,
"text": "Output:"
},
{
"code": null,
"e": 35684,
"s": 35584,
"text": "vertical: It is only used to resize the height of the element according to the requirement of user."
},
{
"code": null,
"e": 35693,
"s": 35684,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>resize property</title> <style> .gfg{ border: 2px solid green; padding: 25px; width: 300px; resize: vertical; overflow: auto; } h1, h2 { color: green; } </style> </head> <body> <center> <h1 style=\"color:green;\">GeeksForGeeks</h1> <h2 style=\"color:green;\">resize:vertical;</h2> <div class=\"gfg\"> <h2 style=\"color:red;\">Sudo Placement</h2> <h3>Course Overview</h3> <p> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> <p> The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> </center> </body></html> ",
"e": 36903,
"s": 35693,
"text": null
},
{
"code": null,
"e": 36911,
"s": 36903,
"text": "Output:"
},
{
"code": null,
"e": 36991,
"s": 36911,
"text": "initial: It sets the Property to its default value.It is same as none property."
},
{
"code": null,
"e": 37000,
"s": 36991,
"text": "Example;"
},
{
"code": "<!DOCTYPE html><html> <head> <title>resize property</title> <style> .gfg{ border: 2px solid green; padding: 25px; width: 300px; resize: initial; overflow: auto; } h1, h2 { color:green; } </style> </head> <body> <center> <h1>GeeksForGeeks</h1> <h2>resize:initial;</h2> <div class=\"gfg\"> <h2 style=\"color:red;\">Sudo Placement</h2> <h3>Course Overview</h3> <p> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> <p> The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> </center> </body></html> ",
"e": 38165,
"s": 37000,
"text": null
},
{
"code": null,
"e": 38173,
"s": 38165,
"text": "Output:"
},
{
"code": null,
"e": 38253,
"s": 38173,
"text": "Supported Browsers: the browsers supported by resize Property are listed below:"
},
{
"code": null,
"e": 38267,
"s": 38253,
"text": "Google Chrome"
},
{
"code": null,
"e": 38285,
"s": 38267,
"text": "Internet Explorer"
},
{
"code": null,
"e": 38293,
"s": 38285,
"text": "Firefox"
},
{
"code": null,
"e": 38299,
"s": 38293,
"text": "Opera"
},
{
"code": null,
"e": 38306,
"s": 38299,
"text": "Safari"
},
{
"code": null,
"e": 38443,
"s": 38306,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 38458,
"s": 38443,
"text": "CSS-Properties"
},
{
"code": null,
"e": 38462,
"s": 38458,
"text": "CSS"
},
{
"code": null,
"e": 38467,
"s": 38462,
"text": "HTML"
},
{
"code": null,
"e": 38484,
"s": 38467,
"text": "Web Technologies"
},
{
"code": null,
"e": 38489,
"s": 38484,
"text": "HTML"
},
{
"code": null,
"e": 38587,
"s": 38489,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38637,
"s": 38587,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 38699,
"s": 38637,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 38747,
"s": 38699,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 38805,
"s": 38747,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 38860,
"s": 38805,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 38910,
"s": 38860,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 38972,
"s": 38910,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 39020,
"s": 38972,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 39080,
"s": 39020,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
Java.lang.Number Class in Java - GeeksforGeeks
|
28 Jun, 2021
Most of the time, while working with numbers in java, we use primitive data types. But, Java also provides various numeric wrapper sub classes under the abstract class Number present in java.lang package. There are mainly six sub-classes under Number class.These sub-classes define some useful methods which are used frequently while dealing with numbers.
These classes “wrap” the primitive data type in a corresponding object. Often, the wrapping is done by the compiler. If you use a primitive where an object is expected, the compiler boxes the primitive in its wrapper class for you. Similarly, if you use a Number object when a primitive is expected, the compiler unboxes the object for you. This is also called Autoboxing and Unboxing.Why to use a Number class object over primitive data?
Constants defined by the number class, such as MIN_VALUE and MAX_VALUE, that provide the upper and lower bounds of the data type are very much useful.
Number class object can be used as an argument of a method that expects an object (often used when manipulating collections of numbers).
Class methods can be used for converting values to and from other primitive types, for converting to and from strings, and for converting between number systems (decimal, octal, hexadecimal, binary).
Methods common to all sub classes of Number:
xxx xxxValue() : Here xxx represent primitive number data types (byte, short, int, long, float, double). This method is used to convert the value of this Number object to the primitive data type specified.
xxx xxxValue() : Here xxx represent primitive number data types (byte, short, int, long, float, double). This method is used to convert the value of this Number object to the primitive data type specified.
Syntax :
byte byteValue()
short shortValue()
int intValue()
long longValue()
float floatValue()
double doubleValue()
Parameters :
----
Returns :
the numeric value represented by this object
after conversion to specified type
Java
//Java program to demonstrate xxxValue() methodpublic class Test{ public static void main(String[] args) { // Creating a Double Class object with value "6.9685" Double d = new Double("6.9685"); // Converting this Double(Number) object to // different primitive data types byte b = d.byteValue(); short s = d.shortValue(); int i = d.intValue(); long l = d.longValue(); float f = d.floatValue(); double d1 = d.doubleValue(); System.out.println("value of d after converting it to byte : " + b); System.out.println("value of d after converting it to short : " + s); System.out.println("value of d after converting it to int : " + i); System.out.println("value of d after converting it to long : " + l); System.out.println("value of d after converting it to float : " + f); System.out.println("value of d after converting it to double : " + d1); }}
Output:
value of d after converting it to byte : 6
value of d after converting it to short : 6
value of d after converting it to int : 6
value of d after converting it to long : 6
value of d after converting it to float : 6.9685
value of d after converting it to double : 6.9685
Note : While converting, possible loss of precision may occur. For example, as we can see that fraction part(“.9685”) has been left out while converting from Double object to int data type.
int compareTo(NumberSubClass referenceName) : This method is used to compare this Number object to the argument specified. However, two different types cannot be compared, so both the argument and the Number object that invoke the method should be of the same type.The referenceName could be a Byte, Double, Integer, Float, Long, or Short.
Syntax :
public int compareTo( NumberSubClass referenceName )
Parameters :
referenceName - any NumberSubClass type value
Returns :
the value 0 if the Number is equal to the argument.
the value 1 if the Number is less than the argument.
the value -1 if the Number is greater than the argument.
Java
//Java program to demonstrate compareTo() methodpublic class Test{ public static void main(String[] args) { // creating an Integer Class object with value "10" Integer i = new Integer("10"); // comparing value of i System.out.println(i.compareTo(7)); System.out.println(i.compareTo(11)); System.out.println(i.compareTo(10)); }}
Output:
1
-1
0
boolean equals(Object obj) : This method determine whether this Number object is equal to the argument.
Syntax :
public boolean equals(Object obj)
Parameters :
obj - any object
Returns :
The method returns true if the argument is not null and
is an object of the same type and with the same numeric value,
otherwise false.
Java
//Java program to demonstrate equals() methodpublic class Test{ public static void main(String[] args) { // creating a Short Class object with value "15" Short s = new Short("15"); // creating a Short Class object with value "10" Short x = 10; // creating an Integer Class object with value "15" Integer y = 15; // creating another Short Class object with value "15" Short z = 15; //comparing s with other objects System.out.println(s.equals(x)); System.out.println(s.equals(y)); System.out.println(s.equals(z)); }}
Output:
false
false
true
int parseInt(String s,int radix) : This method is used to get the primitive data type of a String. Radix is used to return decimal(10), octal(8), or hexadecimal(16) etc representation as output.
Syntax :
static int parseInt(String s, int radix)
Parameters :
s - any String representation of decimal
radix - any radix value
Returns :
the integer value represented by the argument in decimal.
Throws :
NumberFormatException : if the string does not contain a parsable integer.
Java
//Java program to demonstrate Integer.parseInt() methodpublic class Test{ public static void main(String[] args) { // parsing different strings int z = Integer.parseInt("654",8); int a = Integer.parseInt("-FF", 16); long l = Long.parseLong("2158611234",10); System.out.println(z); System.out.println(a); System.out.println(l); // run-time NumberFormatException will occur here // "Geeks" is not a parsable string int x = Integer.parseInt("Geeks",8); // run-time NumberFormatException will occur here // (for octal(8),allowed digits are [0-7]) int y = Integer.parseInt("99",8); }}
Output:
428
-255
2158611234
Exception in thread "main" java.lang.NumberFormatException: For input string: "Geeks"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at Test.main(Test.java:17)
int parseInt(String s) : This method is another variant of above method where by default radix is 10(decimal).
Syntax :
static int parseInt(String s)
Parameters :
s - any String representation of decimal
Returns :
the integer value represented by the argument in decimal.
Throws :
NumberFormatException : if the string does not contain a parsable integer.
Java
//Java program to demonstrate Integer.parseInt() methodpublic class Test{ public static void main(String[] args) { // parsing different strings int z = Integer.parseInt("654"); long l = Long.parseLong("2158611234"); System.out.println(z); System.out.println(l); // run-time NumberFormatException will occur here // "Geeks" is not a parsable string int x = Integer.parseInt("Geeks"); // run-time NumberFormatException will occur here // (for decimal(10),allowed digits are [0-9]) int a = Integer.parseInt("-FF"); }}
Output:
654
2158611234
Exception in thread "main" java.lang.NumberFormatException: For input string: "Geeks"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at Test.main(Test.java:15)
String toString() : There are two variants of toString() method. They are used to get String representation of a number. The other variants of these methods are Integer.toBinaryString(int i), Integer.toHexString(int i), Integer.toOctalString(int i) which will return binary, hexa-decimal, octal string representation of specified integer(i) respectively.
Syntax :
String toString()
String toString(int i)
Parameters :
String toString() - no parameter
String toString(int i) - i: any integer value
Returns :
String toString() -
returns a String object representing the value of the Number object
on which it is invoked.
String toString(int i) -
returns a decimal String object representing the specified integer(i)
Java
//Java program to demonstrate Integer.toString()//and Integer.toString(int i) methodpublic class Test{ public static void main(String[] args) { // demonstrating toString() method Integer x = 12; System.out.println(x.toString()); // demonstrating toString(int i) method System.out.println(Integer.toString(12)); System.out.println(Integer.toBinaryString(152)); System.out.println(Integer.toHexString(152)); System.out.println(Integer.toOctalString(152)); }}
Output:
12
12
10011000
98
230
Integer valueOf() : There are three variants of valueOf() method. All these three methods return an Integer object holding the value of a primitive integer.
Syntax :
Integer valueOf(int i)
Integer valueOf(String s)
Integer valueOf(String s, int radix)
Parameters :
i - any integer value
s - any String representation of decimal
radix - any radix value
Returns :
valueOf(int i) : an Integer object holding the valuerepresented by the int argument.
valueOf(String s) : an Integer object holding value represented by the string argument.
valueOf(String s, int radix) : an Integer object holding the value
represented by the string argument with base radix.
Throws :
valueOf(String s) -
NumberFormatException : if the string does not contain a parsable integer.
valueOf(String s, int radix) -
NumberFormatException : if the string does not contain a parsable integer.
Java
// Java program to demonstrate valueOf() methodpublic class Test{ public static void main(String[] args) { // demonstrating valueOf(int i) method System.out.println("Demonstrating valueOf(int i) method"); Integer i =Integer.valueOf(50); Double d = Double.valueOf(9.36); System.out.println(i); System.out.println(d); // demonstrating valueOf(String s) method System.out.println("Demonstrating valueOf(String s) method"); Integer n = Integer.valueOf("333"); Integer m = Integer.valueOf("-255"); System.out.println(n); System.out.println(m); // demonstrating valueOf(String s,int radix) method System.out.println("Demonstrating (String s,int radix) method"); Integer y = Integer.valueOf("333",8); Integer x = Integer.valueOf("-255",16); Long l = Long.valueOf("51688245",16); System.out.println(y); System.out.println(x); System.out.println(l); // run-time NumberFormatException will occur in below cases Integer a = Integer.valueOf("Geeks"); Integer b = Integer.valueOf("Geeks",16); }}
Output:
Demonstrating valueOf(int i) method
50
9.36
Demonstrating valueOf(String s) method
333
-255
Demonstrating (String s,int radix) method
219
-597
1365803589
Exception in thread "main" java.lang.NumberFormatException: For input string: "Geeks"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.valueOf(Integer.java:766)
at Test.main(Test.java:28)
Practice Question: What is the output of the give java code?
Java
public class Test{ public static void main(String[] args) { Integer i = Integer.parseInt("Kona", 27); System.out.println(i); }}
Options :
A) NumberFormatException at run-time
B) NumberFormatException at compile-time
C) 411787
Answer :
C) 411787
Explanation : Since radix is 27,so allowed characters in a String literal are [0-9],[A-Q](for 10 to 26).So its value will calculated as follows: => a*(27^0) + n*(27^1) + o*(27^2) + k*(27^3) => 10*1 + 23*27 + 24*27*27 + 20*27*27*27 => 10 + 621 + 17496 + 393660 => 411787This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ArunDoddi
Java-lang package
java-wrapper-class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Arrays.sort() in Java with examples
HashMap in Java with Examples
Reverse a string in Java
Stream In Java
Interfaces in Java
How to iterate any Map in Java
|
[
{
"code": null,
"e": 24283,
"s": 24255,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24640,
"s": 24283,
"text": "Most of the time, while working with numbers in java, we use primitive data types. But, Java also provides various numeric wrapper sub classes under the abstract class Number present in java.lang package. There are mainly six sub-classes under Number class.These sub-classes define some useful methods which are used frequently while dealing with numbers. "
},
{
"code": null,
"e": 25081,
"s": 24640,
"text": "These classes “wrap” the primitive data type in a corresponding object. Often, the wrapping is done by the compiler. If you use a primitive where an object is expected, the compiler boxes the primitive in its wrapper class for you. Similarly, if you use a Number object when a primitive is expected, the compiler unboxes the object for you. This is also called Autoboxing and Unboxing.Why to use a Number class object over primitive data? "
},
{
"code": null,
"e": 25232,
"s": 25081,
"text": "Constants defined by the number class, such as MIN_VALUE and MAX_VALUE, that provide the upper and lower bounds of the data type are very much useful."
},
{
"code": null,
"e": 25369,
"s": 25232,
"text": "Number class object can be used as an argument of a method that expects an object (often used when manipulating collections of numbers)."
},
{
"code": null,
"e": 25569,
"s": 25369,
"text": "Class methods can be used for converting values to and from other primitive types, for converting to and from strings, and for converting between number systems (decimal, octal, hexadecimal, binary)."
},
{
"code": null,
"e": 25616,
"s": 25569,
"text": "Methods common to all sub classes of Number: "
},
{
"code": null,
"e": 25824,
"s": 25616,
"text": "xxx xxxValue() : Here xxx represent primitive number data types (byte, short, int, long, float, double). This method is used to convert the value of this Number object to the primitive data type specified. "
},
{
"code": null,
"e": 26032,
"s": 25824,
"text": "xxx xxxValue() : Here xxx represent primitive number data types (byte, short, int, long, float, double). This method is used to convert the value of this Number object to the primitive data type specified. "
},
{
"code": null,
"e": 26262,
"s": 26032,
"text": "Syntax : \nbyte byteValue()\nshort shortValue()\nint intValue()\nlong longValue()\nfloat floatValue()\ndouble doubleValue()\nParameters : \n----\nReturns :\nthe numeric value represented by this object\nafter conversion to specified type\n\n\n"
},
{
"code": null,
"e": 26269,
"s": 26264,
"text": "Java"
},
{
"code": "//Java program to demonstrate xxxValue() methodpublic class Test{ public static void main(String[] args) { // Creating a Double Class object with value \"6.9685\" Double d = new Double(\"6.9685\"); // Converting this Double(Number) object to // different primitive data types byte b = d.byteValue(); short s = d.shortValue(); int i = d.intValue(); long l = d.longValue(); float f = d.floatValue(); double d1 = d.doubleValue(); System.out.println(\"value of d after converting it to byte : \" + b); System.out.println(\"value of d after converting it to short : \" + s); System.out.println(\"value of d after converting it to int : \" + i); System.out.println(\"value of d after converting it to long : \" + l); System.out.println(\"value of d after converting it to float : \" + f); System.out.println(\"value of d after converting it to double : \" + d1); }}",
"e": 27252,
"s": 26269,
"text": null
},
{
"code": null,
"e": 27262,
"s": 27252,
"text": "Output: "
},
{
"code": null,
"e": 27536,
"s": 27262,
"text": "value of d after converting it to byte : 6\nvalue of d after converting it to short : 6\nvalue of d after converting it to int : 6\nvalue of d after converting it to long : 6\nvalue of d after converting it to float : 6.9685\nvalue of d after converting it to double : 6.9685\n\n\n"
},
{
"code": null,
"e": 27728,
"s": 27536,
"text": "Note : While converting, possible loss of precision may occur. For example, as we can see that fraction part(“.9685”) has been left out while converting from Double object to int data type. "
},
{
"code": null,
"e": 28070,
"s": 27728,
"text": "int compareTo(NumberSubClass referenceName) : This method is used to compare this Number object to the argument specified. However, two different types cannot be compared, so both the argument and the Number object that invoke the method should be of the same type.The referenceName could be a Byte, Double, Integer, Float, Long, or Short. "
},
{
"code": null,
"e": 28368,
"s": 28070,
"text": "Syntax : \npublic int compareTo( NumberSubClass referenceName )\nParameters : \nreferenceName - any NumberSubClass type value\nReturns :\nthe value 0 if the Number is equal to the argument.\nthe value 1 if the Number is less than the argument.\nthe value -1 if the Number is greater than the argument.\n\n\n"
},
{
"code": null,
"e": 28375,
"s": 28370,
"text": "Java"
},
{
"code": "//Java program to demonstrate compareTo() methodpublic class Test{ public static void main(String[] args) { // creating an Integer Class object with value \"10\" Integer i = new Integer(\"10\"); // comparing value of i System.out.println(i.compareTo(7)); System.out.println(i.compareTo(11)); System.out.println(i.compareTo(10)); }}",
"e": 28759,
"s": 28375,
"text": null
},
{
"code": null,
"e": 28769,
"s": 28759,
"text": "Output: "
},
{
"code": null,
"e": 28777,
"s": 28769,
"text": "1\n-1\n0\n"
},
{
"code": null,
"e": 28885,
"s": 28779,
"text": "boolean equals(Object obj) : This method determine whether this Number object is equal to the argument. "
},
{
"code": null,
"e": 29110,
"s": 28885,
"text": "Syntax : \npublic boolean equals(Object obj)\nParameters : \nobj - any object\nReturns :\nThe method returns true if the argument is not null and \nis an object of the same type and with the same numeric value,\notherwise false.\n\n\n"
},
{
"code": null,
"e": 29117,
"s": 29112,
"text": "Java"
},
{
"code": "//Java program to demonstrate equals() methodpublic class Test{ public static void main(String[] args) { // creating a Short Class object with value \"15\" Short s = new Short(\"15\"); // creating a Short Class object with value \"10\" Short x = 10; // creating an Integer Class object with value \"15\" Integer y = 15; // creating another Short Class object with value \"15\" Short z = 15; //comparing s with other objects System.out.println(s.equals(x)); System.out.println(s.equals(y)); System.out.println(s.equals(z)); }}",
"e": 29746,
"s": 29117,
"text": null
},
{
"code": null,
"e": 29756,
"s": 29746,
"text": "Output: "
},
{
"code": null,
"e": 29776,
"s": 29756,
"text": "false\nfalse\ntrue\n\n\n"
},
{
"code": null,
"e": 29975,
"s": 29778,
"text": "int parseInt(String s,int radix) : This method is used to get the primitive data type of a String. Radix is used to return decimal(10), octal(8), or hexadecimal(16) etc representation as output. "
},
{
"code": null,
"e": 30260,
"s": 29975,
"text": "Syntax : \nstatic int parseInt(String s, int radix)\nParameters : \ns - any String representation of decimal\nradix - any radix value\nReturns :\nthe integer value represented by the argument in decimal.\nThrows :\nNumberFormatException : if the string does not contain a parsable integer.\n\n\n"
},
{
"code": null,
"e": 30267,
"s": 30262,
"text": "Java"
},
{
"code": "//Java program to demonstrate Integer.parseInt() methodpublic class Test{ public static void main(String[] args) { // parsing different strings int z = Integer.parseInt(\"654\",8); int a = Integer.parseInt(\"-FF\", 16); long l = Long.parseLong(\"2158611234\",10); System.out.println(z); System.out.println(a); System.out.println(l); // run-time NumberFormatException will occur here // \"Geeks\" is not a parsable string int x = Integer.parseInt(\"Geeks\",8); // run-time NumberFormatException will occur here // (for octal(8),allowed digits are [0-7]) int y = Integer.parseInt(\"99\",8); }}",
"e": 30999,
"s": 30267,
"text": null
},
{
"code": null,
"e": 31009,
"s": 30999,
"text": "Output: "
},
{
"code": null,
"e": 31286,
"s": 31009,
"text": "428\n-255\n2158611234\nException in thread \"main\" java.lang.NumberFormatException: For input string: \"Geeks\"\n at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)\n at java.lang.Integer.parseInt(Integer.java:580)\n at Test.main(Test.java:17)\n\n\n"
},
{
"code": null,
"e": 31401,
"s": 31288,
"text": "int parseInt(String s) : This method is another variant of above method where by default radix is 10(decimal). "
},
{
"code": null,
"e": 31651,
"s": 31401,
"text": "Syntax : \nstatic int parseInt(String s)\nParameters : \ns - any String representation of decimal\nReturns :\nthe integer value represented by the argument in decimal.\nThrows :\nNumberFormatException : if the string does not contain a parsable integer.\n\n\n"
},
{
"code": null,
"e": 31658,
"s": 31653,
"text": "Java"
},
{
"code": "//Java program to demonstrate Integer.parseInt() methodpublic class Test{ public static void main(String[] args) { // parsing different strings int z = Integer.parseInt(\"654\"); long l = Long.parseLong(\"2158611234\"); System.out.println(z); System.out.println(l); // run-time NumberFormatException will occur here // \"Geeks\" is not a parsable string int x = Integer.parseInt(\"Geeks\"); // run-time NumberFormatException will occur here // (for decimal(10),allowed digits are [0-9]) int a = Integer.parseInt(\"-FF\"); }}",
"e": 32311,
"s": 31658,
"text": null
},
{
"code": null,
"e": 32321,
"s": 32311,
"text": "Output: "
},
{
"code": null,
"e": 32645,
"s": 32321,
"text": "654\n2158611234\nException in thread \"main\" java.lang.NumberFormatException: For input string: \"Geeks\"\n at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)\n at java.lang.Integer.parseInt(Integer.java:580)\n at java.lang.Integer.parseInt(Integer.java:615)\n at Test.main(Test.java:15)\n\n\n"
},
{
"code": null,
"e": 33004,
"s": 32647,
"text": "String toString() : There are two variants of toString() method. They are used to get String representation of a number. The other variants of these methods are Integer.toBinaryString(int i), Integer.toHexString(int i), Integer.toOctalString(int i) which will return binary, hexa-decimal, octal string representation of specified integer(i) respectively. "
},
{
"code": null,
"e": 33369,
"s": 33004,
"text": "Syntax : \nString toString()\nString toString(int i)\nParameters : \nString toString() - no parameter\nString toString(int i) - i: any integer value\nReturns :\nString toString() -\nreturns a String object representing the value of the Number object \non which it is invoked.\nString toString(int i) -\nreturns a decimal String object representing the specified integer(i)\n\n\n"
},
{
"code": null,
"e": 33374,
"s": 33369,
"text": "Java"
},
{
"code": "//Java program to demonstrate Integer.toString()//and Integer.toString(int i) methodpublic class Test{ public static void main(String[] args) { // demonstrating toString() method Integer x = 12; System.out.println(x.toString()); // demonstrating toString(int i) method System.out.println(Integer.toString(12)); System.out.println(Integer.toBinaryString(152)); System.out.println(Integer.toHexString(152)); System.out.println(Integer.toOctalString(152)); }}",
"e": 33923,
"s": 33374,
"text": null
},
{
"code": null,
"e": 33933,
"s": 33923,
"text": "Output: "
},
{
"code": null,
"e": 33956,
"s": 33933,
"text": "12\n12\n10011000\n98\n230\n"
},
{
"code": null,
"e": 34117,
"s": 33958,
"text": "Integer valueOf() : There are three variants of valueOf() method. All these three methods return an Integer object holding the value of a primitive integer. "
},
{
"code": null,
"e": 34830,
"s": 34117,
"text": "Syntax : \nInteger valueOf(int i)\nInteger valueOf(String s)\nInteger valueOf(String s, int radix)\nParameters : \ni - any integer value\ns - any String representation of decimal\nradix - any radix value\nReturns :\nvalueOf(int i) : an Integer object holding the valuerepresented by the int argument.\nvalueOf(String s) : an Integer object holding value represented by the string argument.\nvalueOf(String s, int radix) : an Integer object holding the value\n represented by the string argument with base radix.\nThrows :\nvalueOf(String s) -\nNumberFormatException : if the string does not contain a parsable integer.\nvalueOf(String s, int radix) -\nNumberFormatException : if the string does not contain a parsable integer.\n\n\n"
},
{
"code": null,
"e": 34837,
"s": 34832,
"text": "Java"
},
{
"code": "// Java program to demonstrate valueOf() methodpublic class Test{ public static void main(String[] args) { // demonstrating valueOf(int i) method System.out.println(\"Demonstrating valueOf(int i) method\"); Integer i =Integer.valueOf(50); Double d = Double.valueOf(9.36); System.out.println(i); System.out.println(d); // demonstrating valueOf(String s) method System.out.println(\"Demonstrating valueOf(String s) method\"); Integer n = Integer.valueOf(\"333\"); Integer m = Integer.valueOf(\"-255\"); System.out.println(n); System.out.println(m); // demonstrating valueOf(String s,int radix) method System.out.println(\"Demonstrating (String s,int radix) method\"); Integer y = Integer.valueOf(\"333\",8); Integer x = Integer.valueOf(\"-255\",16); Long l = Long.valueOf(\"51688245\",16); System.out.println(y); System.out.println(x); System.out.println(l); // run-time NumberFormatException will occur in below cases Integer a = Integer.valueOf(\"Geeks\"); Integer b = Integer.valueOf(\"Geeks\",16); }}",
"e": 36029,
"s": 34837,
"text": null
},
{
"code": null,
"e": 36039,
"s": 36029,
"text": "Output: "
},
{
"code": null,
"e": 36502,
"s": 36039,
"text": "Demonstrating valueOf(int i) method\n50\n9.36\nDemonstrating valueOf(String s) method\n333\n-255\nDemonstrating (String s,int radix) method\n219\n-597\n1365803589\n\nException in thread \"main\" java.lang.NumberFormatException: For input string: \"Geeks\"\n at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)\n at java.lang.Integer.parseInt(Integer.java:580)\n at java.lang.Integer.valueOf(Integer.java:766)\n at Test.main(Test.java:28)\n\n\n"
},
{
"code": null,
"e": 36567,
"s": 36504,
"text": "Practice Question: What is the output of the give java code? "
},
{
"code": null,
"e": 36572,
"s": 36567,
"text": "Java"
},
{
"code": "public class Test{ public static void main(String[] args) { Integer i = Integer.parseInt(\"Kona\", 27); System.out.println(i); }}",
"e": 36718,
"s": 36572,
"text": null
},
{
"code": null,
"e": 36730,
"s": 36718,
"text": "Options : "
},
{
"code": null,
"e": 36821,
"s": 36730,
"text": "A) NumberFormatException at run-time\nB) NumberFormatException at compile-time\nC) 411787\n\n\n"
},
{
"code": null,
"e": 36832,
"s": 36821,
"text": "Answer : "
},
{
"code": null,
"e": 36845,
"s": 36832,
"text": "C) 411787\n\n\n"
},
{
"code": null,
"e": 37537,
"s": 36845,
"text": "Explanation : Since radix is 27,so allowed characters in a String literal are [0-9],[A-Q](for 10 to 26).So its value will calculated as follows: => a*(27^0) + n*(27^1) + o*(27^2) + k*(27^3) => 10*1 + 23*27 + 24*27*27 + 20*27*27*27 => 10 + 621 + 17496 + 393660 => 411787This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 37547,
"s": 37537,
"text": "ArunDoddi"
},
{
"code": null,
"e": 37565,
"s": 37547,
"text": "Java-lang package"
},
{
"code": null,
"e": 37584,
"s": 37565,
"text": "java-wrapper-class"
},
{
"code": null,
"e": 37589,
"s": 37584,
"text": "Java"
},
{
"code": null,
"e": 37594,
"s": 37589,
"text": "Java"
},
{
"code": null,
"e": 37692,
"s": 37594,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37707,
"s": 37692,
"text": "Arrays in Java"
},
{
"code": null,
"e": 37751,
"s": 37707,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 37773,
"s": 37751,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 37824,
"s": 37773,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 37860,
"s": 37824,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 37890,
"s": 37860,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 37915,
"s": 37890,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 37930,
"s": 37915,
"text": "Stream In Java"
},
{
"code": null,
"e": 37949,
"s": 37930,
"text": "Interfaces in Java"
}
] |
Smallest perfect power of 2 greater than n (without using arithmetic operators) - GeeksforGeeks
|
05 Mar, 2021
Given a non-negative integer n. The problem is to find the smallest perfect power of 2 which is greater than n without using the arithmetic operators.Examples :
Input : n = 10
Output : 16
Input : n = 128
Output : 256
Algorithm :
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of smallest perfect power// of 2 greater than n#include <bits/stdc++.h> using namespace std; // Function to find smallest perfect power// of 2 greater than nunsigned int perfectPowerOf2(unsigned int n){ // To store perfect power of 2 unsigned int per_pow = 1; while (n > 0) { // bitwise left shift by 1 per_pow = per_pow << 1; // bitwise right shift by 1 n = n >> 1; } // Required perfect power of 2 return per_pow;} // Driver program to test aboveint main(){ unsigned int n = 128; cout << "Perfect power of 2 greater than " << n << ": " << perfectPowerOf2(n); return 0;}
// JAVA Code for Smallest perfect// power of 2 greater than nimport java.util.*; class GFG { // Function to find smallest perfect // power of 2 greater than n static int perfectPowerOf2( int n) { // To store perfect power of 2 int per_pow = 1; while (n > 0) { // bitwise left shift by 1 per_pow = per_pow << 1; n = n >> 1; } // Required perfect power of 2 return per_pow; } // Driver program public static void main(String[] args) { int n = 12; System.out.println("Perfect power of 2 greater than " + n + ": " + perfectPowerOf2(n)); } } //This code is contributed by Arnav Kr. Mandal.
# Python3 implementation of smallest# perfect power of 2 greater than n # Function to find smallest perfect# power of 2 greater than ndef perfectPowerOf2( n ): # To store perfect power of 2 per_pow = 1 while n > 0: # bitwise left shift by 1 per_pow = per_pow << 1 # bitwise right shift by 1 n = n >> 1 # Required perfect power of 2 return per_pow # Driver program to test aboven = 128print("Perfect power of 2 greater than", n, ":",perfectPowerOf2(n)) # This code is contributed by "Sharad_Bhardwaj".
// C# Code for Smallest perfect// power of 2 greater than nusing System; class GFG { // Function to find smallest perfect // power of 2 greater than n static int perfectPowerOf2(int n) { // To store perfect power of 2 int per_pow = 1; while (n > 0) { // bitwise left shift by 1 per_pow = per_pow << 1; n = n >> 1; } // Required perfect power of 2 return per_pow; } // Driver program public static void Main() { int n = 128; Console.WriteLine("Perfect power of 2 greater than " + n + ": " + perfectPowerOf2(n)); }} // This code is contributed by Sam007
<?php// php implementation of// smallest perfect power// of 2 greater than n // Function to find smallest// perfect power of 2// greater than nfunction perfectPowerOf2($n){ // To store perfect power of 2 $per_pow = 1; while ($n > 0) { // bitwise left shift by 1 $per_pow = $per_pow << 1; // bitwise right shift by 1 $n = $n >> 1; } // Required perfect power of 2 return $per_pow;} // Driver code $n = 128; echo "Perfect power of 2 greater than ". $n . ": ".perfectPowerOf2($n); // This code is contributed by mits?>
<script> // JavaScript implementation of smallest perfect power// of 2 greater than n // Function to find smallest perfect power// of 2 greater than nfunction perfectPowerOf2(n){ // To store perfect power of 2 let per_pow = 1; while (n > 0) { // bitwise left shift by 1 per_pow = per_pow << 1; // bitwise right shift by 1 n = n >> 1; } // Required perfect power of 2 return per_pow;} // Driver program to test above let n = 128; document.write("Perfect power of 2 greater than " + n + ": " + perfectPowerOf2(n)); // This code is contributed by Surbhi Tyagi. </script>
Output:
Perfect power of 2 greater than 128: 256
Time Complexity: O(num), where num is the number of bits in the binary representation of n.
Mithun Kumar
surbhityagi15
Bit Magic
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
Find the size of Largest Subset with positive Bitwise AND
Check whether bitwise AND of a number with any subset of an array is zero or not
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 two nibbles in a byte
Check for Integer Overflow
Swap bits in a given number
Reverse actual bits of the given number
Bit Tricks for Competitive Programming
|
[
{
"code": null,
"e": 26277,
"s": 26249,
"text": "\n05 Mar, 2021"
},
{
"code": null,
"e": 26440,
"s": 26277,
"text": "Given a non-negative integer n. The problem is to find the smallest perfect power of 2 which is greater than n without using the arithmetic operators.Examples : "
},
{
"code": null,
"e": 26497,
"s": 26440,
"text": "Input : n = 10\nOutput : 16\n\nInput : n = 128\nOutput : 256"
},
{
"code": null,
"e": 26513,
"s": 26499,
"text": "Algorithm : "
},
{
"code": null,
"e": 26519,
"s": 26515,
"text": "C++"
},
{
"code": null,
"e": 26524,
"s": 26519,
"text": "Java"
},
{
"code": null,
"e": 26532,
"s": 26524,
"text": "Python3"
},
{
"code": null,
"e": 26535,
"s": 26532,
"text": "C#"
},
{
"code": null,
"e": 26539,
"s": 26535,
"text": "PHP"
},
{
"code": null,
"e": 26550,
"s": 26539,
"text": "Javascript"
},
{
"code": "// C++ implementation of smallest perfect power// of 2 greater than n#include <bits/stdc++.h> using namespace std; // Function to find smallest perfect power// of 2 greater than nunsigned int perfectPowerOf2(unsigned int n){ // To store perfect power of 2 unsigned int per_pow = 1; while (n > 0) { // bitwise left shift by 1 per_pow = per_pow << 1; // bitwise right shift by 1 n = n >> 1; } // Required perfect power of 2 return per_pow;} // Driver program to test aboveint main(){ unsigned int n = 128; cout << \"Perfect power of 2 greater than \" << n << \": \" << perfectPowerOf2(n); return 0;}",
"e": 27212,
"s": 26550,
"text": null
},
{
"code": "// JAVA Code for Smallest perfect// power of 2 greater than nimport java.util.*; class GFG { // Function to find smallest perfect // power of 2 greater than n static int perfectPowerOf2( int n) { // To store perfect power of 2 int per_pow = 1; while (n > 0) { // bitwise left shift by 1 per_pow = per_pow << 1; n = n >> 1; } // Required perfect power of 2 return per_pow; } // Driver program public static void main(String[] args) { int n = 12; System.out.println(\"Perfect power of 2 greater than \" + n + \": \" + perfectPowerOf2(n)); } } //This code is contributed by Arnav Kr. Mandal.",
"e": 28004,
"s": 27212,
"text": null
},
{
"code": "# Python3 implementation of smallest# perfect power of 2 greater than n # Function to find smallest perfect# power of 2 greater than ndef perfectPowerOf2( n ): # To store perfect power of 2 per_pow = 1 while n > 0: # bitwise left shift by 1 per_pow = per_pow << 1 # bitwise right shift by 1 n = n >> 1 # Required perfect power of 2 return per_pow # Driver program to test aboven = 128print(\"Perfect power of 2 greater than\", n, \":\",perfectPowerOf2(n)) # This code is contributed by \"Sharad_Bhardwaj\".",
"e": 28592,
"s": 28004,
"text": null
},
{
"code": "// C# Code for Smallest perfect// power of 2 greater than nusing System; class GFG { // Function to find smallest perfect // power of 2 greater than n static int perfectPowerOf2(int n) { // To store perfect power of 2 int per_pow = 1; while (n > 0) { // bitwise left shift by 1 per_pow = per_pow << 1; n = n >> 1; } // Required perfect power of 2 return per_pow; } // Driver program public static void Main() { int n = 128; Console.WriteLine(\"Perfect power of 2 greater than \" + n + \": \" + perfectPowerOf2(n)); }} // This code is contributed by Sam007",
"e": 29298,
"s": 28592,
"text": null
},
{
"code": "<?php// php implementation of// smallest perfect power// of 2 greater than n // Function to find smallest// perfect power of 2// greater than nfunction perfectPowerOf2($n){ // To store perfect power of 2 $per_pow = 1; while ($n > 0) { // bitwise left shift by 1 $per_pow = $per_pow << 1; // bitwise right shift by 1 $n = $n >> 1; } // Required perfect power of 2 return $per_pow;} // Driver code $n = 128; echo \"Perfect power of 2 greater than \". $n . \": \".perfectPowerOf2($n); // This code is contributed by mits?>",
"e": 29890,
"s": 29298,
"text": null
},
{
"code": "<script> // JavaScript implementation of smallest perfect power// of 2 greater than n // Function to find smallest perfect power// of 2 greater than nfunction perfectPowerOf2(n){ // To store perfect power of 2 let per_pow = 1; while (n > 0) { // bitwise left shift by 1 per_pow = per_pow << 1; // bitwise right shift by 1 n = n >> 1; } // Required perfect power of 2 return per_pow;} // Driver program to test above let n = 128; document.write(\"Perfect power of 2 greater than \" + n + \": \" + perfectPowerOf2(n)); // This code is contributed by Surbhi Tyagi. </script>",
"e": 30525,
"s": 29890,
"text": null
},
{
"code": null,
"e": 30534,
"s": 30525,
"text": "Output: "
},
{
"code": null,
"e": 30575,
"s": 30534,
"text": "Perfect power of 2 greater than 128: 256"
},
{
"code": null,
"e": 30668,
"s": 30575,
"text": "Time Complexity: O(num), where num is the number of bits in the binary representation of n. "
},
{
"code": null,
"e": 30681,
"s": 30668,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 30695,
"s": 30681,
"text": "surbhityagi15"
},
{
"code": null,
"e": 30705,
"s": 30695,
"text": "Bit Magic"
},
{
"code": null,
"e": 30715,
"s": 30705,
"text": "Bit Magic"
},
{
"code": null,
"e": 30813,
"s": 30715,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30864,
"s": 30813,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 30922,
"s": 30864,
"text": "Find the size of Largest Subset with positive Bitwise AND"
},
{
"code": null,
"e": 31003,
"s": 30922,
"text": "Check whether bitwise AND of a number with any subset of an array is zero or not"
},
{
"code": null,
"e": 31067,
"s": 31003,
"text": "Write an Efficient Method to Check if a Number is Multiple of 3"
},
{
"code": null,
"e": 31121,
"s": 31067,
"text": "Highest power of 2 less than or equal to given number"
},
{
"code": null,
"e": 31148,
"s": 31121,
"text": "Swap two nibbles in a byte"
},
{
"code": null,
"e": 31175,
"s": 31148,
"text": "Check for Integer Overflow"
},
{
"code": null,
"e": 31203,
"s": 31175,
"text": "Swap bits in a given number"
},
{
"code": null,
"e": 31243,
"s": 31203,
"text": "Reverse actual bits of the given number"
}
] |
Python range() Method - GeeksforGeeks
|
05 Aug, 2021
There are many iterables in Python like list, tuple etc. range() gives another way to initialize a sequence of numbers using some conditions.range() is commonly used in for looping hence, knowledge of same is key aspect when dealing with any kind of Python code.
Syntax : range(start, stop, step)Parameters : start : Element from which sequence constructed has to start. (default:0) stop : Element number at which numbers in sequence have to end (exclusive). step : Can be +ve or -ve number, denoting the elements need to be skipped during filling of list. (default:1)Returns : The list using the formula : list[n] = start + step*n (for both positive and negative step) where, n >=0 and list[n] = 0 and list[n] > stop (for negative step)Returns ValueError if step is 0. Value constraint is checked in case of step, failing to meet returns empty sequence, else returns sequence according to formula.
Code #1 : Demonstrating range() without step parameter
Python3
# Python3 code to demonstrate the# working of range() without step # using range()lis1 = list(range(6))lis2 = list(range(3, 6))lis3 = list(range(-6, 2)) # initializing list using range, 1 parameter# only stop parameterprint("List generated using 1 parameter : " + str(lis1)) # initializing list using range, 2 parameters# only step and stop parametersprint("List generated using 2 parameters : " + str(lis2)) # initializing list using range, 2 parameter# only step and stop parametersprint("List generated using 2 parameters with negatives : " + str(lis3))
Output:
List generated using 1 parameter : [0, 1, 2, 3, 4, 5]
List generated using 2 parameters : [3, 4, 5]
List generated using 2 parameters with negatives : [-6, -5, -4, -3, -2, -1, 0, 1]
Code #2 : Demonstrating range() using step
Python3
# Python 3 code to demonstrate the# working of range() with step # initializing list using range# using stepprint("List generated using step : " + str(list(range(3, 10, 2)))) # initializing list using range# using negative stepprint("List generated using negative step : " + str(list(range(10, -5, -3)))) # initializing list using range# using negative step,# value constraints fail caseprint("List generated using step, value constraints fail : " + str(list(range(10, -5, 3)))) # initializing list using range# using 0 step# errorprint("List generated using 0 step : " + str(list(range(3, 7, 0))))
Output:
List generated using step : [3, 5, 7, 9]
List generated using negative step : [10, 7, 4, 1, -2]
List generated using step, value constraints fail : []
Exception:
Traceback (most recent call last):
File "/home/bdae725dff7b38d3681eee38f6a6d434.py", line 23, in
print("List generated using 0 step : " + str(list(range(3, 7, 0))))
ValueError: range() arg 3 must not be zero
saurabh1990aror
Python-Built-in-functions
python-list
python-tuple
Python
python-list
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?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25562,
"s": 25534,
"text": "\n05 Aug, 2021"
},
{
"code": null,
"e": 25826,
"s": 25562,
"text": "There are many iterables in Python like list, tuple etc. range() gives another way to initialize a sequence of numbers using some conditions.range() is commonly used in for looping hence, knowledge of same is key aspect when dealing with any kind of Python code. "
},
{
"code": null,
"e": 26464,
"s": 25826,
"text": "Syntax : range(start, stop, step)Parameters : start : Element from which sequence constructed has to start. (default:0) stop : Element number at which numbers in sequence have to end (exclusive). step : Can be +ve or -ve number, denoting the elements need to be skipped during filling of list. (default:1)Returns : The list using the formula : list[n] = start + step*n (for both positive and negative step) where, n >=0 and list[n] = 0 and list[n] > stop (for negative step)Returns ValueError if step is 0. Value constraint is checked in case of step, failing to meet returns empty sequence, else returns sequence according to formula. "
},
{
"code": null,
"e": 26521,
"s": 26464,
"text": "Code #1 : Demonstrating range() without step parameter "
},
{
"code": null,
"e": 26529,
"s": 26521,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate the# working of range() without step # using range()lis1 = list(range(6))lis2 = list(range(3, 6))lis3 = list(range(-6, 2)) # initializing list using range, 1 parameter# only stop parameterprint(\"List generated using 1 parameter : \" + str(lis1)) # initializing list using range, 2 parameters# only step and stop parametersprint(\"List generated using 2 parameters : \" + str(lis2)) # initializing list using range, 2 parameter# only step and stop parametersprint(\"List generated using 2 parameters with negatives : \" + str(lis3))",
"e": 27086,
"s": 26529,
"text": null
},
{
"code": null,
"e": 27096,
"s": 27086,
"text": "Output: "
},
{
"code": null,
"e": 27278,
"s": 27096,
"text": "List generated using 1 parameter : [0, 1, 2, 3, 4, 5]\nList generated using 2 parameters : [3, 4, 5]\nList generated using 2 parameters with negatives : [-6, -5, -4, -3, -2, -1, 0, 1]"
},
{
"code": null,
"e": 27324,
"s": 27278,
"text": " Code #2 : Demonstrating range() using step "
},
{
"code": null,
"e": 27332,
"s": 27324,
"text": "Python3"
},
{
"code": "# Python 3 code to demonstrate the# working of range() with step # initializing list using range# using stepprint(\"List generated using step : \" + str(list(range(3, 10, 2)))) # initializing list using range# using negative stepprint(\"List generated using negative step : \" + str(list(range(10, -5, -3)))) # initializing list using range# using negative step,# value constraints fail caseprint(\"List generated using step, value constraints fail : \" + str(list(range(10, -5, 3)))) # initializing list using range# using 0 step# errorprint(\"List generated using 0 step : \" + str(list(range(3, 7, 0))))",
"e": 27996,
"s": 27332,
"text": null
},
{
"code": null,
"e": 28006,
"s": 27996,
"text": "Output: "
},
{
"code": null,
"e": 28157,
"s": 28006,
"text": "List generated using step : [3, 5, 7, 9]\nList generated using negative step : [10, 7, 4, 1, -2]\nList generated using step, value constraints fail : []"
},
{
"code": null,
"e": 28169,
"s": 28157,
"text": "Exception: "
},
{
"code": null,
"e": 28384,
"s": 28169,
"text": "Traceback (most recent call last):\n File \"/home/bdae725dff7b38d3681eee38f6a6d434.py\", line 23, in \n print(\"List generated using 0 step : \" + str(list(range(3, 7, 0))))\nValueError: range() arg 3 must not be zero"
},
{
"code": null,
"e": 28402,
"s": 28386,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 28428,
"s": 28402,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 28440,
"s": 28428,
"text": "python-list"
},
{
"code": null,
"e": 28453,
"s": 28440,
"text": "python-tuple"
},
{
"code": null,
"e": 28460,
"s": 28453,
"text": "Python"
},
{
"code": null,
"e": 28472,
"s": 28460,
"text": "python-list"
},
{
"code": null,
"e": 28570,
"s": 28472,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28602,
"s": 28570,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28644,
"s": 28602,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28686,
"s": 28644,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28742,
"s": 28686,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28769,
"s": 28742,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28800,
"s": 28769,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28839,
"s": 28800,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28868,
"s": 28839,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28890,
"s": 28868,
"text": "Defaultdict in Python"
}
] |
Python program to count number of vowels using sets in given string - GeeksforGeeks
|
18 Dec, 2019
Given a string, count the number of vowels present in given string using Sets.
Prerequisite: Sets in Python
Examples:
Input : GeeksforGeeks
Output : No. of vowels : 5
Input : Hello World
Output : No. of vowels : 3
Approach:1. Create a set of vowels using set() and initialize a count variable to 0.2. Traverse through the alphabets in the string and check if the letter in the string is present in set vowel.3. If it is present, the vowel count is incremented.
Below is the implementation of above approach:
# Python3 code to count vowel in # a string using set # Function to count voweldef vowel_count(str): # Initializing count variable to 0 count = 0 # Creating a set of vowels vowel = set("aeiouAEIOU") # Loop to traverse the alphabet # in the given string for alphabet in str: # If alphabet is present # in set vowel if alphabet in vowel: count = count + 1 print("No. of vowels :", count) # Driver code str = "GeeksforGeeks" # Function Callvowel_count(str)
Output:
No. of vowels : 5
shubham_singh
Python set-programs
Python string-programs
python-set
Python
Python Programs
Strings
python-set
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
|
[
{
"code": null,
"e": 26051,
"s": 26023,
"text": "\n18 Dec, 2019"
},
{
"code": null,
"e": 26130,
"s": 26051,
"text": "Given a string, count the number of vowels present in given string using Sets."
},
{
"code": null,
"e": 26159,
"s": 26130,
"text": "Prerequisite: Sets in Python"
},
{
"code": null,
"e": 26169,
"s": 26159,
"text": "Examples:"
},
{
"code": null,
"e": 26268,
"s": 26169,
"text": "Input : GeeksforGeeks\nOutput : No. of vowels : 5\n\nInput : Hello World\nOutput : No. of vowels : 3\n"
},
{
"code": null,
"e": 26515,
"s": 26268,
"text": "Approach:1. Create a set of vowels using set() and initialize a count variable to 0.2. Traverse through the alphabets in the string and check if the letter in the string is present in set vowel.3. If it is present, the vowel count is incremented."
},
{
"code": null,
"e": 26562,
"s": 26515,
"text": "Below is the implementation of above approach:"
},
{
"code": "# Python3 code to count vowel in # a string using set # Function to count voweldef vowel_count(str): # Initializing count variable to 0 count = 0 # Creating a set of vowels vowel = set(\"aeiouAEIOU\") # Loop to traverse the alphabet # in the given string for alphabet in str: # If alphabet is present # in set vowel if alphabet in vowel: count = count + 1 print(\"No. of vowels :\", count) # Driver code str = \"GeeksforGeeks\" # Function Callvowel_count(str)",
"e": 27109,
"s": 26562,
"text": null
},
{
"code": null,
"e": 27117,
"s": 27109,
"text": "Output:"
},
{
"code": null,
"e": 27136,
"s": 27117,
"text": "No. of vowels : 5\n"
},
{
"code": null,
"e": 27150,
"s": 27136,
"text": "shubham_singh"
},
{
"code": null,
"e": 27170,
"s": 27150,
"text": "Python set-programs"
},
{
"code": null,
"e": 27193,
"s": 27170,
"text": "Python string-programs"
},
{
"code": null,
"e": 27204,
"s": 27193,
"text": "python-set"
},
{
"code": null,
"e": 27211,
"s": 27204,
"text": "Python"
},
{
"code": null,
"e": 27227,
"s": 27211,
"text": "Python Programs"
},
{
"code": null,
"e": 27235,
"s": 27227,
"text": "Strings"
},
{
"code": null,
"e": 27246,
"s": 27235,
"text": "python-set"
},
{
"code": null,
"e": 27254,
"s": 27246,
"text": "Strings"
},
{
"code": null,
"e": 27352,
"s": 27254,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27384,
"s": 27352,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27426,
"s": 27384,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27455,
"s": 27426,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27492,
"s": 27455,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27528,
"s": 27492,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 27550,
"s": 27528,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27589,
"s": 27550,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27635,
"s": 27589,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27673,
"s": 27635,
"text": "Python | Convert a list to dictionary"
}
] |
CSS | rotate3d() Function - GeeksforGeeks
|
08 Aug, 2019
The rotate3d() function is an inbuilt function which is used to rotate an element around a fixed axis in 3D space.
Syntax:
rotate3d( x, y, z, angle )
Parameters: This function accepts four parameters as mentioned above and described below:
x: It holds a number denoting the x-coordinate. Its value lies between 0 to 1.
y: It holds a number denoting the y-coordinate. Its value lies between 0 to 1.
z: It holds a number denoting the z-coordinate. Its value lies between 0 to 1.
angle: It holds the angle of rotation. The positive angle represents a clockwise rotation and a negative angle represents a counter-clockwise rotation.
Below examples illustrate the rotate3d() function in CSS:
Example 1:
<!DOCTYPE html> <html> <head> <title>CSS rotate3d() function</title> <style> body { text-align:center; } h1 { color:green; } .rotate3d_image { transform: rotate3d(1, 1, 0, 60deg); } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>CSS rotate3d() function</h2> <br><br> <img class="rotate3d_image" src= "https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" alt="GeeksforGeeks logo"> </body> </html>
Output:
Example 2:
<!DOCTYPE html> <html> <head> <title>CSS rotate3d() function</title> <style> body { text-align:center; } h1 { color:green; } .GFG { font-size:35px; font-weight:bold; color:green; transform: rotate3d(1, 1, 0, 60deg); } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>CSS rotate3d() function</h2> <br><br> <div class="GFG">Welcome to GeeksforGeeks</div> </body> </html>
Output:
Supported Browsers: The browsers supported by rotate3d() function are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
CSS-Functions
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
How to set space between the flexbox ?
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
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 ?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26621,
"s": 26593,
"text": "\n08 Aug, 2019"
},
{
"code": null,
"e": 26736,
"s": 26621,
"text": "The rotate3d() function is an inbuilt function which is used to rotate an element around a fixed axis in 3D space."
},
{
"code": null,
"e": 26744,
"s": 26736,
"text": "Syntax:"
},
{
"code": null,
"e": 26771,
"s": 26744,
"text": "rotate3d( x, y, z, angle )"
},
{
"code": null,
"e": 26861,
"s": 26771,
"text": "Parameters: This function accepts four parameters as mentioned above and described below:"
},
{
"code": null,
"e": 26940,
"s": 26861,
"text": "x: It holds a number denoting the x-coordinate. Its value lies between 0 to 1."
},
{
"code": null,
"e": 27019,
"s": 26940,
"text": "y: It holds a number denoting the y-coordinate. Its value lies between 0 to 1."
},
{
"code": null,
"e": 27098,
"s": 27019,
"text": "z: It holds a number denoting the z-coordinate. Its value lies between 0 to 1."
},
{
"code": null,
"e": 27250,
"s": 27098,
"text": "angle: It holds the angle of rotation. The positive angle represents a clockwise rotation and a negative angle represents a counter-clockwise rotation."
},
{
"code": null,
"e": 27308,
"s": 27250,
"text": "Below examples illustrate the rotate3d() function in CSS:"
},
{
"code": null,
"e": 27319,
"s": 27308,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title>CSS rotate3d() function</title> <style> body { text-align:center; } h1 { color:green; } .rotate3d_image { transform: rotate3d(1, 1, 0, 60deg); } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>CSS rotate3d() function</h2> <br><br> <img class=\"rotate3d_image\" src= \"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\" alt=\"GeeksforGeeks logo\"> </body> </html> ",
"e": 27878,
"s": 27319,
"text": null
},
{
"code": null,
"e": 27886,
"s": 27878,
"text": "Output:"
},
{
"code": null,
"e": 27897,
"s": 27886,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title>CSS rotate3d() function</title> <style> body { text-align:center; } h1 { color:green; } .GFG { font-size:35px; font-weight:bold; color:green; transform: rotate3d(1, 1, 0, 60deg); } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>CSS rotate3d() function</h2> <br><br> <div class=\"GFG\">Welcome to GeeksforGeeks</div> </body> </html> ",
"e": 28430,
"s": 27897,
"text": null
},
{
"code": null,
"e": 28438,
"s": 28430,
"text": "Output:"
},
{
"code": null,
"e": 28522,
"s": 28438,
"text": "Supported Browsers: The browsers supported by rotate3d() function are listed below:"
},
{
"code": null,
"e": 28536,
"s": 28522,
"text": "Google Chrome"
},
{
"code": null,
"e": 28554,
"s": 28536,
"text": "Internet Explorer"
},
{
"code": null,
"e": 28562,
"s": 28554,
"text": "Firefox"
},
{
"code": null,
"e": 28569,
"s": 28562,
"text": "Safari"
},
{
"code": null,
"e": 28575,
"s": 28569,
"text": "Opera"
},
{
"code": null,
"e": 28589,
"s": 28575,
"text": "CSS-Functions"
},
{
"code": null,
"e": 28593,
"s": 28589,
"text": "CSS"
},
{
"code": null,
"e": 28610,
"s": 28593,
"text": "Web Technologies"
},
{
"code": null,
"e": 28708,
"s": 28610,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28745,
"s": 28708,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 28784,
"s": 28745,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 28813,
"s": 28784,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 28855,
"s": 28813,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 28890,
"s": 28855,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 28930,
"s": 28890,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28963,
"s": 28930,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29008,
"s": 28963,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29051,
"s": 29008,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Java ArrayList of Arrays - GeeksforGeeks
|
08 Oct, 2021
ArrayList of arrays can be created just like any other objects using ArrayList constructor. In 2D arrays, it might happen that most of the part in the array is empty. For optimizing the space complexity, Arraylist of arrays can be used.
ArrayList<String[ ] > geeks = new ArrayList<String[ ] >();
Example:
Input :int array1[] = {1, 2, 3},
int array2[] = {31, 22},
int array3[] = {51, 12, 23}
Output: ArrayList of Arrays = {{1, 2, 3},{31, 22},{51, 12, 23}}
Approach:
Create ArrayList object of String[] type, say, list.
Store arrays of string, say, names[], age[] and address[] into list object.
Print ArrayList of Array.
Below is the implementation of the above approach:
Java
// Java ArrayList of Arraysimport java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // create an ArrayList of String Array type ArrayList<String[]> list = new ArrayList<String[]>(); // create a string array called Names String names[] = { "Rohan", "Ritik", "Prerit" }; // create a string array called Age String age[] = { "23", "20" }; // create a string array called address String address[] = { "Lucknow", "Delhi", "Jaipur" }; // add the above arrays to ArrayList Object list.add(names); list.add(age); list.add(address); // print arrays from ArrayList for (String i[] : list) { System.out.println(Arrays.toString(i)); } }}
[Rohan, Ritik, Prerit]
[23, 20]
[Lucknow, Delhi, Jaipur]
varshagumber28
Java-ArrayList
Picked
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": 25250,
"s": 25222,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 25487,
"s": 25250,
"text": "ArrayList of arrays can be created just like any other objects using ArrayList constructor. In 2D arrays, it might happen that most of the part in the array is empty. For optimizing the space complexity, Arraylist of arrays can be used."
},
{
"code": null,
"e": 25546,
"s": 25487,
"text": "ArrayList<String[ ] > geeks = new ArrayList<String[ ] >();"
},
{
"code": null,
"e": 25555,
"s": 25546,
"text": "Example:"
},
{
"code": null,
"e": 25719,
"s": 25555,
"text": "Input :int array1[] = {1, 2, 3},\n int array2[] = {31, 22},\n int array3[] = {51, 12, 23}\nOutput: ArrayList of Arrays = {{1, 2, 3},{31, 22},{51, 12, 23}}"
},
{
"code": null,
"e": 25730,
"s": 25719,
"text": "Approach: "
},
{
"code": null,
"e": 25783,
"s": 25730,
"text": "Create ArrayList object of String[] type, say, list."
},
{
"code": null,
"e": 25859,
"s": 25783,
"text": "Store arrays of string, say, names[], age[] and address[] into list object."
},
{
"code": null,
"e": 25885,
"s": 25859,
"text": "Print ArrayList of Array."
},
{
"code": null,
"e": 25936,
"s": 25885,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25941,
"s": 25936,
"text": "Java"
},
{
"code": "// Java ArrayList of Arraysimport java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // create an ArrayList of String Array type ArrayList<String[]> list = new ArrayList<String[]>(); // create a string array called Names String names[] = { \"Rohan\", \"Ritik\", \"Prerit\" }; // create a string array called Age String age[] = { \"23\", \"20\" }; // create a string array called address String address[] = { \"Lucknow\", \"Delhi\", \"Jaipur\" }; // add the above arrays to ArrayList Object list.add(names); list.add(age); list.add(address); // print arrays from ArrayList for (String i[] : list) { System.out.println(Arrays.toString(i)); } }}",
"e": 26770,
"s": 25941,
"text": null
},
{
"code": null,
"e": 26827,
"s": 26770,
"text": "[Rohan, Ritik, Prerit]\n[23, 20]\n[Lucknow, Delhi, Jaipur]"
},
{
"code": null,
"e": 26842,
"s": 26827,
"text": "varshagumber28"
},
{
"code": null,
"e": 26857,
"s": 26842,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 26864,
"s": 26857,
"text": "Picked"
},
{
"code": null,
"e": 26869,
"s": 26864,
"text": "Java"
},
{
"code": null,
"e": 26874,
"s": 26869,
"text": "Java"
},
{
"code": null,
"e": 26972,
"s": 26874,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26987,
"s": 26972,
"text": "Stream In Java"
},
{
"code": null,
"e": 27008,
"s": 26987,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27027,
"s": 27008,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27057,
"s": 27027,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27103,
"s": 27057,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27120,
"s": 27103,
"text": "Generics in Java"
},
{
"code": null,
"e": 27141,
"s": 27120,
"text": "Introduction to Java"
},
{
"code": null,
"e": 27184,
"s": 27141,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 27220,
"s": 27184,
"text": "Internal Working of HashMap in Java"
}
] |
Internal Storage in Android with Example - GeeksforGeeks
|
11 Apr, 2022
The aim of this article is to show users how to use internal storage. In this article will be creating an application that can write data to a file and store it in internal storage and read data from the file and display it on the main activity using TextView. Saving and loading data on the internal storage is private for an application that can not be accessed by other applications. When the app is uninstalled the data stored in the internal by that app is removed. To read and write in the android internal storage we have two methods
OpenFileOutput(): used for creating and saving a file. This method returns a FileOutputStream instance.
Syntax: OpenFileOutput(String filename,int mode)
Parameters:
mode:
Context.MODE_PRIVATE: If the file exists then it is overridden else a new file is created.
Context.MODE_APPEND: if the file exists then the data is appended at the end of the file.
Returns:
FileOutputStream object
OpenFileInput(): Used to read data from a file, this returns an FileInputStream instance.
Syntax: OpenFileInput( String filename)
Returns:
FileInputStream object
A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Working with the activity_main.xml file
The activity_main.xml file has the following widgets
One EditText for accepting user inputTwo Buttons one for reading data and the other for writingOne TextView to display the content of the file
One EditText for accepting user input
Two Buttons one for reading data and the other for writing
One TextView to display the content of the file
Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/textView2" android:layout_width="337dp" android:layout_height="28dp" android:text=" File Content " android:textAlignment="center" android:textColor="#000" android:textSize="24sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.52" /> <Button android:id="@+id/write_button" android:layout_width="wrap_content" android:layout_height="48dp" android:layout_marginStart="160dp" android:layout_marginEnd="159dp" android:layout_marginBottom="16dp" android:text="Write" app:layout_constraintBottom_toTopOf="@+id/read_button" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.904" /> <Button android:id="@+id/read_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="160dp" android:layout_marginEnd="158dp" android:layout_marginBottom="48dp" android:text="Read" app:layout_constraintBottom_toTopOf="@+id/textView2" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toStartOf="parent" /> <EditText android:id="@+id/userInput" android:layout_width="319dp" android:layout_height="50dp" android:layout_marginStart="46dp" android:layout_marginTop="91dp" android:layout_marginEnd="46dp" android:ems="10" android:inputType="textPersonName" android:text="Name" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/content" android:layout_width="332dp" android:layout_height="306dp" android:layout_marginStart="33dp" android:layout_marginTop="21dp" android:layout_marginEnd="33dp" android:layout_marginBottom="6dp" android:text="" android:textAlignment="center" android:textColor="#000" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.461" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView2" app:layout_constraintVertical_bias="0.0" /> </androidx.constraintlayout.widget.ConstraintLayout>
Output UI:
Step 3: Working with the MainActivity.java file
Inside the MainActivity.java file we are going to do the following things:
Initialize variables:
Java
private String filename = "demoFile.txt";read = findViewById(R.id.read_button);write = findViewById(R.id.write_button);userInput = findViewById(R.id.userInput);fileContent = findViewById(R.id.content);
The file will be creating is DemoFile.txt. this can be found in Device File Explorer > data > data > application_package > files
Read and Write methods:
The following method is used to read data from the internal data.
Java
private void readData(){ try { FileInputStream fin = openFileInput(filename); int a; StringBuilder temp = new StringBuilder(); while ((a = fin.read()) != -1) { temp.append((char)a); } // setting text from the file. fileContent.setText(temp.toString()); fin.close(); } catch (IOException e) { e.printStackTrace(); } printMessage("reading to file " + filename + " completed..");}
The method used for creating a file and writing data to internal storage.
Java
private void writeData(){ try { FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE); String data = userInput.getText().toString(); fos.write(data.getBytes()); fos.flush(); fos.close(); } catch (IOException e) { e.printStackTrace(); } userInput.setText(""); printMessage("writing to file " + filename + "completed...");}
Below is the complete code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.content.Context;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException; public class MainActivity extends AppCompatActivity implements View.OnClickListener { // declare the variables Button read, write; EditText userInput; TextView fileContent; private String filename = "demoFile.txt"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); read = findViewById(R.id.read_button); write = findViewById(R.id.write_button); userInput = findViewById(R.id.userInput); fileContent = findViewById(R.id.content); read.setOnClickListener(this); write.setOnClickListener(this); } public void printMessage(String m) { Toast.makeText(this, m, Toast.LENGTH_LONG).show(); } @Override public void onClick(View view) { Button b = (Button) view; // get the button text : in out case either read or // write depending on the button pressed. String b_text = b.getText().toString(); switch (b_text.toLowerCase()) { case "write": { writeData(); break; } case "read": { readData(); break; } } } private void writeData() { try { FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE); String data = userInput.getText().toString(); fos.write(data.getBytes()); fos.flush(); fos.close(); } catch (IOException e) { e.printStackTrace(); } userInput.setText(""); printMessage("writing to file " + filename + "completed..."); } private void readData() { try { FileInputStream fin = openFileInput(filename); int a; StringBuilder temp = new StringBuilder(); while ((a = fin.read()) != -1) { temp.append((char) a); } // setting text from the file. fileContent.setText(temp.toString()); fin.close(); } catch (IOException e) { e.printStackTrace(); } printMessage("reading to file " + filename + " completed.."); }}
rkbhola5
android
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
|
[
{
"code": null,
"e": 26381,
"s": 26353,
"text": "\n11 Apr, 2022"
},
{
"code": null,
"e": 26923,
"s": 26381,
"text": "The aim of this article is to show users how to use internal storage. In this article will be creating an application that can write data to a file and store it in internal storage and read data from the file and display it on the main activity using TextView. Saving and loading data on the internal storage is private for an application that can not be accessed by other applications. When the app is uninstalled the data stored in the internal by that app is removed. To read and write in the android internal storage we have two methods "
},
{
"code": null,
"e": 27027,
"s": 26923,
"text": "OpenFileOutput(): used for creating and saving a file. This method returns a FileOutputStream instance."
},
{
"code": null,
"e": 27076,
"s": 27027,
"text": "Syntax: OpenFileOutput(String filename,int mode)"
},
{
"code": null,
"e": 27089,
"s": 27076,
"text": "Parameters: "
},
{
"code": null,
"e": 27096,
"s": 27089,
"text": "mode: "
},
{
"code": null,
"e": 27188,
"s": 27096,
"text": "Context.MODE_PRIVATE: If the file exists then it is overridden else a new file is created. "
},
{
"code": null,
"e": 27278,
"s": 27188,
"text": "Context.MODE_APPEND: if the file exists then the data is appended at the end of the file."
},
{
"code": null,
"e": 27288,
"s": 27278,
"text": "Returns: "
},
{
"code": null,
"e": 27314,
"s": 27288,
"text": "FileOutputStream object "
},
{
"code": null,
"e": 27405,
"s": 27314,
"text": "OpenFileInput(): Used to read data from a file, this returns an FileInputStream instance. "
},
{
"code": null,
"e": 27445,
"s": 27405,
"text": "Syntax: OpenFileInput( String filename)"
},
{
"code": null,
"e": 27454,
"s": 27445,
"text": "Returns:"
},
{
"code": null,
"e": 27478,
"s": 27454,
"text": "FileInputStream object "
},
{
"code": null,
"e": 27643,
"s": 27478,
"text": "A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 27672,
"s": 27643,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 27834,
"s": 27672,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 27882,
"s": 27834,
"text": "Step 2: Working with the activity_main.xml file"
},
{
"code": null,
"e": 27936,
"s": 27882,
"text": "The activity_main.xml file has the following widgets "
},
{
"code": null,
"e": 28079,
"s": 27936,
"text": "One EditText for accepting user inputTwo Buttons one for reading data and the other for writingOne TextView to display the content of the file"
},
{
"code": null,
"e": 28117,
"s": 28079,
"text": "One EditText for accepting user input"
},
{
"code": null,
"e": 28176,
"s": 28117,
"text": "Two Buttons one for reading data and the other for writing"
},
{
"code": null,
"e": 28224,
"s": 28176,
"text": "One TextView to display the content of the file"
},
{
"code": null,
"e": 28275,
"s": 28224,
"text": "Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 28279,
"s": 28275,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <TextView android:id=\"@+id/textView2\" android:layout_width=\"337dp\" android:layout_height=\"28dp\" android:text=\" File Content \" android:textAlignment=\"center\" android:textColor=\"#000\" android:textSize=\"24sp\" android:textStyle=\"bold\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.52\" /> <Button android:id=\"@+id/write_button\" android:layout_width=\"wrap_content\" android:layout_height=\"48dp\" android:layout_marginStart=\"160dp\" android:layout_marginEnd=\"159dp\" android:layout_marginBottom=\"16dp\" android:text=\"Write\" app:layout_constraintBottom_toTopOf=\"@+id/read_button\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.0\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.904\" /> <Button android:id=\"@+id/read_button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"160dp\" android:layout_marginEnd=\"158dp\" android:layout_marginBottom=\"48dp\" android:text=\"Read\" app:layout_constraintBottom_toTopOf=\"@+id/textView2\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.0\" app:layout_constraintStart_toStartOf=\"parent\" /> <EditText android:id=\"@+id/userInput\" android:layout_width=\"319dp\" android:layout_height=\"50dp\" android:layout_marginStart=\"46dp\" android:layout_marginTop=\"91dp\" android:layout_marginEnd=\"46dp\" android:ems=\"10\" android:inputType=\"textPersonName\" android:text=\"Name\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <TextView android:id=\"@+id/content\" android:layout_width=\"332dp\" android:layout_height=\"306dp\" android:layout_marginStart=\"33dp\" android:layout_marginTop=\"21dp\" android:layout_marginEnd=\"33dp\" android:layout_marginBottom=\"6dp\" android:text=\"\" android:textAlignment=\"center\" android:textColor=\"#000\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.461\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/textView2\" app:layout_constraintVertical_bias=\"0.0\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 31532,
"s": 28279,
"text": null
},
{
"code": null,
"e": 31543,
"s": 31532,
"text": "Output UI:"
},
{
"code": null,
"e": 31591,
"s": 31543,
"text": "Step 3: Working with the MainActivity.java file"
},
{
"code": null,
"e": 31666,
"s": 31591,
"text": "Inside the MainActivity.java file we are going to do the following things:"
},
{
"code": null,
"e": 31689,
"s": 31666,
"text": "Initialize variables: "
},
{
"code": null,
"e": 31694,
"s": 31689,
"text": "Java"
},
{
"code": "private String filename = \"demoFile.txt\";read = findViewById(R.id.read_button);write = findViewById(R.id.write_button);userInput = findViewById(R.id.userInput);fileContent = findViewById(R.id.content);",
"e": 31896,
"s": 31694,
"text": null
},
{
"code": null,
"e": 32026,
"s": 31896,
"text": "The file will be creating is DemoFile.txt. this can be found in Device File Explorer > data > data > application_package > files "
},
{
"code": null,
"e": 32050,
"s": 32026,
"text": "Read and Write methods:"
},
{
"code": null,
"e": 32117,
"s": 32050,
"text": "The following method is used to read data from the internal data. "
},
{
"code": null,
"e": 32122,
"s": 32117,
"text": "Java"
},
{
"code": "private void readData(){ try { FileInputStream fin = openFileInput(filename); int a; StringBuilder temp = new StringBuilder(); while ((a = fin.read()) != -1) { temp.append((char)a); } // setting text from the file. fileContent.setText(temp.toString()); fin.close(); } catch (IOException e) { e.printStackTrace(); } printMessage(\"reading to file \" + filename + \" completed..\");}",
"e": 32585,
"s": 32122,
"text": null
},
{
"code": null,
"e": 32660,
"s": 32585,
"text": "The method used for creating a file and writing data to internal storage. "
},
{
"code": null,
"e": 32665,
"s": 32660,
"text": "Java"
},
{
"code": "private void writeData(){ try { FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE); String data = userInput.getText().toString(); fos.write(data.getBytes()); fos.flush(); fos.close(); } catch (IOException e) { e.printStackTrace(); } userInput.setText(\"\"); printMessage(\"writing to file \" + filename + \"completed...\");}",
"e": 33057,
"s": 32665,
"text": null
},
{
"code": null,
"e": 33190,
"s": 33057,
"text": "Below is the complete code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 33195,
"s": 33190,
"text": "Java"
},
{
"code": "import android.content.Context;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException; public class MainActivity extends AppCompatActivity implements View.OnClickListener { // declare the variables Button read, write; EditText userInput; TextView fileContent; private String filename = \"demoFile.txt\"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); read = findViewById(R.id.read_button); write = findViewById(R.id.write_button); userInput = findViewById(R.id.userInput); fileContent = findViewById(R.id.content); read.setOnClickListener(this); write.setOnClickListener(this); } public void printMessage(String m) { Toast.makeText(this, m, Toast.LENGTH_LONG).show(); } @Override public void onClick(View view) { Button b = (Button) view; // get the button text : in out case either read or // write depending on the button pressed. String b_text = b.getText().toString(); switch (b_text.toLowerCase()) { case \"write\": { writeData(); break; } case \"read\": { readData(); break; } } } private void writeData() { try { FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE); String data = userInput.getText().toString(); fos.write(data.getBytes()); fos.flush(); fos.close(); } catch (IOException e) { e.printStackTrace(); } userInput.setText(\"\"); printMessage(\"writing to file \" + filename + \"completed...\"); } private void readData() { try { FileInputStream fin = openFileInput(filename); int a; StringBuilder temp = new StringBuilder(); while ((a = fin.read()) != -1) { temp.append((char) a); } // setting text from the file. fileContent.setText(temp.toString()); fin.close(); } catch (IOException e) { e.printStackTrace(); } printMessage(\"reading to file \" + filename + \" completed..\"); }}",
"e": 35758,
"s": 33195,
"text": null
},
{
"code": null,
"e": 35767,
"s": 35758,
"text": "rkbhola5"
},
{
"code": null,
"e": 35775,
"s": 35767,
"text": "android"
},
{
"code": null,
"e": 35783,
"s": 35775,
"text": "Android"
},
{
"code": null,
"e": 35788,
"s": 35783,
"text": "Java"
},
{
"code": null,
"e": 35793,
"s": 35788,
"text": "Java"
},
{
"code": null,
"e": 35801,
"s": 35793,
"text": "Android"
},
{
"code": null,
"e": 35899,
"s": 35801,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35937,
"s": 35899,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 35976,
"s": 35937,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 36026,
"s": 35976,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 36068,
"s": 36026,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 36119,
"s": 36068,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 36134,
"s": 36119,
"text": "Arrays in Java"
},
{
"code": null,
"e": 36178,
"s": 36134,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 36200,
"s": 36178,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 36251,
"s": 36200,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
Virtualization | Xen: Paravirtualization
|
11 Jul, 2022
Prerequisites – Introduction to Virtualization, Machine Reference Model of Virtualization Xen is an open source hypervisor based on paravirtualization. It is the most popular application of paravirtualization. Xen has been extended to compatible with full virtualization using hardware-assisted virtualization. It enables high performance to execute guest operating system. This is probably done by removing the performance loss while executing the instructions requiring significant handling and by modifying portion of the guest operating system executed by Xen, with reference to the execution of such instructions. Hence this especially support x86, which is the most used architecture on commodity machines and servers.
Figure – Xen Architecture and Guest OSnManagement
Above figure describes the Xen Architecture and its mapping onto a classic x86 privilege model. A Xen based system is handled by Xen hypervisor, which is executed in the most privileged mode and maintains the access of guest operating system to the basic hardware. Guest operating system are run between domains, which represents virtual machine instances.
In addition, particular control software, which has privileged access to the host and handles all other guest OS, runs in a special domain called Domain 0. This the only one loaded once the virtual machine manager has fully booted, and hosts an HTTP server that delivers requests for virtual machine creation, configuration, and termination. This component establishes the primary version of a shared virtual machine manager (VMM), which is a necessary part of Cloud computing system delivering Infrastructure-as-a-Service (IaaS) solution.
Various x86 implementation support four distinct security levels, termed as rings, i.e.,
Ring 0,
Ring 1,
Ring 2,
Ring 3
Here, Ring 0 represents the level having most privilege and Ring 3 represents the level having least privilege. Almost all the frequently used Operating system, except for OS/2, uses only two levels i.e. Ring 0 for the Kernel code and Ring 3 for user application and non-privilege OS program. This provides a chance to the Xen to implement paravirtualization. This enables Xen to control unchanged the Application Binary Interface (ABI) thus allowing a simple shift to Xen-virtualized solutions, from an application perspective.
Due to the structure of x86 instruction set, some instructions allow code execution in Ring 3 to switch to Ring 0 (Kernel mode). Such an operation is done at hardware level, and hence between a virtualized environment, it will lead to a TRAP or a silent fault, thus preventing the general operation of the guest OS as it is now running in Ring 1.
This condition is basically occurred by a subset of system calls. To eliminate this situation, implementation in operating system requires a modification and all the sensitive system calls needs re-implementation with hypercalls. Here, hypercalls are the particular calls revealed by the virtual machine (VM) interface of Xen and by use of it, Xen hypervisor tends to catch the execution of all the sensitive instructions, manage them, and return the control to the guest OS with the help of a supplied handler.
Paravirtualization demands the OS codebase be changed, and hence all operating systems can not be referred to as guest OS in a Xen-based environment. This condition holds where hardware-assisted virtualization can not be free, which enables to run the hypervisor in Ring 1 and the guest OS in Ring 0. Hence, Xen shows some limitations in terms of legacy hardware and in terms of legacy OS.
In fact, these are not possible to modify to be run in Ring 1 safely as their codebase is not reachable, and concurrently, the primary hardware hasn’t any support to execute them in a more privileged mode than Ring 0. Open source OS like Linux can be simply modified as its code is openly available, and Xen delivers full support to virtualization, while components of Windows are basically not compatible with Xen, unless hardware-assisted virtualization is available. As new releases of OS are designed to be virtualized, the problem is getting resolved and new hardware supports x86 virtualization.
Pros:
a) Xen server is developed over open-source Xen hypervisor and it uses a combination of hardware-based virtualization and paravirtualization. This tightly coupled collaboration between the operating system and virtualized platform enables the system to develop lighter and flexible hypervisor that delivers their functionalities in an optimized manner.
b) Xen supports balancing of large workload efficiently that capture CPU, Memory, disk input-output and network input-output of data. It offers two modes to handle this workload: Performance enhancement, and For handling data density.
c) It also comes equipped with a special storage feature that we call Citrix storage link. Which allows a system administrator to uses the features of arrays from Giant companies- Hp, Netapp, Dell Equal logic etc.
d) It also supports multiple processor, Iive migration one machine to another, physical server to virtual machine or virtual server to virtual machine conversion tools, centralized multiserver management, real time performance monitoring over window and linux.
Cons:
a) Xen is more reliable over linux rather than on window.
b) Xen relies on 3rd-party component to manage the resources like drivers, storage, backup, recovery & fault tolerance.
c) Xen deployment could be a burden some on your Linux kernel system as time passes.
d) Xen sometimes may cause increase in load on your resources by high input-output rate and and may cause starvation of other Vm’s.
madhav_mohan
rkbhola5
Cloud-Computing
virtualization
Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Jul, 2022"
},
{
"code": null,
"e": 754,
"s": 28,
"text": "Prerequisites – Introduction to Virtualization, Machine Reference Model of Virtualization Xen is an open source hypervisor based on paravirtualization. It is the most popular application of paravirtualization. Xen has been extended to compatible with full virtualization using hardware-assisted virtualization. It enables high performance to execute guest operating system. This is probably done by removing the performance loss while executing the instructions requiring significant handling and by modifying portion of the guest operating system executed by Xen, with reference to the execution of such instructions. Hence this especially support x86, which is the most used architecture on commodity machines and servers. "
},
{
"code": null,
"e": 807,
"s": 756,
"text": "Figure – Xen Architecture and Guest OSnManagement "
},
{
"code": null,
"e": 1165,
"s": 807,
"text": "Above figure describes the Xen Architecture and its mapping onto a classic x86 privilege model. A Xen based system is handled by Xen hypervisor, which is executed in the most privileged mode and maintains the access of guest operating system to the basic hardware. Guest operating system are run between domains, which represents virtual machine instances. "
},
{
"code": null,
"e": 1706,
"s": 1165,
"text": "In addition, particular control software, which has privileged access to the host and handles all other guest OS, runs in a special domain called Domain 0. This the only one loaded once the virtual machine manager has fully booted, and hosts an HTTP server that delivers requests for virtual machine creation, configuration, and termination. This component establishes the primary version of a shared virtual machine manager (VMM), which is a necessary part of Cloud computing system delivering Infrastructure-as-a-Service (IaaS) solution. "
},
{
"code": null,
"e": 1797,
"s": 1706,
"text": "Various x86 implementation support four distinct security levels, termed as rings, i.e., "
},
{
"code": null,
"e": 1828,
"s": 1797,
"text": "Ring 0,\nRing 1,\nRing 2,\nRing 3"
},
{
"code": null,
"e": 2358,
"s": 1828,
"text": "Here, Ring 0 represents the level having most privilege and Ring 3 represents the level having least privilege. Almost all the frequently used Operating system, except for OS/2, uses only two levels i.e. Ring 0 for the Kernel code and Ring 3 for user application and non-privilege OS program. This provides a chance to the Xen to implement paravirtualization. This enables Xen to control unchanged the Application Binary Interface (ABI) thus allowing a simple shift to Xen-virtualized solutions, from an application perspective. "
},
{
"code": null,
"e": 2706,
"s": 2358,
"text": "Due to the structure of x86 instruction set, some instructions allow code execution in Ring 3 to switch to Ring 0 (Kernel mode). Such an operation is done at hardware level, and hence between a virtualized environment, it will lead to a TRAP or a silent fault, thus preventing the general operation of the guest OS as it is now running in Ring 1. "
},
{
"code": null,
"e": 3219,
"s": 2706,
"text": "This condition is basically occurred by a subset of system calls. To eliminate this situation, implementation in operating system requires a modification and all the sensitive system calls needs re-implementation with hypercalls. Here, hypercalls are the particular calls revealed by the virtual machine (VM) interface of Xen and by use of it, Xen hypervisor tends to catch the execution of all the sensitive instructions, manage them, and return the control to the guest OS with the help of a supplied handler. "
},
{
"code": null,
"e": 3610,
"s": 3219,
"text": "Paravirtualization demands the OS codebase be changed, and hence all operating systems can not be referred to as guest OS in a Xen-based environment. This condition holds where hardware-assisted virtualization can not be free, which enables to run the hypervisor in Ring 1 and the guest OS in Ring 0. Hence, Xen shows some limitations in terms of legacy hardware and in terms of legacy OS. "
},
{
"code": null,
"e": 4213,
"s": 3610,
"text": "In fact, these are not possible to modify to be run in Ring 1 safely as their codebase is not reachable, and concurrently, the primary hardware hasn’t any support to execute them in a more privileged mode than Ring 0. Open source OS like Linux can be simply modified as its code is openly available, and Xen delivers full support to virtualization, while components of Windows are basically not compatible with Xen, unless hardware-assisted virtualization is available. As new releases of OS are designed to be virtualized, the problem is getting resolved and new hardware supports x86 virtualization. "
},
{
"code": null,
"e": 4219,
"s": 4213,
"text": "Pros:"
},
{
"code": null,
"e": 4572,
"s": 4219,
"text": "a) Xen server is developed over open-source Xen hypervisor and it uses a combination of hardware-based virtualization and paravirtualization. This tightly coupled collaboration between the operating system and virtualized platform enables the system to develop lighter and flexible hypervisor that delivers their functionalities in an optimized manner."
},
{
"code": null,
"e": 4807,
"s": 4572,
"text": "b) Xen supports balancing of large workload efficiently that capture CPU, Memory, disk input-output and network input-output of data. It offers two modes to handle this workload: Performance enhancement, and For handling data density."
},
{
"code": null,
"e": 5021,
"s": 4807,
"text": "c) It also comes equipped with a special storage feature that we call Citrix storage link. Which allows a system administrator to uses the features of arrays from Giant companies- Hp, Netapp, Dell Equal logic etc."
},
{
"code": null,
"e": 5282,
"s": 5021,
"text": "d) It also supports multiple processor, Iive migration one machine to another, physical server to virtual machine or virtual server to virtual machine conversion tools, centralized multiserver management, real time performance monitoring over window and linux."
},
{
"code": null,
"e": 5288,
"s": 5282,
"text": "Cons:"
},
{
"code": null,
"e": 5346,
"s": 5288,
"text": "a) Xen is more reliable over linux rather than on window."
},
{
"code": null,
"e": 5466,
"s": 5346,
"text": "b) Xen relies on 3rd-party component to manage the resources like drivers, storage, backup, recovery & fault tolerance."
},
{
"code": null,
"e": 5551,
"s": 5466,
"text": "c) Xen deployment could be a burden some on your Linux kernel system as time passes."
},
{
"code": null,
"e": 5683,
"s": 5551,
"text": "d) Xen sometimes may cause increase in load on your resources by high input-output rate and and may cause starvation of other Vm’s."
},
{
"code": null,
"e": 5696,
"s": 5683,
"text": "madhav_mohan"
},
{
"code": null,
"e": 5705,
"s": 5696,
"text": "rkbhola5"
},
{
"code": null,
"e": 5721,
"s": 5705,
"text": "Cloud-Computing"
},
{
"code": null,
"e": 5736,
"s": 5721,
"text": "virtualization"
},
{
"code": null,
"e": 5753,
"s": 5736,
"text": "Computer Subject"
}
] |
Node.js util.format() Method
|
01 Sep, 2021
The util.format() (Added in v0.5.3) method is an inbuilt application programming interface of the util module which is like printf format string and returns a formatted string using the first argument. The formatted string contains zero or more format specifiers in which the corresponding argument value is converted and replaced. It is used as a debugging tool is a synchronous method hence, it can have a significant performance overhead that could block the event loop. It is recommended not to use this function in a hot code path.
Syntax:
util.format(format[, ...args])
Parameters: This method accept two parameters as mentioned above and described below:
format: It consists of specifiers of <string> type, which is like printf format string.
args: It is the <string> type list of arguments.
Supported specifiers are:
%%: It replaces specifier with a single percent sign (‘%%’/‘%’) and doesn’t consume any argument even if it provided.
%s (String): It converts all values according to given format except Object, BigInt, and -0. Objects that have no user-defined toString function are inspected using util.inspect() and BigInt values are represented with n.
%c(CSS): If any CSS is passed, it will be skipped. Usually, this specifier is ignored.
%d (Number): It converts all values according to the given format except Symbol and BigInt.
%i (parseInt()): It parses a <string> and returns an integer, it is used for all values except BigInt and Symbol.
%f (parseFloat()): It parses a string and returns a floating-point number, it is used for all values except Symbols.
%j (JSON): No complicated parsing or translations, if there are circular references in the argument then it is replaced with the string ‘[Circular]’.
%o(Object): It is a string representation of an object with generic JavaScript object formatting. Similar to util.inspect(). It shows the full object along with non-enumerable properties and proxies.
%O(Object): It is similar to ‘%o’ but without options, it does not include non-enumerable properties and proxies.
Return Value: It returns the formatted string of <string> type.
Example 1:Filename: index.js
javascript
// Node.js to demonstrate the// util.format() method // Import the util module const util = require('util'); function fun1() { var val1 = util.format('%s:%s:%s', 'abc'); // Returns: 'foo:%s' var val2 = util.format('%s:%s', 'abc', 'def', 'ghi', 'jkl'); // Returns: 'foo:bar baz' var val3 = util.format(10, 20, 30); // Returns: '1 2 3' var val4 = util.format('%% : %s : %d'); // Returns: '%% %s' var val5 = util.format('%% : %s', 567); // Returns: '% : 567' console.log(val1, '\n', val2, '\n', val3, '\n', val4, '\n', val5);} // Function callfun1();
Run index.js file using the following command:
node index.js
Output:
abc:
:abc:def ghi jkl
10 20 30
%% : %s : %d
% : 567
Example 2:Filename: index.js
javascript
// Node.js program to demonstrate// the util.format() method // Import the util module const util = require('util'); // Passing multiple values and// -0 on string specifierconsole.log("1.>", util.format( '%%: %s', 'abc', 'def', -0)); // Passing multiple values console.log("2.>", util.format( '%%', 'abc', 'def', 'ghi')); // Passing bigInt to string specifierconsole.log("3.>", util.format('%s', 'abc', 94321321321223372036854775807)); // Creating and passing Object along // with null prototype and a variableconsole.log("4.>", util.format('%s', 'abc', Object.create(null, { [Symbol.toStringTag]: { value: 'def' } }))); // Passing string to Number specifierconsole.log("5.>", util.format('%d', 'abc', 94303685)); // Passing Symbol and Number to// parseInt specifierconsole.log("6.>", util.format( '%i', '2020 year 2021, ', 'He was 40,' , '10.33, ', '10, ', 10)); // Passing string and Numbers// to parseFloat specifierconsole.log("7.>", util.format('%f', '94321321321.564000 year 6546', 'abc', 943036854775807)); // Passing JSON string and Number// to JSON specifierconsole.log("8.>", util.format('%j', '{ "name":"John", "age":31, "city":"New York" }', 'abc', 943036854775807)); // Passing class, string, and Number// to object specifierconsole.log("9.>", util.format('%o', class Bar { }, 'abc', 943036854775807)); // Passing class, string, and Number// to Object specifierconsole.log("10.>", util.format('%o:%d', class Foo { get [Symbol.toStringTag]() { return 'abc'; } }, 'abc', 943036854775807)); // Random classclass randomClass { } // Inspecting random classconsole.log("11.>", util.inspect(new randomClass()));
Run index.js file using the following command:
node index.js
Output:
1.> %: abc def -0
2.> % abc def ghi
3.> abc 9.432132132122338e+28
4.> abc [Object: null prototype] [def] {}
5.> NaN 94303685
6.> 2020 He was 40, 10.33, 10, 10
7.> 94321321321.564 abc 943036854775807
8.> "{ \"name\":\"John\", \"age\":31,
\"city\":\"New York\" }" abc 943036854775807
9.> <ref *1> [Function: Bar] {
[length]: 0,
[prototype]: Bar { [constructor]: [Circular *1] },
[name]: 'Bar'
} abc 943036854775807
10.> <ref *1> [Function: Foo] {
[length]: 0,
[prototype]: Foo {
[constructor]: [Circular *1],
[Symbol(Symbol.toStringTag)]: [Getter]
},
[name]: 'Foo'
}:NaN 943036854775807
11.> randomClass {}
Conditions:
If no corresponding argument is passed to the specifier then it is not replaced.
If multiple arguments are passed than the number of specifiers, then extra arguments will be concatenated to the returned string.
If ‘values’ do not belong to format string and their type is not a string then they are formatted using util.inspect() method.
If the first argument doesn’t have a valid format specifier, then util.format() returns concatenated arguments.
Reference: https://nodejs.org/api/util.html#util_util_format_format_args
surindertarika1234
Node.js-util-module
Node.js
Web Technologies
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 ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to update NPM ?
Difference between promise and async await in Node.js
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Sep, 2021"
},
{
"code": null,
"e": 565,
"s": 28,
"text": "The util.format() (Added in v0.5.3) method is an inbuilt application programming interface of the util module which is like printf format string and returns a formatted string using the first argument. The formatted string contains zero or more format specifiers in which the corresponding argument value is converted and replaced. It is used as a debugging tool is a synchronous method hence, it can have a significant performance overhead that could block the event loop. It is recommended not to use this function in a hot code path."
},
{
"code": null,
"e": 574,
"s": 565,
"text": "Syntax: "
},
{
"code": null,
"e": 605,
"s": 574,
"text": "util.format(format[, ...args])"
},
{
"code": null,
"e": 693,
"s": 607,
"text": "Parameters: This method accept two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 793,
"s": 693,
"text": " format: It consists of specifiers of <string> type, which is like printf format string."
},
{
"code": null,
"e": 857,
"s": 793,
"text": " args: It is the <string> type list of arguments."
},
{
"code": null,
"e": 883,
"s": 857,
"text": "Supported specifiers are:"
},
{
"code": null,
"e": 1001,
"s": 883,
"text": "%%: It replaces specifier with a single percent sign (‘%%’/‘%’) and doesn’t consume any argument even if it provided."
},
{
"code": null,
"e": 1223,
"s": 1001,
"text": "%s (String): It converts all values according to given format except Object, BigInt, and -0. Objects that have no user-defined toString function are inspected using util.inspect() and BigInt values are represented with n."
},
{
"code": null,
"e": 1310,
"s": 1223,
"text": "%c(CSS): If any CSS is passed, it will be skipped. Usually, this specifier is ignored."
},
{
"code": null,
"e": 1402,
"s": 1310,
"text": "%d (Number): It converts all values according to the given format except Symbol and BigInt."
},
{
"code": null,
"e": 1516,
"s": 1402,
"text": "%i (parseInt()): It parses a <string> and returns an integer, it is used for all values except BigInt and Symbol."
},
{
"code": null,
"e": 1633,
"s": 1516,
"text": "%f (parseFloat()): It parses a string and returns a floating-point number, it is used for all values except Symbols."
},
{
"code": null,
"e": 1783,
"s": 1633,
"text": "%j (JSON): No complicated parsing or translations, if there are circular references in the argument then it is replaced with the string ‘[Circular]’."
},
{
"code": null,
"e": 1983,
"s": 1783,
"text": "%o(Object): It is a string representation of an object with generic JavaScript object formatting. Similar to util.inspect(). It shows the full object along with non-enumerable properties and proxies."
},
{
"code": null,
"e": 2097,
"s": 1983,
"text": "%O(Object): It is similar to ‘%o’ but without options, it does not include non-enumerable properties and proxies."
},
{
"code": null,
"e": 2161,
"s": 2097,
"text": "Return Value: It returns the formatted string of <string> type."
},
{
"code": null,
"e": 2191,
"s": 2161,
"text": "Example 1:Filename: index.js "
},
{
"code": null,
"e": 2202,
"s": 2191,
"text": "javascript"
},
{
"code": "// Node.js to demonstrate the// util.format() method // Import the util module const util = require('util'); function fun1() { var val1 = util.format('%s:%s:%s', 'abc'); // Returns: 'foo:%s' var val2 = util.format('%s:%s', 'abc', 'def', 'ghi', 'jkl'); // Returns: 'foo:bar baz' var val3 = util.format(10, 20, 30); // Returns: '1 2 3' var val4 = util.format('%% : %s : %d'); // Returns: '%% %s' var val5 = util.format('%% : %s', 567); // Returns: '% : 567' console.log(val1, '\\n', val2, '\\n', val3, '\\n', val4, '\\n', val5);} // Function callfun1(); ",
"e": 2814,
"s": 2202,
"text": null
},
{
"code": null,
"e": 2862,
"s": 2814,
"text": "Run index.js file using the following command: "
},
{
"code": null,
"e": 2876,
"s": 2862,
"text": "node index.js"
},
{
"code": null,
"e": 2884,
"s": 2876,
"text": "Output:"
},
{
"code": null,
"e": 2936,
"s": 2884,
"text": "abc:\n:abc:def ghi jkl\n10 20 30\n%% : %s : %d\n% : 567"
},
{
"code": null,
"e": 2966,
"s": 2936,
"text": "Example 2:Filename: index.js "
},
{
"code": null,
"e": 2977,
"s": 2966,
"text": "javascript"
},
{
"code": "// Node.js program to demonstrate// the util.format() method // Import the util module const util = require('util'); // Passing multiple values and// -0 on string specifierconsole.log(\"1.>\", util.format( '%%: %s', 'abc', 'def', -0)); // Passing multiple values console.log(\"2.>\", util.format( '%%', 'abc', 'def', 'ghi')); // Passing bigInt to string specifierconsole.log(\"3.>\", util.format('%s', 'abc', 94321321321223372036854775807)); // Creating and passing Object along // with null prototype and a variableconsole.log(\"4.>\", util.format('%s', 'abc', Object.create(null, { [Symbol.toStringTag]: { value: 'def' } }))); // Passing string to Number specifierconsole.log(\"5.>\", util.format('%d', 'abc', 94303685)); // Passing Symbol and Number to// parseInt specifierconsole.log(\"6.>\", util.format( '%i', '2020 year 2021, ', 'He was 40,' , '10.33, ', '10, ', 10)); // Passing string and Numbers// to parseFloat specifierconsole.log(\"7.>\", util.format('%f', '94321321321.564000 year 6546', 'abc', 943036854775807)); // Passing JSON string and Number// to JSON specifierconsole.log(\"8.>\", util.format('%j', '{ \"name\":\"John\", \"age\":31, \"city\":\"New York\" }', 'abc', 943036854775807)); // Passing class, string, and Number// to object specifierconsole.log(\"9.>\", util.format('%o', class Bar { }, 'abc', 943036854775807)); // Passing class, string, and Number// to Object specifierconsole.log(\"10.>\", util.format('%o:%d', class Foo { get [Symbol.toStringTag]() { return 'abc'; } }, 'abc', 943036854775807)); // Random classclass randomClass { } // Inspecting random classconsole.log(\"11.>\", util.inspect(new randomClass()));",
"e": 4711,
"s": 2977,
"text": null
},
{
"code": null,
"e": 4759,
"s": 4711,
"text": "Run index.js file using the following command: "
},
{
"code": null,
"e": 4773,
"s": 4759,
"text": "node index.js"
},
{
"code": null,
"e": 4781,
"s": 4773,
"text": "Output:"
},
{
"code": null,
"e": 5433,
"s": 4781,
"text": "1.> %: abc def -0\n2.> % abc def ghi\n3.> abc 9.432132132122338e+28\n4.> abc [Object: null prototype] [def] {}\n5.> NaN 94303685\n6.> 2020 He was 40, 10.33, 10, 10\n7.> 94321321321.564 abc 943036854775807\n8.> \"{ \\\"name\\\":\\\"John\\\", \\\"age\\\":31, \n \\\"city\\\":\\\"New York\\\" }\" abc 943036854775807\n9.> <ref *1> [Function: Bar] {\n [length]: 0,\n [prototype]: Bar { [constructor]: [Circular *1] },\n [name]: 'Bar'\n } abc 943036854775807\n10.> <ref *1> [Function: Foo] {\n [length]: 0,\n [prototype]: Foo {\n [constructor]: [Circular *1],\n [Symbol(Symbol.toStringTag)]: [Getter]\n },\n [name]: 'Foo'\n }:NaN 943036854775807\n11.> randomClass {}"
},
{
"code": null,
"e": 5445,
"s": 5433,
"text": "Conditions:"
},
{
"code": null,
"e": 5526,
"s": 5445,
"text": "If no corresponding argument is passed to the specifier then it is not replaced."
},
{
"code": null,
"e": 5656,
"s": 5526,
"text": "If multiple arguments are passed than the number of specifiers, then extra arguments will be concatenated to the returned string."
},
{
"code": null,
"e": 5783,
"s": 5656,
"text": "If ‘values’ do not belong to format string and their type is not a string then they are formatted using util.inspect() method."
},
{
"code": null,
"e": 5895,
"s": 5783,
"text": "If the first argument doesn’t have a valid format specifier, then util.format() returns concatenated arguments."
},
{
"code": null,
"e": 5968,
"s": 5895,
"text": "Reference: https://nodejs.org/api/util.html#util_util_format_format_args"
},
{
"code": null,
"e": 5987,
"s": 5968,
"text": "surindertarika1234"
},
{
"code": null,
"e": 6007,
"s": 5987,
"text": "Node.js-util-module"
},
{
"code": null,
"e": 6015,
"s": 6007,
"text": "Node.js"
},
{
"code": null,
"e": 6032,
"s": 6015,
"text": "Web Technologies"
},
{
"code": null,
"e": 6130,
"s": 6032,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6178,
"s": 6130,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 6211,
"s": 6178,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 6241,
"s": 6211,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 6261,
"s": 6241,
"text": "How to update NPM ?"
},
{
"code": null,
"e": 6315,
"s": 6261,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 6377,
"s": 6315,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 6438,
"s": 6377,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 6488,
"s": 6438,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 6531,
"s": 6488,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Get() method for dictionaries in Python
|
05 Oct, 2021
Python get() method return the value for the given key if present in the dictionary. If not, then it will return None (if get() is used with only one argument).
Syntax : Dict.get(key, default=None)
Parameters:
key: The keyname of the item you want to return the value from
Value: (Optional) Value to be returned if the key is not found. The default value is None.
Returns: Returns the value of the item with the specified key.
Python
dic = {"A": 1, "B": 2}print(dic.get("A"))print(dic.get("C"))print(dic.get("C", "Not Found ! "))
Output:
1
None
Not Found !
The get() to check and assign in absence of value to achieve this particular task. Just returns non-error None if any key is not present.
Python3
# Python3 code to demonstrate working of# Safe access nested dictionary key# Using nested get() # initializing dictionarytest_dict = {'Gfg' : {'is' : 'best'}} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # using nested get()# Safe access nested dictionary keyres = test_dict.get('Gfg', {}).get('is') # printing resultprint("The nested safely accessed value is : " + str(res))
Output:
The original dictionary is : {'Gfg': {'is': 'best'}}
The nested safely accessed value is : best
This article is contributed by Mayank Rawat. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
kumar_satyam
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Oct, 2021"
},
{
"code": null,
"e": 213,
"s": 52,
"text": "Python get() method return the value for the given key if present in the dictionary. If not, then it will return None (if get() is used with only one argument)."
},
{
"code": null,
"e": 250,
"s": 213,
"text": "Syntax : Dict.get(key, default=None)"
},
{
"code": null,
"e": 263,
"s": 250,
"text": "Parameters: "
},
{
"code": null,
"e": 326,
"s": 263,
"text": "key: The keyname of the item you want to return the value from"
},
{
"code": null,
"e": 417,
"s": 326,
"text": "Value: (Optional) Value to be returned if the key is not found. The default value is None."
},
{
"code": null,
"e": 480,
"s": 417,
"text": "Returns: Returns the value of the item with the specified key."
},
{
"code": null,
"e": 487,
"s": 480,
"text": "Python"
},
{
"code": "dic = {\"A\": 1, \"B\": 2}print(dic.get(\"A\"))print(dic.get(\"C\"))print(dic.get(\"C\", \"Not Found ! \"))",
"e": 583,
"s": 487,
"text": null
},
{
"code": null,
"e": 592,
"s": 583,
"text": "Output: "
},
{
"code": null,
"e": 611,
"s": 592,
"text": "1\nNone\nNot Found !"
},
{
"code": null,
"e": 749,
"s": 611,
"text": "The get() to check and assign in absence of value to achieve this particular task. Just returns non-error None if any key is not present."
},
{
"code": null,
"e": 757,
"s": 749,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Safe access nested dictionary key# Using nested get() # initializing dictionarytest_dict = {'Gfg' : {'is' : 'best'}} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # using nested get()# Safe access nested dictionary keyres = test_dict.get('Gfg', {}).get('is') # printing resultprint(\"The nested safely accessed value is : \" + str(res))",
"e": 1183,
"s": 757,
"text": null
},
{
"code": null,
"e": 1191,
"s": 1183,
"text": "Output:"
},
{
"code": null,
"e": 1288,
"s": 1191,
"text": "The original dictionary is : {'Gfg': {'is': 'best'}}\nThe nested safely accessed value is : best"
},
{
"code": null,
"e": 1584,
"s": 1288,
"text": "This article is contributed by Mayank Rawat. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 1709,
"s": 1584,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 1722,
"s": 1709,
"text": "kumar_satyam"
},
{
"code": null,
"e": 1734,
"s": 1722,
"text": "python-dict"
},
{
"code": null,
"e": 1741,
"s": 1734,
"text": "Python"
},
{
"code": null,
"e": 1753,
"s": 1741,
"text": "python-dict"
},
{
"code": null,
"e": 1851,
"s": 1753,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1879,
"s": 1851,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 1929,
"s": 1879,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 1951,
"s": 1929,
"text": "Python map() function"
},
{
"code": null,
"e": 1969,
"s": 1951,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2013,
"s": 1969,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 2055,
"s": 2013,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2078,
"s": 2055,
"text": "Taking input in Python"
},
{
"code": null,
"e": 2100,
"s": 2078,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2135,
"s": 2100,
"text": "Read a file line by line in Python"
}
] |
Minimum number of prefix reversals to sort permutation of first N numbers
|
08 Dec, 2021
Given N numbers that have a permutation of first N numbers. In a single operation, any prefix can be reversed. The task is to find the minimum number of such operations such that the numbers in the array are in increasing order. Examples:
Input : a[] = {3, 1, 2}
Output : 2
Step1: Reverse the complete array a, a[] = {2, 1, 3}
Step2: Reverse the prefix(0-1) in s, a[] = {1, 2, 3}
Input : a[] = {1, 2, 4, 3}
Output : 3
Step1: Reverse the complete array a, a[] = {3, 4, 2, 1}
Step2: Reverse the prefix(0-1) in s, a[] = {4, 3, 2, 1}
Step3: Reverse the complete array a, a[] = {1, 2, 3, 4}
The approach to solve this problem is to use BFS.
Encode the given numbers in a string. Sort the array and encode it into a string destination.
Then do a BFS from the initial permutation. Each time, check all permutations induced by reversing a prefix of current permutation.
If it is not visited, put it into the queue with the count of reversals done.
When the permutation of the encoded string is same as the destination string, return the numbers of reversals required to reach here.
That is, all permutations of strings are done and the minimal of those is returned as the answer.
Below is the implementation of the above approach:
C++
Java
C#
Javascript
Python3
// C++ program to find// minimum number of prefix reversals// to sort permutation of first N numbers#include <bits/stdc++.h>using namespace std; // Function to return the minimum prefix reversalsint minimumPrefixReversals(int a[], int n){ string start = ""; string destination = "", t, r; for (int i = 0; i < n; i++) { // converts the number to a character // and add to string start += to_string(a[i]); } sort(a, a + n); for (int i = 0; i < n; i++) { destination += to_string(a[i]); } // Queue to store the pairs // of string and number of reversals queue<pair<string, int> > qu; pair<string, int> p; // Initially push the original string qu.push(make_pair(start, 0)); // if original string is the destination string if (start == destination) { return 0; } // iterate till queue is empty while (!qu.empty()) { // pair at the top p = qu.front(); // string t = p.first; // pop the top-most element qu.pop(); // perform prefix reversals for all index and push // in the queue and check for the minimal for (int j = 2; j <= n; j++) { r = t; // reverse the string till prefix j reverse(r.begin(), r.begin() + j); // if after reversing the string from first i index // it is the destination if (r == destination) { return p.second + 1; } // push the number of reversals for string r qu.push(make_pair(r, p.second + 1)); } }} // Driver Codeint main(){ int a[] = { 1, 2, 4, 3 }; int n = sizeof(a) / sizeof(a[0]); // Calling function cout << minimumPrefixReversals(a, n); return 0;}
// Java program to find minimum// number of prefix reversals to// sort permutation of first N numbersimport java.util.*; public class Main{ // function to find minimum prefix reversal through BFS public static int minimumPrefixReversals(int[] a) { // size of array int n = a.length; // string for initial and goal nodes String start = "", destination = ""; // string for manipulation in while loop String original = "",modified = ""; // node to store temporary values from front of queue Node temp = null; // create the starting string for (int i = 0; i < n; i++) start += a[i]; // sort the array and prepare final destination string Arrays.sort(a); for (int i = 0; i < n; i++) destination += a[i]; // this queue will store all the BFS siblings Queue<Node> q = new LinkedList<>(); // place the starting node in queue q.add(new Node(start, 0)); //base case:- if array is already sorted if (start == destination) return 0; // loop until the size of queue is empty while (q.size() != 0) { // put front node of queue in temporary variable temp = q.poll(); // store the original string at this step original = temp.string; for (int j = 2; j <= n; j++) { // modified will be used to generate all // manipulation of original string // like if original = 1342 // modified = 3142 , 4312 , 2431 modified = original; // generate the permutation by reversing modified = reverse (modified , j); if (modified.equals(destination)) { // if string match then return // the height of the current node return temp.steps + 1; } // else put this node into queue q.add(new Node(modified,temp.steps + 1)); } } // if no case match then default value return Integer.MIN_VALUE; } // function to reverse the string upto an index public static String reverse (String s , int index) { char temp []= s.toCharArray(); int i = 0; while (i < index) { char c = temp[i]; temp[i] = temp[index-1]; temp[index-1] = c; i++;index--; } return String.valueOf(temp); } // Driver code public static void main(String []args) { int a[] = new int []{1,2,4,3}; System.out.println(minimumPrefixReversals(a)); } // Node class to store a combined set of values static class Node { public String string ; public int steps; public Node(String string,int steps) { this.string = string; this.steps= steps; } }} // This code is contributed by Sparsh Singhal
// C# program to find minimum// number of prefix reversals to// sort permutation of first N numbersusing System;using System.Collections.Generic; class GFG{ // Node class to store a combined set of values public class Node { public String str; public int steps; public Node(String str,int steps) { this.str = str; this.steps= steps; } } // function to find minimum prefix reversal through BFS public static int minimumPrefixReversals(int[] a) { // size of array int n = a.Length; // string for initial and goal nodes String start = "", destination = ""; // string for manipulation in while loop String original = "", modified = ""; // node to store temporary values // from front of queue Node temp = null; // create the starting string for (int i = 0; i < n; i++) start += a[i]; // sort the array and prepare // final destination string Array.Sort(a); for (int i = 0; i < n; i++) destination += a[i]; // this queue will store all the BFS siblings Queue<Node> q = new Queue<Node>(); // place the starting node in queue q.Enqueue(new Node(start, 0)); //base case:- if array is already sorted if (start == destination) return 0; // loop until the size of queue is empty while (q.Count != 0) { // put front node of queue in temporary variable temp = q.Dequeue(); // store the original string at this step original = temp.str; for (int j = 2; j <= n; j++) { // modified will be used to generate all // manipulation of original string // like if original = 1342 // modified = 3142 , 4312 , 2431 modified = original; // generate the permutation by reversing modified = reverse (modified , j); if (modified.Equals(destination)) { // if string match then return // the height of the current node return temp.steps + 1; } // else put this node into queue q.Enqueue(new Node(modified, temp.steps + 1)); } } // if no case match then default value return int.MinValue; } // function to reverse the string upto an index public static String reverse (String s, int index) { char []temp = s.ToCharArray(); int i = 0; while (i < index) { char c = temp[i]; temp[i] = temp[index - 1]; temp[index - 1] = c; i++;index--; } return String.Join("", temp); } // Driver code public static void Main(String []args) { int []a = new int []{1, 2, 4, 3}; Console.WriteLine(minimumPrefixReversals(a)); }} // This code is contributed by 29AjayKumar
<script> class Node{ constructor(string,steps) { this.string = string; this.steps= steps; }} function minimumPrefixReversals(a){ // size of array let n = a.length; // string for initial and goal nodes let start = "", destination = ""; // string for manipulation in while loop let original = "",modified = ""; // node to store temporary values from front of queue let temp = null; // create the starting string for (let i = 0; i < n; i++) start += a[i]; // sort the array and prepare final destination string a.sort(function(a,b){return a-b;}); for (let i = 0; i < n; i++) destination += a[i]; // this queue will store all the BFS siblings let q = []; // place the starting node in queue q.push(new Node(start, 0)); //base case:- if array is already sorted if (start == destination) return 0; // loop until the size of queue is empty while (q.length != 0) { // put front node of queue in temporary variable temp = q.shift(); // store the original string at this step original = temp.string; for (let j = 2; j <= n; j++) { // modified will be used to generate all // manipulation of original string // like if original = 1342 // modified = 3142 , 4312 , 2431 modified = original; // generate the permutation by reversing modified = reverse (modified , j); if (modified == (destination)) { // if string match then return // the height of the current node return temp.steps + 1; } // else put this node into queue q.push(new Node(modified,temp.steps + 1)); } } // if no case match then default value return Number.MIN_VALUE;} function reverse (s,index){ let temp = s.split(""); let i = 0; while (i < index) { let c = temp[i]; temp[i] = temp[index-1]; temp[index-1] = c; i++;index--; } return (temp).join("");} let a = [1, 2, 4, 3];document.write(minimumPrefixReversals(a)); // This code is contributed by rag2127</script>
# Python3 program to find# minimum number of prefix reversals# to sort permutation of [0] N numbersfrom queue import Queue # Function to return the minimum prefix reversalsdef minimumPrefixReversals( a, n): start = "" destination = "" for i in range(n): # converts the number to a character # and add to start += str(a[i]) a.sort() for i in range(n): destination += str(a[i]) # Queue to store the pairs # of and number of reversals qu=Queue() # Initially push the original qu.put((start, 0)) # if original is the destination if (start == destination) : return 0 # iterate till queue is empty while qu.not_empty : # pair at the top p = qu.get() # t = p[0] # perform prefix reversals for all index and push # in the queue and check for the minimal for j in range(2,n+1) : r = t # reverse the till prefix j tmpR=list(r) tmpR[:j]=tmpR[j-1::-1] r=''.join(tmpR) # if after reversing the from [0] i index # it is the destination if (r == destination) : return p[1] + 1 # push the number of reversals for r qu.put((r, p[1] + 1)) # Driver Codeif __name__ == '__main__': a = [ 1, 2, 4, 3] n = len(a) # Calling function print(minimumPrefixReversals(a, n))
3
Time Complexity: O(N! * N2) Auxiliary Space: O(N!)
vaibhav2992
sparsh singhal
29AjayKumar
clintra
akshaysingh98088
surinderdawra388
rag2127
pankajsharmagfg
amartyaghoshgfg
BFS
cpp-pair
cpp-queue
Permutation and Combination
Sorting Quiz
Algorithms
BFS
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Hashing | A Complete Tutorial
Find if there is a path between two vertices in an undirected graph
How to Start Learning DSA?
Complete Roadmap To Learn DSA From Scratch
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Difference between NP hard and NP complete problem
What Should I Learn First: Data Structures or Algorithms?
Ternary Search
K means Clustering - Introduction
Hash Functions and list/types of Hash functions
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Dec, 2021"
},
{
"code": null,
"e": 293,
"s": 52,
"text": "Given N numbers that have a permutation of first N numbers. In a single operation, any prefix can be reversed. The task is to find the minimum number of such operations such that the numbers in the array are in increasing order. Examples: "
},
{
"code": null,
"e": 650,
"s": 293,
"text": "Input : a[] = {3, 1, 2} \nOutput : 2 \nStep1: Reverse the complete array a, a[] = {2, 1, 3} \nStep2: Reverse the prefix(0-1) in s, a[] = {1, 2, 3} \n\nInput : a[] = {1, 2, 4, 3} \nOutput : 3 \nStep1: Reverse the complete array a, a[] = {3, 4, 2, 1} \nStep2: Reverse the prefix(0-1) in s, a[] = {4, 3, 2, 1} \nStep3: Reverse the complete array a, a[] = {1, 2, 3, 4} "
},
{
"code": null,
"e": 704,
"s": 652,
"text": "The approach to solve this problem is to use BFS. "
},
{
"code": null,
"e": 798,
"s": 704,
"text": "Encode the given numbers in a string. Sort the array and encode it into a string destination."
},
{
"code": null,
"e": 930,
"s": 798,
"text": "Then do a BFS from the initial permutation. Each time, check all permutations induced by reversing a prefix of current permutation."
},
{
"code": null,
"e": 1008,
"s": 930,
"text": "If it is not visited, put it into the queue with the count of reversals done."
},
{
"code": null,
"e": 1142,
"s": 1008,
"text": "When the permutation of the encoded string is same as the destination string, return the numbers of reversals required to reach here."
},
{
"code": null,
"e": 1240,
"s": 1142,
"text": "That is, all permutations of strings are done and the minimal of those is returned as the answer."
},
{
"code": null,
"e": 1293,
"s": 1240,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1297,
"s": 1293,
"text": "C++"
},
{
"code": null,
"e": 1302,
"s": 1297,
"text": "Java"
},
{
"code": null,
"e": 1305,
"s": 1302,
"text": "C#"
},
{
"code": null,
"e": 1316,
"s": 1305,
"text": "Javascript"
},
{
"code": null,
"e": 1324,
"s": 1316,
"text": "Python3"
},
{
"code": "// C++ program to find// minimum number of prefix reversals// to sort permutation of first N numbers#include <bits/stdc++.h>using namespace std; // Function to return the minimum prefix reversalsint minimumPrefixReversals(int a[], int n){ string start = \"\"; string destination = \"\", t, r; for (int i = 0; i < n; i++) { // converts the number to a character // and add to string start += to_string(a[i]); } sort(a, a + n); for (int i = 0; i < n; i++) { destination += to_string(a[i]); } // Queue to store the pairs // of string and number of reversals queue<pair<string, int> > qu; pair<string, int> p; // Initially push the original string qu.push(make_pair(start, 0)); // if original string is the destination string if (start == destination) { return 0; } // iterate till queue is empty while (!qu.empty()) { // pair at the top p = qu.front(); // string t = p.first; // pop the top-most element qu.pop(); // perform prefix reversals for all index and push // in the queue and check for the minimal for (int j = 2; j <= n; j++) { r = t; // reverse the string till prefix j reverse(r.begin(), r.begin() + j); // if after reversing the string from first i index // it is the destination if (r == destination) { return p.second + 1; } // push the number of reversals for string r qu.push(make_pair(r, p.second + 1)); } }} // Driver Codeint main(){ int a[] = { 1, 2, 4, 3 }; int n = sizeof(a) / sizeof(a[0]); // Calling function cout << minimumPrefixReversals(a, n); return 0;}",
"e": 3105,
"s": 1324,
"text": null
},
{
"code": "// Java program to find minimum// number of prefix reversals to// sort permutation of first N numbersimport java.util.*; public class Main{ // function to find minimum prefix reversal through BFS public static int minimumPrefixReversals(int[] a) { // size of array int n = a.length; // string for initial and goal nodes String start = \"\", destination = \"\"; // string for manipulation in while loop String original = \"\",modified = \"\"; // node to store temporary values from front of queue Node temp = null; // create the starting string for (int i = 0; i < n; i++) start += a[i]; // sort the array and prepare final destination string Arrays.sort(a); for (int i = 0; i < n; i++) destination += a[i]; // this queue will store all the BFS siblings Queue<Node> q = new LinkedList<>(); // place the starting node in queue q.add(new Node(start, 0)); //base case:- if array is already sorted if (start == destination) return 0; // loop until the size of queue is empty while (q.size() != 0) { // put front node of queue in temporary variable temp = q.poll(); // store the original string at this step original = temp.string; for (int j = 2; j <= n; j++) { // modified will be used to generate all // manipulation of original string // like if original = 1342 // modified = 3142 , 4312 , 2431 modified = original; // generate the permutation by reversing modified = reverse (modified , j); if (modified.equals(destination)) { // if string match then return // the height of the current node return temp.steps + 1; } // else put this node into queue q.add(new Node(modified,temp.steps + 1)); } } // if no case match then default value return Integer.MIN_VALUE; } // function to reverse the string upto an index public static String reverse (String s , int index) { char temp []= s.toCharArray(); int i = 0; while (i < index) { char c = temp[i]; temp[i] = temp[index-1]; temp[index-1] = c; i++;index--; } return String.valueOf(temp); } // Driver code public static void main(String []args) { int a[] = new int []{1,2,4,3}; System.out.println(minimumPrefixReversals(a)); } // Node class to store a combined set of values static class Node { public String string ; public int steps; public Node(String string,int steps) { this.string = string; this.steps= steps; } }} // This code is contributed by Sparsh Singhal",
"e": 6353,
"s": 3105,
"text": null
},
{
"code": "// C# program to find minimum// number of prefix reversals to// sort permutation of first N numbersusing System;using System.Collections.Generic; class GFG{ // Node class to store a combined set of values public class Node { public String str; public int steps; public Node(String str,int steps) { this.str = str; this.steps= steps; } } // function to find minimum prefix reversal through BFS public static int minimumPrefixReversals(int[] a) { // size of array int n = a.Length; // string for initial and goal nodes String start = \"\", destination = \"\"; // string for manipulation in while loop String original = \"\", modified = \"\"; // node to store temporary values // from front of queue Node temp = null; // create the starting string for (int i = 0; i < n; i++) start += a[i]; // sort the array and prepare // final destination string Array.Sort(a); for (int i = 0; i < n; i++) destination += a[i]; // this queue will store all the BFS siblings Queue<Node> q = new Queue<Node>(); // place the starting node in queue q.Enqueue(new Node(start, 0)); //base case:- if array is already sorted if (start == destination) return 0; // loop until the size of queue is empty while (q.Count != 0) { // put front node of queue in temporary variable temp = q.Dequeue(); // store the original string at this step original = temp.str; for (int j = 2; j <= n; j++) { // modified will be used to generate all // manipulation of original string // like if original = 1342 // modified = 3142 , 4312 , 2431 modified = original; // generate the permutation by reversing modified = reverse (modified , j); if (modified.Equals(destination)) { // if string match then return // the height of the current node return temp.steps + 1; } // else put this node into queue q.Enqueue(new Node(modified, temp.steps + 1)); } } // if no case match then default value return int.MinValue; } // function to reverse the string upto an index public static String reverse (String s, int index) { char []temp = s.ToCharArray(); int i = 0; while (i < index) { char c = temp[i]; temp[i] = temp[index - 1]; temp[index - 1] = c; i++;index--; } return String.Join(\"\", temp); } // Driver code public static void Main(String []args) { int []a = new int []{1, 2, 4, 3}; Console.WriteLine(minimumPrefixReversals(a)); }} // This code is contributed by 29AjayKumar",
"e": 9632,
"s": 6353,
"text": null
},
{
"code": "<script> class Node{ constructor(string,steps) { this.string = string; this.steps= steps; }} function minimumPrefixReversals(a){ // size of array let n = a.length; // string for initial and goal nodes let start = \"\", destination = \"\"; // string for manipulation in while loop let original = \"\",modified = \"\"; // node to store temporary values from front of queue let temp = null; // create the starting string for (let i = 0; i < n; i++) start += a[i]; // sort the array and prepare final destination string a.sort(function(a,b){return a-b;}); for (let i = 0; i < n; i++) destination += a[i]; // this queue will store all the BFS siblings let q = []; // place the starting node in queue q.push(new Node(start, 0)); //base case:- if array is already sorted if (start == destination) return 0; // loop until the size of queue is empty while (q.length != 0) { // put front node of queue in temporary variable temp = q.shift(); // store the original string at this step original = temp.string; for (let j = 2; j <= n; j++) { // modified will be used to generate all // manipulation of original string // like if original = 1342 // modified = 3142 , 4312 , 2431 modified = original; // generate the permutation by reversing modified = reverse (modified , j); if (modified == (destination)) { // if string match then return // the height of the current node return temp.steps + 1; } // else put this node into queue q.push(new Node(modified,temp.steps + 1)); } } // if no case match then default value return Number.MIN_VALUE;} function reverse (s,index){ let temp = s.split(\"\"); let i = 0; while (i < index) { let c = temp[i]; temp[i] = temp[index-1]; temp[index-1] = c; i++;index--; } return (temp).join(\"\");} let a = [1, 2, 4, 3];document.write(minimumPrefixReversals(a)); // This code is contributed by rag2127</script>",
"e": 12289,
"s": 9632,
"text": null
},
{
"code": "# Python3 program to find# minimum number of prefix reversals# to sort permutation of [0] N numbersfrom queue import Queue # Function to return the minimum prefix reversalsdef minimumPrefixReversals( a, n): start = \"\" destination = \"\" for i in range(n): # converts the number to a character # and add to start += str(a[i]) a.sort() for i in range(n): destination += str(a[i]) # Queue to store the pairs # of and number of reversals qu=Queue() # Initially push the original qu.put((start, 0)) # if original is the destination if (start == destination) : return 0 # iterate till queue is empty while qu.not_empty : # pair at the top p = qu.get() # t = p[0] # perform prefix reversals for all index and push # in the queue and check for the minimal for j in range(2,n+1) : r = t # reverse the till prefix j tmpR=list(r) tmpR[:j]=tmpR[j-1::-1] r=''.join(tmpR) # if after reversing the from [0] i index # it is the destination if (r == destination) : return p[1] + 1 # push the number of reversals for r qu.put((r, p[1] + 1)) # Driver Codeif __name__ == '__main__': a = [ 1, 2, 4, 3] n = len(a) # Calling function print(minimumPrefixReversals(a, n))",
"e": 13756,
"s": 12289,
"text": null
},
{
"code": null,
"e": 13758,
"s": 13756,
"text": "3"
},
{
"code": null,
"e": 13812,
"s": 13760,
"text": "Time Complexity: O(N! * N2) Auxiliary Space: O(N!) "
},
{
"code": null,
"e": 13824,
"s": 13812,
"text": "vaibhav2992"
},
{
"code": null,
"e": 13839,
"s": 13824,
"text": "sparsh singhal"
},
{
"code": null,
"e": 13851,
"s": 13839,
"text": "29AjayKumar"
},
{
"code": null,
"e": 13859,
"s": 13851,
"text": "clintra"
},
{
"code": null,
"e": 13876,
"s": 13859,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 13893,
"s": 13876,
"text": "surinderdawra388"
},
{
"code": null,
"e": 13901,
"s": 13893,
"text": "rag2127"
},
{
"code": null,
"e": 13917,
"s": 13901,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 13933,
"s": 13917,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 13937,
"s": 13933,
"text": "BFS"
},
{
"code": null,
"e": 13946,
"s": 13937,
"text": "cpp-pair"
},
{
"code": null,
"e": 13956,
"s": 13946,
"text": "cpp-queue"
},
{
"code": null,
"e": 13984,
"s": 13956,
"text": "Permutation and Combination"
},
{
"code": null,
"e": 13997,
"s": 13984,
"text": "Sorting Quiz"
},
{
"code": null,
"e": 14008,
"s": 13997,
"text": "Algorithms"
},
{
"code": null,
"e": 14012,
"s": 14008,
"text": "BFS"
},
{
"code": null,
"e": 14023,
"s": 14012,
"text": "Algorithms"
},
{
"code": null,
"e": 14121,
"s": 14023,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14159,
"s": 14121,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 14227,
"s": 14159,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 14254,
"s": 14227,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 14297,
"s": 14254,
"text": "Complete Roadmap To Learn DSA From Scratch"
},
{
"code": null,
"e": 14364,
"s": 14297,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 14415,
"s": 14364,
"text": "Difference between NP hard and NP complete problem"
},
{
"code": null,
"e": 14473,
"s": 14415,
"text": "What Should I Learn First: Data Structures or Algorithms?"
},
{
"code": null,
"e": 14488,
"s": 14473,
"text": "Ternary Search"
},
{
"code": null,
"e": 14522,
"s": 14488,
"text": "K means Clustering - Introduction"
}
] |
Reverse String according to the number of words
|
16 Jun, 2022
Given a string containing a number of words. If the count of words in string is even then reverse its even position’s words else reverse its odd position, push reversed words at the starting of a new string and append the remaining words as it is in order.
Examples:
Input: Ashish Yadav Abhishek Rajput Sunil Pundir
Output: ridnuP tupjaR vadaY Ashish Abhishek Sunil
Input: Ashish Yadav Abhishek Rajput Sunil Pundir Prem
Output: merP linuS kehsihbA hsihsA Yadav Rajput Pundir
Approach: If number of words are even then even position’s words come first and also reverse that particular word, and if number of words are odd then odd position’s words come first and also reverse that particular word, after then the remaining words are appended in order. For e.g.
Ashish Yadav Abhishek Rajput Sunil Pundir. In the above string, the number of words is even then “Yadav Rajput Pundir” comes at the even position and then the final output will be: ridnuP tupjaR vadaY Ashish Abhishek Sunil
C++
C
Java
Python3
C#
Javascript
// C++ program to reverse string// according to the number of words#include <bits/stdc++.h>using namespace std; // Reverse the letters of the wordvoid reverse(char str[], int start, int end){ // Temporary variable to store character char temp; while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; }} // This function forms the required stringvoid reverseletter(char str[], int start, int end){ int wstart, wend; for (wstart = wend = start; wend < end; wend++) { if (str[wend] == ' ') continue; // Checking the number of words // present in string to reverse while (str[wend] != ' ' && wend <= end) wend++; wend--; // Reverse the letter // of the words reverse(str, wstart, wend); }} // Driver Codeint main(){ char str[1000] = "Ashish Yadav Abhishek Rajput Sunil Pundir"; reverseletter(str, 0, strlen(str) - 1); cout << str; return 0;} // This code is contributed by SHUBHAMSINGH10
// C program to reverse string// according to the number of words#include<stdio.h>#include<string.h> // Reverse the letters of the wordvoid reverse(char str[], int start, int end) { // Temporary variable to store character char temp; while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; }} // This function forms the required stringvoid reverseletter(char str[], int start, int end) { int wstart, wend; for (wstart = wend = start; wend < end; wend++) { if (str[wend] == ' ') continue; // Checking the number of words // present in string to reverse while (str[wend] != ' ' && wend <= end) wend++; wend--; //Reverse the letter //of the words reverse(str, wstart, wend); }} // Driver Codeint main(){ char str[1000] = "Ashish Yadav Abhishek Rajput Sunil Pundir"; reverseletter(str, 0, strlen(str)-1); printf("%s", str); return 0;}
// Java program to reverse string// according to the number of wordsclass GFG{ // Reverse the letters of the word static void reverse(char str[], int start, int end) { // Temporary variable to store character char temp; while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } } // This function forms the required string static void reverseletter(char str[], int start, int end) { int wstart, wend; for (wstart = wend = start; wend < end; wend++) { if (str[wend] == ' ') { continue; } // Checking the number of words // present in string to reverse while (wend <= end && str[wend] != ' ') { wend++; } wend--; // Reverse the letter // of the words reverse(str, wstart, wend); } } // Driver Code public static void main(String[] args) { char str[] = "Ashish Yadav Abhishek Rajput Sunil Pundir".toCharArray(); reverseletter(str, 0, str.length - 1); System.out.printf("%s", String.valueOf(str)); }} // This code contributed by Rajput-Ji
# Python3 program to reverse string# according to the number of words # Reverse the letters of the worddef reverse(string, start, end): # Temporary variable to store character temp = '' while start <= end: # Swapping the first and last character temp = string[start] string[start] = string[end] string[end] = temp start += 1 end -= 1 # This function forms the required stringdef reverseletter(string, start, end): wstart, wend = start, start while wend < end: if string[wend] == " ": wend += 1 continue # Checking the number of words # present in string to reverse while wend <= end and string[wend] != " ": wend += 1 wend -= 1 # Reverse the letter # of the words reverse(string, wstart, wend) wend += 1 # Driver Codeif __name__ == "__main__": string = "Ashish Yadav Abhishek Rajput Sunil Pundir" string = list(string) reverseletter(string, 0, len(string) - 1) print(''.join(string)) # This code is contributed by# sanjeev2552
// C# program to reverse string// according to the number of wordsusing System; class GFG{ // Reverse the letters of the word static void reverse(char []str, int start, int end) { // Temporary variable to store character char temp; while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } } // This function forms the required string static void reverseletter(char []str, int start, int end) { int wstart, wend; for (wstart = wend = start; wend < end; wend++) { if (str[wend] == ' ') { continue; } // Checking the number of words // present in string to reverse while (wend <= end && str[wend] != ' ') { wend++; } wend--; // Reverse the letter // of the words reverse(str, wstart, wend); } } // Driver Code public static void Main(String[] args) { char []str = "Ashish Yadav Abhishek Rajput Sunil Pundir".ToCharArray(); reverseletter(str, 0, str.Length - 1); Console.Write("{0}", String.Join("",str)); }} // This code has been contributed by 29AjayKumar
<script>// Javascript program to reverse string// according to the number of words // Reverse the letters of the wordfunction reverse(str,start,end){ // Temporary variable to store character let temp; while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; }} // This function forms the required stringfunction reverseletter(str,start,end){ let wstart, wend; for (wstart = wend = start; wend < end; wend++) { if (str[wend] == ' ') { continue; } // Checking the number of words // present in string to reverse while (wend <= end && str[wend] != ' ') { wend++; } wend--; // Reverse the letter // of the words reverse(str, wstart, wend); }} // Driver Codelet str= "Ashish Yadav Abhishek Rajput Sunil Pundir".split("");reverseletter(str, 0, str.length - 1);document.write((str).join("")); // This code is contributed by rag2127</script>
ridnuP tupjaR vadaY Ashish Abhishek Sunil
Time complexity : O(n) Auxiliary Space : O(1)
Rajput-Ji
29AjayKumar
sanjeev2552
SHUBHAMSINGH10
rag2127
surinderdawra388
a7977370173
Reverse
Strings
Strings
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Longest Palindromic Substring | Set 1
Length of the longest substring without repeating characters
Convert string to char array in C++
Top 50 String Coding Problems for Interviews
What is Data Structure: Types, Classifications and Applications
Check whether two strings are anagram of each other
Print all the duplicates in the input string
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Jun, 2022"
},
{
"code": null,
"e": 309,
"s": 52,
"text": "Given a string containing a number of words. If the count of words in string is even then reverse its even position’s words else reverse its odd position, push reversed words at the starting of a new string and append the remaining words as it is in order."
},
{
"code": null,
"e": 320,
"s": 309,
"text": "Examples: "
},
{
"code": null,
"e": 532,
"s": 320,
"text": "Input: Ashish Yadav Abhishek Rajput Sunil Pundir\nOutput: ridnuP tupjaR vadaY Ashish Abhishek Sunil\n\nInput: Ashish Yadav Abhishek Rajput Sunil Pundir Prem\nOutput: merP linuS kehsihbA hsihsA Yadav Rajput Pundir "
},
{
"code": null,
"e": 818,
"s": 532,
"text": "Approach: If number of words are even then even position’s words come first and also reverse that particular word, and if number of words are odd then odd position’s words come first and also reverse that particular word, after then the remaining words are appended in order. For e.g. "
},
{
"code": null,
"e": 1042,
"s": 818,
"text": "Ashish Yadav Abhishek Rajput Sunil Pundir. In the above string, the number of words is even then “Yadav Rajput Pundir” comes at the even position and then the final output will be: ridnuP tupjaR vadaY Ashish Abhishek Sunil "
},
{
"code": null,
"e": 1046,
"s": 1042,
"text": "C++"
},
{
"code": null,
"e": 1048,
"s": 1046,
"text": "C"
},
{
"code": null,
"e": 1053,
"s": 1048,
"text": "Java"
},
{
"code": null,
"e": 1061,
"s": 1053,
"text": "Python3"
},
{
"code": null,
"e": 1064,
"s": 1061,
"text": "C#"
},
{
"code": null,
"e": 1075,
"s": 1064,
"text": "Javascript"
},
{
"code": "// C++ program to reverse string// according to the number of words#include <bits/stdc++.h>using namespace std; // Reverse the letters of the wordvoid reverse(char str[], int start, int end){ // Temporary variable to store character char temp; while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; }} // This function forms the required stringvoid reverseletter(char str[], int start, int end){ int wstart, wend; for (wstart = wend = start; wend < end; wend++) { if (str[wend] == ' ') continue; // Checking the number of words // present in string to reverse while (str[wend] != ' ' && wend <= end) wend++; wend--; // Reverse the letter // of the words reverse(str, wstart, wend); }} // Driver Codeint main(){ char str[1000] = \"Ashish Yadav Abhishek Rajput Sunil Pundir\"; reverseletter(str, 0, strlen(str) - 1); cout << str; return 0;} // This code is contributed by SHUBHAMSINGH10",
"e": 2224,
"s": 1075,
"text": null
},
{
"code": "// C program to reverse string// according to the number of words#include<stdio.h>#include<string.h> // Reverse the letters of the wordvoid reverse(char str[], int start, int end) { // Temporary variable to store character char temp; while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; }} // This function forms the required stringvoid reverseletter(char str[], int start, int end) { int wstart, wend; for (wstart = wend = start; wend < end; wend++) { if (str[wend] == ' ') continue; // Checking the number of words // present in string to reverse while (str[wend] != ' ' && wend <= end) wend++; wend--; //Reverse the letter //of the words reverse(str, wstart, wend); }} // Driver Codeint main(){ char str[1000] = \"Ashish Yadav Abhishek Rajput Sunil Pundir\"; reverseletter(str, 0, strlen(str)-1); printf(\"%s\", str); return 0;}",
"e": 3351,
"s": 2224,
"text": null
},
{
"code": "// Java program to reverse string// according to the number of wordsclass GFG{ // Reverse the letters of the word static void reverse(char str[], int start, int end) { // Temporary variable to store character char temp; while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } } // This function forms the required string static void reverseletter(char str[], int start, int end) { int wstart, wend; for (wstart = wend = start; wend < end; wend++) { if (str[wend] == ' ') { continue; } // Checking the number of words // present in string to reverse while (wend <= end && str[wend] != ' ') { wend++; } wend--; // Reverse the letter // of the words reverse(str, wstart, wend); } } // Driver Code public static void main(String[] args) { char str[] = \"Ashish Yadav Abhishek Rajput Sunil Pundir\".toCharArray(); reverseletter(str, 0, str.length - 1); System.out.printf(\"%s\", String.valueOf(str)); }} // This code contributed by Rajput-Ji",
"e": 4774,
"s": 3351,
"text": null
},
{
"code": "# Python3 program to reverse string# according to the number of words # Reverse the letters of the worddef reverse(string, start, end): # Temporary variable to store character temp = '' while start <= end: # Swapping the first and last character temp = string[start] string[start] = string[end] string[end] = temp start += 1 end -= 1 # This function forms the required stringdef reverseletter(string, start, end): wstart, wend = start, start while wend < end: if string[wend] == \" \": wend += 1 continue # Checking the number of words # present in string to reverse while wend <= end and string[wend] != \" \": wend += 1 wend -= 1 # Reverse the letter # of the words reverse(string, wstart, wend) wend += 1 # Driver Codeif __name__ == \"__main__\": string = \"Ashish Yadav Abhishek Rajput Sunil Pundir\" string = list(string) reverseletter(string, 0, len(string) - 1) print(''.join(string)) # This code is contributed by# sanjeev2552",
"e": 5871,
"s": 4774,
"text": null
},
{
"code": "// C# program to reverse string// according to the number of wordsusing System; class GFG{ // Reverse the letters of the word static void reverse(char []str, int start, int end) { // Temporary variable to store character char temp; while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } } // This function forms the required string static void reverseletter(char []str, int start, int end) { int wstart, wend; for (wstart = wend = start; wend < end; wend++) { if (str[wend] == ' ') { continue; } // Checking the number of words // present in string to reverse while (wend <= end && str[wend] != ' ') { wend++; } wend--; // Reverse the letter // of the words reverse(str, wstart, wend); } } // Driver Code public static void Main(String[] args) { char []str = \"Ashish Yadav Abhishek Rajput Sunil Pundir\".ToCharArray(); reverseletter(str, 0, str.Length - 1); Console.Write(\"{0}\", String.Join(\"\",str)); }} // This code has been contributed by 29AjayKumar",
"e": 7326,
"s": 5871,
"text": null
},
{
"code": "<script>// Javascript program to reverse string// according to the number of words // Reverse the letters of the wordfunction reverse(str,start,end){ // Temporary variable to store character let temp; while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; }} // This function forms the required stringfunction reverseletter(str,start,end){ let wstart, wend; for (wstart = wend = start; wend < end; wend++) { if (str[wend] == ' ') { continue; } // Checking the number of words // present in string to reverse while (wend <= end && str[wend] != ' ') { wend++; } wend--; // Reverse the letter // of the words reverse(str, wstart, wend); }} // Driver Codelet str= \"Ashish Yadav Abhishek Rajput Sunil Pundir\".split(\"\");reverseletter(str, 0, str.length - 1);document.write((str).join(\"\")); // This code is contributed by rag2127</script>",
"e": 8535,
"s": 7326,
"text": null
},
{
"code": null,
"e": 8577,
"s": 8535,
"text": "ridnuP tupjaR vadaY Ashish Abhishek Sunil"
},
{
"code": null,
"e": 8625,
"s": 8579,
"text": "Time complexity : O(n) Auxiliary Space : O(1)"
},
{
"code": null,
"e": 8635,
"s": 8625,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 8647,
"s": 8635,
"text": "29AjayKumar"
},
{
"code": null,
"e": 8659,
"s": 8647,
"text": "sanjeev2552"
},
{
"code": null,
"e": 8674,
"s": 8659,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 8682,
"s": 8674,
"text": "rag2127"
},
{
"code": null,
"e": 8699,
"s": 8682,
"text": "surinderdawra388"
},
{
"code": null,
"e": 8711,
"s": 8699,
"text": "a7977370173"
},
{
"code": null,
"e": 8719,
"s": 8711,
"text": "Reverse"
},
{
"code": null,
"e": 8727,
"s": 8719,
"text": "Strings"
},
{
"code": null,
"e": 8735,
"s": 8727,
"text": "Strings"
},
{
"code": null,
"e": 8743,
"s": 8735,
"text": "Reverse"
},
{
"code": null,
"e": 8841,
"s": 8743,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8916,
"s": 8841,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 8973,
"s": 8916,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 9009,
"s": 8973,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 9047,
"s": 9009,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 9108,
"s": 9047,
"text": "Length of the longest substring without repeating characters"
},
{
"code": null,
"e": 9144,
"s": 9108,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 9189,
"s": 9144,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 9253,
"s": 9189,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 9305,
"s": 9253,
"text": "Check whether two strings are anagram of each other"
}
] |
Program to print the pattern ‘G’
|
04 Jun, 2022
In this article, we will learn how to print the pattern G using stars and white-spaces. Given a number n, we will write a program to print the pattern G over n lines or rows.Examples:
Input : 7
Output :
***
*
*
* ***
* *
* *
***
Input : 9
Output :
*****
*
*
*
* ***
* *
* *
* *
*****
In this program, we have used the simple logic of iteration over lines to create the pattern G. Please look at the image below which represents the pattern G in the form of a 2-d matrix, where mat[i][j] = ‘ij’:
If we try to analyze this picture with a (row, column) matrix and the circles represent the position of stars in the pattern G, we will learn the steps. Here we are performing the operations column-wise. So for the first line of stars, we set the first if condition, where the row position with 0 and (n-1) won’t get the stars and all other rows from 1 to (n-1), will get the stars. Similarly, for the second, third and fourth column we want stars at the position row = 0 and row = (n-1). The other steps are self-explanatory and can be understood from the position of rows and columns in the diagram.Below is the implementation of above idea:
C++
Java
Python
C#
PHP
Javascript
// C++ program to print the pattern G#include <iostream>using namespace std; void pattern(int line){ int i, j; for(i = 0; i < line; i++) { for(j = 0; j < line; j++) { if((j == 1 && i != 0 && i != line - 1) || ((i == 0 || i == line - 1) && j > 1 && j < line - 2) || (i == ((line - 1) / 2) && j > 2 && j < line - 1) || (j == line - 2 && i != 0 && i >= ((line - 1) / 2) && i != line - 1)) printf("*"); else printf( " "); } printf("\n"); }} // Driver codeint main(){ int line = 7; pattern(line); return 0;} // This code is contributed// by vt_m.
// Java program to print the pattern Gimport java.io.*; class GFG { static void pattern(int line) { int i, j; for(i = 0; i < line; i++) { for(j = 0; j < line; j++) { if((j == 1 && i != 0 && i != line - 1) || ((i == 0 || i == line - 1) && j > 1 && j < line - 2) || (i == ((line - 1) / 2) && j > 2 && j < line - 1) || (j == line - 2 && i != 0 && i >= ((line - 1) / 2) && i != line - 1)) System.out.print("*"); else System.out.print( " "); } System.out.println(); } } // Driver code public static void main (String[] args) { int line = 7; pattern(line); }} // This code is contributed by vt_m.
# Python program to print pattern Gdef Pattern(line): pat="" for i in range(0,line): for j in range(0,line): if ((j == 1 and i != 0 and i != line-1) or ((i == 0 or i == line-1) and j > 1 and j < line-2) or (i == ((line-1)/2) and j > line-5 and j < line-1) or (j == line-2 and i != 0 and i != line-1 and i >=((line-1)/2))): pat=pat+"*" else: pat=pat+" " pat=pat+"\n" return pat # Driver Codeline = 7print(Pattern(line))
// C# program to print the pattern Gusing System; class GFG { static void pattern(int line) { int i, j; for(i = 0; i < line; i++) { for(j = 0; j < line; j++) { if((j == 1 && i != 0 && i != line - 1) || ((i == 0 || i == line - 1) && j > 1 && j < line - 2) || (i == ((line - 1) / 2) && j > 2 && j < line - 1) || (j == line - 2 && i != 0 && i >= ((line - 1) / 2) && i != line - 1)) Console.Write("*"); else Console.Write( " "); } Console.WriteLine(); } } // Driver code public static void Main () { int line = 7; pattern(line); }} // This code is contributed by vt_m.
<?php// PHP program to print pattern G function Pattern($line){ for ($i=0; $i<$line; $i++) { for ($j=0; $j<=$line; $j++) { if (($j == 1 and $i != 0 and $i != $line-1) or (($i == 0 or $i == $line-1) and $j > 1 and $j < $line-2) or ($i == (($line-1)/2) and $j > 2 and $j < $line-1) or ($j == $line-2 and $i != 0 and $i >=(($line-1)/2) and $i != $line-1)) echo "*"; else echo " "; } echo "\n"; }} // Driver Code$line = 7;Pattern($line)?>
<script> // JavaScript program to print the pattern G function pattern(line) { var i, j; for (i = 0; i < line; i++) { for (j = 0; j < line; j++) { if ( (j == 1 && i != 0 && i != line - 1) || ((i == 0 || i == line - 1) && j > 1 && j < line - 2) || (i == (line - 1) / 2 && j > 2 && j < line - 1) || (j == line - 2 && i != 0 && i >= (line - 1) / 2 && i != line - 1) ) document.write("*"); else document.write(" "); } document.write("<br>"); } } // Driver code var line = 7; pattern(line); // This code is contributed by rdtank. </script>
Output:
***
*
*
* ***
* *
* *
***
Time Complexity: O(n2), where n represents the given input.Auxiliary Space: O(1), no extra space is required, so it is a constant.
rdtank
samim2000
pattern-printing
Python Programs
School Programming
pattern-printing
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Python program to check whether a number is Prime or not
Python program to add two numbers
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n04 Jun, 2022"
},
{
"code": null,
"e": 240,
"s": 54,
"text": "In this article, we will learn how to print the pattern G using stars and white-spaces. Given a number n, we will write a program to print the pattern G over n lines or rows.Examples: "
},
{
"code": null,
"e": 425,
"s": 240,
"text": "Input : 7\nOutput :\n *** \n * \n * \n * *** \n * * \n * * \n *** \n\nInput : 9\nOutput :\n ***** \n * \n * \n * \n * *** \n * * \n * * \n * * \n ***** "
},
{
"code": null,
"e": 640,
"s": 427,
"text": "In this program, we have used the simple logic of iteration over lines to create the pattern G. Please look at the image below which represents the pattern G in the form of a 2-d matrix, where mat[i][j] = ‘ij’: "
},
{
"code": null,
"e": 1286,
"s": 640,
"text": "If we try to analyze this picture with a (row, column) matrix and the circles represent the position of stars in the pattern G, we will learn the steps. Here we are performing the operations column-wise. So for the first line of stars, we set the first if condition, where the row position with 0 and (n-1) won’t get the stars and all other rows from 1 to (n-1), will get the stars. Similarly, for the second, third and fourth column we want stars at the position row = 0 and row = (n-1). The other steps are self-explanatory and can be understood from the position of rows and columns in the diagram.Below is the implementation of above idea: "
},
{
"code": null,
"e": 1290,
"s": 1286,
"text": "C++"
},
{
"code": null,
"e": 1295,
"s": 1290,
"text": "Java"
},
{
"code": null,
"e": 1302,
"s": 1295,
"text": "Python"
},
{
"code": null,
"e": 1305,
"s": 1302,
"text": "C#"
},
{
"code": null,
"e": 1309,
"s": 1305,
"text": "PHP"
},
{
"code": null,
"e": 1320,
"s": 1309,
"text": "Javascript"
},
{
"code": "// C++ program to print the pattern G#include <iostream>using namespace std; void pattern(int line){ int i, j; for(i = 0; i < line; i++) { for(j = 0; j < line; j++) { if((j == 1 && i != 0 && i != line - 1) || ((i == 0 || i == line - 1) && j > 1 && j < line - 2) || (i == ((line - 1) / 2) && j > 2 && j < line - 1) || (j == line - 2 && i != 0 && i >= ((line - 1) / 2) && i != line - 1)) printf(\"*\"); else printf( \" \"); } printf(\"\\n\"); }} // Driver codeint main(){ int line = 7; pattern(line); return 0;} // This code is contributed// by vt_m.",
"e": 2017,
"s": 1320,
"text": null
},
{
"code": "// Java program to print the pattern Gimport java.io.*; class GFG { static void pattern(int line) { int i, j; for(i = 0; i < line; i++) { for(j = 0; j < line; j++) { if((j == 1 && i != 0 && i != line - 1) || ((i == 0 || i == line - 1) && j > 1 && j < line - 2) || (i == ((line - 1) / 2) && j > 2 && j < line - 1) || (j == line - 2 && i != 0 && i >= ((line - 1) / 2) && i != line - 1)) System.out.print(\"*\"); else System.out.print( \" \"); } System.out.println(); } } // Driver code public static void main (String[] args) { int line = 7; pattern(line); }} // This code is contributed by vt_m.",
"e": 2854,
"s": 2017,
"text": null
},
{
"code": "# Python program to print pattern Gdef Pattern(line): pat=\"\" for i in range(0,line): for j in range(0,line): if ((j == 1 and i != 0 and i != line-1) or ((i == 0 or i == line-1) and j > 1 and j < line-2) or (i == ((line-1)/2) and j > line-5 and j < line-1) or (j == line-2 and i != 0 and i != line-1 and i >=((line-1)/2))): pat=pat+\"*\" else: pat=pat+\" \" pat=pat+\"\\n\" return pat # Driver Codeline = 7print(Pattern(line))",
"e": 3413,
"s": 2854,
"text": null
},
{
"code": "// C# program to print the pattern Gusing System; class GFG { static void pattern(int line) { int i, j; for(i = 0; i < line; i++) { for(j = 0; j < line; j++) { if((j == 1 && i != 0 && i != line - 1) || ((i == 0 || i == line - 1) && j > 1 && j < line - 2) || (i == ((line - 1) / 2) && j > 2 && j < line - 1) || (j == line - 2 && i != 0 && i >= ((line - 1) / 2) && i != line - 1)) Console.Write(\"*\"); else Console.Write( \" \"); } Console.WriteLine(); } } // Driver code public static void Main () { int line = 7; pattern(line); }} // This code is contributed by vt_m.",
"e": 4224,
"s": 3413,
"text": null
},
{
"code": "<?php// PHP program to print pattern G function Pattern($line){ for ($i=0; $i<$line; $i++) { for ($j=0; $j<=$line; $j++) { if (($j == 1 and $i != 0 and $i != $line-1) or (($i == 0 or $i == $line-1) and $j > 1 and $j < $line-2) or ($i == (($line-1)/2) and $j > 2 and $j < $line-1) or ($j == $line-2 and $i != 0 and $i >=(($line-1)/2) and $i != $line-1)) echo \"*\"; else echo \" \"; } echo \"\\n\"; }} // Driver Code$line = 7;Pattern($line)?>",
"e": 4787,
"s": 4224,
"text": null
},
{
"code": "<script> // JavaScript program to print the pattern G function pattern(line) { var i, j; for (i = 0; i < line; i++) { for (j = 0; j < line; j++) { if ( (j == 1 && i != 0 && i != line - 1) || ((i == 0 || i == line - 1) && j > 1 && j < line - 2) || (i == (line - 1) / 2 && j > 2 && j < line - 1) || (j == line - 2 && i != 0 && i >= (line - 1) / 2 && i != line - 1) ) document.write(\"*\"); else document.write(\" \"); } document.write(\"<br>\"); } } // Driver code var line = 7; pattern(line); // This code is contributed by rdtank. </script>",
"e": 5522,
"s": 4787,
"text": null
},
{
"code": null,
"e": 5532,
"s": 5522,
"text": "Output: "
},
{
"code": null,
"e": 5588,
"s": 5532,
"text": " *** \n * \n * \n * *** \n * * \n * * \n *** "
},
{
"code": null,
"e": 5719,
"s": 5588,
"text": "Time Complexity: O(n2), where n represents the given input.Auxiliary Space: O(1), no extra space is required, so it is a constant."
},
{
"code": null,
"e": 5726,
"s": 5719,
"text": "rdtank"
},
{
"code": null,
"e": 5736,
"s": 5726,
"text": "samim2000"
},
{
"code": null,
"e": 5753,
"s": 5736,
"text": "pattern-printing"
},
{
"code": null,
"e": 5769,
"s": 5753,
"text": "Python Programs"
},
{
"code": null,
"e": 5788,
"s": 5769,
"text": "School Programming"
},
{
"code": null,
"e": 5805,
"s": 5788,
"text": "pattern-printing"
},
{
"code": null,
"e": 5903,
"s": 5805,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5941,
"s": 5903,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 5990,
"s": 5941,
"text": "Python | Convert string dictionary to dictionary"
},
{
"code": null,
"e": 6027,
"s": 5990,
"text": "Python Program for Fibonacci numbers"
},
{
"code": null,
"e": 6084,
"s": 6027,
"text": "Python program to check whether a number is Prime or not"
},
{
"code": null,
"e": 6118,
"s": 6084,
"text": "Python program to add two numbers"
},
{
"code": null,
"e": 6136,
"s": 6118,
"text": "Python Dictionary"
},
{
"code": null,
"e": 6161,
"s": 6136,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 6177,
"s": 6161,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 6200,
"s": 6177,
"text": "Introduction To PYTHON"
}
] |
Code Golfing in Python
|
16 Jun, 2022
Code Golf in Python refers to attempting to solve a problem using the least amount of characters possible. Like in Golf, the low score wins, the fewest amount of characters “wins”.
Python is a fantastic language for code golfing due to backward compatibility, quirks, it being a high-level language, and all the coercion. So, here we will look at some Code golfing techniques in Python language.
Collapse two numerical loops: Suppose you are iterating over a matrix of m rows and n columns. Instead of two nested for loops, one for the row and one of the columns, it’s usually shorter to use a single loop to iterate over the m*n matrix.
Original Code :
m = n = 3
for i in range(m):
for j in range(n):
print(i, j)
Golfed Code :
m = n = 3
for i in range(m*n):
print(i//n, i%n)
This technique is not limited to only two nested loops, we can even write the same loop for 3 or more nested loops
m, n, o = 2, 3, 4
for k in range(m*n*o):
print(k//n//o, k%(n*o), k%o)
Addition or Subtraction by 1: For integer n you can write -~n is equivalent to n+1~-n is equivalent to n-1
-~n is equivalent to n+1
~-n is equivalent to n-1
This works because the bit flip ~x equals -x-1. This uses the same number of characters, but can indirectly cut spaces or parens for operator precedence.
Membership in Set: We write set in Python as S = {1, 2, 3, 4, 5}. To check whether an element e exists in Set S or not we can check the condition as {e}&S Original Code:
Original Code:
S = {1, 2, 3, 4, 5, 6, 7}
if 5 in S:
print("Present")
else:
print("Absent")
Golfed Code:
S = {1, 2, 3, 4, 5, 6, 7}
if {5}&S:
print("Present")
else:
print("Absent")
Sibling of AND operator: When we have two boolean or integer values, a and b, if we want to find out if both a and b are true, use * instead of and. Original Code:
Original Code:
if a and b:
print("geeks")
else:
print("geeksforgeeks")
Golfed Code:
if a*b:
print("geeks")
else:
print("geeksforgeeks")
Sibling of OR operator: When we have two boolean or integer values, a and b, if we want to find out if any one from a and b is true or both, use | instead of or. Original Code:
Original Code:
if a or b:
print("geeks")
else:
print("geeksforgeeks")
Golfed Code:
if a|b:
print("geeks")
else:
print("geeksforgeeks")
Use += instead of append: Instead of using append for adding one item to an existing list, we can use += operator. Original Code:
Original Code:
A.append(B)
Golfed Code:
A+=B,
Note: B, here creates a one-element tuple which can be used to extend A just like [B] in A+=[B].
Use += instead of extend: Instead of using extend for merging one list into another at the end, we can use += operator. Original Code:
Original Code:
A.extend(B)
Golfed Code:
A+=B
Magical Comparison Operators: We face many situations in which we have to compare a single variable with different values, and generally we defend them by different comparisons and combining them with AND operator. But Python allows us to put all comparison operators in a single line without using the AND operator. Original Code:
if a>1 and a<10:
print(a)
Golfed Code:
if 1<a<10:
print(a)
Note: We can use this technique for multiple variables also at the same time.
Original Code:
if a > 10 and b > 10 and 30 > a and 50 > b:
print(a)
Golfed Code:
if 30 > a > 10 < b < 50:
print(a)
Sibling of Floor function: Suppose we want to find the floor value of a real number, we generally import floor function from math and then apply on the number. But we can simply apply the floor division with 1, which will give us a fruitful result. Original Code:
Original Code:
from math import floor
n = 3/2
print(floor(n))
Golfed Code:
n = 3/2
print(n//1)
Sibling of Ceil function: Suppose we want to find the ceil value of a real number, we generally import ceil function from math and then apply on the number. But we can do this operation in a more beautiful manner by first multiplying with -1 and then apply floor division with 1 and again multiply with -1. Original Code:
Original Code:
from math import ceil
n = 3/2
print(ceil(n))
Golfed Code:
n = 3/2
print(-(-n//1))
Lambda functions: Lambda definition does not include a “return” statement, it always contains an expression which is returned. We can also put a lambda definition anywhere a function is expected, and we don’t have to assign it to a variable at all. This is the simplicity of lambda functions. Original Code:
Original Code:
def c(a):
if a < 3: return a-5
else: return a+5
Golfed Code:
c=lambda a:a<3and a-5or a+5
To get the entire alphabet string: We can use the map function of python to get the string of whole alphabet set. Original code:
Original code:
string = 'abcdefghijklmnopqrstuvwxyz'
or
string = [chr(i+97)for i in range(26)]
Golfed Code:
string = map(chr,range(97,123))
Indexing Technique for conditions: When we have a certain condition which will give the answer in the form of small integers then we can use that in integer index in list or tuple to get our final answer. Original Code:
Original Code:
if a<b:return a
else:return b
Golfed Code:
return (b, a)[a<b]
Reverse the Sequence: We can reverse any list sequence using the good alien smiley face. Original Code:
Original Code:
string = 'geeksforgeeks'
for i in range(len(string)-1,-1,-1):
print(string[i])
Golfed Code:
string = 'geeksforgeeks'
for i in string[::-1]:
print(i)
Use ~ to index from the back of a list: If L is a list, use L[~i] to get the i’th element from the back. This is the i’th element of the reverse of L. The bit complement ~i equals -i-1, and so fixes the off-by-one error from L[-i]. Original Code:
Original Code:
string = 'geeksforgeeks'
for i in range(len(string)-1,-1,-1):
print(string[i])
Golfed Code:
for i in range(len(string)):
print(string[~i])
Print the items of the list: We can print the items of a list by using the * operator with the name of the list instead of looping through the list. Original Code:
Original Code:
A = [1,2,3,4,5,6,7]
for i in A:
print(i,end = ' ')
Golfed Code:
A = [1,2,3,4,5,6,7]
print(*A)
Assigning the same values to multiple variables: We can assign the same value to multiple variables either in a single line or multiple lines. Original Code:
# multiple lines
a = 0
b = 0
c = 0
# single line
a,b,c = 0,0,0
Golfed Code:
a = b = c = 0
Assigning same or different characters to variable: We can assign the same of different characters to multiple variables either in a single line or multiple lines. Original Code:
# multiple lines
a = 'p'
b = 'q'
c = 'r'
# single line
a,b,c = 'p','q','r'
Golfed Code:
a,b,c = 'pqr'
Converting iterables into the list: Imagine you have any ordered iterable like a tuple or string but you want to convert it into a list, so you can do this with * operator. Original Code:
Original Code:
a = (2,3,5,7,11)
x = list(a)
a = 'geeksforgeek'
x = list(a)
Golfed Code:
a = (2,3,5,7,11)
*x, = a
a = 'geeksforgeeks'
*x, = a
Converting iterables into the Set: Imagine you have any iterable like a list, tuple or string but you want to convert it into a Set, so you can do this with * operator. Original Code:
Original Code:
a = (2,3,5,7,11)
x = set(a)
a = [2,3,5,7,11]
x = set(a)
a = 'geeksforgeeks'
x = set(a)
Golfed Code:
a = (2,3,5,7,11)
x = {*a}
a = [2,3,5,7,11]
x = {*a}
a = 'geeksforgeeks'
x = {*a}
Converting iterables into the Tuple: Imagine you have any iterable like a list, set, or string but you want to convert it into a Tuple, so you can do this with * operator. Original Code:
Original Code:
a = (2,3,5,7,11)
x = tuple(a)
a = [2,3,5,7,11]
x = tuple(a)
a = 'geeksforgeeks'
x = tuple(a)
Golfed Code:
a = (2,3,5,7,11)
x = (*a,)
a = [2,3,5,7,11]
x = (*a,)
a = 'geeksforgeeks'
x = (*a,)
Joining multiple Lists: We can join the multiple lists using + operator, but for code golfing we can do the same using * operator. Original Code:
Original Code:
T = [2,3,4,5,6,7,8,9]
new_T = [1]+T+[10]
Golfed Code:
T = [2,3,4,5,6,7,8,9]
new_T = [1,*T,10]
Joining multiple Lists: We can join the multiple lists using + operator, but for code golfing we can do the same using * operator. Original Code:
Original Code:
T = (2,3,4,5,6,7,8,9)
new_T = (1,)+T+(10,)
Golfed Code:
T = (2,3,4,5,6,7,8,9)
new_T = (1,*T,10)
sagartomar9927
anikakapoor
vinayedula
Python-Miscellaneous
python-utility
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Jun, 2022"
},
{
"code": null,
"e": 234,
"s": 52,
"text": "Code Golf in Python refers to attempting to solve a problem using the least amount of characters possible. Like in Golf, the low score wins, the fewest amount of characters “wins”. "
},
{
"code": null,
"e": 450,
"s": 234,
"text": "Python is a fantastic language for code golfing due to backward compatibility, quirks, it being a high-level language, and all the coercion. So, here we will look at some Code golfing techniques in Python language. "
},
{
"code": null,
"e": 693,
"s": 450,
"text": "Collapse two numerical loops: Suppose you are iterating over a matrix of m rows and n columns. Instead of two nested for loops, one for the row and one of the columns, it’s usually shorter to use a single loop to iterate over the m*n matrix. "
},
{
"code": null,
"e": 710,
"s": 693,
"text": "Original Code : "
},
{
"code": null,
"e": 782,
"s": 710,
"text": "m = n = 3\nfor i in range(m):\n for j in range(n):\n print(i, j)"
},
{
"code": null,
"e": 798,
"s": 782,
"text": "Golfed Code : "
},
{
"code": null,
"e": 850,
"s": 798,
"text": "m = n = 3\nfor i in range(m*n):\n print(i//n, i%n)"
},
{
"code": null,
"e": 967,
"s": 850,
"text": "This technique is not limited to only two nested loops, we can even write the same loop for 3 or more nested loops "
},
{
"code": null,
"e": 1041,
"s": 967,
"text": "m, n, o = 2, 3, 4\nfor k in range(m*n*o):\n print(k//n//o, k%(n*o), k%o)"
},
{
"code": null,
"e": 1148,
"s": 1041,
"text": "Addition or Subtraction by 1: For integer n you can write -~n is equivalent to n+1~-n is equivalent to n-1"
},
{
"code": null,
"e": 1173,
"s": 1148,
"text": "-~n is equivalent to n+1"
},
{
"code": null,
"e": 1198,
"s": 1173,
"text": "~-n is equivalent to n-1"
},
{
"code": null,
"e": 1352,
"s": 1198,
"text": "This works because the bit flip ~x equals -x-1. This uses the same number of characters, but can indirectly cut spaces or parens for operator precedence."
},
{
"code": null,
"e": 1523,
"s": 1352,
"text": "Membership in Set: We write set in Python as S = {1, 2, 3, 4, 5}. To check whether an element e exists in Set S or not we can check the condition as {e}&S Original Code: "
},
{
"code": null,
"e": 1539,
"s": 1523,
"text": "Original Code: "
},
{
"code": null,
"e": 1623,
"s": 1539,
"text": "S = {1, 2, 3, 4, 5, 6, 7}\nif 5 in S:\n print(\"Present\")\nelse:\n print(\"Absent\")"
},
{
"code": null,
"e": 1637,
"s": 1623,
"text": "Golfed Code: "
},
{
"code": null,
"e": 1720,
"s": 1637,
"text": "S = {1, 2, 3, 4, 5, 6, 7}\nif {5}&S:\n print(\"Present\")\nelse:\n print(\"Absent\")"
},
{
"code": null,
"e": 1885,
"s": 1720,
"text": "Sibling of AND operator: When we have two boolean or integer values, a and b, if we want to find out if both a and b are true, use * instead of and. Original Code: "
},
{
"code": null,
"e": 1901,
"s": 1885,
"text": "Original Code: "
},
{
"code": null,
"e": 1965,
"s": 1901,
"text": "if a and b:\n print(\"geeks\")\nelse:\n print(\"geeksforgeeks\")"
},
{
"code": null,
"e": 1979,
"s": 1965,
"text": "Golfed Code: "
},
{
"code": null,
"e": 2039,
"s": 1979,
"text": "if a*b:\n print(\"geeks\")\nelse:\n print(\"geeksforgeeks\")"
},
{
"code": null,
"e": 2217,
"s": 2039,
"text": "Sibling of OR operator: When we have two boolean or integer values, a and b, if we want to find out if any one from a and b is true or both, use | instead of or. Original Code: "
},
{
"code": null,
"e": 2233,
"s": 2217,
"text": "Original Code: "
},
{
"code": null,
"e": 2296,
"s": 2233,
"text": "if a or b:\n print(\"geeks\")\nelse:\n print(\"geeksforgeeks\")"
},
{
"code": null,
"e": 2310,
"s": 2296,
"text": "Golfed Code: "
},
{
"code": null,
"e": 2370,
"s": 2310,
"text": "if a|b:\n print(\"geeks\")\nelse:\n print(\"geeksforgeeks\")"
},
{
"code": null,
"e": 2501,
"s": 2370,
"text": "Use += instead of append: Instead of using append for adding one item to an existing list, we can use += operator. Original Code: "
},
{
"code": null,
"e": 2517,
"s": 2501,
"text": "Original Code: "
},
{
"code": null,
"e": 2529,
"s": 2517,
"text": "A.append(B)"
},
{
"code": null,
"e": 2543,
"s": 2529,
"text": "Golfed Code: "
},
{
"code": null,
"e": 2549,
"s": 2543,
"text": "A+=B,"
},
{
"code": null,
"e": 2647,
"s": 2549,
"text": "Note: B, here creates a one-element tuple which can be used to extend A just like [B] in A+=[B]. "
},
{
"code": null,
"e": 2783,
"s": 2647,
"text": "Use += instead of extend: Instead of using extend for merging one list into another at the end, we can use += operator. Original Code: "
},
{
"code": null,
"e": 2799,
"s": 2783,
"text": "Original Code: "
},
{
"code": null,
"e": 2811,
"s": 2799,
"text": "A.extend(B)"
},
{
"code": null,
"e": 2825,
"s": 2811,
"text": "Golfed Code: "
},
{
"code": null,
"e": 2830,
"s": 2825,
"text": "A+=B"
},
{
"code": null,
"e": 3163,
"s": 2830,
"text": "Magical Comparison Operators: We face many situations in which we have to compare a single variable with different values, and generally we defend them by different comparisons and combining them with AND operator. But Python allows us to put all comparison operators in a single line without using the AND operator. Original Code: "
},
{
"code": null,
"e": 3193,
"s": 3163,
"text": "if a>1 and a<10:\n print(a)"
},
{
"code": null,
"e": 3207,
"s": 3193,
"text": "Golfed Code: "
},
{
"code": null,
"e": 3231,
"s": 3207,
"text": "if 1<a<10:\n print(a)"
},
{
"code": null,
"e": 3310,
"s": 3231,
"text": "Note: We can use this technique for multiple variables also at the same time. "
},
{
"code": null,
"e": 3326,
"s": 3310,
"text": "Original Code: "
},
{
"code": null,
"e": 3383,
"s": 3326,
"text": "if a > 10 and b > 10 and 30 > a and 50 > b:\n print(a)"
},
{
"code": null,
"e": 3397,
"s": 3383,
"text": "Golfed Code: "
},
{
"code": null,
"e": 3435,
"s": 3397,
"text": "if 30 > a > 10 < b < 50:\n print(a)"
},
{
"code": null,
"e": 3700,
"s": 3435,
"text": "Sibling of Floor function: Suppose we want to find the floor value of a real number, we generally import floor function from math and then apply on the number. But we can simply apply the floor division with 1, which will give us a fruitful result. Original Code: "
},
{
"code": null,
"e": 3716,
"s": 3700,
"text": "Original Code: "
},
{
"code": null,
"e": 3763,
"s": 3716,
"text": "from math import floor\nn = 3/2\nprint(floor(n))"
},
{
"code": null,
"e": 3777,
"s": 3763,
"text": "Golfed Code: "
},
{
"code": null,
"e": 3797,
"s": 3777,
"text": "n = 3/2\nprint(n//1)"
},
{
"code": null,
"e": 4120,
"s": 3797,
"text": "Sibling of Ceil function: Suppose we want to find the ceil value of a real number, we generally import ceil function from math and then apply on the number. But we can do this operation in a more beautiful manner by first multiplying with -1 and then apply floor division with 1 and again multiply with -1. Original Code: "
},
{
"code": null,
"e": 4136,
"s": 4120,
"text": "Original Code: "
},
{
"code": null,
"e": 4181,
"s": 4136,
"text": "from math import ceil\nn = 3/2\nprint(ceil(n))"
},
{
"code": null,
"e": 4195,
"s": 4181,
"text": "Golfed Code: "
},
{
"code": null,
"e": 4219,
"s": 4195,
"text": "n = 3/2\nprint(-(-n//1))"
},
{
"code": null,
"e": 4528,
"s": 4219,
"text": "Lambda functions: Lambda definition does not include a “return” statement, it always contains an expression which is returned. We can also put a lambda definition anywhere a function is expected, and we don’t have to assign it to a variable at all. This is the simplicity of lambda functions. Original Code: "
},
{
"code": null,
"e": 4544,
"s": 4528,
"text": "Original Code: "
},
{
"code": null,
"e": 4596,
"s": 4544,
"text": "def c(a):\n if a < 3: return a-5\n else: return a+5"
},
{
"code": null,
"e": 4610,
"s": 4596,
"text": "Golfed Code: "
},
{
"code": null,
"e": 4638,
"s": 4610,
"text": "c=lambda a:a<3and a-5or a+5"
},
{
"code": null,
"e": 4768,
"s": 4638,
"text": "To get the entire alphabet string: We can use the map function of python to get the string of whole alphabet set. Original code: "
},
{
"code": null,
"e": 4784,
"s": 4768,
"text": "Original code: "
},
{
"code": null,
"e": 4865,
"s": 4784,
"text": "string = 'abcdefghijklmnopqrstuvwxyz'\nor \nstring = [chr(i+97)for i in range(26)]"
},
{
"code": null,
"e": 4879,
"s": 4865,
"text": "Golfed Code: "
},
{
"code": null,
"e": 4911,
"s": 4879,
"text": "string = map(chr,range(97,123))"
},
{
"code": null,
"e": 5132,
"s": 4911,
"text": "Indexing Technique for conditions: When we have a certain condition which will give the answer in the form of small integers then we can use that in integer index in list or tuple to get our final answer. Original Code: "
},
{
"code": null,
"e": 5148,
"s": 5132,
"text": "Original Code: "
},
{
"code": null,
"e": 5178,
"s": 5148,
"text": "if a<b:return a\nelse:return b"
},
{
"code": null,
"e": 5192,
"s": 5178,
"text": "Golfed Code: "
},
{
"code": null,
"e": 5211,
"s": 5192,
"text": "return (b, a)[a<b]"
},
{
"code": null,
"e": 5316,
"s": 5211,
"text": "Reverse the Sequence: We can reverse any list sequence using the good alien smiley face. Original Code: "
},
{
"code": null,
"e": 5332,
"s": 5316,
"text": "Original Code: "
},
{
"code": null,
"e": 5415,
"s": 5332,
"text": "string = 'geeksforgeeks'\nfor i in range(len(string)-1,-1,-1):\n print(string[i])"
},
{
"code": null,
"e": 5429,
"s": 5415,
"text": "Golfed Code: "
},
{
"code": null,
"e": 5490,
"s": 5429,
"text": "string = 'geeksforgeeks'\nfor i in string[::-1]:\n print(i)"
},
{
"code": null,
"e": 5738,
"s": 5490,
"text": "Use ~ to index from the back of a list: If L is a list, use L[~i] to get the i’th element from the back. This is the i’th element of the reverse of L. The bit complement ~i equals -i-1, and so fixes the off-by-one error from L[-i]. Original Code: "
},
{
"code": null,
"e": 5754,
"s": 5738,
"text": "Original Code: "
},
{
"code": null,
"e": 5837,
"s": 5754,
"text": "string = 'geeksforgeeks'\nfor i in range(len(string)-1,-1,-1):\n print(string[i])"
},
{
"code": null,
"e": 5851,
"s": 5837,
"text": "Golfed Code: "
},
{
"code": null,
"e": 5902,
"s": 5851,
"text": "for i in range(len(string)):\n print(string[~i])"
},
{
"code": null,
"e": 6067,
"s": 5902,
"text": "Print the items of the list: We can print the items of a list by using the * operator with the name of the list instead of looping through the list. Original Code: "
},
{
"code": null,
"e": 6083,
"s": 6067,
"text": "Original Code: "
},
{
"code": null,
"e": 6138,
"s": 6083,
"text": "A = [1,2,3,4,5,6,7]\nfor i in A:\n print(i,end = ' ')"
},
{
"code": null,
"e": 6152,
"s": 6138,
"text": "Golfed Code: "
},
{
"code": null,
"e": 6183,
"s": 6152,
"text": "A = [1,2,3,4,5,6,7]\nprint(*A) "
},
{
"code": null,
"e": 6342,
"s": 6183,
"text": "Assigning the same values to multiple variables: We can assign the same value to multiple variables either in a single line or multiple lines. Original Code: "
},
{
"code": null,
"e": 6406,
"s": 6342,
"text": "# multiple lines\na = 0\nb = 0\nc = 0\n\n# single line\na,b,c = 0,0,0"
},
{
"code": null,
"e": 6420,
"s": 6406,
"text": "Golfed Code: "
},
{
"code": null,
"e": 6434,
"s": 6420,
"text": "a = b = c = 0"
},
{
"code": null,
"e": 6614,
"s": 6434,
"text": "Assigning same or different characters to variable: We can assign the same of different characters to multiple variables either in a single line or multiple lines. Original Code: "
},
{
"code": null,
"e": 6690,
"s": 6614,
"text": "# multiple lines\na = 'p'\nb = 'q'\nc = 'r'\n\n# single line\na,b,c = 'p','q','r'"
},
{
"code": null,
"e": 6704,
"s": 6690,
"text": "Golfed Code: "
},
{
"code": null,
"e": 6718,
"s": 6704,
"text": "a,b,c = 'pqr'"
},
{
"code": null,
"e": 6907,
"s": 6718,
"text": "Converting iterables into the list: Imagine you have any ordered iterable like a tuple or string but you want to convert it into a list, so you can do this with * operator. Original Code: "
},
{
"code": null,
"e": 6923,
"s": 6907,
"text": "Original Code: "
},
{
"code": null,
"e": 6984,
"s": 6923,
"text": "a = (2,3,5,7,11)\nx = list(a)\n\na = 'geeksforgeek'\nx = list(a)"
},
{
"code": null,
"e": 6998,
"s": 6984,
"text": "Golfed Code: "
},
{
"code": null,
"e": 7052,
"s": 6998,
"text": "a = (2,3,5,7,11)\n*x, = a\n\na = 'geeksforgeeks'\n*x, = a"
},
{
"code": null,
"e": 7237,
"s": 7052,
"text": "Converting iterables into the Set: Imagine you have any iterable like a list, tuple or string but you want to convert it into a Set, so you can do this with * operator. Original Code: "
},
{
"code": null,
"e": 7253,
"s": 7237,
"text": "Original Code: "
},
{
"code": null,
"e": 7342,
"s": 7253,
"text": "a = (2,3,5,7,11)\nx = set(a)\n\na = [2,3,5,7,11]\nx = set(a)\n\na = 'geeksforgeeks'\nx = set(a)"
},
{
"code": null,
"e": 7356,
"s": 7342,
"text": "Golfed Code: "
},
{
"code": null,
"e": 7439,
"s": 7356,
"text": "a = (2,3,5,7,11)\nx = {*a}\n\na = [2,3,5,7,11]\nx = {*a}\n\na = 'geeksforgeeks'\nx = {*a}"
},
{
"code": null,
"e": 7627,
"s": 7439,
"text": "Converting iterables into the Tuple: Imagine you have any iterable like a list, set, or string but you want to convert it into a Tuple, so you can do this with * operator. Original Code: "
},
{
"code": null,
"e": 7643,
"s": 7627,
"text": "Original Code: "
},
{
"code": null,
"e": 7738,
"s": 7643,
"text": "a = (2,3,5,7,11)\nx = tuple(a)\n\na = [2,3,5,7,11]\nx = tuple(a)\n\na = 'geeksforgeeks'\nx = tuple(a)"
},
{
"code": null,
"e": 7752,
"s": 7738,
"text": "Golfed Code: "
},
{
"code": null,
"e": 7838,
"s": 7752,
"text": "a = (2,3,5,7,11)\nx = (*a,)\n\na = [2,3,5,7,11]\nx = (*a,)\n\na = 'geeksforgeeks'\nx = (*a,)"
},
{
"code": null,
"e": 7985,
"s": 7838,
"text": "Joining multiple Lists: We can join the multiple lists using + operator, but for code golfing we can do the same using * operator. Original Code: "
},
{
"code": null,
"e": 8001,
"s": 7985,
"text": "Original Code: "
},
{
"code": null,
"e": 8042,
"s": 8001,
"text": "T = [2,3,4,5,6,7,8,9]\nnew_T = [1]+T+[10]"
},
{
"code": null,
"e": 8056,
"s": 8042,
"text": "Golfed Code: "
},
{
"code": null,
"e": 8096,
"s": 8056,
"text": "T = [2,3,4,5,6,7,8,9]\nnew_T = [1,*T,10]"
},
{
"code": null,
"e": 8243,
"s": 8096,
"text": "Joining multiple Lists: We can join the multiple lists using + operator, but for code golfing we can do the same using * operator. Original Code: "
},
{
"code": null,
"e": 8259,
"s": 8243,
"text": "Original Code: "
},
{
"code": null,
"e": 8302,
"s": 8259,
"text": "T = (2,3,4,5,6,7,8,9)\nnew_T = (1,)+T+(10,)"
},
{
"code": null,
"e": 8316,
"s": 8302,
"text": "Golfed Code: "
},
{
"code": null,
"e": 8356,
"s": 8316,
"text": "T = (2,3,4,5,6,7,8,9)\nnew_T = (1,*T,10)"
},
{
"code": null,
"e": 8371,
"s": 8356,
"text": "sagartomar9927"
},
{
"code": null,
"e": 8383,
"s": 8371,
"text": "anikakapoor"
},
{
"code": null,
"e": 8394,
"s": 8383,
"text": "vinayedula"
},
{
"code": null,
"e": 8415,
"s": 8394,
"text": "Python-Miscellaneous"
},
{
"code": null,
"e": 8430,
"s": 8415,
"text": "python-utility"
},
{
"code": null,
"e": 8437,
"s": 8430,
"text": "Python"
},
{
"code": null,
"e": 8456,
"s": 8437,
"text": "Technical Scripter"
},
{
"code": null,
"e": 8554,
"s": 8456,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8572,
"s": 8554,
"text": "Python Dictionary"
},
{
"code": null,
"e": 8614,
"s": 8572,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 8636,
"s": 8614,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 8671,
"s": 8636,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 8697,
"s": 8671,
"text": "Python String | replace()"
},
{
"code": null,
"e": 8729,
"s": 8697,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 8756,
"s": 8729,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 8786,
"s": 8756,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 8807,
"s": 8786,
"text": "Python OOPs Concepts"
}
] |
Java program to check for prime and find next Prime in Java
|
Any whole number which is greater than 1 and has only two factors that is 1 and the number itself, is called a prime number. Other than these two number it has no positive divisor. For example: 7 = 1 × 7
Following is the algorithm to find whether a number is prime or not −
Take integer variable A.
Take integer variable A.
Divide the variable A with (A-1 to 2).
Divide the variable A with (A-1 to 2).
If A is divisible by any value (A-1 to 2) it is not prime.
If A is divisible by any value (A-1 to 2) it is not prime.
Else it is prime.
Else it is prime.
Following Java program accepts an integer from the user, finds whether the given number is prime and, prints the next prime number.
import java.util.Scanner;
public class NextNumberisPrime {
public static int isPrime(int num){
int prime = 1;
for(int i = 2; i < num; i++) {
if((num % i) == 0) {
prime = 0;
}
}
return num;
}
public static int nextPrime(int num) {
num++;
for (int i = 2; i < num; i++) {
if(num%i == 0) {
num++;
i=2;
} else {
continue;
}
}
return num;
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number ::");
int num = sc.nextInt();
int result = 0;
int prime = isPrime(num);
if (prime == 1) {
System.out.println(num+" is a prime number");
} else {
System.out.println(num+" is not a prime number");
}
System.out.println("Next prime number is: "+nextPrime(num));
}
}
Enter a number ::
25
25 is not a prime number
Next prime number is: 29
|
[
{
"code": null,
"e": 1391,
"s": 1187,
"text": "Any whole number which is greater than 1 and has only two factors that is 1 and the number itself, is called a prime number. Other than these two number it has no positive divisor. For example: 7 = 1 × 7"
},
{
"code": null,
"e": 1461,
"s": 1391,
"text": "Following is the algorithm to find whether a number is prime or not −"
},
{
"code": null,
"e": 1486,
"s": 1461,
"text": "Take integer variable A."
},
{
"code": null,
"e": 1511,
"s": 1486,
"text": "Take integer variable A."
},
{
"code": null,
"e": 1550,
"s": 1511,
"text": "Divide the variable A with (A-1 to 2)."
},
{
"code": null,
"e": 1589,
"s": 1550,
"text": "Divide the variable A with (A-1 to 2)."
},
{
"code": null,
"e": 1648,
"s": 1589,
"text": "If A is divisible by any value (A-1 to 2) it is not prime."
},
{
"code": null,
"e": 1707,
"s": 1648,
"text": "If A is divisible by any value (A-1 to 2) it is not prime."
},
{
"code": null,
"e": 1725,
"s": 1707,
"text": "Else it is prime."
},
{
"code": null,
"e": 1743,
"s": 1725,
"text": "Else it is prime."
},
{
"code": null,
"e": 1875,
"s": 1743,
"text": "Following Java program accepts an integer from the user, finds whether the given number is prime and, prints the next prime number."
},
{
"code": null,
"e": 2815,
"s": 1875,
"text": "import java.util.Scanner;\npublic class NextNumberisPrime {\n public static int isPrime(int num){\n int prime = 1;\n for(int i = 2; i < num; i++) {\n if((num % i) == 0) {\n prime = 0;\n }\n }\n return num;\n }\n public static int nextPrime(int num) {\n num++;\n for (int i = 2; i < num; i++) {\n if(num%i == 0) {\n num++;\n i=2;\n } else {\n continue;\n }\n }\n return num;\n }\n public static void main(String args[]){\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter a number ::\");\n int num = sc.nextInt();\n int result = 0;\n int prime = isPrime(num);\n if (prime == 1) {\n System.out.println(num+\" is a prime number\");\n } else {\n System.out.println(num+\" is not a prime number\");\n }\n System.out.println(\"Next prime number is: \"+nextPrime(num));\n }\n}"
},
{
"code": null,
"e": 2886,
"s": 2815,
"text": "Enter a number ::\n25\n25 is not a prime number\nNext prime number is: 29"
}
] |
Python | Matrix creation of n*n
|
30 Dec, 2020
Many times while working with numbers in data science we come across the problem in which we need to work with data science we need to transform a number to a matrix of consecutive numbers and hence this problem has a good application. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using list comprehensionList comprehension can be used to accomplish this particular task by using the range function for each list that needs to be constructed consecutively.
# Python3 code to demonstrate# matrix creation of n * n# using list comprehension # initializing NN = 4 # printing dimensionprint("The dimension : " + str(N)) # using list comprehension# matrix creation of n * nres = [list(range(1 + N * i, 1 + N * (i + 1))) for i in range(N)] # print resultprint("The created matrix of N * N: " + str(res))
The dimension : 4
The created matrix of N*N: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
Method #2 : Using next() + itertools.count()The count function can be used start the count of numbers and next function does the task of creation of sublist consecutively. List comprehension handles the processing.
# Python3 code to demonstrate# matrix creation of n * n# using next() + itertools.count()import itertools # initializing NN = 4 # printing dimensionprint("The dimension : " + str(N)) # using next() + itertools.count()# matrix creation of n * ntemp = itertools.count(1) res = [[next(temp) for i in range(N)] for i in range(N)] # print resultprint("The created matrix of N * N: " + str(res))
The dimension : 4
The created matrix of N*N: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
Python list-programs
Python matrix-program
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Dec, 2020"
},
{
"code": null,
"e": 328,
"s": 28,
"text": "Many times while working with numbers in data science we come across the problem in which we need to work with data science we need to transform a number to a matrix of consecutive numbers and hence this problem has a good application. Let’s discuss certain ways in which this problem can be solved."
},
{
"code": null,
"e": 516,
"s": 328,
"text": "Method #1 : Using list comprehensionList comprehension can be used to accomplish this particular task by using the range function for each list that needs to be constructed consecutively."
},
{
"code": "# Python3 code to demonstrate# matrix creation of n * n# using list comprehension # initializing NN = 4 # printing dimensionprint(\"The dimension : \" + str(N)) # using list comprehension# matrix creation of n * nres = [list(range(1 + N * i, 1 + N * (i + 1))) for i in range(N)] # print resultprint(\"The created matrix of N * N: \" + str(res))",
"e": 888,
"s": 516,
"text": null
},
{
"code": null,
"e": 998,
"s": 888,
"text": "The dimension : 4\nThe created matrix of N*N: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]\n"
},
{
"code": null,
"e": 1215,
"s": 1000,
"text": "Method #2 : Using next() + itertools.count()The count function can be used start the count of numbers and next function does the task of creation of sublist consecutively. List comprehension handles the processing."
},
{
"code": "# Python3 code to demonstrate# matrix creation of n * n# using next() + itertools.count()import itertools # initializing NN = 4 # printing dimensionprint(\"The dimension : \" + str(N)) # using next() + itertools.count()# matrix creation of n * ntemp = itertools.count(1) res = [[next(temp) for i in range(N)] for i in range(N)] # print resultprint(\"The created matrix of N * N: \" + str(res))",
"e": 1609,
"s": 1215,
"text": null
},
{
"code": null,
"e": 1719,
"s": 1609,
"text": "The dimension : 4\nThe created matrix of N*N: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]\n"
},
{
"code": null,
"e": 1740,
"s": 1719,
"text": "Python list-programs"
},
{
"code": null,
"e": 1762,
"s": 1740,
"text": "Python matrix-program"
},
{
"code": null,
"e": 1774,
"s": 1762,
"text": "python-list"
},
{
"code": null,
"e": 1781,
"s": 1774,
"text": "Python"
},
{
"code": null,
"e": 1797,
"s": 1781,
"text": "Python Programs"
},
{
"code": null,
"e": 1809,
"s": 1797,
"text": "python-list"
},
{
"code": null,
"e": 1907,
"s": 1809,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1939,
"s": 1907,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1966,
"s": 1939,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1987,
"s": 1966,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2010,
"s": 1987,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2066,
"s": 2010,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2088,
"s": 2066,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2127,
"s": 2088,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2165,
"s": 2127,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2214,
"s": 2165,
"text": "Python | Convert string dictionary to dictionary"
}
] |
How to create an empty class in Python?
|
29 Dec, 2020
A class is a user-defined blueprint or prototype from which objects are created. Class can be considered as a user-defined data type. Generally, a class contains data members known as attributes of the class and member functions that are used to modify the attributes of the class. But have you ever wondered how to define an empty class i.e a class without members and member functions?
In Python, if we write something like the following, it would raise a SyntaxError.
# Incorrect empty class in # Python class Geeks:
Output:
File "gfg.py", line 5
^
SyntaxError: unexpected EOF while parsing
In Python, to write an empty class pass statement is used. pass is a special statement in Python that does nothing. It only works as a dummy statement. However, objects of an empty class can also be created.
Example:
# Python program to demonstrate# empty class class Geeks: pass # Driver's codeobj = Geeks() print(obj)
Output:
<__main__.Geeks object at 0x02B4A340>
Python also allows us to set the attributes of an object of an empty class. We can also set different attributes for different objects. See the following example for better understanding.
# Python program to demonstrate# empty class class Employee: pass # Driver's code# Object 1 detailsobj1 = Employee()obj1.name = 'Nikhil'obj1.office = 'GeeksforGeeks' # Object 2 detailsobj2 = Employee()obj2.name = 'Abhinav'obj2.office = 'GeeksforGeeks'obj2.phone = 1234567889 # Printing detailsprint("obj1 Details:")print("Name:", obj1.name)print("Office:", obj1.office)print() print("obj2 Details:")print("Name:", obj2.name)print("Office:", obj2.office)print("Phone:", obj2.phone) # Uncommenting this print("Phone:", obj1.phone)# will raise an AttributeError
Output:
obj1 Details:
Name: Nikhil
Office: GeeksforGeeks
obj2 Details:
Name: Abhinav
Office: GeeksforGeeks
Phone: 1234567889
Traceback (most recent call last):
File "gfg.py", line 34, in
print("Phone:", obj1.phone)
AttributeError: 'Employee' object has no attribute 'phone'
Python Oops-programs
Python-OOP
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 416,
"s": 28,
"text": "A class is a user-defined blueprint or prototype from which objects are created. Class can be considered as a user-defined data type. Generally, a class contains data members known as attributes of the class and member functions that are used to modify the attributes of the class. But have you ever wondered how to define an empty class i.e a class without members and member functions?"
},
{
"code": null,
"e": 499,
"s": 416,
"text": "In Python, if we write something like the following, it would raise a SyntaxError."
},
{
"code": "# Incorrect empty class in # Python class Geeks:",
"e": 549,
"s": 499,
"text": null
},
{
"code": null,
"e": 557,
"s": 549,
"text": "Output:"
},
{
"code": null,
"e": 643,
"s": 557,
"text": " File \"gfg.py\", line 5\n\n ^\nSyntaxError: unexpected EOF while parsing\n"
},
{
"code": null,
"e": 851,
"s": 643,
"text": "In Python, to write an empty class pass statement is used. pass is a special statement in Python that does nothing. It only works as a dummy statement. However, objects of an empty class can also be created."
},
{
"code": null,
"e": 860,
"s": 851,
"text": "Example:"
},
{
"code": "# Python program to demonstrate# empty class class Geeks: pass # Driver's codeobj = Geeks() print(obj)",
"e": 969,
"s": 860,
"text": null
},
{
"code": null,
"e": 977,
"s": 969,
"text": "Output:"
},
{
"code": null,
"e": 1016,
"s": 977,
"text": "<__main__.Geeks object at 0x02B4A340>\n"
},
{
"code": null,
"e": 1204,
"s": 1016,
"text": "Python also allows us to set the attributes of an object of an empty class. We can also set different attributes for different objects. See the following example for better understanding."
},
{
"code": "# Python program to demonstrate# empty class class Employee: pass # Driver's code# Object 1 detailsobj1 = Employee()obj1.name = 'Nikhil'obj1.office = 'GeeksforGeeks' # Object 2 detailsobj2 = Employee()obj2.name = 'Abhinav'obj2.office = 'GeeksforGeeks'obj2.phone = 1234567889 # Printing detailsprint(\"obj1 Details:\")print(\"Name:\", obj1.name)print(\"Office:\", obj1.office)print() print(\"obj2 Details:\")print(\"Name:\", obj2.name)print(\"Office:\", obj2.office)print(\"Phone:\", obj2.phone) # Uncommenting this print(\"Phone:\", obj1.phone)# will raise an AttributeError",
"e": 1780,
"s": 1204,
"text": null
},
{
"code": null,
"e": 1788,
"s": 1780,
"text": "Output:"
},
{
"code": null,
"e": 1907,
"s": 1788,
"text": "obj1 Details:\nName: Nikhil\nOffice: GeeksforGeeks\n\nobj2 Details:\nName: Abhinav\nOffice: GeeksforGeeks\nPhone: 1234567889\n"
},
{
"code": null,
"e": 2064,
"s": 1907,
"text": "Traceback (most recent call last):\n File \"gfg.py\", line 34, in \n print(\"Phone:\", obj1.phone)\nAttributeError: 'Employee' object has no attribute 'phone'\n"
},
{
"code": null,
"e": 2085,
"s": 2064,
"text": "Python Oops-programs"
},
{
"code": null,
"e": 2096,
"s": 2085,
"text": "Python-OOP"
},
{
"code": null,
"e": 2103,
"s": 2096,
"text": "Python"
},
{
"code": null,
"e": 2119,
"s": 2103,
"text": "Python Programs"
},
{
"code": null,
"e": 2217,
"s": 2119,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2249,
"s": 2217,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2276,
"s": 2249,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2297,
"s": 2276,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2320,
"s": 2297,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2376,
"s": 2320,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2398,
"s": 2376,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2437,
"s": 2398,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2475,
"s": 2437,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2524,
"s": 2475,
"text": "Python | Convert string dictionary to dictionary"
}
] |
filepath.Dir() Function in Golang With Examples
|
10 May, 2020
In Go language, path package used for paths separated by forwarding slashes, such as the paths in URLs. The filepath.Dir() function in Go language used to return all the elements of the specified path except the last element. After dropping the final element, Dir calls Clean on the path and trailing slashes are removed. If the path is empty, Dir returns “.”. If the path consists entirely of separators, Dir returns a single separator. The returned path does not end in a separator unless it is the root directory. Moreover, this function is defined under the path package. Here, you need to import the “path/filepath” package in order to use these functions.
Syntax:
func Dir(path string) string
Here, ‘path’ is the specified path.
Return Value: It returns all the elements of the specified path except the last element.
Example 1:
// Golang program to illustrate the usage of// filepath.Dir() function // Including the main packagepackage main // Importing fmt and path/filepathimport ( "fmt" "path/filepath") // Calling mainfunc main() { // Calling the Dir() function fmt.Println(filepath.Dir("/Geeks/GFG/gfg.org")) fmt.Println(filepath.Dir("/Geeks/GFG/gfg")) fmt.Println(filepath.Dir("/Geeks/GFG/gfg/")) fmt.Println(filepath.Dir("/GFG/gfg///")) fmt.Println(filepath.Dir("/gfg.org")) fmt.Println(filepath.Dir("gfg.org"))}
Output:
/Geeks/GFG
/Geeks/GFG
/Geeks/GFG/gfg
/GFG/gfg
/
.
Example 2:
// Golang program to illustrate the usage of// filepath.Dir() function // Including the main packagepackage main // Importing fmt and path/filepathimport ( "fmt" "path/filepath") // Calling mainfunc main() { // Calling the Dir() function fmt.Println(filepath.Dir("")) fmt.Println(filepath.Dir(".")) fmt.Println(filepath.Dir("/")) fmt.Println(filepath.Dir("//")) fmt.Println(filepath.Dir("../gfg.org")) }
Output:
.
.
/
/
..
Golang-filepath
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Go
Golang Maps
How to Split a String in Golang?
Interfaces in Golang
Slices in Golang
Different Ways to Find the Type of Variable in Golang
How to Parse JSON in Golang?
How to Trim a String in Golang?
How to convert a string in lower case in Golang?
How to compare times in Golang?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 690,
"s": 28,
"text": "In Go language, path package used for paths separated by forwarding slashes, such as the paths in URLs. The filepath.Dir() function in Go language used to return all the elements of the specified path except the last element. After dropping the final element, Dir calls Clean on the path and trailing slashes are removed. If the path is empty, Dir returns “.”. If the path consists entirely of separators, Dir returns a single separator. The returned path does not end in a separator unless it is the root directory. Moreover, this function is defined under the path package. Here, you need to import the “path/filepath” package in order to use these functions."
},
{
"code": null,
"e": 698,
"s": 690,
"text": "Syntax:"
},
{
"code": null,
"e": 728,
"s": 698,
"text": "func Dir(path string) string\n"
},
{
"code": null,
"e": 764,
"s": 728,
"text": "Here, ‘path’ is the specified path."
},
{
"code": null,
"e": 853,
"s": 764,
"text": "Return Value: It returns all the elements of the specified path except the last element."
},
{
"code": null,
"e": 864,
"s": 853,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate the usage of// filepath.Dir() function // Including the main packagepackage main // Importing fmt and path/filepathimport ( \"fmt\" \"path/filepath\") // Calling mainfunc main() { // Calling the Dir() function fmt.Println(filepath.Dir(\"/Geeks/GFG/gfg.org\")) fmt.Println(filepath.Dir(\"/Geeks/GFG/gfg\")) fmt.Println(filepath.Dir(\"/Geeks/GFG/gfg/\")) fmt.Println(filepath.Dir(\"/GFG/gfg///\")) fmt.Println(filepath.Dir(\"/gfg.org\")) fmt.Println(filepath.Dir(\"gfg.org\"))}",
"e": 1388,
"s": 864,
"text": null
},
{
"code": null,
"e": 1396,
"s": 1388,
"text": "Output:"
},
{
"code": null,
"e": 1447,
"s": 1396,
"text": "/Geeks/GFG\n/Geeks/GFG\n/Geeks/GFG/gfg\n/GFG/gfg\n/\n.\n"
},
{
"code": null,
"e": 1458,
"s": 1447,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate the usage of// filepath.Dir() function // Including the main packagepackage main // Importing fmt and path/filepathimport ( \"fmt\" \"path/filepath\") // Calling mainfunc main() { // Calling the Dir() function fmt.Println(filepath.Dir(\"\")) fmt.Println(filepath.Dir(\".\")) fmt.Println(filepath.Dir(\"/\")) fmt.Println(filepath.Dir(\"//\")) fmt.Println(filepath.Dir(\"../gfg.org\")) }",
"e": 1892,
"s": 1458,
"text": null
},
{
"code": null,
"e": 1900,
"s": 1892,
"text": "Output:"
},
{
"code": null,
"e": 1912,
"s": 1900,
"text": ".\n.\n/\n/\n..\n"
},
{
"code": null,
"e": 1928,
"s": 1912,
"text": "Golang-filepath"
},
{
"code": null,
"e": 1940,
"s": 1928,
"text": "Go Language"
},
{
"code": null,
"e": 2038,
"s": 1940,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2051,
"s": 2038,
"text": "Arrays in Go"
},
{
"code": null,
"e": 2063,
"s": 2051,
"text": "Golang Maps"
},
{
"code": null,
"e": 2096,
"s": 2063,
"text": "How to Split a String in Golang?"
},
{
"code": null,
"e": 2117,
"s": 2096,
"text": "Interfaces in Golang"
},
{
"code": null,
"e": 2134,
"s": 2117,
"text": "Slices in Golang"
},
{
"code": null,
"e": 2188,
"s": 2134,
"text": "Different Ways to Find the Type of Variable in Golang"
},
{
"code": null,
"e": 2217,
"s": 2188,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 2249,
"s": 2217,
"text": "How to Trim a String in Golang?"
},
{
"code": null,
"e": 2298,
"s": 2249,
"text": "How to convert a string in lower case in Golang?"
}
] |
java.time.LocalDateTime Class in Java
|
26 May, 2021
java.time.LocalDateTime class, introduced in Java 8, represents a local date-time object without timezone information. The LocalDateTime class in Java is an immutable date-time object that represents a date in the yyyy-MM-dd-HH-mm-ss.zzz format. It implements the ChronoLocalDateTime interface and inherits the object class.
Wherever we need to represent time without a timezone reference, we can use the LocalDateTime instances. LocalDateTime, for example, can be used to start batch jobs in any application. Jobs will be run at a fixed time in the timezone in which the server is located. Note LocalDateTime instances are immutable and thread.
Syntax: Class declaration
public final class LocalDateTime
extends Object
implements Temporal, TemporalAdjuster, ChronoLocalDateTime<LocalDate>, Serializable
Methods of this class are as follows:
Some more methods to modify local time are as follows in LocalDateTime can be used to get to a new localdatetime instance relative to an existing localdatetime instance. They are namely as follows:
plusYears(), plusMonths(), plusDays(), plusHours(), plusMinutes(), plusSeconds(), plusNanos(), minusYears(), minusMonths(), minusDays(), minusHours(), minusMinutes(), minusSeconds(), minusNanos()
Examples 1:
Java
// Java Program to illustrate LocalDateTime Class of java.time package // Importing LocalDateTime class from java.time packageimport java.time.LocalDateTime; // Main class for LocalDateTimepublic class GFG { // Main driver method public static void main(String[] args) { // Creating an object of LocalDateTime class // in the main() method LocalDateTime now = LocalDateTime.now(); // Print statement System.out.println(now); // Adding 1 year, 1 month, 1 week and 1 day LocalDateTime localDateTime1 = now.plusYears(1) .plusMonths(1) .plusWeeks(1) .plusDays(1); // Print statement System.out.println(localDateTime1); // Subtracting 1 year, 1 month, 1 week and 1 day LocalDateTime localDateTime2 = localDateTime1.minusYears(1) .minusMonths(1) .minusWeeks(1) .minusDays(1); // Print statement System.out.println(localDateTime2); // Adding 1 hour, 1 minute, 1 second and 100 // nanoseconds LocalDateTime localDateTime3 = localDateTime2.plusHours(1) .plusMinutes(1) .plusSeconds(1) .plusNanos(100); // Print statement System.out.println(localDateTime3); // Subtracting 1 hour, 1 minute, 1 second and 100 // nanoseconds LocalDateTime localDateTime4 = localDateTime3.minusHours(1) .minusMinutes(1) .minusSeconds(1) .minusNanos(100); // Print statement System.out.println(localDateTime4); }}
Output:
Example 2: Creating a specified time
Java
// Java Program to illustrate LocalDateTime Class// of java.time package by creating specific time // Importing required classes from resp packagesimport java.time.*;import java.time.format.*; // main classclass GFG { // Main driver method public static void main(String[] args) { // Milliseconds LocalDateTime localDateTime1 = LocalDateTime.of( 2021, 04, 24, 14, 33, 48, 123456789); // Print statement System.out.println(localDateTime1); // Month LocalDateTime localDateTime2 = LocalDateTime.of( 2021, Month.APRIL, 24, 14, 33, 48, 123456789); // Print statement System.out.println(localDateTime2); // Seconds LocalDateTime localDateTime3 = LocalDateTime.of( 2021, Month.APRIL, 24, 14, 33, 48); // Print statement System.out.println(localDateTime3); // Minutes LocalDateTime localDateTime4 = LocalDateTime.of( 2021, Month.APRIL, 24, 14, 33); // Print statement System.out.println(localDateTime4); // Local date + Local time LocalDate date = LocalDate.of(2021, 04, 24); LocalTime time = LocalTime.of(10, 34); LocalDateTime localDateTime5 = LocalDateTime.of(date, time); // Print statement System.out.println(localDateTime5); }}
Output:
Example 3: Format LocalDateTime to string
To format a local time to the desired string representation, use the LocalDateTime.format(DateTimeFormatter) method.
Java
// Java Program to illustrate LocalDateTime Class by// Formatting LocalDateTime to string // Importing all classes from java.time packageimport java.time.LocalDateTime;import java.time.format.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of DateTimeFormatter class DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyyy-MM-dd HH:mm:ss a"); // Creating an object of LocalDateTime class // and getting local date and time using now() // method LocalDateTime now = LocalDateTime.now(); // Formatting LocalDateTime to string String dateTimeString = now.format(formatter); // Print and Display System.out.println(dateTimeString); }}
Output:
Note: In order to parse a string to LocalDateTime, convert time in a string to a local time instance, the LocalDateTime class has two overloaded parse() methods.
parse(CharSequence text)
parse(CharSequence text, DateTimeFormatter formatter)
saurabh1990aror
Java-Classes
Java-LocalDateTime
Java-time package
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 May, 2021"
},
{
"code": null,
"e": 353,
"s": 28,
"text": "java.time.LocalDateTime class, introduced in Java 8, represents a local date-time object without timezone information. The LocalDateTime class in Java is an immutable date-time object that represents a date in the yyyy-MM-dd-HH-mm-ss.zzz format. It implements the ChronoLocalDateTime interface and inherits the object class."
},
{
"code": null,
"e": 675,
"s": 353,
"text": "Wherever we need to represent time without a timezone reference, we can use the LocalDateTime instances. LocalDateTime, for example, can be used to start batch jobs in any application. Jobs will be run at a fixed time in the timezone in which the server is located. Note LocalDateTime instances are immutable and thread. "
},
{
"code": null,
"e": 701,
"s": 675,
"text": "Syntax: Class declaration"
},
{
"code": null,
"e": 735,
"s": 701,
"text": "public final class LocalDateTime "
},
{
"code": null,
"e": 751,
"s": 735,
"text": "extends Object "
},
{
"code": null,
"e": 835,
"s": 751,
"text": "implements Temporal, TemporalAdjuster, ChronoLocalDateTime<LocalDate>, Serializable"
},
{
"code": null,
"e": 873,
"s": 835,
"text": "Methods of this class are as follows:"
},
{
"code": null,
"e": 1072,
"s": 873,
"text": "Some more methods to modify local time are as follows in LocalDateTime can be used to get to a new localdatetime instance relative to an existing localdatetime instance. They are namely as follows:"
},
{
"code": null,
"e": 1268,
"s": 1072,
"text": "plusYears(), plusMonths(), plusDays(), plusHours(), plusMinutes(), plusSeconds(), plusNanos(), minusYears(), minusMonths(), minusDays(), minusHours(), minusMinutes(), minusSeconds(), minusNanos()"
},
{
"code": null,
"e": 1280,
"s": 1268,
"text": "Examples 1:"
},
{
"code": null,
"e": 1285,
"s": 1280,
"text": "Java"
},
{
"code": "// Java Program to illustrate LocalDateTime Class of java.time package // Importing LocalDateTime class from java.time packageimport java.time.LocalDateTime; // Main class for LocalDateTimepublic class GFG { // Main driver method public static void main(String[] args) { // Creating an object of LocalDateTime class // in the main() method LocalDateTime now = LocalDateTime.now(); // Print statement System.out.println(now); // Adding 1 year, 1 month, 1 week and 1 day LocalDateTime localDateTime1 = now.plusYears(1) .plusMonths(1) .plusWeeks(1) .plusDays(1); // Print statement System.out.println(localDateTime1); // Subtracting 1 year, 1 month, 1 week and 1 day LocalDateTime localDateTime2 = localDateTime1.minusYears(1) .minusMonths(1) .minusWeeks(1) .minusDays(1); // Print statement System.out.println(localDateTime2); // Adding 1 hour, 1 minute, 1 second and 100 // nanoseconds LocalDateTime localDateTime3 = localDateTime2.plusHours(1) .plusMinutes(1) .plusSeconds(1) .plusNanos(100); // Print statement System.out.println(localDateTime3); // Subtracting 1 hour, 1 minute, 1 second and 100 // nanoseconds LocalDateTime localDateTime4 = localDateTime3.minusHours(1) .minusMinutes(1) .minusSeconds(1) .minusNanos(100); // Print statement System.out.println(localDateTime4); }}",
"e": 3060,
"s": 1285,
"text": null
},
{
"code": null,
"e": 3068,
"s": 3060,
"text": "Output:"
},
{
"code": null,
"e": 3105,
"s": 3068,
"text": "Example 2: Creating a specified time"
},
{
"code": null,
"e": 3110,
"s": 3105,
"text": "Java"
},
{
"code": "// Java Program to illustrate LocalDateTime Class// of java.time package by creating specific time // Importing required classes from resp packagesimport java.time.*;import java.time.format.*; // main classclass GFG { // Main driver method public static void main(String[] args) { // Milliseconds LocalDateTime localDateTime1 = LocalDateTime.of( 2021, 04, 24, 14, 33, 48, 123456789); // Print statement System.out.println(localDateTime1); // Month LocalDateTime localDateTime2 = LocalDateTime.of( 2021, Month.APRIL, 24, 14, 33, 48, 123456789); // Print statement System.out.println(localDateTime2); // Seconds LocalDateTime localDateTime3 = LocalDateTime.of( 2021, Month.APRIL, 24, 14, 33, 48); // Print statement System.out.println(localDateTime3); // Minutes LocalDateTime localDateTime4 = LocalDateTime.of( 2021, Month.APRIL, 24, 14, 33); // Print statement System.out.println(localDateTime4); // Local date + Local time LocalDate date = LocalDate.of(2021, 04, 24); LocalTime time = LocalTime.of(10, 34); LocalDateTime localDateTime5 = LocalDateTime.of(date, time); // Print statement System.out.println(localDateTime5); }}",
"e": 4465,
"s": 3110,
"text": null
},
{
"code": null,
"e": 4473,
"s": 4465,
"text": "Output:"
},
{
"code": null,
"e": 4515,
"s": 4473,
"text": "Example 3: Format LocalDateTime to string"
},
{
"code": null,
"e": 4632,
"s": 4515,
"text": "To format a local time to the desired string representation, use the LocalDateTime.format(DateTimeFormatter) method."
},
{
"code": null,
"e": 4637,
"s": 4632,
"text": "Java"
},
{
"code": "// Java Program to illustrate LocalDateTime Class by// Formatting LocalDateTime to string // Importing all classes from java.time packageimport java.time.LocalDateTime;import java.time.format.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of DateTimeFormatter class DateTimeFormatter formatter = DateTimeFormatter.ofPattern( \"yyyy-MM-dd HH:mm:ss a\"); // Creating an object of LocalDateTime class // and getting local date and time using now() // method LocalDateTime now = LocalDateTime.now(); // Formatting LocalDateTime to string String dateTimeString = now.format(formatter); // Print and Display System.out.println(dateTimeString); }}",
"e": 5474,
"s": 4637,
"text": null
},
{
"code": null,
"e": 5482,
"s": 5474,
"text": "Output:"
},
{
"code": null,
"e": 5644,
"s": 5482,
"text": "Note: In order to parse a string to LocalDateTime, convert time in a string to a local time instance, the LocalDateTime class has two overloaded parse() methods."
},
{
"code": null,
"e": 5669,
"s": 5644,
"text": "parse(CharSequence text)"
},
{
"code": null,
"e": 5723,
"s": 5669,
"text": "parse(CharSequence text, DateTimeFormatter formatter)"
},
{
"code": null,
"e": 5739,
"s": 5723,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 5752,
"s": 5739,
"text": "Java-Classes"
},
{
"code": null,
"e": 5771,
"s": 5752,
"text": "Java-LocalDateTime"
},
{
"code": null,
"e": 5789,
"s": 5771,
"text": "Java-time package"
},
{
"code": null,
"e": 5796,
"s": 5789,
"text": "Picked"
},
{
"code": null,
"e": 5801,
"s": 5796,
"text": "Java"
},
{
"code": null,
"e": 5806,
"s": 5801,
"text": "Java"
},
{
"code": null,
"e": 5904,
"s": 5806,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5919,
"s": 5904,
"text": "Stream In Java"
},
{
"code": null,
"e": 5940,
"s": 5919,
"text": "Introduction to Java"
},
{
"code": null,
"e": 5961,
"s": 5940,
"text": "Constructors in Java"
},
{
"code": null,
"e": 5980,
"s": 5961,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 5997,
"s": 5980,
"text": "Generics in Java"
},
{
"code": null,
"e": 6027,
"s": 5997,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 6053,
"s": 6027,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 6069,
"s": 6053,
"text": "Strings in Java"
},
{
"code": null,
"e": 6106,
"s": 6069,
"text": "Differences between JDK, JRE and JVM"
}
] |
How to plot two Seaborn lmplots side-by-side (Matplotlib)?
|
To plot two graphs side-by-side in Seaborn, we can take the following steps −
To create two graphs, we can use nrows=1, ncols=2 with figure size (7, 7).
To create two graphs, we can use nrows=1, ncols=2 with figure size (7, 7).
Create a data frame with keys, col1 and col2, using Pandas.
Create a data frame with keys, col1 and col2, using Pandas.
Use countplot() to show the counts of observations in each categorical bin using bars.
Use countplot() to show the counts of observations in each categorical bin using bars.
Adjust the padding between and around the subplots.
Adjust the padding between and around the subplots.
To display the figure, use show() method.
To display the figure, use show() method.
import pandas as pd
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
f, axes = plt.subplots(1, 2)
df = pd.DataFrame(dict(col1=np.linspace(1, 10, 5), col2=np.linspace(1, 10, 5)))
sns.countplot(df.col1, x='col1', color="red", ax=axes[0])
sns.countplot(df.col2, x="col2", color="green", ax=axes[1])
plt.show()
|
[
{
"code": null,
"e": 1265,
"s": 1187,
"text": "To plot two graphs side-by-side in Seaborn, we can take the following steps −"
},
{
"code": null,
"e": 1340,
"s": 1265,
"text": "To create two graphs, we can use nrows=1, ncols=2 with figure size (7, 7)."
},
{
"code": null,
"e": 1415,
"s": 1340,
"text": "To create two graphs, we can use nrows=1, ncols=2 with figure size (7, 7)."
},
{
"code": null,
"e": 1475,
"s": 1415,
"text": "Create a data frame with keys, col1 and col2, using Pandas."
},
{
"code": null,
"e": 1535,
"s": 1475,
"text": "Create a data frame with keys, col1 and col2, using Pandas."
},
{
"code": null,
"e": 1622,
"s": 1535,
"text": "Use countplot() to show the counts of observations in each categorical bin using bars."
},
{
"code": null,
"e": 1709,
"s": 1622,
"text": "Use countplot() to show the counts of observations in each categorical bin using bars."
},
{
"code": null,
"e": 1761,
"s": 1709,
"text": "Adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1813,
"s": 1761,
"text": "Adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1855,
"s": 1813,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1897,
"s": 1855,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2320,
"s": 1897,
"text": "import pandas as pd\nimport numpy as np\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nf, axes = plt.subplots(1, 2)\ndf = pd.DataFrame(dict(col1=np.linspace(1, 10, 5), col2=np.linspace(1, 10, 5)))\nsns.countplot(df.col1, x='col1', color=\"red\", ax=axes[0])\nsns.countplot(df.col2, x=\"col2\", color=\"green\", ax=axes[1])\nplt.show()"
}
] |
Gensim - Using LDA Topic Model
|
In this chapter, we will understand how to use Latent Dirichlet Allocation (LDA) topic model.
The LDA model (lda_model) we have created above can be used to view the topics from the documents. It can be done with the help of following script −
pprint(lda_model.print_topics())
doc_lda = lda_model[corpus]
[
(0,
'0.036*"go" + 0.027*"get" + 0.021*"time" + 0.017*"back" + 0.015*"good" + '
'0.014*"much" + 0.014*"be" + 0.013*"car" + 0.013*"well" + 0.013*"year"'),
(1,
'0.078*"screen" + 0.067*"video" + 0.052*"character" + 0.046*"normal" + '
'0.045*"mouse" + 0.034*"manager" + 0.034*"disease" + 0.031*"processor" + '
'0.028*"excuse" + 0.028*"choice"'),
(2,
'0.776*"ax" + 0.079*"_" + 0.011*"boy" + 0.008*"ticket" + 0.006*"red" + '
'0.004*"conservative" + 0.004*"cult" + 0.004*"amazing" + 0.003*"runner" + '
'0.003*"roughly"'),
(3,
'0.086*"season" + 0.078*"fan" + 0.072*"reality" + 0.065*"trade" + '
'0.045*"concept" + 0.040*"pen" + 0.028*"blow" + 0.025*"improve" + '
'0.025*"cap" + 0.021*"penguin"'),
(4,
'0.027*"group" + 0.023*"issue" + 0.016*"case" + 0.016*"cause" + '
'0.014*"state" + 0.012*"whole" + 0.012*"support" + 0.011*"government" + '
'0.010*"year" + 0.010*"rate"'),
(5,
'0.133*"evidence" + 0.047*"believe" + 0.044*"religion" + 0.042*"belief" + '
'0.041*"sense" + 0.041*"discussion" + 0.034*"atheist" + 0.030*"conclusion" +
'
'0.029*"explain" + 0.029*"claim"'),
(6,
'0.083*"space" + 0.059*"science" + 0.031*"launch" + 0.030*"earth" + '
'0.026*"route" + 0.024*"orbit" + 0.024*"scientific" + 0.021*"mission" + '
'0.018*"plane" + 0.017*"satellite"'),
(7,
'0.065*"file" + 0.064*"program" + 0.048*"card" + 0.041*"window" + '
'0.038*"driver" + 0.037*"software" + 0.034*"run" + 0.029*"machine" + '
'0.029*"entry" + 0.028*"version"'),
(8,
'0.078*"publish" + 0.059*"mount" + 0.050*"turkish" + 0.043*"armenian" + '
'0.027*"western" + 0.026*"russian" + 0.025*"locate" + 0.024*"proceed" + '
'0.024*"electrical" + 0.022*"terrorism"'),
(9,
'0.023*"people" + 0.023*"child" + 0.021*"kill" + 0.020*"man" + 0.019*"death" '
'+ 0.015*"die" + 0.015*"live" + 0.014*"attack" + 0.013*"age" + '
'0.011*"church"'),
(10,
'0.092*"cpu" + 0.085*"black" + 0.071*"controller" + 0.039*"white" + '
'0.028*"water" + 0.027*"cold" + 0.025*"solid" + 0.024*"cool" + 0.024*"heat" '
'+ 0.023*"nuclear"'),
(11,
'0.071*"monitor" + 0.044*"box" + 0.042*"option" + 0.041*"generate" + '
'0.038*"vote" + 0.032*"battery" + 0.029*"wave" + 0.026*"tradition" + '
'0.026*"fairly" + 0.025*"task"'),
(12,
'0.048*"send" + 0.045*"mail" + 0.036*"list" + 0.033*"include" + '
'0.032*"price" + 0.031*"address" + 0.027*"email" + 0.026*"receive" + '
'0.024*"book" + 0.024*"sell"'),
(13,
'0.515*"drive" + 0.052*"laboratory" + 0.042*"blind" + 0.020*"investment" + '
'0.011*"creature" + 0.010*"loop" + 0.005*"dialog" + 0.000*"slave" + '
'0.000*"jumper" + 0.000*"sector"'),
(14,
'0.153*"patient" + 0.066*"treatment" + 0.062*"printer" + 0.059*"doctor" + '
'0.036*"medical" + 0.031*"energy" + 0.029*"study" + 0.029*"probe" + '
'0.024*"mph" + 0.020*"physician"'),
(15,
'0.068*"law" + 0.055*"gun" + 0.039*"government" + 0.036*"right" + '
'0.029*"state" + 0.026*"drug" + 0.022*"crime" + 0.019*"person" + '
'0.019*"citizen" + 0.019*"weapon"'),
(16,
'0.107*"team" + 0.102*"game" + 0.078*"play" + 0.055*"win" + 0.052*"player" + '
'0.051*"year" + 0.030*"score" + 0.025*"goal" + 0.023*"wing" + 0.023*"run"'),
(17,
'0.031*"say" + 0.026*"think" + 0.022*"people" + 0.020*"make" + 0.017*"see" + '
'0.016*"know" + 0.013*"come" + 0.013*"even" + 0.013*"thing" + 0.013*"give"'),
(18,
'0.039*"system" + 0.034*"use" + 0.023*"key" + 0.016*"bit" + 0.016*"also" + '
'0.015*"information" + 0.014*"source" + 0.013*"chip" + 0.013*"available" + '
'0.010*"provide"'),
(19,
'0.085*"line" + 0.073*"write" + 0.053*"article" + 0.046*"organization" + '
'0.034*"host" + 0.023*"be" + 0.023*"know" + 0.017*"thank" + 0.016*"want" + '
'0.014*"help"')
]
The LDA model (lda_model) we have created above can be used to compute the model’s perplexity, i.e. how good the model is. The lower the score the better the model will be. It can be done with the help of following script −
print('\nPerplexity: ', lda_model.log_perplexity(corpus))
Perplexity: -12.338664984332151
The LDA model (lda_model) we have created above can be used to compute the model’s coherence score i.e. the average /median of the pairwise word-similarity scores of the words in the topic. It can be done with the help of following script −
coherence_model_lda = CoherenceModel(
model=lda_model, texts=data_lemmatized, dictionary=id2word, coherence='c_v'
)
coherence_lda = coherence_model_lda.get_coherence()
print('\nCoherence Score: ', coherence_lda)
Coherence Score: 0.510264381411751
The LDA model (lda_model) we have created above can be used to examine the produced topics and the associated keywords. It can be visualised by using pyLDAvispackage as follows −
pyLDAvis.enable_notebook()
vis = pyLDAvis.gensim.prepare(lda_model, corpus, id2word)
vis
From the above output, the bubbles on the left-side represents a topic and larger the bubble, the more prevalent is that topic. The topic model will be good if the topic model has big, non-overlapping bubbles scattered throughout the chart.
|
[
{
"code": null,
"e": 2280,
"s": 2186,
"text": "In this chapter, we will understand how to use Latent Dirichlet Allocation (LDA) topic model."
},
{
"code": null,
"e": 2430,
"s": 2280,
"text": "The LDA model (lda_model) we have created above can be used to view the topics from the documents. It can be done with the help of following script −"
},
{
"code": null,
"e": 2491,
"s": 2430,
"text": "pprint(lda_model.print_topics())\ndoc_lda = lda_model[corpus]"
},
{
"code": null,
"e": 6275,
"s": 2491,
"text": "[\n (0, \n '0.036*\"go\" + 0.027*\"get\" + 0.021*\"time\" + 0.017*\"back\" + 0.015*\"good\" + '\n '0.014*\"much\" + 0.014*\"be\" + 0.013*\"car\" + 0.013*\"well\" + 0.013*\"year\"'),\n (1,\n '0.078*\"screen\" + 0.067*\"video\" + 0.052*\"character\" + 0.046*\"normal\" + '\n '0.045*\"mouse\" + 0.034*\"manager\" + 0.034*\"disease\" + 0.031*\"processor\" + '\n '0.028*\"excuse\" + 0.028*\"choice\"'),\n (2,\n '0.776*\"ax\" + 0.079*\"_\" + 0.011*\"boy\" + 0.008*\"ticket\" + 0.006*\"red\" + '\n '0.004*\"conservative\" + 0.004*\"cult\" + 0.004*\"amazing\" + 0.003*\"runner\" + '\n '0.003*\"roughly\"'),\n (3,\n '0.086*\"season\" + 0.078*\"fan\" + 0.072*\"reality\" + 0.065*\"trade\" + '\n '0.045*\"concept\" + 0.040*\"pen\" + 0.028*\"blow\" + 0.025*\"improve\" + '\n '0.025*\"cap\" + 0.021*\"penguin\"'),\n (4,\n '0.027*\"group\" + 0.023*\"issue\" + 0.016*\"case\" + 0.016*\"cause\" + '\n '0.014*\"state\" + 0.012*\"whole\" + 0.012*\"support\" + 0.011*\"government\" + '\n '0.010*\"year\" + 0.010*\"rate\"'),\n (5,\n '0.133*\"evidence\" + 0.047*\"believe\" + 0.044*\"religion\" + 0.042*\"belief\" + '\n '0.041*\"sense\" + 0.041*\"discussion\" + 0.034*\"atheist\" + 0.030*\"conclusion\" +\n '\n '0.029*\"explain\" + 0.029*\"claim\"'),\n (6,\n '0.083*\"space\" + 0.059*\"science\" + 0.031*\"launch\" + 0.030*\"earth\" + '\n '0.026*\"route\" + 0.024*\"orbit\" + 0.024*\"scientific\" + 0.021*\"mission\" + '\n '0.018*\"plane\" + 0.017*\"satellite\"'),\n (7,\n '0.065*\"file\" + 0.064*\"program\" + 0.048*\"card\" + 0.041*\"window\" + '\n '0.038*\"driver\" + 0.037*\"software\" + 0.034*\"run\" + 0.029*\"machine\" + '\n '0.029*\"entry\" + 0.028*\"version\"'),\n (8,\n '0.078*\"publish\" + 0.059*\"mount\" + 0.050*\"turkish\" + 0.043*\"armenian\" + '\n '0.027*\"western\" + 0.026*\"russian\" + 0.025*\"locate\" + 0.024*\"proceed\" + '\n '0.024*\"electrical\" + 0.022*\"terrorism\"'),\n (9,\n '0.023*\"people\" + 0.023*\"child\" + 0.021*\"kill\" + 0.020*\"man\" + 0.019*\"death\" '\n '+ 0.015*\"die\" + 0.015*\"live\" + 0.014*\"attack\" + 0.013*\"age\" + '\n '0.011*\"church\"'),\n (10,\n '0.092*\"cpu\" + 0.085*\"black\" + 0.071*\"controller\" + 0.039*\"white\" + '\n '0.028*\"water\" + 0.027*\"cold\" + 0.025*\"solid\" + 0.024*\"cool\" + 0.024*\"heat\" '\n '+ 0.023*\"nuclear\"'),\n (11,\n '0.071*\"monitor\" + 0.044*\"box\" + 0.042*\"option\" + 0.041*\"generate\" + '\n '0.038*\"vote\" + 0.032*\"battery\" + 0.029*\"wave\" + 0.026*\"tradition\" + '\n '0.026*\"fairly\" + 0.025*\"task\"'),\n (12,\n '0.048*\"send\" + 0.045*\"mail\" + 0.036*\"list\" + 0.033*\"include\" + '\n '0.032*\"price\" + 0.031*\"address\" + 0.027*\"email\" + 0.026*\"receive\" + '\n '0.024*\"book\" + 0.024*\"sell\"'),\n (13,\n '0.515*\"drive\" + 0.052*\"laboratory\" + 0.042*\"blind\" + 0.020*\"investment\" + '\n '0.011*\"creature\" + 0.010*\"loop\" + 0.005*\"dialog\" + 0.000*\"slave\" + '\n '0.000*\"jumper\" + 0.000*\"sector\"'),\n (14,\n '0.153*\"patient\" + 0.066*\"treatment\" + 0.062*\"printer\" + 0.059*\"doctor\" + '\n\n '0.036*\"medical\" + 0.031*\"energy\" + 0.029*\"study\" + 0.029*\"probe\" + '\n '0.024*\"mph\" + 0.020*\"physician\"'),\n (15,\n '0.068*\"law\" + 0.055*\"gun\" + 0.039*\"government\" + 0.036*\"right\" + '\n '0.029*\"state\" + 0.026*\"drug\" + 0.022*\"crime\" + 0.019*\"person\" + '\n '0.019*\"citizen\" + 0.019*\"weapon\"'),\n (16,\n '0.107*\"team\" + 0.102*\"game\" + 0.078*\"play\" + 0.055*\"win\" + 0.052*\"player\" + '\n '0.051*\"year\" + 0.030*\"score\" + 0.025*\"goal\" + 0.023*\"wing\" + 0.023*\"run\"'),\n (17,\n '0.031*\"say\" + 0.026*\"think\" + 0.022*\"people\" + 0.020*\"make\" + 0.017*\"see\" + '\n '0.016*\"know\" + 0.013*\"come\" + 0.013*\"even\" + 0.013*\"thing\" + 0.013*\"give\"'),\n (18,\n '0.039*\"system\" + 0.034*\"use\" + 0.023*\"key\" + 0.016*\"bit\" + 0.016*\"also\" + '\n '0.015*\"information\" + 0.014*\"source\" + 0.013*\"chip\" + 0.013*\"available\" + '\n '0.010*\"provide\"'),\n (19,\n '0.085*\"line\" + 0.073*\"write\" + 0.053*\"article\" + 0.046*\"organization\" + '\n '0.034*\"host\" + 0.023*\"be\" + 0.023*\"know\" + 0.017*\"thank\" + 0.016*\"want\" + '\n '0.014*\"help\"')\n]\n"
},
{
"code": null,
"e": 6499,
"s": 6275,
"text": "The LDA model (lda_model) we have created above can be used to compute the model’s perplexity, i.e. how good the model is. The lower the score the better the model will be. It can be done with the help of following script −"
},
{
"code": null,
"e": 6558,
"s": 6499,
"text": "print('\\nPerplexity: ', lda_model.log_perplexity(corpus))\n"
},
{
"code": null,
"e": 6591,
"s": 6558,
"text": "Perplexity: -12.338664984332151\n"
},
{
"code": null,
"e": 6832,
"s": 6591,
"text": "The LDA model (lda_model) we have created above can be used to compute the model’s coherence score i.e. the average /median of the pairwise word-similarity scores of the words in the topic. It can be done with the help of following script −"
},
{
"code": null,
"e": 7047,
"s": 6832,
"text": "coherence_model_lda = CoherenceModel(\n model=lda_model, texts=data_lemmatized, dictionary=id2word, coherence='c_v'\n)\ncoherence_lda = coherence_model_lda.get_coherence()\nprint('\\nCoherence Score: ', coherence_lda)"
},
{
"code": null,
"e": 7083,
"s": 7047,
"text": "Coherence Score: 0.510264381411751\n"
},
{
"code": null,
"e": 7262,
"s": 7083,
"text": "The LDA model (lda_model) we have created above can be used to examine the produced topics and the associated keywords. It can be visualised by using pyLDAvispackage as follows −"
},
{
"code": null,
"e": 7351,
"s": 7262,
"text": "pyLDAvis.enable_notebook()\nvis = pyLDAvis.gensim.prepare(lda_model, corpus, id2word)\nvis"
}
] |
Different Types of HTML Helpers in ASP.NET MVC
|
09 Sep, 2021
ASP.NET provides a wide range of built-in HTML helpers that can be used as per the user’s choice as there are multiple overrides available for them. There are three types of built-in HTML helpers offered by ASP.NET.
The HTML helpers that are mainly used to render HTML elements like text boxes, checkboxes, Radio Buttons, and Dropdown lists, etc. are called Standard HTML helpers.
List of Standard HTML Helpers
@Html.ActionLink() - Used to create link on html page
@Html.TextBox() - Used to create text box
@Html.CheckBox() - Used to create check box
@Html.RadioButton() - Used to create Radio Button
@Html.BeginFrom() - Used to start a form
@Html.EndFrom() - Used to end a form
@Html.DropDownList() - Used to create drop down list
@Html.Hidden() - Used to create hidden fields
@Html.label() - Used for creating HTML label is on the browser
@Html.TextArea() - The TextArea Method renders textarea element on browser
@Html.Password() - This method is responsible for creating password input field on browser
@Html.ListBox() - The ListBox helper method creates html ListBox with scrollbar on browser
HTML
@{ Layout = null;} <!DOCTYPE html> <html><head> <meta name="viewport" content="width=device-width" /> <title>Built-in HTML Helper</title></head><body> <div> <h3>Label example</h3> @Html.Label("firstName", "First Name") <h3>Text Box Example</h3> @Html.TextBox("txtFirstName", "", new { @class = "form-control", placeholder = "First Name" }) <h3>Text Area Example</h3> @Html.TextArea("address", new { @class = "form-control", rows = "5" }) <h3>password Example</h3> @Html.Password("password", " ", new { @class = "form-control" }) <h3>Radio Button Example</h3> @Html.RadioButton("MaritalStatus", "Married", new { id = "IsMarried" }) Married <h3>Check Box Example</h3> @Html.CheckBox("htmlSkill") HTML 5 <h3>List Box Example</h3> @Html.ListBox("Skills", new List<SelectListItem> { new SelectListItem { Text="ASP.NET",Value="1"}, new SelectListItem { Text="MVC",Value="2"}, new SelectListItem { Text="SQL Server",Value="3"}, new SelectListItem { Text="Angular",Value="4"}, new SelectListItem { Text="Web API",Value="5"} }, new { @class = "form-control" }) <h3>drop down List Example</h3> @Html.DropDownList("Gender", new List<SelectListItem> { new SelectListItem {Text="Select Gender",Value="-1" }, new SelectListItem {Text="Male",Value="1" }, new SelectListItem {Text="Female", Value="2" } }, new { @class = "custom-select" }) </div></body></html>
The Strongly-Typed HTML helper takes a lambda as a parameter that tells the helper, which element of the model to be utilized in the typed view. The Strongly typed views are used for rendering specific sorts of model objects, rather than using the overall View-Data structure.
List of strongly-Typed HTML Helper
@Html.HiddenFor()
@Html.LabelFor()
@Html.TextBoxFor()
@Html.RadioButtonFor()
@Html.DropDownListFor()
@Html.CheckBoxFor()
@Html.TextAreaFor()
@Html.PasswordFor()
@Html.ListBoxFor()
The functionality of all of these are the same as above but they are used with modal classes. Now, as we know we need a model class to use strongly typed HTML. So firstly we will add a model class as follows
C#
using System;using System.Collections.Generic;using System.Linq;using System.Web; namespace HTML_Helper_Demo.Models{ public class Employee { public int EmpId { get; set; } public string Name { get; set; } public string Gender { get; set; } public city city { get; set; } public skills skills { get; set; } public string Address { get; set; } public string Password { get; set; } public bool AgreeTerm { get; set; } }}public enum city{ Dehli, Mumbai, Kolkata, Channai, Bangalore}public enum skills{ HTML5, CSS3, Bootstrap, JavaScript, JQuery, Angular, MVC, WebAPI}
Now write the following code in the controller. And then add a view with the default properties.
C#
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using HTML_Helper_Demo.Models; namespace HTML_Helper_Demo.Controllers{ public class HomeController : Controller { public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(Employee emp) { return View(); } }}
Now write the HTML as follows:
HTML
@using HTML_Helper_Demo.Models@model Employee@{ ViewBag.Title = "Index";} <div> <h3>Label Example</h3> @Html.LabelFor(model => model.Name, new { @class = "label-control" }) <h3>Text box Example</h3> @Html.TextBoxFor(model => model.Name, new { @class = "form-control" }) <h3>Text Box Example 2</h3> @Html.TextAreaFor(model => model.Address, new { @class = "form-control", rows = "5" }) <h3>Password for example</h3> @Html.PasswordFor(model => model.Password, new { @class = "form-control" }) <h3>Radio Button Example</h3> @Html.RadioButtonFor(model => model.Gender, true, new { id = "male-true" }) @Html.Label("male-true", "Male") @Html.RadioButtonFor(model => model.Gender, false, new { id = "female-true" }) @Html.Label("female-true", "Female") <h3>Check Box Example</h3> @Html.CheckBoxFor(model => model.AgreeTerm) <h3>List Box Example</h3> @Html.ListBoxFor(model => model.skills, new SelectList(Enum.GetValues(typeof(skills))), new { @class = "form-control" }) <h3>Drop Down List Example</h3> @Html.DropDownListFor(model => model.city, new SelectList(Enum.GetValues(typeof(city))), "Select City", new { @class = "form-control" }) </div>
The output will be as follows:
The templated HTML Helper is used for data display and input. It generates HTML automatically as per model property and it can generate HTML for a complete model with a single tag. These are divided into two categories
Display Template
Editor Template
List of Templated HTML Helpers
Display
@Html.Display()
@Html.DisplayFor()
@Html.DisplayName()
@Html.DisplayNameFor()
@Html.DisplayText()
@Html.DisplayTextFor()
@Html.DisplayModelFor()
Edit / Input
@Html.Editor()
@Html.EditorFor()
@Html.EditorForModel()
Now, here we can use the previously created model class and then we should write this code in the controller
C#
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using HTML_Helper_Demo.Models; namespace HTML_Helper_Demo.Controllers{ public class HomeController : Controller { public ActionResult Details() { //Here we are hardcoded the Employee Details //In Realtime you will get the data from any data source Employee employee = new Employee() { EmpId = 1, Name = "Rishabh Tyagi", Gender = "Male", city = city.Dehli, skills = skills.WebAPI, Address = "lajpat Nagar", AgreeTerm = true }; ViewData["EmployeeData"] = employee; return View(); } }}
Now add the view with all the default properties and write the following code
HTML
@{ ViewBag.Title = "Details";}<fieldset> <legend>Employee Details</legend> @Html.Display("EmployeeData")</fieldset>
The output will be as follows
sagartomar9927
CSharp ASP-NET
C#
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Multiple inheritance using interfaces
Introduction to .NET Framework
Differences Between .NET Core and .NET Framework
C# | Delegates
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
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Sep, 2021"
},
{
"code": null,
"e": 244,
"s": 28,
"text": "ASP.NET provides a wide range of built-in HTML helpers that can be used as per the user’s choice as there are multiple overrides available for them. There are three types of built-in HTML helpers offered by ASP.NET."
},
{
"code": null,
"e": 410,
"s": 244,
"text": "The HTML helpers that are mainly used to render HTML elements like text boxes, checkboxes, Radio Buttons, and Dropdown lists, etc. are called Standard HTML helpers. "
},
{
"code": null,
"e": 442,
"s": 410,
"text": "List of Standard HTML Helpers "
},
{
"code": null,
"e": 1129,
"s": 442,
"text": "@Html.ActionLink() - Used to create link on html page\n@Html.TextBox() - Used to create text box\n@Html.CheckBox() - Used to create check box\n@Html.RadioButton() - Used to create Radio Button\n@Html.BeginFrom() - Used to start a form\n@Html.EndFrom() - Used to end a form\n@Html.DropDownList() - Used to create drop down list\n@Html.Hidden() - Used to create hidden fields\n@Html.label() - Used for creating HTML label is on the browser\n@Html.TextArea() - The TextArea Method renders textarea element on browser\n@Html.Password() - This method is responsible for creating password input field on browser\n@Html.ListBox() - The ListBox helper method creates html ListBox with scrollbar on browser"
},
{
"code": null,
"e": 1136,
"s": 1131,
"text": "HTML"
},
{
"code": "@{ Layout = null;} <!DOCTYPE html> <html><head> <meta name=\"viewport\" content=\"width=device-width\" /> <title>Built-in HTML Helper</title></head><body> <div> <h3>Label example</h3> @Html.Label(\"firstName\", \"First Name\") <h3>Text Box Example</h3> @Html.TextBox(\"txtFirstName\", \"\", new { @class = \"form-control\", placeholder = \"First Name\" }) <h3>Text Area Example</h3> @Html.TextArea(\"address\", new { @class = \"form-control\", rows = \"5\" }) <h3>password Example</h3> @Html.Password(\"password\", \" \", new { @class = \"form-control\" }) <h3>Radio Button Example</h3> @Html.RadioButton(\"MaritalStatus\", \"Married\", new { id = \"IsMarried\" }) Married <h3>Check Box Example</h3> @Html.CheckBox(\"htmlSkill\") HTML 5 <h3>List Box Example</h3> @Html.ListBox(\"Skills\", new List<SelectListItem> { new SelectListItem { Text=\"ASP.NET\",Value=\"1\"}, new SelectListItem { Text=\"MVC\",Value=\"2\"}, new SelectListItem { Text=\"SQL Server\",Value=\"3\"}, new SelectListItem { Text=\"Angular\",Value=\"4\"}, new SelectListItem { Text=\"Web API\",Value=\"5\"} }, new { @class = \"form-control\" }) <h3>drop down List Example</h3> @Html.DropDownList(\"Gender\", new List<SelectListItem> { new SelectListItem {Text=\"Select Gender\",Value=\"-1\" }, new SelectListItem {Text=\"Male\",Value=\"1\" }, new SelectListItem {Text=\"Female\", Value=\"2\" } }, new { @class = \"custom-select\" }) </div></body></html>",
"e": 2754,
"s": 1136,
"text": null
},
{
"code": null,
"e": 3034,
"s": 2756,
"text": "The Strongly-Typed HTML helper takes a lambda as a parameter that tells the helper, which element of the model to be utilized in the typed view. The Strongly typed views are used for rendering specific sorts of model objects, rather than using the overall View-Data structure. "
},
{
"code": null,
"e": 3071,
"s": 3034,
"text": "List of strongly-Typed HTML Helper "
},
{
"code": null,
"e": 3251,
"s": 3071,
"text": "@Html.HiddenFor()\n@Html.LabelFor()\n@Html.TextBoxFor()\n@Html.RadioButtonFor()\n@Html.DropDownListFor()\n@Html.CheckBoxFor()\n@Html.TextAreaFor()\n@Html.PasswordFor()\n@Html.ListBoxFor()"
},
{
"code": null,
"e": 3460,
"s": 3251,
"text": "The functionality of all of these are the same as above but they are used with modal classes. Now, as we know we need a model class to use strongly typed HTML. So firstly we will add a model class as follows "
},
{
"code": null,
"e": 3463,
"s": 3460,
"text": "C#"
},
{
"code": "using System;using System.Collections.Generic;using System.Linq;using System.Web; namespace HTML_Helper_Demo.Models{ public class Employee { public int EmpId { get; set; } public string Name { get; set; } public string Gender { get; set; } public city city { get; set; } public skills skills { get; set; } public string Address { get; set; } public string Password { get; set; } public bool AgreeTerm { get; set; } }}public enum city{ Dehli, Mumbai, Kolkata, Channai, Bangalore}public enum skills{ HTML5, CSS3, Bootstrap, JavaScript, JQuery, Angular, MVC, WebAPI}",
"e": 4131,
"s": 3463,
"text": null
},
{
"code": null,
"e": 4231,
"s": 4133,
"text": "Now write the following code in the controller. And then add a view with the default properties. "
},
{
"code": null,
"e": 4234,
"s": 4231,
"text": "C#"
},
{
"code": "using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using HTML_Helper_Demo.Models; namespace HTML_Helper_Demo.Controllers{ public class HomeController : Controller { public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(Employee emp) { return View(); } }}",
"e": 4650,
"s": 4234,
"text": null
},
{
"code": null,
"e": 4689,
"s": 4657,
"text": "Now write the HTML as follows: "
},
{
"code": null,
"e": 4696,
"s": 4691,
"text": "HTML"
},
{
"code": "@using HTML_Helper_Demo.Models@model Employee@{ ViewBag.Title = \"Index\";} <div> <h3>Label Example</h3> @Html.LabelFor(model => model.Name, new { @class = \"label-control\" }) <h3>Text box Example</h3> @Html.TextBoxFor(model => model.Name, new { @class = \"form-control\" }) <h3>Text Box Example 2</h3> @Html.TextAreaFor(model => model.Address, new { @class = \"form-control\", rows = \"5\" }) <h3>Password for example</h3> @Html.PasswordFor(model => model.Password, new { @class = \"form-control\" }) <h3>Radio Button Example</h3> @Html.RadioButtonFor(model => model.Gender, true, new { id = \"male-true\" }) @Html.Label(\"male-true\", \"Male\") @Html.RadioButtonFor(model => model.Gender, false, new { id = \"female-true\" }) @Html.Label(\"female-true\", \"Female\") <h3>Check Box Example</h3> @Html.CheckBoxFor(model => model.AgreeTerm) <h3>List Box Example</h3> @Html.ListBoxFor(model => model.skills, new SelectList(Enum.GetValues(typeof(skills))), new { @class = \"form-control\" }) <h3>Drop Down List Example</h3> @Html.DropDownListFor(model => model.city, new SelectList(Enum.GetValues(typeof(city))), \"Select City\", new { @class = \"form-control\" }) </div>",
"e": 5993,
"s": 4696,
"text": null
},
{
"code": null,
"e": 6032,
"s": 6000,
"text": "The output will be as follows: "
},
{
"code": null,
"e": 6258,
"s": 6038,
"text": "The templated HTML Helper is used for data display and input. It generates HTML automatically as per model property and it can generate HTML for a complete model with a single tag. These are divided into two categories "
},
{
"code": null,
"e": 6277,
"s": 6260,
"text": "Display Template"
},
{
"code": null,
"e": 6293,
"s": 6277,
"text": "Editor Template"
},
{
"code": null,
"e": 6326,
"s": 6293,
"text": "List of Templated HTML Helpers "
},
{
"code": null,
"e": 6553,
"s": 6328,
"text": "Display\n\n@Html.Display()\n@Html.DisplayFor()\n@Html.DisplayName()\n@Html.DisplayNameFor()\n@Html.DisplayText()\n@Html.DisplayTextFor()\n@Html.DisplayModelFor()\n\nEdit / Input\n\n@Html.Editor()\n@Html.EditorFor()\n@Html.EditorForModel()"
},
{
"code": null,
"e": 6664,
"s": 6553,
"text": "Now, here we can use the previously created model class and then we should write this code in the controller "
},
{
"code": null,
"e": 6669,
"s": 6666,
"text": "C#"
},
{
"code": "using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using HTML_Helper_Demo.Models; namespace HTML_Helper_Demo.Controllers{ public class HomeController : Controller { public ActionResult Details() { //Here we are hardcoded the Employee Details //In Realtime you will get the data from any data source Employee employee = new Employee() { EmpId = 1, Name = \"Rishabh Tyagi\", Gender = \"Male\", city = city.Dehli, skills = skills.WebAPI, Address = \"lajpat Nagar\", AgreeTerm = true }; ViewData[\"EmployeeData\"] = employee; return View(); } }}",
"e": 7466,
"s": 6669,
"text": null
},
{
"code": null,
"e": 7548,
"s": 7468,
"text": "Now add the view with all the default properties and write the following code "
},
{
"code": null,
"e": 7553,
"s": 7548,
"text": "HTML"
},
{
"code": "@{ ViewBag.Title = \"Details\";}<fieldset> <legend>Employee Details</legend> @Html.Display(\"EmployeeData\")</fieldset>",
"e": 7678,
"s": 7553,
"text": null
},
{
"code": null,
"e": 7712,
"s": 7680,
"text": "The output will be as follows "
},
{
"code": null,
"e": 7729,
"s": 7714,
"text": "sagartomar9927"
},
{
"code": null,
"e": 7744,
"s": 7729,
"text": "CSharp ASP-NET"
},
{
"code": null,
"e": 7747,
"s": 7744,
"text": "C#"
},
{
"code": null,
"e": 7752,
"s": 7747,
"text": "HTML"
},
{
"code": null,
"e": 7757,
"s": 7752,
"text": "HTML"
},
{
"code": null,
"e": 7855,
"s": 7757,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7883,
"s": 7855,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 7926,
"s": 7883,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 7957,
"s": 7926,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 8006,
"s": 7957,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 8021,
"s": 8006,
"text": "C# | Delegates"
},
{
"code": null,
"e": 8069,
"s": 8021,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 8131,
"s": 8069,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 8181,
"s": 8131,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 8205,
"s": 8181,
"text": "REST API (Introduction)"
}
] |
matplotlib.pyplot.imread() in Python
|
22 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
The imread() function in pyplot module of matplotlib library is used to read an image from a file into an array.
Syntax: matplotlib.pyplot.imread(fname, format=None)
Parameters: This method accepts the following parameters.
fname : This parameter is the image file to read.
format: This parameter is the image file format assumed for reading the data.
Returns: This method return the following.
imagedata : This returns the image data
Below examples illustrate the matplotlib.pyplot.imread() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.cbook as cbookimport matplotlib.image as imageimport matplotlib.pyplot as plt with cbook.get_sample_data('loggf.png') as image_file: image = plt.imread(image_file) fig, ax = plt.subplots()ax.imshow(image)ax.axis('off') plt.title('matplotlib.pyplot.imread() function Example', fontweight ="bold")plt.show()
Output:
Example #2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.cbook as cbookimport matplotlib.image as imageimport matplotlib.pyplot as plt with cbook.get_sample_data('loggf.png') as file: im = image.imread(file) fig, ax = plt.subplots() ax.plot(np.cos(10 * np.linspace(0, 1)), '-o', ms = 15, alpha = 0.6, mfc ='green') ax.grid()fig.figimage(im, 10, 10, zorder = 3, alpha =.5) plt.title('matplotlib.pyplot.imread() function Example', fontweight ="bold")plt.show()
Output:
Python-matplotlib
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": 28,
"s": 0,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 223,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface."
},
{
"code": null,
"e": 336,
"s": 223,
"text": "The imread() function in pyplot module of matplotlib library is used to read an image from a file into an array."
},
{
"code": null,
"e": 389,
"s": 336,
"text": "Syntax: matplotlib.pyplot.imread(fname, format=None)"
},
{
"code": null,
"e": 447,
"s": 389,
"text": "Parameters: This method accepts the following parameters."
},
{
"code": null,
"e": 497,
"s": 447,
"text": "fname : This parameter is the image file to read."
},
{
"code": null,
"e": 575,
"s": 497,
"text": "format: This parameter is the image file format assumed for reading the data."
},
{
"code": null,
"e": 618,
"s": 575,
"text": "Returns: This method return the following."
},
{
"code": null,
"e": 658,
"s": 618,
"text": "imagedata : This returns the image data"
},
{
"code": null,
"e": 746,
"s": 658,
"text": "Below examples illustrate the matplotlib.pyplot.imread() function in matplotlib.pyplot:"
},
{
"code": null,
"e": 758,
"s": 746,
"text": "Example #1:"
},
{
"code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.cbook as cbookimport matplotlib.image as imageimport matplotlib.pyplot as plt with cbook.get_sample_data('loggf.png') as image_file: image = plt.imread(image_file) fig, ax = plt.subplots()ax.imshow(image)ax.axis('off') plt.title('matplotlib.pyplot.imread() function Example', fontweight =\"bold\")plt.show()",
"e": 1182,
"s": 758,
"text": null
},
{
"code": null,
"e": 1190,
"s": 1182,
"text": "Output:"
},
{
"code": null,
"e": 1202,
"s": 1190,
"text": "Example #2:"
},
{
"code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.cbook as cbookimport matplotlib.image as imageimport matplotlib.pyplot as plt with cbook.get_sample_data('loggf.png') as file: im = image.imread(file) fig, ax = plt.subplots() ax.plot(np.cos(10 * np.linspace(0, 1)), '-o', ms = 15, alpha = 0.6, mfc ='green') ax.grid()fig.figimage(im, 10, 10, zorder = 3, alpha =.5) plt.title('matplotlib.pyplot.imread() function Example', fontweight =\"bold\")plt.show()",
"e": 1753,
"s": 1202,
"text": null
},
{
"code": null,
"e": 1761,
"s": 1753,
"text": "Output:"
},
{
"code": null,
"e": 1779,
"s": 1761,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 1786,
"s": 1779,
"text": "Python"
},
{
"code": null,
"e": 1884,
"s": 1786,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1916,
"s": 1884,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1943,
"s": 1916,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1964,
"s": 1943,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1987,
"s": 1964,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2018,
"s": 1987,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2074,
"s": 2018,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2116,
"s": 2074,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2158,
"s": 2116,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2197,
"s": 2158,
"text": "Python | Get unique values from a list"
}
] |
How to Create Dashed Underline under TextView in Android?
|
06 Jun, 2021
In this article, we will explain how to create a dashed underline below a text view in android. A sample image is shown below to give an idea of what we are going to build.
Step 1: Create a new project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.
Step 2: Working with dashed_underline.xml
Go to res > drawable > new > drawable resource file and create a new file and name it “dashed_underline.xml” and define all properties of the dashed line that we need. Later we will add this as the background of TextView. Below is the code for dashed_underline.xml comments is added for a better understanding of the code.
XML
<?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android" ><!--Create a layer list and add item of shape "Rectangle to it"--> <item android:left="-5dp" android:right="-5dp" android:top="-5dp"> <shape android:shape="rectangle"> <!--Give the dashed lines their property like color, width, and dashGap--> <stroke android:color="@color/black" android:dashWidth="2dp" android:dashGap="3dp" android:width="1dp"/> </shape> </item></layer-list>
Step 3: Working with the activity_main.xml
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. It has only a TextView that we want to be underlined.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--Create a Text View and inside the background tag add the dashed_underline that we created earlier--> <TextView android:id="@+id/tv_dashed" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/dashed_underline" android:text="Welcome to GFG!" android:textColor="@color/black" android:textSize="24sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
Output UI:
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jun, 2021"
},
{
"code": null,
"e": 201,
"s": 28,
"text": "In this article, we will explain how to create a dashed underline below a text view in android. A sample image is shown below to give an idea of what we are going to build."
},
{
"code": null,
"e": 230,
"s": 201,
"text": "Step 1: Create a new project"
},
{
"code": null,
"e": 342,
"s": 230,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. "
},
{
"code": null,
"e": 384,
"s": 342,
"text": "Step 2: Working with dashed_underline.xml"
},
{
"code": null,
"e": 707,
"s": 384,
"text": "Go to res > drawable > new > drawable resource file and create a new file and name it “dashed_underline.xml” and define all properties of the dashed line that we need. Later we will add this as the background of TextView. Below is the code for dashed_underline.xml comments is added for a better understanding of the code."
},
{
"code": null,
"e": 711,
"s": 707,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><layer-list xmlns:android=\"http://schemas.android.com/apk/res/android\" ><!--Create a layer list and add item of shape \"Rectangle to it\"--> <item android:left=\"-5dp\" android:right=\"-5dp\" android:top=\"-5dp\"> <shape android:shape=\"rectangle\"> <!--Give the dashed lines their property like color, width, and dashGap--> <stroke android:color=\"@color/black\" android:dashWidth=\"2dp\" android:dashGap=\"3dp\" android:width=\"1dp\"/> </shape> </item></layer-list>",
"e": 1349,
"s": 711,
"text": null
},
{
"code": null,
"e": 1392,
"s": 1349,
"text": "Step 3: Working with the activity_main.xml"
},
{
"code": null,
"e": 1562,
"s": 1392,
"text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. It has only a TextView that we want to be underlined."
},
{
"code": null,
"e": 1566,
"s": 1562,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--Create a Text View and inside the background tag add the dashed_underline that we created earlier--> <TextView android:id=\"@+id/tv_dashed\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:background=\"@drawable/dashed_underline\" android:text=\"Welcome to GFG!\" android:textColor=\"@color/black\" android:textSize=\"24sp\" android:textStyle=\"bold\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 2656,
"s": 1566,
"text": null
},
{
"code": null,
"e": 2667,
"s": 2656,
"text": "Output UI:"
},
{
"code": null,
"e": 2675,
"s": 2667,
"text": "Android"
},
{
"code": null,
"e": 2683,
"s": 2675,
"text": "Android"
}
] |
How many ways are there to initialize a final variable in java?
|
In Java, final is the access modifier which can be used with a filed, class and a method.
When a method if final it cannot be overridden.
When a variable is final its value cannot be modified further.
When a class is final it cannot be extended.
Once you declare a final variable, it is a must to initialize it. You can initialize the final instance variable −
At the time of declaration as.
public final String name = "Raju";
public final int age = 20;
Within an instance (non-static) block.
{
this.name = "Raju";
this.age = 20;
}
Within a default constructor.
public final String name;
public final int age;
public Student(){
this.name = "Raju";
this.age = 20;
}
Note − If you try to initialize the final instance variable elsewhere, a compile-time error will be generated.
In the following Java program, the class Student contains two final variables − name, age and, we are initializing them at the time of declaration −
Live Demo
public class Student {
public final String name = "Raju";
public final int age = 20;
public void display(){
System.out.println("Name of the Student: "+this.name );
System.out.println("Age of the Student: "+this.age );
}
public static void main(String args[]) {
new Student().display();
}
}
Name of the Student: Raju
Age of the Student: 20
In the following Java program, the class Student contains two final variables− name, age and, we are initializing them within an instance block −
Live Demo
public class Student {
public final String name;
public final int age; {
this.name = "Raju";
this.age = 20;
}
public void display(){
System.out.println("Name of the Student: "+this.name );
System.out.println("Age of the Student: "+this.age );
}
public static void main(String args[]) {
new Student().display();
}
}
Name of the Student: Raju
Age of the Student: 20
In the following Java program, the class Student contains two final variables − name, age and, we are initializing them within a default constructor −
Live Demo
public class Student {
public final String name;
public final int age;
public Student(){
this.name = "Raju";
this.age = 20;
}
public void display(){
System.out.println("Name of the Student: "+this.name );
System.out.println("Age of the Student: "+this.age );
}
public static void main(String args[]) {
new Student().display();
}
}
Name of the Student: Raju
Age of the Student: 20
|
[
{
"code": null,
"e": 1152,
"s": 1062,
"text": "In Java, final is the access modifier which can be used with a filed, class and a method."
},
{
"code": null,
"e": 1200,
"s": 1152,
"text": "When a method if final it cannot be overridden."
},
{
"code": null,
"e": 1263,
"s": 1200,
"text": "When a variable is final its value cannot be modified further."
},
{
"code": null,
"e": 1308,
"s": 1263,
"text": "When a class is final it cannot be extended."
},
{
"code": null,
"e": 1423,
"s": 1308,
"text": "Once you declare a final variable, it is a must to initialize it. You can initialize the final instance variable −"
},
{
"code": null,
"e": 1454,
"s": 1423,
"text": "At the time of declaration as."
},
{
"code": null,
"e": 1516,
"s": 1454,
"text": "public final String name = \"Raju\";\npublic final int age = 20;"
},
{
"code": null,
"e": 1555,
"s": 1516,
"text": "Within an instance (non-static) block."
},
{
"code": null,
"e": 1600,
"s": 1555,
"text": "{\n this.name = \"Raju\";\n this.age = 20;\n}"
},
{
"code": null,
"e": 1630,
"s": 1600,
"text": "Within a default constructor."
},
{
"code": null,
"e": 1739,
"s": 1630,
"text": "public final String name;\npublic final int age;\npublic Student(){\n this.name = \"Raju\";\n this.age = 20;\n}"
},
{
"code": null,
"e": 1850,
"s": 1739,
"text": "Note − If you try to initialize the final instance variable elsewhere, a compile-time error will be generated."
},
{
"code": null,
"e": 1999,
"s": 1850,
"text": "In the following Java program, the class Student contains two final variables − name, age and, we are initializing them at the time of declaration −"
},
{
"code": null,
"e": 2010,
"s": 1999,
"text": " Live Demo"
},
{
"code": null,
"e": 2336,
"s": 2010,
"text": "public class Student {\n public final String name = \"Raju\";\n public final int age = 20;\n public void display(){\n System.out.println(\"Name of the Student: \"+this.name );\n System.out.println(\"Age of the Student: \"+this.age );\n }\n public static void main(String args[]) {\n new Student().display();\n }\n}"
},
{
"code": null,
"e": 2385,
"s": 2336,
"text": "Name of the Student: Raju\nAge of the Student: 20"
},
{
"code": null,
"e": 2531,
"s": 2385,
"text": "In the following Java program, the class Student contains two final variables− name, age and, we are initializing them within an instance block −"
},
{
"code": null,
"e": 2542,
"s": 2531,
"text": " Live Demo"
},
{
"code": null,
"e": 2908,
"s": 2542,
"text": "public class Student {\n public final String name;\n public final int age; {\n this.name = \"Raju\";\n this.age = 20;\n }\n public void display(){\n System.out.println(\"Name of the Student: \"+this.name );\n System.out.println(\"Age of the Student: \"+this.age );\n }\n public static void main(String args[]) {\n new Student().display();\n }\n}"
},
{
"code": null,
"e": 2957,
"s": 2908,
"text": "Name of the Student: Raju\nAge of the Student: 20"
},
{
"code": null,
"e": 3108,
"s": 2957,
"text": "In the following Java program, the class Student contains two final variables − name, age and, we are initializing them within a default constructor −"
},
{
"code": null,
"e": 3119,
"s": 3108,
"text": " Live Demo"
},
{
"code": null,
"e": 3504,
"s": 3119,
"text": "public class Student {\n public final String name;\n public final int age;\n public Student(){\n this.name = \"Raju\";\n this.age = 20;\n }\n public void display(){\n System.out.println(\"Name of the Student: \"+this.name );\n System.out.println(\"Age of the Student: \"+this.age );\n }\n public static void main(String args[]) {\n new Student().display();\n }\n}"
},
{
"code": null,
"e": 3553,
"s": 3504,
"text": "Name of the Student: Raju\nAge of the Student: 20"
}
] |
Credit Card Fraud Detection. Fraud detection using the multivariate... | by Christos Mousmoulas | Towards Data Science
|
Nowadays most of the transactions take place online, meaning that credit cards and other online payment systems are involved. This method is convenient both for the company and for the consumer. Consumers save time because they don’t have to go to the store to make their purchases and companies save money by not owing physical stores and avoiding expensive rental payments. It seems that the digital age brought some highly useful features which changed the way that both companies and consumers interact with each other but with one cost... Companies need to hire skilled software engineers and penetration testers to make sure that all the transactions are legal and non-fraudulent. Those people are designing the company’s servers in a way that the client has no control over critical transaction parts such as payment amount. With careful designing most (if not all) of the problems can be eliminated but even the framework which was used to create the server is not perfect. For example, if you follow the django framework release notes, you will see that there are many bug fixes among versions, thus a company should not rely only on its engineering skills.
In this article, I will present a way to detect if someone bypasses the security walls and makes an illegal transaction. You can find the code and the dataset in my github repo but I strongly encourage you to build it along with the instructions of this article.
The dataset consists of credit card transactions whose features are the product of PCA analysis and thus we don’t know what they represent except from the ‘Amount’, ‘Time’ and ‘Class’ ones. ‘Amount’ is the price of each transaction, ‘Time’ is the <<seconds elapsed between each transaction and the first transaction>> and ‘Class’ represents a fraud transaction when its value equals 1 and a valid transaction when its value equals 0. Initially, we will install the required packages so grub the ‘requirements.txt’ file from my GitHub repo, create a virtual environment install them:
pip install -r requirements.txt
Initially create a ‘main.py’ file and import the following:
import numpy as npimport pandas as pdimport sklearnfrom scipy.stats import normfrom scipy.stats import multivariate_normalfrom sklearn.preprocessing import MinMaxScalerimport matplotlib.pyplot as pltimport seaborn as sns
Now we will read the dataset and check if there is any missing value:
df = pd.read_csv('creditcardfraud/creditcard.csv')# missing valuesprint("missing values:", df.isnull().values.any())
There are no missing values so we can proceed with the visualizations to better understand our data. Let’s plot how balanced our dataset is:
# plot normal and fraudcount_classes = pd.value_counts(df['Class'], sort=True)count_classes.plot(kind='bar', rot=0)plt.title("Distributed Transactions")plt.xticks(range(2), ['Normal', 'Fraud'])plt.xlabel("Class")plt.ylabel("Frequency")plt.show()
We see that our data is highly imbalanced. Therefore, we cannot use any supervised learning algorithm directly because it will overfit based on the ‘Normal’ examples. At this point we are still in the data investigation-analysis stage so let’s plot the heatmap:
# heatmapsns.heatmap(df.corr(), vmin=-1)plt.show()
It seems that we don’t have highly correlated features although there is a slightly negative correlation between ‘V2’ and ‘Amount’ (label not shown in the above heatmap but it is near the ‘Class’ feature) features. The ‘Amount’ feature is slightly correlated with the other features as well, meaning that it can partially be calculated by them so we can try dropping it (from my tests, this gave a nice amount of improvement to the final score). There is also a little correlation between ‘Time’ and other features but we will see a more important reason to drop it in the aftermath of this article.
Until now, we did some nice data analysis but we didn’t do the most important part which is, learning “where our data came from”. Thus the next graph will be the data distribution one:
fig, axs = plt.subplots(6, 5, squeeze=False)for i, ax in enumerate(axs.flatten()): ax.set_facecolor('xkcd:charcoal') ax.set_title(df.columns[i]) sns.distplot(df.iloc[:, i], ax=ax, fit=norm, color="#DC143C", fit_kws={"color": "#4e8ef5"}) ax.set_xlabel('')fig.tight_layout(h_pad=-1.5, w_pad=-1.5)plt.show()
I encourage you to execute the above code snippet in your local machine to see the results better. The blue line indicates the actual Gaussian distribution, while the red one our data’s probability density function. We see that almost every feature comes from the normal (or gaussian) distribution except from the ‘Time’ one. Therefore, this will be our motivation to do fraud detection with the multivariate Gaussian distribution. This method works only for features from the gaussian distribution, thus if your data is not gaussian-like you can transform it to be with a method that I describe in this article. For example, you can try this technique on features ‘V26’, ‘V4’, ‘V1’ and see if you get improvements in our final score. The ‘Time’ feature comes from the bimodal distribution which can’t be transformed to gaussian-like, thus we will discard it. Another reason to discard ‘Time’ feature is that it doesn’t seem to contain extreme values like the features shown in the other graphs.
Moreover, the algorithm which we will be using is sensitive to distance metrics so if we scale the features to a fixed range, we will obtain much better results. Add the following code snippet which will drop the features mentioned above and scale the others so that they take values between 0 and 1:
classes = df['Class']df.drop(['Time', 'Class', 'Amount'], axis=1, inplace=True)cols = df.columns.difference(['Class'])MMscaller = MinMaxScaler()df = MMscaller.fit_transform(df)df = pd.DataFrame(data=df, columns=cols)df = pd.concat([df, classes], axis=1)
Note that MinMaxScaler won’t change the shape of the distribution so the outliers will still be on the right place.
At this point, we finished with our data analysis and preprocessing and we are ready to dive into the algorithm’s implementation details. The steps of the algorithm are the following:
Find features that may contain anomalous examples (done)Calculate the mean of each feature in the training set which contains usually the 60% of the normal transactionsCalculate the covariance matrix on the training setCalculate the multivariate normal pdf (probability density function) on the training set (given below)Calculate the multivariate normal pdf on the validation set (contains 50% of the fraudulent transactions and usually 20% of the normal ones)Calculate the multivariate normal pdf on the test set (contains 50% of the fraudulent transactions and usually 20% of the normal ones)Find a threshold based on the pdf from validation set which indicates that the pdf values (of any set) which are smaller than the threshold are outliersCalculate the outliers on the test set which are the sum of the pdf values that are smaller than the previous threshold
Find features that may contain anomalous examples (done)
Calculate the mean of each feature in the training set which contains usually the 60% of the normal transactions
Calculate the covariance matrix on the training set
Calculate the multivariate normal pdf (probability density function) on the training set (given below)
Calculate the multivariate normal pdf on the validation set (contains 50% of the fraudulent transactions and usually 20% of the normal ones)
Calculate the multivariate normal pdf on the test set (contains 50% of the fraudulent transactions and usually 20% of the normal ones)
Find a threshold based on the pdf from validation set which indicates that the pdf values (of any set) which are smaller than the threshold are outliers
Calculate the outliers on the test set which are the sum of the pdf values that are smaller than the previous threshold
where μ is the mean, det is the determinant, Σ is the covariance matrix, and κ is the dimension of the space where x takes values.
In general, this pdf returns the <<confidence>> that a transaction is normal. If that number is lower than the threshold then the transaction is an outlier.
And yes, I know that the above pdf hurts your eyes (just like mine) but it is already implemented in the scipy package...
Continuing with our code, create a file called ‘functions.py’ where we will add useful functions to implement certain stages of the algorithm and place the following function which will split our dataset into train, validation and test sets:
import pandas as pdimport numpy as npdef train_validation_splits(df): # Fraud Transactions fraud = df[df['Class'] == 1] # Normal Transactions normal = df[df['Class'] == 0] print('normal:', normal.shape[0]) print('fraud:', fraud.shape[0]) normal_test_start = int(normal.shape[0] * .2) fraud_test_start = int(fraud.shape[0] * .5) normal_train_start = normal_test_start * 2 val_normal = normal[:normal_test_start] val_fraud = fraud[:fraud_test_start] validation_set = pd.concat([val_normal, val_fraud], axis=0) test_normal = normal[normal_test_start:normal_train_start] test_fraud = fraud[fraud_test_start:fraud.shape[0]] test_set = pd.concat([test_normal, test_fraud], axis=0) Xval = validation_set.iloc[:, :-1] Yval = validation_set.iloc[:, -1] Xtest = test_set.iloc[:, :-1] Ytest = test_set.iloc[:, -1] train_set = normal[normal_train_start:normal.shape[0]] Xtrain = train_set.iloc[:, :-1] return Xtrain.to_numpy(), Xtest.to_numpy(), Xval.to_numpy(), Ytest.to_numpy(), Yval.to_numpy()
Now add the function below which will calculate the mean and the covariance matrix:
def estimate_gaussian_params(X): """ Calculates the mean and the covariance for each feature. Arguments: X: dataset """ mu = np.mean(X, axis=0) sigma = np.cov(X.T) return mu, sigma
Back to our “main.py”, import and call the above functions along with the multivariate normal pdf for each of our sets:
(Xtrain, Xtest, Xval, Ytest, Yval) = train_validation_splits(df)(mu, sigma) = estimate_gaussian_params(Xtrain)# calculate gaussian pdfp = multivariate_normal.pdf(Xtrain, mu, sigma)pval = multivariate_normal.pdf(Xval, mu, sigma)ptest = multivariate_normal.pdf(Xtest, mu, sigma)
Now it’s time to refer to the threshold (or ‘epsilon’). In general, a good practice is to initialize the threshold with the minimum value of the pdf and increment it with a small step until you reach the maximum pdf while saving each threshold value in a vector. For our problem, I found that the values from the pdf can effectively be used to create the threshold vector. After creating the vector, we create a ‘for’ loop and iterate over it. In every iteration, we compare the current threshold with the values of the pdf which yield our predictions. We then calculate the F1 score based on our predictions and the ground truth values and if the F1 score that we found is greater than the previous one, we override a “best threshold” variable. At the end of the ‘for’ loop, we have the epsilon value that generated the best F1 score.
Note that we can’t use accuracy as our metric! If we identify all the transactions as ‘normal’ we could have 99% accuracy and a useless algorithm.
To implement the above, add the following functions to the “functions.py”:
def metrics(y, predictions): fp = np.sum(np.all([predictions == 1, y == 0], axis=0)) tp = np.sum(np.all([predictions == 1, y == 1], axis=0)) fn = np.sum(np.all([predictions == 0, y == 1], axis=0)) precision = (tp / (tp + fp)) if (tp + fp) > 0 else 0 recall = (tp / (tp + fn)) if (tp + fn) > 0 else 0 F1 = (2 * precision * recall) / (precision + recall) if (precision + recall) > 0 else 0 return precision, recall, F1def selectThreshold(yval, pval): e_values = pval bestF1 = 0 bestEpsilon = 0 for epsilon in e_values: predictions = pval < epsilon (precision, recall, F1) = metrics(yval, predictions) if F1 > bestF1: bestF1 = F1 bestEpsilon = epsilon return bestEpsilon, bestF1
Finally, import the functions in our “main.py” file and call them to return our threshold and the F1 score on the validation set, and to evaluate our model on our test set:
(epsilon, F1) = selectThreshold(Yval, pval)print("Best epsilon found:", epsilon)print("Best F1 on cross validation set:", F1)(test_precision, test_recall, test_F1) = metrics(Ytest, ptest < epsilon)print("Outliers found:", np.sum(ptest < epsilon))print("Test set Precision:", test_precision)print("Test set Recall:", test_recall)print("Test set F1 score:", test_F1)
The results are:
Best epsilon found: 5e-324 Best F1 on cross validation set: 0.7852998065764023 Outliers found: 210 Test set Precision: 0.9095238095238095 Test set Recall: 0.7764227642276422 Test set F1 score: 0.837719298245614
which are pretty good!
You reached the end of this tutorial, I hope that you found this information useful. Please feel free to comment, and ask about things you didn’t understand and I will try to reply as soon as possible!
Originally published at Fraud detection in Python (devnal.com).
|
[
{
"code": null,
"e": 1339,
"s": 172,
"text": "Nowadays most of the transactions take place online, meaning that credit cards and other online payment systems are involved. This method is convenient both for the company and for the consumer. Consumers save time because they don’t have to go to the store to make their purchases and companies save money by not owing physical stores and avoiding expensive rental payments. It seems that the digital age brought some highly useful features which changed the way that both companies and consumers interact with each other but with one cost... Companies need to hire skilled software engineers and penetration testers to make sure that all the transactions are legal and non-fraudulent. Those people are designing the company’s servers in a way that the client has no control over critical transaction parts such as payment amount. With careful designing most (if not all) of the problems can be eliminated but even the framework which was used to create the server is not perfect. For example, if you follow the django framework release notes, you will see that there are many bug fixes among versions, thus a company should not rely only on its engineering skills."
},
{
"code": null,
"e": 1602,
"s": 1339,
"text": "In this article, I will present a way to detect if someone bypasses the security walls and makes an illegal transaction. You can find the code and the dataset in my github repo but I strongly encourage you to build it along with the instructions of this article."
},
{
"code": null,
"e": 2185,
"s": 1602,
"text": "The dataset consists of credit card transactions whose features are the product of PCA analysis and thus we don’t know what they represent except from the ‘Amount’, ‘Time’ and ‘Class’ ones. ‘Amount’ is the price of each transaction, ‘Time’ is the <<seconds elapsed between each transaction and the first transaction>> and ‘Class’ represents a fraud transaction when its value equals 1 and a valid transaction when its value equals 0. Initially, we will install the required packages so grub the ‘requirements.txt’ file from my GitHub repo, create a virtual environment install them:"
},
{
"code": null,
"e": 2217,
"s": 2185,
"text": "pip install -r requirements.txt"
},
{
"code": null,
"e": 2277,
"s": 2217,
"text": "Initially create a ‘main.py’ file and import the following:"
},
{
"code": null,
"e": 2498,
"s": 2277,
"text": "import numpy as npimport pandas as pdimport sklearnfrom scipy.stats import normfrom scipy.stats import multivariate_normalfrom sklearn.preprocessing import MinMaxScalerimport matplotlib.pyplot as pltimport seaborn as sns"
},
{
"code": null,
"e": 2568,
"s": 2498,
"text": "Now we will read the dataset and check if there is any missing value:"
},
{
"code": null,
"e": 2685,
"s": 2568,
"text": "df = pd.read_csv('creditcardfraud/creditcard.csv')# missing valuesprint(\"missing values:\", df.isnull().values.any())"
},
{
"code": null,
"e": 2826,
"s": 2685,
"text": "There are no missing values so we can proceed with the visualizations to better understand our data. Let’s plot how balanced our dataset is:"
},
{
"code": null,
"e": 3072,
"s": 2826,
"text": "# plot normal and fraudcount_classes = pd.value_counts(df['Class'], sort=True)count_classes.plot(kind='bar', rot=0)plt.title(\"Distributed Transactions\")plt.xticks(range(2), ['Normal', 'Fraud'])plt.xlabel(\"Class\")plt.ylabel(\"Frequency\")plt.show()"
},
{
"code": null,
"e": 3334,
"s": 3072,
"text": "We see that our data is highly imbalanced. Therefore, we cannot use any supervised learning algorithm directly because it will overfit based on the ‘Normal’ examples. At this point we are still in the data investigation-analysis stage so let’s plot the heatmap:"
},
{
"code": null,
"e": 3385,
"s": 3334,
"text": "# heatmapsns.heatmap(df.corr(), vmin=-1)plt.show()"
},
{
"code": null,
"e": 3985,
"s": 3385,
"text": "It seems that we don’t have highly correlated features although there is a slightly negative correlation between ‘V2’ and ‘Amount’ (label not shown in the above heatmap but it is near the ‘Class’ feature) features. The ‘Amount’ feature is slightly correlated with the other features as well, meaning that it can partially be calculated by them so we can try dropping it (from my tests, this gave a nice amount of improvement to the final score). There is also a little correlation between ‘Time’ and other features but we will see a more important reason to drop it in the aftermath of this article."
},
{
"code": null,
"e": 4170,
"s": 3985,
"text": "Until now, we did some nice data analysis but we didn’t do the most important part which is, learning “where our data came from”. Thus the next graph will be the data distribution one:"
},
{
"code": null,
"e": 4503,
"s": 4170,
"text": "fig, axs = plt.subplots(6, 5, squeeze=False)for i, ax in enumerate(axs.flatten()): ax.set_facecolor('xkcd:charcoal') ax.set_title(df.columns[i]) sns.distplot(df.iloc[:, i], ax=ax, fit=norm, color=\"#DC143C\", fit_kws={\"color\": \"#4e8ef5\"}) ax.set_xlabel('')fig.tight_layout(h_pad=-1.5, w_pad=-1.5)plt.show()"
},
{
"code": null,
"e": 5499,
"s": 4503,
"text": "I encourage you to execute the above code snippet in your local machine to see the results better. The blue line indicates the actual Gaussian distribution, while the red one our data’s probability density function. We see that almost every feature comes from the normal (or gaussian) distribution except from the ‘Time’ one. Therefore, this will be our motivation to do fraud detection with the multivariate Gaussian distribution. This method works only for features from the gaussian distribution, thus if your data is not gaussian-like you can transform it to be with a method that I describe in this article. For example, you can try this technique on features ‘V26’, ‘V4’, ‘V1’ and see if you get improvements in our final score. The ‘Time’ feature comes from the bimodal distribution which can’t be transformed to gaussian-like, thus we will discard it. Another reason to discard ‘Time’ feature is that it doesn’t seem to contain extreme values like the features shown in the other graphs."
},
{
"code": null,
"e": 5800,
"s": 5499,
"text": "Moreover, the algorithm which we will be using is sensitive to distance metrics so if we scale the features to a fixed range, we will obtain much better results. Add the following code snippet which will drop the features mentioned above and scale the others so that they take values between 0 and 1:"
},
{
"code": null,
"e": 6054,
"s": 5800,
"text": "classes = df['Class']df.drop(['Time', 'Class', 'Amount'], axis=1, inplace=True)cols = df.columns.difference(['Class'])MMscaller = MinMaxScaler()df = MMscaller.fit_transform(df)df = pd.DataFrame(data=df, columns=cols)df = pd.concat([df, classes], axis=1)"
},
{
"code": null,
"e": 6170,
"s": 6054,
"text": "Note that MinMaxScaler won’t change the shape of the distribution so the outliers will still be on the right place."
},
{
"code": null,
"e": 6354,
"s": 6170,
"text": "At this point, we finished with our data analysis and preprocessing and we are ready to dive into the algorithm’s implementation details. The steps of the algorithm are the following:"
},
{
"code": null,
"e": 7221,
"s": 6354,
"text": "Find features that may contain anomalous examples (done)Calculate the mean of each feature in the training set which contains usually the 60% of the normal transactionsCalculate the covariance matrix on the training setCalculate the multivariate normal pdf (probability density function) on the training set (given below)Calculate the multivariate normal pdf on the validation set (contains 50% of the fraudulent transactions and usually 20% of the normal ones)Calculate the multivariate normal pdf on the test set (contains 50% of the fraudulent transactions and usually 20% of the normal ones)Find a threshold based on the pdf from validation set which indicates that the pdf values (of any set) which are smaller than the threshold are outliersCalculate the outliers on the test set which are the sum of the pdf values that are smaller than the previous threshold"
},
{
"code": null,
"e": 7278,
"s": 7221,
"text": "Find features that may contain anomalous examples (done)"
},
{
"code": null,
"e": 7391,
"s": 7278,
"text": "Calculate the mean of each feature in the training set which contains usually the 60% of the normal transactions"
},
{
"code": null,
"e": 7443,
"s": 7391,
"text": "Calculate the covariance matrix on the training set"
},
{
"code": null,
"e": 7546,
"s": 7443,
"text": "Calculate the multivariate normal pdf (probability density function) on the training set (given below)"
},
{
"code": null,
"e": 7687,
"s": 7546,
"text": "Calculate the multivariate normal pdf on the validation set (contains 50% of the fraudulent transactions and usually 20% of the normal ones)"
},
{
"code": null,
"e": 7822,
"s": 7687,
"text": "Calculate the multivariate normal pdf on the test set (contains 50% of the fraudulent transactions and usually 20% of the normal ones)"
},
{
"code": null,
"e": 7975,
"s": 7822,
"text": "Find a threshold based on the pdf from validation set which indicates that the pdf values (of any set) which are smaller than the threshold are outliers"
},
{
"code": null,
"e": 8095,
"s": 7975,
"text": "Calculate the outliers on the test set which are the sum of the pdf values that are smaller than the previous threshold"
},
{
"code": null,
"e": 8226,
"s": 8095,
"text": "where μ is the mean, det is the determinant, Σ is the covariance matrix, and κ is the dimension of the space where x takes values."
},
{
"code": null,
"e": 8383,
"s": 8226,
"text": "In general, this pdf returns the <<confidence>> that a transaction is normal. If that number is lower than the threshold then the transaction is an outlier."
},
{
"code": null,
"e": 8505,
"s": 8383,
"text": "And yes, I know that the above pdf hurts your eyes (just like mine) but it is already implemented in the scipy package..."
},
{
"code": null,
"e": 8747,
"s": 8505,
"text": "Continuing with our code, create a file called ‘functions.py’ where we will add useful functions to implement certain stages of the algorithm and place the following function which will split our dataset into train, validation and test sets:"
},
{
"code": null,
"e": 9798,
"s": 8747,
"text": "import pandas as pdimport numpy as npdef train_validation_splits(df): # Fraud Transactions fraud = df[df['Class'] == 1] # Normal Transactions normal = df[df['Class'] == 0] print('normal:', normal.shape[0]) print('fraud:', fraud.shape[0]) normal_test_start = int(normal.shape[0] * .2) fraud_test_start = int(fraud.shape[0] * .5) normal_train_start = normal_test_start * 2 val_normal = normal[:normal_test_start] val_fraud = fraud[:fraud_test_start] validation_set = pd.concat([val_normal, val_fraud], axis=0) test_normal = normal[normal_test_start:normal_train_start] test_fraud = fraud[fraud_test_start:fraud.shape[0]] test_set = pd.concat([test_normal, test_fraud], axis=0) Xval = validation_set.iloc[:, :-1] Yval = validation_set.iloc[:, -1] Xtest = test_set.iloc[:, :-1] Ytest = test_set.iloc[:, -1] train_set = normal[normal_train_start:normal.shape[0]] Xtrain = train_set.iloc[:, :-1] return Xtrain.to_numpy(), Xtest.to_numpy(), Xval.to_numpy(), Ytest.to_numpy(), Yval.to_numpy()"
},
{
"code": null,
"e": 9882,
"s": 9798,
"text": "Now add the function below which will calculate the mean and the covariance matrix:"
},
{
"code": null,
"e": 10087,
"s": 9882,
"text": "def estimate_gaussian_params(X): \"\"\" Calculates the mean and the covariance for each feature. Arguments: X: dataset \"\"\" mu = np.mean(X, axis=0) sigma = np.cov(X.T) return mu, sigma"
},
{
"code": null,
"e": 10207,
"s": 10087,
"text": "Back to our “main.py”, import and call the above functions along with the multivariate normal pdf for each of our sets:"
},
{
"code": null,
"e": 10484,
"s": 10207,
"text": "(Xtrain, Xtest, Xval, Ytest, Yval) = train_validation_splits(df)(mu, sigma) = estimate_gaussian_params(Xtrain)# calculate gaussian pdfp = multivariate_normal.pdf(Xtrain, mu, sigma)pval = multivariate_normal.pdf(Xval, mu, sigma)ptest = multivariate_normal.pdf(Xtest, mu, sigma)"
},
{
"code": null,
"e": 11320,
"s": 10484,
"text": "Now it’s time to refer to the threshold (or ‘epsilon’). In general, a good practice is to initialize the threshold with the minimum value of the pdf and increment it with a small step until you reach the maximum pdf while saving each threshold value in a vector. For our problem, I found that the values from the pdf can effectively be used to create the threshold vector. After creating the vector, we create a ‘for’ loop and iterate over it. In every iteration, we compare the current threshold with the values of the pdf which yield our predictions. We then calculate the F1 score based on our predictions and the ground truth values and if the F1 score that we found is greater than the previous one, we override a “best threshold” variable. At the end of the ‘for’ loop, we have the epsilon value that generated the best F1 score."
},
{
"code": null,
"e": 11467,
"s": 11320,
"text": "Note that we can’t use accuracy as our metric! If we identify all the transactions as ‘normal’ we could have 99% accuracy and a useless algorithm."
},
{
"code": null,
"e": 11542,
"s": 11467,
"text": "To implement the above, add the following functions to the “functions.py”:"
},
{
"code": null,
"e": 12333,
"s": 11542,
"text": "def metrics(y, predictions): fp = np.sum(np.all([predictions == 1, y == 0], axis=0)) tp = np.sum(np.all([predictions == 1, y == 1], axis=0)) fn = np.sum(np.all([predictions == 0, y == 1], axis=0)) precision = (tp / (tp + fp)) if (tp + fp) > 0 else 0 recall = (tp / (tp + fn)) if (tp + fn) > 0 else 0 F1 = (2 * precision * recall) / (precision + recall) if (precision + recall) > 0 else 0 return precision, recall, F1def selectThreshold(yval, pval): e_values = pval bestF1 = 0 bestEpsilon = 0 for epsilon in e_values: predictions = pval < epsilon (precision, recall, F1) = metrics(yval, predictions) if F1 > bestF1: bestF1 = F1 bestEpsilon = epsilon return bestEpsilon, bestF1"
},
{
"code": null,
"e": 12506,
"s": 12333,
"text": "Finally, import the functions in our “main.py” file and call them to return our threshold and the F1 score on the validation set, and to evaluate our model on our test set:"
},
{
"code": null,
"e": 12871,
"s": 12506,
"text": "(epsilon, F1) = selectThreshold(Yval, pval)print(\"Best epsilon found:\", epsilon)print(\"Best F1 on cross validation set:\", F1)(test_precision, test_recall, test_F1) = metrics(Ytest, ptest < epsilon)print(\"Outliers found:\", np.sum(ptest < epsilon))print(\"Test set Precision:\", test_precision)print(\"Test set Recall:\", test_recall)print(\"Test set F1 score:\", test_F1)"
},
{
"code": null,
"e": 12888,
"s": 12871,
"text": "The results are:"
},
{
"code": null,
"e": 13099,
"s": 12888,
"text": "Best epsilon found: 5e-324 Best F1 on cross validation set: 0.7852998065764023 Outliers found: 210 Test set Precision: 0.9095238095238095 Test set Recall: 0.7764227642276422 Test set F1 score: 0.837719298245614"
},
{
"code": null,
"e": 13122,
"s": 13099,
"text": "which are pretty good!"
},
{
"code": null,
"e": 13324,
"s": 13122,
"text": "You reached the end of this tutorial, I hope that you found this information useful. Please feel free to comment, and ask about things you didn’t understand and I will try to reply as soon as possible!"
}
] |
How to check two numbers are approximately equal in JavaScript ? - GeeksforGeeks
|
31 Mar, 2021
Given two numbers and the task is to check the given numbers are approximately equal to each other or not. If both numbers are approximately the same then print true otherwise print false.
Example:
Input: num1 = 10.3
num2 = 10
Output: true
Approach: To check the numbers are approximately the same or not, first, we have to decide the epsilon value. Epsilon is the maximum difference between two numbers, if the difference of the numbers is less than or equal to epsilon then the numbers are approximately equal to each other. So first we create a function named checkApprox which takes three arguments num1, num2, and epsilon. Now check the absolute difference of num1 and num2 is less than epsilon or not.
Example 1:
Javascript
<script>const checkApprox = (num1, num2, epsilon) => { // Calculating the absolute difference // and compare with epsilon return Math.abs(num1 - num2) < epsilon;} console.log(checkApprox(10.003, 10.001, 0.005));</script>
Output:
true
Example 2:
Javascript
<script>const checkApprox = (num1, num2, epsilon = 0.004) => { return Math.abs(num1 - num2) < epsilon;} console.log(checkApprox(Math.PI / 2.0, 1.5708));</script>
Output:
true
Example 3:
Javascript
<script>const checkApprox = (num1, num2, epsilon = 0.004) => { return Math.abs(num1 - num2) < epsilon;} console.log(checkApprox(0.003, 0.03));</script>
Output:
false
ES6
javascript-math
JavaScript-Questions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
File uploading in React.js
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 37579,
"s": 37551,
"text": "\n31 Mar, 2021"
},
{
"code": null,
"e": 37768,
"s": 37579,
"text": "Given two numbers and the task is to check the given numbers are approximately equal to each other or not. If both numbers are approximately the same then print true otherwise print false."
},
{
"code": null,
"e": 37777,
"s": 37768,
"text": "Example:"
},
{
"code": null,
"e": 37829,
"s": 37777,
"text": "Input: num1 = 10.3\n num2 = 10\n\nOutput: true"
},
{
"code": null,
"e": 38297,
"s": 37829,
"text": "Approach: To check the numbers are approximately the same or not, first, we have to decide the epsilon value. Epsilon is the maximum difference between two numbers, if the difference of the numbers is less than or equal to epsilon then the numbers are approximately equal to each other. So first we create a function named checkApprox which takes three arguments num1, num2, and epsilon. Now check the absolute difference of num1 and num2 is less than epsilon or not."
},
{
"code": null,
"e": 38308,
"s": 38297,
"text": "Example 1:"
},
{
"code": null,
"e": 38319,
"s": 38308,
"text": "Javascript"
},
{
"code": "<script>const checkApprox = (num1, num2, epsilon) => { // Calculating the absolute difference // and compare with epsilon return Math.abs(num1 - num2) < epsilon;} console.log(checkApprox(10.003, 10.001, 0.005));</script>",
"e": 38546,
"s": 38319,
"text": null
},
{
"code": null,
"e": 38554,
"s": 38546,
"text": "Output:"
},
{
"code": null,
"e": 38559,
"s": 38554,
"text": "true"
},
{
"code": null,
"e": 38570,
"s": 38559,
"text": "Example 2:"
},
{
"code": null,
"e": 38581,
"s": 38570,
"text": "Javascript"
},
{
"code": "<script>const checkApprox = (num1, num2, epsilon = 0.004) => { return Math.abs(num1 - num2) < epsilon;} console.log(checkApprox(Math.PI / 2.0, 1.5708));</script>",
"e": 38745,
"s": 38581,
"text": null
},
{
"code": null,
"e": 38753,
"s": 38745,
"text": "Output:"
},
{
"code": null,
"e": 38758,
"s": 38753,
"text": "true"
},
{
"code": null,
"e": 38769,
"s": 38758,
"text": "Example 3:"
},
{
"code": null,
"e": 38780,
"s": 38769,
"text": "Javascript"
},
{
"code": "<script>const checkApprox = (num1, num2, epsilon = 0.004) => { return Math.abs(num1 - num2) < epsilon;} console.log(checkApprox(0.003, 0.03));</script>",
"e": 38934,
"s": 38780,
"text": null
},
{
"code": null,
"e": 38942,
"s": 38934,
"text": "Output:"
},
{
"code": null,
"e": 38948,
"s": 38942,
"text": "false"
},
{
"code": null,
"e": 38952,
"s": 38948,
"text": "ES6"
},
{
"code": null,
"e": 38968,
"s": 38952,
"text": "javascript-math"
},
{
"code": null,
"e": 38989,
"s": 38968,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 39000,
"s": 38989,
"text": "JavaScript"
},
{
"code": null,
"e": 39017,
"s": 39000,
"text": "Web Technologies"
},
{
"code": null,
"e": 39115,
"s": 39017,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39124,
"s": 39115,
"text": "Comments"
},
{
"code": null,
"e": 39137,
"s": 39124,
"text": "Old Comments"
},
{
"code": null,
"e": 39198,
"s": 39137,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 39243,
"s": 39198,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 39315,
"s": 39243,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 39384,
"s": 39315,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 39411,
"s": 39384,
"text": "File uploading in React.js"
},
{
"code": null,
"e": 39467,
"s": 39411,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 39500,
"s": 39467,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 39562,
"s": 39500,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 39605,
"s": 39562,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Bootstrap 4 .border-0 class
|
Use the border-0 class in Bootstrap to eliminate all borders from an element as shown below −
<div class="mystyle border border-0">
No border
</div>
We have also set CSS style above −
.mystyle {
width: 120px;
height: 100px;
margin: 10px;
background: gray;
}
You can try to run the following code to implement the border-0 class −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<style>
.mystyle {
width: 120px;
height: 100px;
margin: 10px;
background: gray;
}
</style>
</head>
<body>
<div class="container">
<h4>Two Rectangles</h4>
<div class="mystyle border border-success">orange border</div>
<div class="mystyle border border-0">No border</div>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1156,
"s": 1062,
"text": "Use the border-0 class in Bootstrap to eliminate all borders from an element as shown below −"
},
{
"code": null,
"e": 1213,
"s": 1156,
"text": "<div class=\"mystyle border border-0\">\n No border\n</div>"
},
{
"code": null,
"e": 1248,
"s": 1213,
"text": "We have also set CSS style above −"
},
{
"code": null,
"e": 1330,
"s": 1248,
"text": ".mystyle {\n width: 120px;\n height: 100px;\n margin: 10px;\n background: gray;\n}"
},
{
"code": null,
"e": 1402,
"s": 1330,
"text": "You can try to run the following code to implement the border-0 class −"
},
{
"code": null,
"e": 1412,
"s": 1402,
"text": "Live Demo"
},
{
"code": null,
"e": 2238,
"s": 1412,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\"> \n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n <style>\n .mystyle {\n width: 120px;\n height: 100px;\n margin: 10px;\n background: gray;\n }\n </style>\n </head>\n<body>\n <div class=\"container\">\n <h4>Two Rectangles</h4>\n <div class=\"mystyle border border-success\">orange border</div>\n <div class=\"mystyle border border-0\">No border</div>\n </div>\n</body>\n</html>"
}
] |
jQuery - eq( index ) Method
|
The eq( index ) method reduces the set of matched elements to a single element.
Here is the simple syntax to use this method −
selector.eq( index )
Here is the description of all the parameters used by this method −
index − This is the position of the element in the set of matched elements, starting at 0 and going to length - 1.
index − This is the position of the element in the set of matched elements, starting at 0 and going to length - 1.
Following is a simple example which adds the color to second list item.
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("li").eq(2).addClass("selected");
});
</script>
<style>
.selected { color:red; }
</style>
</head>
<body>
<div>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
<li>list item 6</li>
</ul>
</div>
</body>
</html>
This will produce following result −
list item 1
list item 2
list item 3
list item 4
list item 5
list item 6
Following is an example showing a simple usage of this method −
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("li").eq(2).addClass("selected");
});
</script>
<style>
.selected { color:red; }
</style>
</head>
<body>
<div>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li class = "selected">list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
<li>list item 6</li>
</ul>
</div>
</body>
</html>
This will produce following result −
list item 1
list item 2
list item 3
list item 4
list item 5
list item 6
27 Lectures
1 hours
Mahesh Kumar
27 Lectures
1.5 hours
Pratik Singh
72 Lectures
4.5 hours
Frahaan Hussain
60 Lectures
9 hours
Eduonix Learning Solutions
17 Lectures
2 hours
Sandip Bhattacharya
12 Lectures
53 mins
Laurence Svekis
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2402,
"s": 2322,
"text": "The eq( index ) method reduces the set of matched elements to a single element."
},
{
"code": null,
"e": 2449,
"s": 2402,
"text": "Here is the simple syntax to use this method −"
},
{
"code": null,
"e": 2471,
"s": 2449,
"text": "selector.eq( index )\n"
},
{
"code": null,
"e": 2539,
"s": 2471,
"text": "Here is the description of all the parameters used by this method −"
},
{
"code": null,
"e": 2654,
"s": 2539,
"text": "index − This is the position of the element in the set of matched elements, starting at 0 and going to length - 1."
},
{
"code": null,
"e": 2769,
"s": 2654,
"text": "index − This is the position of the element in the set of matched elements, starting at 0 and going to length - 1."
},
{
"code": null,
"e": 2841,
"s": 2769,
"text": "Following is a simple example which adds the color to second list item."
},
{
"code": null,
"e": 3581,
"s": 2841,
"text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"li\").eq(2).addClass(\"selected\");\n });\n </script>\n\t\t\n <style>\n .selected { color:red; }\n </style>\n </head>\n\t\n <body>\n <div>\n <ul>\n <li>list item 1</li>\n <li>list item 2</li>\n <li>list item 3</li>\n <li>list item 4</li>\n <li>list item 5</li>\n <li>list item 6</li>\n </ul>\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 3618,
"s": 3581,
"text": "This will produce following result −"
},
{
"code": null,
"e": 3630,
"s": 3618,
"text": "list item 1"
},
{
"code": null,
"e": 3642,
"s": 3630,
"text": "list item 2"
},
{
"code": null,
"e": 3654,
"s": 3642,
"text": "list item 3"
},
{
"code": null,
"e": 3666,
"s": 3654,
"text": "list item 4"
},
{
"code": null,
"e": 3678,
"s": 3666,
"text": "list item 5"
},
{
"code": null,
"e": 3690,
"s": 3678,
"text": "list item 6"
},
{
"code": null,
"e": 3754,
"s": 3690,
"text": "Following is an example showing a simple usage of this method −"
},
{
"code": null,
"e": 4513,
"s": 3754,
"text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"li\").eq(2).addClass(\"selected\");\n });\n </script>\n\t\t\n <style>\n .selected { color:red; }\n </style>\n </head>\n\t\n <body>\n <div>\n <ul>\n <li>list item 1</li>\n <li>list item 2</li>\n <li class = \"selected\">list item 3</li>\n <li>list item 4</li>\n <li>list item 5</li>\n <li>list item 6</li>\n </ul>\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 4550,
"s": 4513,
"text": "This will produce following result −"
},
{
"code": null,
"e": 4562,
"s": 4550,
"text": "list item 1"
},
{
"code": null,
"e": 4574,
"s": 4562,
"text": "list item 2"
},
{
"code": null,
"e": 4586,
"s": 4574,
"text": "list item 3"
},
{
"code": null,
"e": 4598,
"s": 4586,
"text": "list item 4"
},
{
"code": null,
"e": 4610,
"s": 4598,
"text": "list item 5"
},
{
"code": null,
"e": 4622,
"s": 4610,
"text": "list item 6"
},
{
"code": null,
"e": 4655,
"s": 4622,
"text": "\n 27 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4669,
"s": 4655,
"text": " Mahesh Kumar"
},
{
"code": null,
"e": 4704,
"s": 4669,
"text": "\n 27 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4718,
"s": 4704,
"text": " Pratik Singh"
},
{
"code": null,
"e": 4753,
"s": 4718,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4770,
"s": 4753,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4803,
"s": 4770,
"text": "\n 60 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 4831,
"s": 4803,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4864,
"s": 4831,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4885,
"s": 4864,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 4917,
"s": 4885,
"text": "\n 12 Lectures \n 53 mins\n"
},
{
"code": null,
"e": 4934,
"s": 4917,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 4941,
"s": 4934,
"text": " Print"
},
{
"code": null,
"e": 4952,
"s": 4941,
"text": " Add Notes"
}
] |
How to Differentiate Between Scaling, Normalization, and Log Transformations | by Bex T. | Towards Data Science
|
Learn the underlying difference between Standardization (Scaling), Normalization, and the Log transforms. Develop strong knowledge in when to apply each of them and choose one method over the other.
You have probably come across this in courses or articles:
The features in the dataset should conform to the statistical assumptions of the models.
What does it mean to conform to statistical assumptions? Many models implemented in Sklearn might perform poorly if the numeric features do not more or less follow a standard Gaussian (normal) distribution. Except for tree-based models, the objective function of Sklearn algorithms assumes the features follow a normal distribution.
Actually, using the word assume would be putting things lightly. For models like K-Nearest-Neighbors, feature transformation is a requirement for the algorithm to perform expectedly:
In practice, you may even face scenarios where feature transformations have an even larger effect than a 5% increase in performance.
There are many techniques you can apply to make your features more or less follow a normal distribution. They differ based on the underlying distributions of each feature.
This article will teach you about 3 such techniques: Scaling, normalization, and logarithmic transformers. You will develop a practical understanding of their differences and when to apply them in your own workflow.
Before applying any of the techniques you will be learning, it is important to explore each feature visually. You don’t have to create perfect plots; simple histograms and boxplots with default styles will be enough to identify distributions. Take a look at these histograms from the Diamonds dataset of Seaborn:
Pay close attention to the shape of the distributions and the ranges on the X-axes. From the subplots, we can see that price and carat features follow a skewed distribution. Depth, table, and x may remotely resemble a normal distribution.
Apart from the distributions, the range of values is also an important aspect of features. Boxplots are best at showing this using the 5-figure summary:
>>> diamonds.boxplot()
The above plot is enough to tell us that the features have very different scales. As diamond prices have a larger scale of values, they squished other boxplots into a line. Here is the 5-figure summary for further comparison:
>>> diamonds.describe().T.round(2)
Now that you learned how to identify the shape of the distributions and the difference of each feature’s scale, by the end of the article, we will have made all features have the same scale and more or less follow a normal distribution like so:
One of the default methods of solving situations where one feature has a much larger variance than others is using scaling (also called standardization):
According to the official Sklearn guide on scaling:
Many elements used in the objective function of a learning algorithm assume that all features are centered around zero and have variance in the same order. If a feature has a variance that is orders of magnitude larger than others, it might dominate the objective function and make the estimator unable to learn from other features correctly as expected.
So, to achieve high performances with many models, scaling is often required. Sklearn implements this in the StandardScaler() transformer. It transforms numerical features in the dataset to have a mean of 0 and a variance of 1.
SS accomplishes this by using two operations:
Centering: subtract the mean from each value in the distribution.Scaling: divide each result by the standard deviation.
Centering: subtract the mean from each value in the distribution.
Scaling: divide each result by the standard deviation.
The operations leave the original feature following a normal distribution. Here is how we would do this manually:
We are leaving out price and carat feature because they follow a skewed distribution. More on this later.
Let’s do the same with the StandardScaler():
The same results.
Checking the mean and variances:
Now, let’s pay attention to the effectiveness of the scaling. Depth and x now genuinely look like a Gaussian distribution. However, the features table, y, and z are still squished into the corner of their plots, suggesting the presence of outliers (otherwise, the bulk of the histograms would be in the center). This means the scaling worked better on the depth and x features but not on the others. We will make a note of this for the next sections.
When a feature does not follow a linear distribution, it would be unwise to use the mean and the standard deviation to scale it. For example, here is what would have happened if we scaled the skewed distributions of price and carat:
The fact that the features are still skewed confirms that standardization does not work on them.
To implement non-linear transformations, Sklearn offers a PowerTransformer class (uses logarithmic functions under the hood) that helps minimize skewness and map any distribution to a normal one as close as possible:
>>> diamonds[["carat", "price"]].var()carat 1.000019price 1.000019dtype: float64
The new features look much better than the old skewed ones. So, whenever faced with a skewed distribution, use the PowerTransformer class.
An alternative method to scaling is called normalization. Instead of using the variance and the mean, normalization uses the minimum and the maximum values of the distribution. The following equation is used for each value :
The effect of this transformation is to give the distribution an absolute minimum and a maximum value, usually between 0 and 1. Sklearn provides a similar MinMaxScaler transformer to implement this:
Even though it forces features to follow a normal distribution, the features won’t have unit variance and a mean of 0:
However, there are caveats to using this method. For example, if the maximum value in the training set is smaller than the maximum in the test set, the scaling may lead to unexpected results in predictions. The same is true for the minimum value.
Also, MinMaxScaler does not work well with features with outliers. I leave you to think about why (hint: pay attention to the formula of the MMScaler).
Besides, MinMaxScaler does not change the shape of the distribution at all. After normalization, the values lie within the given range, but the shape of the distribution remains unchanged.
Because of these reasons, StandardScaler is used more often.
In this section, we will try to predict the diamond cuts using a LogisticRegression algorithmm. We will be using the StandardScaler and PowerTransformer inside a pipeline. If you are not familiar with how Sklearn pipelines and ColumnTransformers work, check out this post:
towardsdatascience.com
Let’s get started. First, we will build the feature/target arrays and extract the names of the columns we will be applying the transformers:
Next, we will create a ColumnTransformer object which maps the transformers to the relevant columns:
We will plug this transformer into a Pipeline ending with a LogisticRegression:
Finally, we divide the data into training and test sets and measure the classifier’s performance:
We got a ROC AUC score of 0.83. At this point, you can start hyperparameter-tuning to improve on this.
Whenever you are doing preprocessing, always watch out for data leakage. Since all the transformers we learned today derive metrics from the underlying distributions of the features, it is easy for them to leak data from the test data.
That’s why it is advised to divide the data into train/test sets before doing any preprocessing. Also, never use the fit_transform() method on the test set. The transformers should all be fitted to the training data, and the subsequent transformations should only use transform method:
However, when using these transformers in pipelines, you don’t have to worry about this. Sklearn takes care of data leakage under the hood when fitting and transforming features.
In this article, you learned how to feature engineer your numeric features to conform to the statistical assumptions of many models. Specifically, we learned how to:
Scale data using StandardScaler, a transformer used when we want a feature to follow a normal distribution with mean 0 and unit variance. Used most often with distributions without too many outliers or other generally-shaped distributions.
Log transform data using PowerTransformer, a transformer used when we want a heavily skewed feature to be transformed into a normal distribution as close as possible.
Normalize data using MinMaxScaler, a transformer used when we want the feature values to lie within a certain min and max values. It doesn't work well with many outliers and prone to unexpected behaviors if values go out of the given range in the test set. It is a less popular alternative to scaling.
Sklearn Preprocessing Official Guide
How to Use Normal Distribution Like You Know What You Are Doing
How to think Probabilistically with Discrete Distributions
Logarithmic Scale in Data Science
Automatic Hyperparameter Tuning with Sklearn GridSearchCV and RandomizedSearchCV
11 Times Faster Hyperparameter Tuning with HalvingGridSearch
Intro to Object-Oriented Programming For Data Scientists
|
[
{
"code": null,
"e": 371,
"s": 172,
"text": "Learn the underlying difference between Standardization (Scaling), Normalization, and the Log transforms. Develop strong knowledge in when to apply each of them and choose one method over the other."
},
{
"code": null,
"e": 430,
"s": 371,
"text": "You have probably come across this in courses or articles:"
},
{
"code": null,
"e": 519,
"s": 430,
"text": "The features in the dataset should conform to the statistical assumptions of the models."
},
{
"code": null,
"e": 852,
"s": 519,
"text": "What does it mean to conform to statistical assumptions? Many models implemented in Sklearn might perform poorly if the numeric features do not more or less follow a standard Gaussian (normal) distribution. Except for tree-based models, the objective function of Sklearn algorithms assumes the features follow a normal distribution."
},
{
"code": null,
"e": 1035,
"s": 852,
"text": "Actually, using the word assume would be putting things lightly. For models like K-Nearest-Neighbors, feature transformation is a requirement for the algorithm to perform expectedly:"
},
{
"code": null,
"e": 1168,
"s": 1035,
"text": "In practice, you may even face scenarios where feature transformations have an even larger effect than a 5% increase in performance."
},
{
"code": null,
"e": 1340,
"s": 1168,
"text": "There are many techniques you can apply to make your features more or less follow a normal distribution. They differ based on the underlying distributions of each feature."
},
{
"code": null,
"e": 1556,
"s": 1340,
"text": "This article will teach you about 3 such techniques: Scaling, normalization, and logarithmic transformers. You will develop a practical understanding of their differences and when to apply them in your own workflow."
},
{
"code": null,
"e": 1869,
"s": 1556,
"text": "Before applying any of the techniques you will be learning, it is important to explore each feature visually. You don’t have to create perfect plots; simple histograms and boxplots with default styles will be enough to identify distributions. Take a look at these histograms from the Diamonds dataset of Seaborn:"
},
{
"code": null,
"e": 2108,
"s": 1869,
"text": "Pay close attention to the shape of the distributions and the ranges on the X-axes. From the subplots, we can see that price and carat features follow a skewed distribution. Depth, table, and x may remotely resemble a normal distribution."
},
{
"code": null,
"e": 2261,
"s": 2108,
"text": "Apart from the distributions, the range of values is also an important aspect of features. Boxplots are best at showing this using the 5-figure summary:"
},
{
"code": null,
"e": 2284,
"s": 2261,
"text": ">>> diamonds.boxplot()"
},
{
"code": null,
"e": 2510,
"s": 2284,
"text": "The above plot is enough to tell us that the features have very different scales. As diamond prices have a larger scale of values, they squished other boxplots into a line. Here is the 5-figure summary for further comparison:"
},
{
"code": null,
"e": 2545,
"s": 2510,
"text": ">>> diamonds.describe().T.round(2)"
},
{
"code": null,
"e": 2790,
"s": 2545,
"text": "Now that you learned how to identify the shape of the distributions and the difference of each feature’s scale, by the end of the article, we will have made all features have the same scale and more or less follow a normal distribution like so:"
},
{
"code": null,
"e": 2944,
"s": 2790,
"text": "One of the default methods of solving situations where one feature has a much larger variance than others is using scaling (also called standardization):"
},
{
"code": null,
"e": 2996,
"s": 2944,
"text": "According to the official Sklearn guide on scaling:"
},
{
"code": null,
"e": 3351,
"s": 2996,
"text": "Many elements used in the objective function of a learning algorithm assume that all features are centered around zero and have variance in the same order. If a feature has a variance that is orders of magnitude larger than others, it might dominate the objective function and make the estimator unable to learn from other features correctly as expected."
},
{
"code": null,
"e": 3579,
"s": 3351,
"text": "So, to achieve high performances with many models, scaling is often required. Sklearn implements this in the StandardScaler() transformer. It transforms numerical features in the dataset to have a mean of 0 and a variance of 1."
},
{
"code": null,
"e": 3625,
"s": 3579,
"text": "SS accomplishes this by using two operations:"
},
{
"code": null,
"e": 3745,
"s": 3625,
"text": "Centering: subtract the mean from each value in the distribution.Scaling: divide each result by the standard deviation."
},
{
"code": null,
"e": 3811,
"s": 3745,
"text": "Centering: subtract the mean from each value in the distribution."
},
{
"code": null,
"e": 3866,
"s": 3811,
"text": "Scaling: divide each result by the standard deviation."
},
{
"code": null,
"e": 3980,
"s": 3866,
"text": "The operations leave the original feature following a normal distribution. Here is how we would do this manually:"
},
{
"code": null,
"e": 4086,
"s": 3980,
"text": "We are leaving out price and carat feature because they follow a skewed distribution. More on this later."
},
{
"code": null,
"e": 4131,
"s": 4086,
"text": "Let’s do the same with the StandardScaler():"
},
{
"code": null,
"e": 4149,
"s": 4131,
"text": "The same results."
},
{
"code": null,
"e": 4182,
"s": 4149,
"text": "Checking the mean and variances:"
},
{
"code": null,
"e": 4633,
"s": 4182,
"text": "Now, let’s pay attention to the effectiveness of the scaling. Depth and x now genuinely look like a Gaussian distribution. However, the features table, y, and z are still squished into the corner of their plots, suggesting the presence of outliers (otherwise, the bulk of the histograms would be in the center). This means the scaling worked better on the depth and x features but not on the others. We will make a note of this for the next sections."
},
{
"code": null,
"e": 4866,
"s": 4633,
"text": "When a feature does not follow a linear distribution, it would be unwise to use the mean and the standard deviation to scale it. For example, here is what would have happened if we scaled the skewed distributions of price and carat:"
},
{
"code": null,
"e": 4963,
"s": 4866,
"text": "The fact that the features are still skewed confirms that standardization does not work on them."
},
{
"code": null,
"e": 5180,
"s": 4963,
"text": "To implement non-linear transformations, Sklearn offers a PowerTransformer class (uses logarithmic functions under the hood) that helps minimize skewness and map any distribution to a normal one as close as possible:"
},
{
"code": null,
"e": 5267,
"s": 5180,
"text": ">>> diamonds[[\"carat\", \"price\"]].var()carat 1.000019price 1.000019dtype: float64"
},
{
"code": null,
"e": 5406,
"s": 5267,
"text": "The new features look much better than the old skewed ones. So, whenever faced with a skewed distribution, use the PowerTransformer class."
},
{
"code": null,
"e": 5631,
"s": 5406,
"text": "An alternative method to scaling is called normalization. Instead of using the variance and the mean, normalization uses the minimum and the maximum values of the distribution. The following equation is used for each value :"
},
{
"code": null,
"e": 5830,
"s": 5631,
"text": "The effect of this transformation is to give the distribution an absolute minimum and a maximum value, usually between 0 and 1. Sklearn provides a similar MinMaxScaler transformer to implement this:"
},
{
"code": null,
"e": 5949,
"s": 5830,
"text": "Even though it forces features to follow a normal distribution, the features won’t have unit variance and a mean of 0:"
},
{
"code": null,
"e": 6196,
"s": 5949,
"text": "However, there are caveats to using this method. For example, if the maximum value in the training set is smaller than the maximum in the test set, the scaling may lead to unexpected results in predictions. The same is true for the minimum value."
},
{
"code": null,
"e": 6348,
"s": 6196,
"text": "Also, MinMaxScaler does not work well with features with outliers. I leave you to think about why (hint: pay attention to the formula of the MMScaler)."
},
{
"code": null,
"e": 6537,
"s": 6348,
"text": "Besides, MinMaxScaler does not change the shape of the distribution at all. After normalization, the values lie within the given range, but the shape of the distribution remains unchanged."
},
{
"code": null,
"e": 6598,
"s": 6537,
"text": "Because of these reasons, StandardScaler is used more often."
},
{
"code": null,
"e": 6871,
"s": 6598,
"text": "In this section, we will try to predict the diamond cuts using a LogisticRegression algorithmm. We will be using the StandardScaler and PowerTransformer inside a pipeline. If you are not familiar with how Sklearn pipelines and ColumnTransformers work, check out this post:"
},
{
"code": null,
"e": 6894,
"s": 6871,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 7035,
"s": 6894,
"text": "Let’s get started. First, we will build the feature/target arrays and extract the names of the columns we will be applying the transformers:"
},
{
"code": null,
"e": 7136,
"s": 7035,
"text": "Next, we will create a ColumnTransformer object which maps the transformers to the relevant columns:"
},
{
"code": null,
"e": 7216,
"s": 7136,
"text": "We will plug this transformer into a Pipeline ending with a LogisticRegression:"
},
{
"code": null,
"e": 7314,
"s": 7216,
"text": "Finally, we divide the data into training and test sets and measure the classifier’s performance:"
},
{
"code": null,
"e": 7417,
"s": 7314,
"text": "We got a ROC AUC score of 0.83. At this point, you can start hyperparameter-tuning to improve on this."
},
{
"code": null,
"e": 7653,
"s": 7417,
"text": "Whenever you are doing preprocessing, always watch out for data leakage. Since all the transformers we learned today derive metrics from the underlying distributions of the features, it is easy for them to leak data from the test data."
},
{
"code": null,
"e": 7939,
"s": 7653,
"text": "That’s why it is advised to divide the data into train/test sets before doing any preprocessing. Also, never use the fit_transform() method on the test set. The transformers should all be fitted to the training data, and the subsequent transformations should only use transform method:"
},
{
"code": null,
"e": 8118,
"s": 7939,
"text": "However, when using these transformers in pipelines, you don’t have to worry about this. Sklearn takes care of data leakage under the hood when fitting and transforming features."
},
{
"code": null,
"e": 8284,
"s": 8118,
"text": "In this article, you learned how to feature engineer your numeric features to conform to the statistical assumptions of many models. Specifically, we learned how to:"
},
{
"code": null,
"e": 8524,
"s": 8284,
"text": "Scale data using StandardScaler, a transformer used when we want a feature to follow a normal distribution with mean 0 and unit variance. Used most often with distributions without too many outliers or other generally-shaped distributions."
},
{
"code": null,
"e": 8691,
"s": 8524,
"text": "Log transform data using PowerTransformer, a transformer used when we want a heavily skewed feature to be transformed into a normal distribution as close as possible."
},
{
"code": null,
"e": 8993,
"s": 8691,
"text": "Normalize data using MinMaxScaler, a transformer used when we want the feature values to lie within a certain min and max values. It doesn't work well with many outliers and prone to unexpected behaviors if values go out of the given range in the test set. It is a less popular alternative to scaling."
},
{
"code": null,
"e": 9030,
"s": 8993,
"text": "Sklearn Preprocessing Official Guide"
},
{
"code": null,
"e": 9094,
"s": 9030,
"text": "How to Use Normal Distribution Like You Know What You Are Doing"
},
{
"code": null,
"e": 9153,
"s": 9094,
"text": "How to think Probabilistically with Discrete Distributions"
},
{
"code": null,
"e": 9187,
"s": 9153,
"text": "Logarithmic Scale in Data Science"
},
{
"code": null,
"e": 9268,
"s": 9187,
"text": "Automatic Hyperparameter Tuning with Sklearn GridSearchCV and RandomizedSearchCV"
},
{
"code": null,
"e": 9329,
"s": 9268,
"text": "11 Times Faster Hyperparameter Tuning with HalvingGridSearch"
}
] |
Add an element to specified index of ArrayList in Java
|
An element can be added to the specified index of an ArrayList by using the java.util.ArrayList.add() method. This method has two parameters i.e. the specific index at which to insert the element in the ArrayList and the element itself. If there is an element already present at the index specified by ArrayList.add() then that element and all subsequent elements shift to the right by one.
A program that demonstrates this is given as follows −
Live Demo
import java.util.ArrayList;
import java.util.List;
public class Demo {
public static void main(String args[]) throws Exception {
List aList = new ArrayList();
aList.add(0, "Dog");
aList.add(1, "Cat");
aList.add(2, "Horse");
aList.add(2, "Pig");
aList.add(3, "Cow");
System.out.println("The ArrayList elements are: " + aList);
}
}
The ArrayList elements are: [Dog, Cat, Pig, Cow, Horse]
Now let us understand the above program.
The ArrayList aList is created. Then ArrayList.add() is used to add the elements at the specified index in the ArrayList. Finally, the ArrayList is displayed. A code snippet which demonstrates this is as follows −
List aList = new ArrayList();
aList.add(0, "Dog");
aList.add(1, "Cat");
aList.add(2, "Horse");
aList.add(2, "Pig");
aList.add(3, "Cow");
System.out.println("The ArrayList elements are: " + aList);
|
[
{
"code": null,
"e": 1453,
"s": 1062,
"text": "An element can be added to the specified index of an ArrayList by using the java.util.ArrayList.add() method. This method has two parameters i.e. the specific index at which to insert the element in the ArrayList and the element itself. If there is an element already present at the index specified by ArrayList.add() then that element and all subsequent elements shift to the right by one."
},
{
"code": null,
"e": 1508,
"s": 1453,
"text": "A program that demonstrates this is given as follows −"
},
{
"code": null,
"e": 1519,
"s": 1508,
"text": " Live Demo"
},
{
"code": null,
"e": 1897,
"s": 1519,
"text": "import java.util.ArrayList;\nimport java.util.List;\npublic class Demo {\n public static void main(String args[]) throws Exception {\n List aList = new ArrayList();\n aList.add(0, \"Dog\");\n aList.add(1, \"Cat\");\n aList.add(2, \"Horse\");\n aList.add(2, \"Pig\");\n aList.add(3, \"Cow\");\n System.out.println(\"The ArrayList elements are: \" + aList);\n }\n}"
},
{
"code": null,
"e": 1953,
"s": 1897,
"text": "The ArrayList elements are: [Dog, Cat, Pig, Cow, Horse]"
},
{
"code": null,
"e": 1994,
"s": 1953,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 2208,
"s": 1994,
"text": "The ArrayList aList is created. Then ArrayList.add() is used to add the elements at the specified index in the ArrayList. Finally, the ArrayList is displayed. A code snippet which demonstrates this is as follows −"
},
{
"code": null,
"e": 2405,
"s": 2208,
"text": "List aList = new ArrayList();\naList.add(0, \"Dog\");\naList.add(1, \"Cat\");\naList.add(2, \"Horse\");\naList.add(2, \"Pig\");\naList.add(3, \"Cow\");\nSystem.out.println(\"The ArrayList elements are: \" + aList);"
}
] |
Positive and negative elements | Practice | GeeksforGeeks
|
Given an array arr[ ] containing equal number of positive and negative elements, arrange the array such that every positive element is followed by a negative element.
Note- The relative order of positive and negative numbers should be maintained.
Example 1:
Input:
N = 6
arr[] = {-1, 2, -3, 4, -5, 6}
Output:
2 -1 4 -3 6 -5
Explanation: Positive numbers in order
are 2, 4 and 6. Negative numbers in order
are -1, -3 and -5. So the arrangement we
get is 2, -1, 4, -3, 6 and -5.
Example 2:
Input:
N = 4
arr[] = {-3, 2, -4, 1}
Output:
2 -3 1 -4
Your Task:
This is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function arranged() that takes array arr[ ] and its size integer N as parameters and returns the required array.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ N ≤ 106
1 ≤ arr[i] ≤ 109
0
mayank20212 weeks ago
C++ : 0.28/1.6 vector<int> arranged(int a[],int n) { vector<int> vec; int b[n], i=0, j=n-1; for(int k=0; k<n ; k++) { if(a[k] >0) b[i++]=a[k]; else b[j--]=a[k]; } i=0, j=n-1; while(i<j) { vec.push_back(b[i++]); vec.push_back(b[j--]); } return vec; }
0
arvind16yadav4 weeks ago
/*JAVA SOLUTION*/
class Solution{ ArrayList<Long> arranged(long a[], int n) { long b[] = new long[n]; int positive_counter = 0; int negative_counter = 1; for(long x: a){ if(x >= 0){ b[positive_counter] = x; positive_counter += 2; } else{ b[negative_counter] = x; negative_counter += 2; } } ArrayList<Long> ans = new ArrayList<>(); for(long y : b){ ans.add(y); } return ans;
}}
0
priyaranjandash1 month ago
class Solution{ ArrayList<Long> arranged(long a[], int n) { ArrayList<Long> list = new ArrayList<Long>(n); ArrayList<Long> positive = new ArrayList<Long>(n/2); ArrayList<Long> negative = new ArrayList<Long>(n/2);// long negative[] = new long[n/2];// long positive[] = new long[n/2]; for(int i=0;i<n;i++){ if(a[i] > 0) positive.add(a[i]); else negative.add(a[i]); } for(int i=0, j=0;i<n/2 && j<n/2;i++,j++){ list.add(positive.get(i)); list.add(negative.get(j)); } return list;
}}
+1
hasnainraza1998hr1 month ago
vector<int> arranged(int a[],int n) { vector<int> v(n); for(int i=0,pIndex=0,nIndex=1;i<n;i++){ if(a[i]>0){ v[pIndex]=a[i]; pIndex += 2; } else{ v[nIndex]=a[i]; nIndex += 2; } } return v; }
0
coderaky2 months ago
coderaky.com
vector<int> arranged(int a[],int n) { vector<int>res(n,0); for(int i=0,e=0,o=1;i<n;i++){ if(a[i]>0)res[e]=a[i],e+=2; else res[o]=a[i],o+=2; } return res; }
0
dangrio2 months ago
vector<int> arranged(int a[],int n) { vector<int> vec(n); int ind = 0; for(int i=0;i<n;i++){ if(a[i]>0){ vec[ind] = a[i]; ind += 2; } } ind = 1; for(int j=0;j<n;j++){ if(a[j]<0){ vec[ind] = a[j]; ind += 2; } } return vec; }
0
codersheaven693 months ago
Python Solution
positive =[] negative = [] new_array = [] for i in range(n): if a[i] >= 0: positive.append(a[i]) # return positive else: negative.append(a[i]) # return negative # print(positive) # print(negative) for i in range(n//2): new_array.append(positive[i]) new_array.append(negative[i]) return new_array
0
abhishekworld4 months ago
vector<int> arranged(int arr[],int n) { vector<int> output; bool flag = true; int i = 0; int j = 0; while(i<n || j<n){ if(flag){ if(arr[i]>0){ output.push_back(arr[i]); flag = false; } i++; } else{ if(arr[j]<0){ output.push_back(arr[j]); flag = true; } j++; } } return output; }
+1
sr52465796 months ago
class Solution: def arranged(self,a,n): #Code here neg = [] pos = [] for i in a: if i<0: neg.append(i) else: pos.append(i) s=[] for i in range(n//2): s.append(pos[i]) s.append(neg[i]) return s
+2
badgujarsachin836 months ago
vector<int> arranged(int a[],int n)
{
vector<int> aa,b,c;
for(int i=0;i<n;i++){
if(a[i]<0){
aa.push_back(a[i]);
}
if(a[i]>0){
b.push_back(a[i]);
}
}
for(int i=0;i<n;i++){
c.push_back(b[i]);
c.push_back(aa[i]);
}
return c;
}
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": 473,
"s": 226,
"text": "Given an array arr[ ] containing equal number of positive and negative elements, arrange the array such that every positive element is followed by a negative element.\nNote- The relative order of positive and negative numbers should be maintained."
},
{
"code": null,
"e": 484,
"s": 473,
"text": "Example 1:"
},
{
"code": null,
"e": 709,
"s": 484,
"text": "Input:\nN = 6\narr[] = {-1, 2, -3, 4, -5, 6}\nOutput: \n2 -1 4 -3 6 -5\nExplanation: Positive numbers in order \nare 2, 4 and 6. Negative numbers in order \nare -1, -3 and -5. So the arrangement we \nget is 2, -1, 4, -3, 6 and -5.\n"
},
{
"code": null,
"e": 720,
"s": 709,
"text": "Example 2:"
},
{
"code": null,
"e": 778,
"s": 720,
"text": "Input:\nN = 4\narr[] = {-3, 2, -4, 1}\nOutput: \n2 -3 1 -4 \n"
},
{
"code": null,
"e": 1044,
"s": 778,
"text": "Your Task:\nThis is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function arranged() that takes array arr[ ] and its size integer N as parameters and returns the required array."
},
{
"code": null,
"e": 1106,
"s": 1044,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)"
},
{
"code": null,
"e": 1148,
"s": 1106,
"text": "Constraints:\n1 ≤ N ≤ 106\n1 ≤ arr[i] ≤ 109"
},
{
"code": null,
"e": 1150,
"s": 1148,
"text": "0"
},
{
"code": null,
"e": 1172,
"s": 1150,
"text": "mayank20212 weeks ago"
},
{
"code": null,
"e": 1560,
"s": 1172,
"text": "C++ : 0.28/1.6 vector<int> arranged(int a[],int n) { vector<int> vec; int b[n], i=0, j=n-1; for(int k=0; k<n ; k++) { if(a[k] >0) b[i++]=a[k]; else b[j--]=a[k]; } i=0, j=n-1; while(i<j) { vec.push_back(b[i++]); vec.push_back(b[j--]); } return vec; }"
},
{
"code": null,
"e": 1562,
"s": 1560,
"text": "0"
},
{
"code": null,
"e": 1587,
"s": 1562,
"text": "arvind16yadav4 weeks ago"
},
{
"code": null,
"e": 1605,
"s": 1587,
"text": "/*JAVA SOLUTION*/"
},
{
"code": null,
"e": 2161,
"s": 1605,
"text": "class Solution{ ArrayList<Long> arranged(long a[], int n) { long b[] = new long[n]; int positive_counter = 0; int negative_counter = 1; for(long x: a){ if(x >= 0){ b[positive_counter] = x; positive_counter += 2; } else{ b[negative_counter] = x; negative_counter += 2; } } ArrayList<Long> ans = new ArrayList<>(); for(long y : b){ ans.add(y); } return ans; "
},
{
"code": null,
"e": 2168,
"s": 2161,
"text": " }} "
},
{
"code": null,
"e": 2170,
"s": 2168,
"text": "0"
},
{
"code": null,
"e": 2197,
"s": 2170,
"text": "priyaranjandash1 month ago"
},
{
"code": null,
"e": 2831,
"s": 2197,
"text": "class Solution{ ArrayList<Long> arranged(long a[], int n) { ArrayList<Long> list = new ArrayList<Long>(n); ArrayList<Long> positive = new ArrayList<Long>(n/2); ArrayList<Long> negative = new ArrayList<Long>(n/2);// long negative[] = new long[n/2];// long positive[] = new long[n/2]; for(int i=0;i<n;i++){ if(a[i] > 0) positive.add(a[i]); else negative.add(a[i]); } for(int i=0, j=0;i<n/2 && j<n/2;i++,j++){ list.add(positive.get(i)); list.add(negative.get(j)); } return list;"
},
{
"code": null,
"e": 2837,
"s": 2831,
"text": " }}"
},
{
"code": null,
"e": 2840,
"s": 2837,
"text": "+1"
},
{
"code": null,
"e": 2869,
"s": 2840,
"text": "hasnainraza1998hr1 month ago"
},
{
"code": null,
"e": 3183,
"s": 2869,
"text": "vector<int> arranged(int a[],int n) { vector<int> v(n); for(int i=0,pIndex=0,nIndex=1;i<n;i++){ if(a[i]>0){ v[pIndex]=a[i]; pIndex += 2; } else{ v[nIndex]=a[i]; nIndex += 2; } } return v; }"
},
{
"code": null,
"e": 3185,
"s": 3183,
"text": "0"
},
{
"code": null,
"e": 3206,
"s": 3185,
"text": "coderaky2 months ago"
},
{
"code": null,
"e": 3219,
"s": 3206,
"text": "coderaky.com"
},
{
"code": null,
"e": 3423,
"s": 3219,
"text": "vector<int> arranged(int a[],int n) { vector<int>res(n,0); for(int i=0,e=0,o=1;i<n;i++){ if(a[i]>0)res[e]=a[i],e+=2; else res[o]=a[i],o+=2; } return res; }"
},
{
"code": null,
"e": 3425,
"s": 3423,
"text": "0"
},
{
"code": null,
"e": 3445,
"s": 3425,
"text": "dangrio2 months ago"
},
{
"code": null,
"e": 3817,
"s": 3445,
"text": "vector<int> arranged(int a[],int n) { vector<int> vec(n); int ind = 0; for(int i=0;i<n;i++){ if(a[i]>0){ vec[ind] = a[i]; ind += 2; } } ind = 1; for(int j=0;j<n;j++){ if(a[j]<0){ vec[ind] = a[j]; ind += 2; } } return vec; }"
},
{
"code": null,
"e": 3819,
"s": 3817,
"text": "0"
},
{
"code": null,
"e": 3846,
"s": 3819,
"text": "codersheaven693 months ago"
},
{
"code": null,
"e": 3862,
"s": 3846,
"text": "Python Solution"
},
{
"code": null,
"e": 4313,
"s": 3864,
"text": " positive =[] negative = [] new_array = [] for i in range(n): if a[i] >= 0: positive.append(a[i]) # return positive else: negative.append(a[i]) # return negative # print(positive) # print(negative) for i in range(n//2): new_array.append(positive[i]) new_array.append(negative[i]) return new_array"
},
{
"code": null,
"e": 4315,
"s": 4313,
"text": "0"
},
{
"code": null,
"e": 4341,
"s": 4315,
"text": "abhishekworld4 months ago"
},
{
"code": null,
"e": 5021,
"s": 4341,
"text": "vector<int> arranged(int arr[],int n) { vector<int> output; bool flag = true; int i = 0; int j = 0; while(i<n || j<n){ if(flag){ if(arr[i]>0){ output.push_back(arr[i]); flag = false; } i++; } else{ if(arr[j]<0){ output.push_back(arr[j]); flag = true; } j++; } } return output; }"
},
{
"code": null,
"e": 5024,
"s": 5021,
"text": "+1"
},
{
"code": null,
"e": 5046,
"s": 5024,
"text": "sr52465796 months ago"
},
{
"code": null,
"e": 5351,
"s": 5046,
"text": "class Solution: def arranged(self,a,n): #Code here neg = [] pos = [] for i in a: if i<0: neg.append(i) else: pos.append(i) s=[] for i in range(n//2): s.append(pos[i]) s.append(neg[i]) return s"
},
{
"code": null,
"e": 5354,
"s": 5351,
"text": "+2"
},
{
"code": null,
"e": 5383,
"s": 5354,
"text": "badgujarsachin836 months ago"
},
{
"code": null,
"e": 5768,
"s": 5383,
"text": " vector<int> arranged(int a[],int n)\n {\n vector<int> aa,b,c;\n for(int i=0;i<n;i++){\n if(a[i]<0){\n aa.push_back(a[i]);\n }\n if(a[i]>0){\n b.push_back(a[i]);\n }\n }\n for(int i=0;i<n;i++){\n c.push_back(b[i]);\n c.push_back(aa[i]);\n }\n return c;\n }"
},
{
"code": null,
"e": 5914,
"s": 5768,
"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": 5950,
"s": 5914,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5960,
"s": 5950,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5970,
"s": 5960,
"text": "\nContest\n"
},
{
"code": null,
"e": 6033,
"s": 5970,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6181,
"s": 6033,
"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": 6389,
"s": 6181,
"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": 6495,
"s": 6389,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
MySQL Tutorial
|
MySQL is a widely used relational database management system (RDBMS).
MySQL is free and open-source.
MySQL is ideal for both small and large applications.
With our online MySQL editor, you can edit the SQL statements, and click on a button to view the result.
Click on the "Try it Yourself" button to see how it works.
Insert the missing statement to get all the columns from the Customers table.
* FROM Customers;
Start the Exercise
Learn by examples! This tutorial supplements all explanations with clarifying examples.
See All SQL Examples
Test your MySQL skills at W3Schools!
Start MySQL Quiz!
At W3Schools you will find a complete reference of MySQL data types and functions:
MySQL Data Types
MySQL Functions
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 70,
"s": 0,
"text": "MySQL is a widely used relational database management system (RDBMS)."
},
{
"code": null,
"e": 101,
"s": 70,
"text": "MySQL is free and open-source."
},
{
"code": null,
"e": 155,
"s": 101,
"text": "MySQL is ideal for both small and large applications."
},
{
"code": null,
"e": 260,
"s": 155,
"text": "With our online MySQL editor, you can edit the SQL statements, and click on a button to view the result."
},
{
"code": null,
"e": 319,
"s": 260,
"text": "Click on the \"Try it Yourself\" button to see how it works."
},
{
"code": null,
"e": 397,
"s": 319,
"text": "Insert the missing statement to get all the columns from the Customers table."
},
{
"code": null,
"e": 417,
"s": 397,
"text": " * FROM Customers;\n"
},
{
"code": null,
"e": 436,
"s": 417,
"text": "Start the Exercise"
},
{
"code": null,
"e": 524,
"s": 436,
"text": "Learn by examples! This tutorial supplements all explanations with clarifying examples."
},
{
"code": null,
"e": 545,
"s": 524,
"text": "See All SQL Examples"
},
{
"code": null,
"e": 582,
"s": 545,
"text": "Test your MySQL skills at W3Schools!"
},
{
"code": null,
"e": 600,
"s": 582,
"text": "Start MySQL Quiz!"
},
{
"code": null,
"e": 683,
"s": 600,
"text": "At W3Schools you will find a complete reference of MySQL data types and functions:"
},
{
"code": null,
"e": 700,
"s": 683,
"text": "MySQL Data Types"
},
{
"code": null,
"e": 716,
"s": 700,
"text": "MySQL Functions"
},
{
"code": null,
"e": 749,
"s": 716,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 791,
"s": 749,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 898,
"s": 791,
"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": 917,
"s": 898,
"text": "help@w3schools.com"
}
] |
Checking for Null or Empty in Java.
|
We can check whether a particular String is empty or not, using isBlank() method of the StringUtils class. This method accepts an integer as a parameter and returns true if the given string is empty, or false if it is not.
Live Demo
import org.apache.commons.lang3.StringUtils;
public class Sample {
public static void main(String args[]) {
String str = "";
Boolean bool = StringUtils.isBlank(str);
System.out.println(bool);
}
}
true
|
[
{
"code": null,
"e": 1285,
"s": 1062,
"text": "We can check whether a particular String is empty or not, using isBlank() method of the StringUtils class. This method accepts an integer as a parameter and returns true if the given string is empty, or false if it is not."
},
{
"code": null,
"e": 1296,
"s": 1285,
"text": " Live Demo"
},
{
"code": null,
"e": 1517,
"s": 1296,
"text": "import org.apache.commons.lang3.StringUtils;\n\npublic class Sample {\n public static void main(String args[]) {\n String str = \"\";\n Boolean bool = StringUtils.isBlank(str);\n System.out.println(bool);\n }\n}"
},
{
"code": null,
"e": 1523,
"s": 1517,
"text": "true\n"
}
] |
PyTorch – torchvision.transforms – RandomVerticalFlip()
|
We apply RandomVerticalFlip() transform to flip an image vertically at a random angle with a given probability. It's one of the transforms provided by the torchvision.transforms module. This module contains many important transformations that can be used to perform different types of manipulations on the image data.
RandomVerticalFlip() accepts both PIL and tensor images. A tensor image is a torch Tensor with shape [C, H, W], where C is the number of channels, H is the image height, and W is the image width.
torchvision.transforms.RandomVerticalFlip(p)(img)
If p = 1, it returns the vertically flipped image.
If p = 1, it returns the vertically flipped image.
If p = 0, It returns the original image.
If p = 0, It returns the original image.
If p is in the range (0,1), then the probability to return the vertically flipped image is p.
If p is in the range (0,1), then the probability to return the vertically flipped image is p.
It returns a vertically flipped image at a random angle with a given probability p.
One could follow the steps given below to vertically flip an image at a random angle with a given probability −
Import the required libraries. In all the following examples, the required Python libraries are torch, Pillow, and torchvision. Make sure you have already installed them
Import the required libraries. In all the following examples, the required Python libraries are torch, Pillow, and torchvision. Make sure you have already installed them
import torch
import torchvision
import torchvision.transforms as T
from PIL import Image
Read the input image. The input image is a PIL image or a tensor image.
Read the input image. The input image is a PIL image or a tensor image.
img = Image.open('mountain.jpg')
Define a transform to vertically flip the image randomly with a given probability p. Here p = 0.25 means, the chance of any input image to be vertically flipped is 25%.
Define a transform to vertically flip the image randomly with a given probability p. Here p = 0.25 means, the chance of any input image to be vertically flipped is 25%.
transform = T.RandomVerticalFlip(p = 0.25)
Apply the above defined transform on the input image to vertically flip the image.
Apply the above defined transform on the input image to vertically flip the image.
vflipped_img = transform(img)
Show the output image.
Show the output image.
vflipped_img.show()
This image is used as the input file in all the following examples.
In this program, we set p=1, so the output image will be vertically flipped image.
# import the required libraries
import torch
import torchvision.transforms as T
from PIL import Image
# read the input image
img = Image.open('mountain.jpg')
# define a transform with probability = 1
# to vertically flip an image
transform = T.RandomVerticalFlip(p=1)
# apply the transform on input image
img = transform(img)
# display the flipped image
img.show()
It will produce the following output −
Notice that the output image is a vertically flipped image, as we set the probability p=1.
In this example, we set the probability p=0.25, so the chance of any image to be vertically flipped is 25%.
import torch
import torchvision.transforms as T
from PIL import Image
import matplotlib.pyplot as plt
# read the input image
img = Image.open('mountain.jpg')
# define a transform with probability = 0.25
transform = T.RandomVerticalFlip(p=0.25)
# save four output images applying the above transform
imgs = [transform(img) for _ in range(4)]
# display these four output images
fig = plt.figure(figsize=(7,4))
rows, cols = 2,2
for j in range(0, len(imgs)):
fig.add_subplot(rows, cols, j+1)
plt.imshow(imgs[j])
plt.xticks([])
plt.yticks([])
plt.show()
It will produce the following output −
Notice that out of the four output images, at least one image is vertically flipped. You may get different number of vertically flipped images.
|
[
{
"code": null,
"e": 1380,
"s": 1062,
"text": "We apply RandomVerticalFlip() transform to flip an image vertically at a random angle with a given probability. It's one of the transforms provided by the torchvision.transforms module. This module contains many important transformations that can be used to perform different types of manipulations on the image data."
},
{
"code": null,
"e": 1576,
"s": 1380,
"text": "RandomVerticalFlip() accepts both PIL and tensor images. A tensor image is a torch Tensor with shape [C, H, W], where C is the number of channels, H is the image height, and W is the image width."
},
{
"code": null,
"e": 1626,
"s": 1576,
"text": "torchvision.transforms.RandomVerticalFlip(p)(img)"
},
{
"code": null,
"e": 1677,
"s": 1626,
"text": "If p = 1, it returns the vertically flipped image."
},
{
"code": null,
"e": 1728,
"s": 1677,
"text": "If p = 1, it returns the vertically flipped image."
},
{
"code": null,
"e": 1769,
"s": 1728,
"text": "If p = 0, It returns the original image."
},
{
"code": null,
"e": 1810,
"s": 1769,
"text": "If p = 0, It returns the original image."
},
{
"code": null,
"e": 1904,
"s": 1810,
"text": "If p is in the range (0,1), then the probability to return the vertically flipped image is p."
},
{
"code": null,
"e": 1998,
"s": 1904,
"text": "If p is in the range (0,1), then the probability to return the vertically flipped image is p."
},
{
"code": null,
"e": 2082,
"s": 1998,
"text": "It returns a vertically flipped image at a random angle with a given probability p."
},
{
"code": null,
"e": 2194,
"s": 2082,
"text": "One could follow the steps given below to vertically flip an image at a random angle with a given probability −"
},
{
"code": null,
"e": 2364,
"s": 2194,
"text": "Import the required libraries. In all the following examples, the required Python libraries are torch, Pillow, and torchvision. Make sure you have already installed them"
},
{
"code": null,
"e": 2534,
"s": 2364,
"text": "Import the required libraries. In all the following examples, the required Python libraries are torch, Pillow, and torchvision. Make sure you have already installed them"
},
{
"code": null,
"e": 2623,
"s": 2534,
"text": "import torch\nimport torchvision\nimport torchvision.transforms as T\nfrom PIL import Image"
},
{
"code": null,
"e": 2695,
"s": 2623,
"text": "Read the input image. The input image is a PIL image or a tensor image."
},
{
"code": null,
"e": 2767,
"s": 2695,
"text": "Read the input image. The input image is a PIL image or a tensor image."
},
{
"code": null,
"e": 2800,
"s": 2767,
"text": "img = Image.open('mountain.jpg')"
},
{
"code": null,
"e": 2969,
"s": 2800,
"text": "Define a transform to vertically flip the image randomly with a given probability p. Here p = 0.25 means, the chance of any input image to be vertically flipped is 25%."
},
{
"code": null,
"e": 3138,
"s": 2969,
"text": "Define a transform to vertically flip the image randomly with a given probability p. Here p = 0.25 means, the chance of any input image to be vertically flipped is 25%."
},
{
"code": null,
"e": 3181,
"s": 3138,
"text": "transform = T.RandomVerticalFlip(p = 0.25)"
},
{
"code": null,
"e": 3264,
"s": 3181,
"text": "Apply the above defined transform on the input image to vertically flip the image."
},
{
"code": null,
"e": 3347,
"s": 3264,
"text": "Apply the above defined transform on the input image to vertically flip the image."
},
{
"code": null,
"e": 3377,
"s": 3347,
"text": "vflipped_img = transform(img)"
},
{
"code": null,
"e": 3400,
"s": 3377,
"text": "Show the output image."
},
{
"code": null,
"e": 3423,
"s": 3400,
"text": "Show the output image."
},
{
"code": null,
"e": 3443,
"s": 3423,
"text": "vflipped_img.show()"
},
{
"code": null,
"e": 3511,
"s": 3443,
"text": "This image is used as the input file in all the following examples."
},
{
"code": null,
"e": 3594,
"s": 3511,
"text": "In this program, we set p=1, so the output image will be vertically flipped image."
},
{
"code": null,
"e": 3963,
"s": 3594,
"text": "# import the required libraries\nimport torch\nimport torchvision.transforms as T\nfrom PIL import Image\n\n# read the input image\nimg = Image.open('mountain.jpg')\n\n# define a transform with probability = 1\n# to vertically flip an image\ntransform = T.RandomVerticalFlip(p=1)\n\n# apply the transform on input image\nimg = transform(img)\n\n# display the flipped image\nimg.show()"
},
{
"code": null,
"e": 4002,
"s": 3963,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 4093,
"s": 4002,
"text": "Notice that the output image is a vertically flipped image, as we set the probability p=1."
},
{
"code": null,
"e": 4201,
"s": 4093,
"text": "In this example, we set the probability p=0.25, so the chance of any image to be vertically flipped is 25%."
},
{
"code": null,
"e": 4766,
"s": 4201,
"text": "import torch\nimport torchvision.transforms as T\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\n# read the input image\nimg = Image.open('mountain.jpg')\n\n# define a transform with probability = 0.25\ntransform = T.RandomVerticalFlip(p=0.25)\n\n# save four output images applying the above transform\nimgs = [transform(img) for _ in range(4)]\n\n# display these four output images\nfig = plt.figure(figsize=(7,4))\nrows, cols = 2,2\nfor j in range(0, len(imgs)):\n fig.add_subplot(rows, cols, j+1)\n plt.imshow(imgs[j])\n plt.xticks([])\n plt.yticks([])\nplt.show()"
},
{
"code": null,
"e": 4805,
"s": 4766,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 4949,
"s": 4805,
"text": "Notice that out of the four output images, at least one image is vertically flipped. You may get different number of vertically flipped images."
}
] |
Add MD5 hash value to MongoDB collection?
|
To add MD5 hash value, use hex_md5(). Let us first create a collection with documents −
>db.addMd5HashValueDemo.insertOne({"UserName":"Adam","UserPassword":"Adam123456"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd6a4c66d78f205348bc619")
}
>db.addMd5HashValueDemo.insertOne({"UserName":"Chris","UserPassword":"Chris_121#"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd6a4e46d78f205348bc61a")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.addMd5HashValueDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5cd6a4c66d78f205348bc619"), "UserName" : "Adam", "UserPassword" : "Adam123456" }
{ "_id" : ObjectId("5cd6a4e46d78f205348bc61a"), "UserName" : "Chris", "UserPassword" : "Chris_121#" }
Following is the query to add md5 hash value to mongo collection −
> db.addMd5HashValueDemo.find().forEach( function(documentPass){
documentPass.Value = hex_md5(documentPass.UserPassword);
db.addMd5HashValueDemo.save(documentPass);
});
Let us check the document once again −
> db.addMd5HashValueDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5cd6a4c66d78f205348bc619"), "UserName" : "Adam", "UserPassword" : "Adam123456", "Value" : "6523857c2bf79b63fd5fa0322575f7be" }
{ "_id" : ObjectId("5cd6a4e46d78f205348bc61a"), "UserName" : "Chris", "UserPassword" : "Chris_121#", "Value" : "3391ccbe33624258cafa23aa50301615" }
|
[
{
"code": null,
"e": 1150,
"s": 1062,
"text": "To add MD5 hash value, use hex_md5(). Let us first create a collection with documents −"
},
{
"code": null,
"e": 1489,
"s": 1150,
"text": ">db.addMd5HashValueDemo.insertOne({\"UserName\":\"Adam\",\"UserPassword\":\"Adam123456\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd6a4c66d78f205348bc619\")\n}\n>db.addMd5HashValueDemo.insertOne({\"UserName\":\"Chris\",\"UserPassword\":\"Chris_121#\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd6a4e46d78f205348bc61a\")\n}"
},
{
"code": null,
"e": 1588,
"s": 1489,
"text": "Following is the query to display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1621,
"s": 1588,
"text": "> db.addMd5HashValueDemo.find();"
},
{
"code": null,
"e": 1662,
"s": 1621,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1865,
"s": 1662,
"text": "{ \"_id\" : ObjectId(\"5cd6a4c66d78f205348bc619\"), \"UserName\" : \"Adam\", \"UserPassword\" : \"Adam123456\" }\n{ \"_id\" : ObjectId(\"5cd6a4e46d78f205348bc61a\"), \"UserName\" : \"Chris\", \"UserPassword\" : \"Chris_121#\" }"
},
{
"code": null,
"e": 1932,
"s": 1865,
"text": "Following is the query to add md5 hash value to mongo collection −"
},
{
"code": null,
"e": 2107,
"s": 1932,
"text": "> db.addMd5HashValueDemo.find().forEach( function(documentPass){\n documentPass.Value = hex_md5(documentPass.UserPassword);\n db.addMd5HashValueDemo.save(documentPass);\n});"
},
{
"code": null,
"e": 2146,
"s": 2107,
"text": "Let us check the document once again −"
},
{
"code": null,
"e": 2179,
"s": 2146,
"text": "> db.addMd5HashValueDemo.find();"
},
{
"code": null,
"e": 2220,
"s": 2179,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2516,
"s": 2220,
"text": "{ \"_id\" : ObjectId(\"5cd6a4c66d78f205348bc619\"), \"UserName\" : \"Adam\", \"UserPassword\" : \"Adam123456\", \"Value\" : \"6523857c2bf79b63fd5fa0322575f7be\" }\n\n{ \"_id\" : ObjectId(\"5cd6a4e46d78f205348bc61a\"), \"UserName\" : \"Chris\", \"UserPassword\" : \"Chris_121#\", \"Value\" : \"3391ccbe33624258cafa23aa50301615\" }"
}
] |
Why can I throw null in Java and why does it upcast to a NullPointerException?
|
In Java there is default value for every type, when you don’t initialize the instance variables of a class Java compiler initializes them on your be-half with these values. Null is the default value of the object type, you can also manually assign null to objects in a method.
Object obj = null;
But, you cannot use an object with null value or (a null value instead of an object) if you do so, a NullPointerException will be thrown.
public class Demo {
String name = "Krishna";
int age = 25;
public static void main(String args[]) {
Demo obj = null;
System.out.println(obj.age);
System.out.println(obj.name);
}
}
Exception in thread "main" java.lang.NullPointerException
at july_set3.Demo.main(Demo.java:11)
You can also throw a NullPointerException in Java using the throw keyword.
public class ExceptionExample {
public static void main(String[] args) {
System.out.println("Hello");
NullPointerException nullPointer = new NullPointerException();
throw nullPointer;
}
}
Hello
Exception in thread "main" java.lang.NullPointerException
at MyPackage.ExceptionExample.main(ExceptionExample.java:6
According to Java documentation a NullPointerException occurs if you try to −
Call the a method (instance) using null object.
Access, modify, print, field of a null value (object).
Trying to access (print/use in statements) the length of null value.
Throw a null value.
Accessing or modifying elements/slots of a null value.
Means if you throw a null value a null pointer exception occurs it is not up casting.
public class Demo {
public static void main(String args[]) {
throw null;
}
}
Exception in thread "main" java.lang.NullPointerException
at july_set3.Demo.main(Demo.java:5)
|
[
{
"code": null,
"e": 1339,
"s": 1062,
"text": "In Java there is default value for every type, when you don’t initialize the instance variables of a class Java compiler initializes them on your be-half with these values. Null is the default value of the object type, you can also manually assign null to objects in a method."
},
{
"code": null,
"e": 1358,
"s": 1339,
"text": "Object obj = null;"
},
{
"code": null,
"e": 1496,
"s": 1358,
"text": "But, you cannot use an object with null value or (a null value instead of an object) if you do so, a NullPointerException will be thrown."
},
{
"code": null,
"e": 1706,
"s": 1496,
"text": "public class Demo {\n String name = \"Krishna\";\n int age = 25;\n public static void main(String args[]) {\n Demo obj = null;\n System.out.println(obj.age);\n System.out.println(obj.name);\n }\n}"
},
{
"code": null,
"e": 1804,
"s": 1706,
"text": "Exception in thread \"main\" java.lang.NullPointerException\n at july_set3.Demo.main(Demo.java:11)"
},
{
"code": null,
"e": 1879,
"s": 1804,
"text": "You can also throw a NullPointerException in Java using the throw keyword."
},
{
"code": null,
"e": 2091,
"s": 1879,
"text": "public class ExceptionExample {\n public static void main(String[] args) {\n System.out.println(\"Hello\");\n NullPointerException nullPointer = new NullPointerException();\n throw nullPointer;\n }\n}"
},
{
"code": null,
"e": 2217,
"s": 2091,
"text": "Hello\nException in thread \"main\" java.lang.NullPointerException\n at MyPackage.ExceptionExample.main(ExceptionExample.java:6"
},
{
"code": null,
"e": 2295,
"s": 2217,
"text": "According to Java documentation a NullPointerException occurs if you try to −"
},
{
"code": null,
"e": 2343,
"s": 2295,
"text": "Call the a method (instance) using null object."
},
{
"code": null,
"e": 2398,
"s": 2343,
"text": "Access, modify, print, field of a null value (object)."
},
{
"code": null,
"e": 2467,
"s": 2398,
"text": "Trying to access (print/use in statements) the length of null value."
},
{
"code": null,
"e": 2487,
"s": 2467,
"text": "Throw a null value."
},
{
"code": null,
"e": 2542,
"s": 2487,
"text": "Accessing or modifying elements/slots of a null value."
},
{
"code": null,
"e": 2628,
"s": 2542,
"text": "Means if you throw a null value a null pointer exception occurs it is not up casting."
},
{
"code": null,
"e": 2717,
"s": 2628,
"text": "public class Demo {\n public static void main(String args[]) {\n throw null;\n }\n}"
},
{
"code": null,
"e": 2814,
"s": 2717,
"text": "Exception in thread \"main\" java.lang.NullPointerException\n at july_set3.Demo.main(Demo.java:5)"
}
] |
Named Entity Recognition with Spacy and the Mighty roBERTa | by Zoumana Keita | Towards Data Science
|
When reading a text, a human being can naturally identify named entities like dates, currencies, locations, person names, medical codes, brands, etc. This step can then be relevant for further information extraction from large text data in order to better answer questions such as:
what is the name of the covid19 variant trending on the news?
what tools are mentioned in a given job description and at what level of proficiency?
etc.
The goal of this article is to use spaCy and roBERTa from spaCy transformers in order to automatically identify and extract entities as defined early in the introduction.
We will be performing the entity extraction of two different text data, a short text and a much longer one respectively (from CNN and Etoro) and finally, compare the performance of traditional spaCy and roBERTa.
A shorter text: “Amy Schneider, an engineering manager from Oakland, California, became the first woman and the fourth person on “Jeopardy!” to earn more than $1 million in winnings on Friday’s episode”.
Longer text: “Good news for consumers, undoubtedly, and good news also for investors. Apple’s recent results, covering the three months to December 31 2016, saw the company’s chief financial officer Luca Maestri announce: ‘We returned nearly $15 billion to investors through share re-purchases and dividends during the quarter.’ The quarterly dividend itself was 57 cents a share, identical to the dividend for the previous three quarters and up on the 52 cents paid for each of the four quarters before that.Business is brisk at Apple. On January 31, Tim Cook, Apple’s chief executive, said of the last three months of 2016: ‘We’re thrilled to report that our holiday quarter results generated Apple’s highest quarterly revenue ever, and broke multiple records along the way. We sold more iPhones than ever before and set all-time revenue records for iPhone, Services, Mac and Apple Watch”
This is about installing all the required libraries for the analysis.
The first function print_entities is used to perform the named entity extraction from a given text and pipeline (traditional spaCy or spaCy transformer in our case). It works as follow:
pipeline is the language object we get from thespacy.loadinstruction. It contains all the components and data required to process the text
pipeline(text)runs pipeline and returns processed document
named entities are obtained by iterating over the document.entsobject.
then at each iteration, we can access the entity text from.textand the entity label from .label_
The second function visualize_entities executesdisplacy.render function to produce a nice visualization of all the entities.
Now that we have installed all the libraries and defined our named entity extraction function, we can proceed with the analysis.
An opensource library for industrial-strength NLP, and has been trained on the OntoNotes 5.0 corpus.
Analysis of the short text
print_entities(nlp_sm, short_text)
visualize_entities(nlp_sm, short_text)
Traditional spaCy successfully identified CNN as an Organisation (ORG), Amy Schneider as a PERSON, Oakland, and California as Geo-Political Entity (GEP), etc. You can find the exhaustive list of the definition of the entity codes from the Entity Names Annotation section of this file.
Analysis of the long text
print_entities(nlp_sm, long_text)
visualize_entities(nlp_sm, short_text)
Observation: For the short text, the result looks perfect, because all the entities have been correctly identified. However, for the second text, the model made the following mistakes by
misidentifying Apple Watch to be an ORG (Organization) instead of a Product.
missing to identify iPhone and Mac.
Let’s see how the roBERTa model behaves on the same texts.
This is from spacy-transformerslibrary introduced by spaCy in 2019. It aims to power spacy pipelines by connecting spaCy to HuggingFace’s transformer models.
Analysis of the short text
print_entities(roberta_nlp, short_text)
visualize_entities(roberta_nlp, short_text)
So far, so good, nothing changes compared to the result of the traditional spaCy on the short text.
Analysis of the long text
print_entities(roberta_nlp, long_text)
visualize_entities(roberta_nlp, long_text)
The following summary table contains the result of both traditional spacy and roBERTa on the long text. We can clearly observe that roBERTa outperformed traditional spacy. roBERTa failed only once by not identifying Mac. On the other hand, traditional spacy fails to identify iPhone and Mac but also misidentified Apple Watch.
I hope this article was useful. Try it yourself by running the code from my Github from the link below. Happy Monday!
Github
Spacy for English
Spacy transformers
Bye for now 🏃🏾
|
[
{
"code": null,
"e": 448,
"s": 166,
"text": "When reading a text, a human being can naturally identify named entities like dates, currencies, locations, person names, medical codes, brands, etc. This step can then be relevant for further information extraction from large text data in order to better answer questions such as:"
},
{
"code": null,
"e": 510,
"s": 448,
"text": "what is the name of the covid19 variant trending on the news?"
},
{
"code": null,
"e": 596,
"s": 510,
"text": "what tools are mentioned in a given job description and at what level of proficiency?"
},
{
"code": null,
"e": 601,
"s": 596,
"text": "etc."
},
{
"code": null,
"e": 772,
"s": 601,
"text": "The goal of this article is to use spaCy and roBERTa from spaCy transformers in order to automatically identify and extract entities as defined early in the introduction."
},
{
"code": null,
"e": 984,
"s": 772,
"text": "We will be performing the entity extraction of two different text data, a short text and a much longer one respectively (from CNN and Etoro) and finally, compare the performance of traditional spaCy and roBERTa."
},
{
"code": null,
"e": 1188,
"s": 984,
"text": "A shorter text: “Amy Schneider, an engineering manager from Oakland, California, became the first woman and the fourth person on “Jeopardy!” to earn more than $1 million in winnings on Friday’s episode”."
},
{
"code": null,
"e": 2079,
"s": 1188,
"text": "Longer text: “Good news for consumers, undoubtedly, and good news also for investors. Apple’s recent results, covering the three months to December 31 2016, saw the company’s chief financial officer Luca Maestri announce: ‘We returned nearly $15 billion to investors through share re-purchases and dividends during the quarter.’ The quarterly dividend itself was 57 cents a share, identical to the dividend for the previous three quarters and up on the 52 cents paid for each of the four quarters before that.Business is brisk at Apple. On January 31, Tim Cook, Apple’s chief executive, said of the last three months of 2016: ‘We’re thrilled to report that our holiday quarter results generated Apple’s highest quarterly revenue ever, and broke multiple records along the way. We sold more iPhones than ever before and set all-time revenue records for iPhone, Services, Mac and Apple Watch”"
},
{
"code": null,
"e": 2149,
"s": 2079,
"text": "This is about installing all the required libraries for the analysis."
},
{
"code": null,
"e": 2335,
"s": 2149,
"text": "The first function print_entities is used to perform the named entity extraction from a given text and pipeline (traditional spaCy or spaCy transformer in our case). It works as follow:"
},
{
"code": null,
"e": 2474,
"s": 2335,
"text": "pipeline is the language object we get from thespacy.loadinstruction. It contains all the components and data required to process the text"
},
{
"code": null,
"e": 2533,
"s": 2474,
"text": "pipeline(text)runs pipeline and returns processed document"
},
{
"code": null,
"e": 2604,
"s": 2533,
"text": "named entities are obtained by iterating over the document.entsobject."
},
{
"code": null,
"e": 2701,
"s": 2604,
"text": "then at each iteration, we can access the entity text from.textand the entity label from .label_"
},
{
"code": null,
"e": 2826,
"s": 2701,
"text": "The second function visualize_entities executesdisplacy.render function to produce a nice visualization of all the entities."
},
{
"code": null,
"e": 2955,
"s": 2826,
"text": "Now that we have installed all the libraries and defined our named entity extraction function, we can proceed with the analysis."
},
{
"code": null,
"e": 3056,
"s": 2955,
"text": "An opensource library for industrial-strength NLP, and has been trained on the OntoNotes 5.0 corpus."
},
{
"code": null,
"e": 3083,
"s": 3056,
"text": "Analysis of the short text"
},
{
"code": null,
"e": 3118,
"s": 3083,
"text": "print_entities(nlp_sm, short_text)"
},
{
"code": null,
"e": 3157,
"s": 3118,
"text": "visualize_entities(nlp_sm, short_text)"
},
{
"code": null,
"e": 3442,
"s": 3157,
"text": "Traditional spaCy successfully identified CNN as an Organisation (ORG), Amy Schneider as a PERSON, Oakland, and California as Geo-Political Entity (GEP), etc. You can find the exhaustive list of the definition of the entity codes from the Entity Names Annotation section of this file."
},
{
"code": null,
"e": 3468,
"s": 3442,
"text": "Analysis of the long text"
},
{
"code": null,
"e": 3502,
"s": 3468,
"text": "print_entities(nlp_sm, long_text)"
},
{
"code": null,
"e": 3541,
"s": 3502,
"text": "visualize_entities(nlp_sm, short_text)"
},
{
"code": null,
"e": 3728,
"s": 3541,
"text": "Observation: For the short text, the result looks perfect, because all the entities have been correctly identified. However, for the second text, the model made the following mistakes by"
},
{
"code": null,
"e": 3805,
"s": 3728,
"text": "misidentifying Apple Watch to be an ORG (Organization) instead of a Product."
},
{
"code": null,
"e": 3841,
"s": 3805,
"text": "missing to identify iPhone and Mac."
},
{
"code": null,
"e": 3900,
"s": 3841,
"text": "Let’s see how the roBERTa model behaves on the same texts."
},
{
"code": null,
"e": 4058,
"s": 3900,
"text": "This is from spacy-transformerslibrary introduced by spaCy in 2019. It aims to power spacy pipelines by connecting spaCy to HuggingFace’s transformer models."
},
{
"code": null,
"e": 4085,
"s": 4058,
"text": "Analysis of the short text"
},
{
"code": null,
"e": 4125,
"s": 4085,
"text": "print_entities(roberta_nlp, short_text)"
},
{
"code": null,
"e": 4169,
"s": 4125,
"text": "visualize_entities(roberta_nlp, short_text)"
},
{
"code": null,
"e": 4269,
"s": 4169,
"text": "So far, so good, nothing changes compared to the result of the traditional spaCy on the short text."
},
{
"code": null,
"e": 4295,
"s": 4269,
"text": "Analysis of the long text"
},
{
"code": null,
"e": 4334,
"s": 4295,
"text": "print_entities(roberta_nlp, long_text)"
},
{
"code": null,
"e": 4377,
"s": 4334,
"text": "visualize_entities(roberta_nlp, long_text)"
},
{
"code": null,
"e": 4704,
"s": 4377,
"text": "The following summary table contains the result of both traditional spacy and roBERTa on the long text. We can clearly observe that roBERTa outperformed traditional spacy. roBERTa failed only once by not identifying Mac. On the other hand, traditional spacy fails to identify iPhone and Mac but also misidentified Apple Watch."
},
{
"code": null,
"e": 4822,
"s": 4704,
"text": "I hope this article was useful. Try it yourself by running the code from my Github from the link below. Happy Monday!"
},
{
"code": null,
"e": 4829,
"s": 4822,
"text": "Github"
},
{
"code": null,
"e": 4847,
"s": 4829,
"text": "Spacy for English"
},
{
"code": null,
"e": 4866,
"s": 4847,
"text": "Spacy transformers"
}
] |
How to limit text length of EditText in Android?
|
This example demonstrate about How to limit text length of EditText in Android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<? xml version= "1.0" encoding= "utf-8" ?>
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: tools = "http://schemas.android.com/tools"
android :layout_width= "match_parent"
android :layout_height= "match_parent"
android :layout_margin= "16dp"
tools :context= ".MainActivity" >
<EditText
android :layout_width= "match_parent"
android :layout_height= "wrap_content"
android :hint= "Enter something..."
android :maxLength= "10" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
package app.tutorialspoint.com.sample ;
import android.support.v7.app.AppCompatActivity ;
import android.os.Bundle ;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState) ;
setContentView(R.layout. activity_main ) ;
}
}
Step 4 − Add the following code to androidManifest.xml
<? xml version= "1.0" encoding= "utf-8" ?>
<manifest xmlns: android = "http://schemas.android.com/apk/res/android"
package= "app.tutorialspoint.com.sample" >
<application
android :allowBackup= "true"
android :icon= "@mipmap/ic_launcher"
android :label= "@string/app_name"
android :roundIcon= "@mipmap/ic_launcher_round"
android :supportsRtl= "true"
android :theme= "@style/AppTheme" >
<activity android :name= ".MainActivity" >
<intent-filter>
<action android :name= "android.intent.action.MAIN" />
<category android :name= "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
|
[
{
"code": null,
"e": 1142,
"s": 1062,
"text": "This example demonstrate about How to limit text length of EditText in Android."
},
{
"code": null,
"e": 1271,
"s": 1142,
"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": 1336,
"s": 1271,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1856,
"s": 1336,
"text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<LinearLayout xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n android :layout_width= \"match_parent\"\n android :layout_height= \"match_parent\"\n android :layout_margin= \"16dp\"\n tools :context= \".MainActivity\" >\n <EditText\n android :layout_width= \"match_parent\"\n android :layout_height= \"wrap_content\"\n android :hint= \"Enter something...\"\n android :maxLength= \"10\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1913,
"s": 1856,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2254,
"s": 1913,
"text": "package app.tutorialspoint.com.sample ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.os.Bundle ;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n }\n}"
},
{
"code": null,
"e": 2309,
"s": 2254,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3026,
"s": 2309,
"text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package= \"app.tutorialspoint.com.sample\" >\n <application\n android :allowBackup= \"true\"\n android :icon= \"@mipmap/ic_launcher\"\n android :label= \"@string/app_name\"\n android :roundIcon= \"@mipmap/ic_launcher_round\"\n android :supportsRtl= \"true\"\n android :theme= \"@style/AppTheme\" >\n <activity android :name= \".MainActivity\" >\n <intent-filter>\n <action android :name= \"android.intent.action.MAIN\" />\n <category android :name= \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 3371,
"s": 3026,
"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"
}
] |
Program for Bridge and Torch problem - GeeksforGeeks
|
04 Mar, 2022
Given an array of positive distinct integer denoting the crossing time of ‘n’ people. These ‘n’ people are standing at one side of bridge. Bridge can hold at max two people at a time. When two people cross the bridge, they must move at the slower person’s pace. Find the minimum total time in which all persons can cross the bridge. See this puzzle to understand more. Note: Slower person space is given by larger time.
Input: Crossing Times = {10, 20, 30}
Output: 60
Explanation
1. Firstly person '1' and '2' cross the bridge
with total time about 20 min(maximum of 10, 20)
2. Now the person '1' will come back with total
time of '10' minutes.
3. Lastly the person '1' and '3' cross the bridge
with total time about 30 minutes
Hence total time incurred in whole journey will be
20 + 10 + 30 = 60
Input: Crossing Times = [1, 2, 5, 8}
Output: 15
Explanation
See this for full explanation.
The approach is to use Dynamic programming. Before getting dive into dynamic programminc let’s see the following observation that will be required in solving the problem.
When any two people cross the bridge, then the fastest person crossing time will not be contributed in answer as both of them move with slowest person speed. When some of the people will cross the river and reached the right side then only the fastest people(smallest integer) will come back to the left side. Person can only be present either left side or right side of the bridge. Thus, if we maintain the left mask, then right mask can easily be calculated by setting the bits ‘1’ which is not present in the left mask. For instance, Right_mask = ((2n) – 1) XOR (left_mask). Any person can easily be represented by bitmask(usually called as ‘mask’). When ith bit of ‘mask’ is set, that means that person is present at left side of the bridge otherwise it would be present at right side of bridge. For instance, let the mask of 6 people is 100101, which represents the person 1, 4, 6 are present at left side of bridge and the person 2, 3 and 5 are present at the right side of the bridge.
When any two people cross the bridge, then the fastest person crossing time will not be contributed in answer as both of them move with slowest person speed.
When some of the people will cross the river and reached the right side then only the fastest people(smallest integer) will come back to the left side.
Person can only be present either left side or right side of the bridge. Thus, if we maintain the left mask, then right mask can easily be calculated by setting the bits ‘1’ which is not present in the left mask. For instance, Right_mask = ((2n) – 1) XOR (left_mask).
Any person can easily be represented by bitmask(usually called as ‘mask’). When ith bit of ‘mask’ is set, that means that person is present at left side of the bridge otherwise it would be present at right side of bridge. For instance, let the mask of 6 people is 100101, which represents the person 1, 4, 6 are present at left side of bridge and the person 2, 3 and 5 are present at the right side of the bridge.
cpp
// C++ program to find minimum time required to// send people on other side of bridge#include <bits/stdc++.h>using namespace std; /* Global dp[2^20][2] array, in dp[i][j]-- 'i' denotes mask in which 'set bits' denotes total people standing at left side of bridge and 'j' denotes the turn that represent on which side we have to send people either from left to right(0) or from right to left(1) */int dp[1 << 20][2]; /* Utility function to find total time required to send people to other side of bridge */int findMinTime(int leftmask, bool turn, int arr[], int& n){ // If all people has been transferred if (!leftmask) return 0; int& res = dp[leftmask][turn]; // If we already have solved this subproblem, // return the answer. if (~res) return res; // Calculate mask of right side of people int rightmask = ((1 << n) - 1) ^ leftmask; /* if turn == 1 means currently people are at right side, thus we need to transfer people to the left side */ if (turn == 1) { int minRow = INT_MAX, person; for (int i = 0; i < n; ++i) { // Select one people whose time is less // among all others present at right // side if (rightmask & (1 << i)) { if (minRow > arr[i]) { person = i; minRow = arr[i]; } } } // Add that person to answer and recurse for next turn // after initializing that person at left side res = arr[person] + findMinTime(leftmask | (1 << person), turn ^ 1, arr, n); } else { // __builtin_popcount() is inbuilt gcc function // which will count total set bits in 'leftmask' if (__builtin_popcount(leftmask) == 1) { for (int i = 0; i < n; ++i) { // Since one person is present at left // side, thus return that person only if (leftmask & (1 << i)) { res = arr[i]; break; } } } else { // try for every pair of people by // sending them to right side // Initialize the result with maximum value res = INT_MAX; for (int i = 0; i < n; ++i) { // If ith person is not present then // skip the rest loop if (!(leftmask & (1 << i))) continue; for (int j = i + 1; j < n; ++j) { if (leftmask & (1 << j)) { // Find maximum integer(slowest // person's time) int val = max(arr[i], arr[j]); // Recurse for other people after un-setting // the ith and jth bit of left-mask val += findMinTime(leftmask ^ (1 << i) ^ (1 << j), turn ^ 1, arr, n); // Find minimum answer among // all chosen values res = min(res, val); } } } } } return res;} // Utility function to find minimum timeint findTime(int arr[], int n){ // Find the mask of 'n' peoples int mask = (1 << n) - 1; // Initialize all entries in dp as -1 memset(dp, -1, sizeof(dp)); return findMinTime(mask, 0, arr, n);} // Driver programint main(){ int arr[] = { 10, 20, 30 }; int n = sizeof(arr)/sizeof(arr[0]); cout << findTime(arr, n); return 0;}
Output
60
Time complexity: Auxiliary space:
rajeev0719singh
sumitgumber28
germanshephered48
sweetyty
Arrays
Dynamic Programming
Arrays
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Next Greater Element
Window Sliding Technique
Count pairs with given sum
Program to find sum of elements in a given array
Reversal algorithm for array rotation
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
Longest Common Subsequence | DP-4
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
|
[
{
"code": null,
"e": 24429,
"s": 24401,
"text": "\n04 Mar, 2022"
},
{
"code": null,
"e": 24851,
"s": 24429,
"text": "Given an array of positive distinct integer denoting the crossing time of ‘n’ people. These ‘n’ people are standing at one side of bridge. Bridge can hold at max two people at a time. When two people cross the bridge, they must move at the slower person’s pace. Find the minimum total time in which all persons can cross the bridge. See this puzzle to understand more. Note: Slower person space is given by larger time. "
},
{
"code": null,
"e": 25332,
"s": 24851,
"text": "Input: Crossing Times = {10, 20, 30}\nOutput: 60\nExplanation\n1. Firstly person '1' and '2' cross the bridge\n with total time about 20 min(maximum of 10, 20) \n2. Now the person '1' will come back with total \n time of '10' minutes.\n3. Lastly the person '1' and '3' cross the bridge\n with total time about 30 minutes\nHence total time incurred in whole journey will be\n20 + 10 + 30 = 60\n\nInput: Crossing Times = [1, 2, 5, 8}\nOutput: 15\nExplanation\nSee this for full explanation."
},
{
"code": null,
"e": 25505,
"s": 25332,
"text": "The approach is to use Dynamic programming. Before getting dive into dynamic programminc let’s see the following observation that will be required in solving the problem. "
},
{
"code": null,
"e": 26500,
"s": 25505,
"text": "When any two people cross the bridge, then the fastest person crossing time will not be contributed in answer as both of them move with slowest person speed. When some of the people will cross the river and reached the right side then only the fastest people(smallest integer) will come back to the left side. Person can only be present either left side or right side of the bridge. Thus, if we maintain the left mask, then right mask can easily be calculated by setting the bits ‘1’ which is not present in the left mask. For instance, Right_mask = ((2n) – 1) XOR (left_mask). Any person can easily be represented by bitmask(usually called as ‘mask’). When ith bit of ‘mask’ is set, that means that person is present at left side of the bridge otherwise it would be present at right side of bridge. For instance, let the mask of 6 people is 100101, which represents the person 1, 4, 6 are present at left side of bridge and the person 2, 3 and 5 are present at the right side of the bridge."
},
{
"code": null,
"e": 26660,
"s": 26500,
"text": "When any two people cross the bridge, then the fastest person crossing time will not be contributed in answer as both of them move with slowest person speed. "
},
{
"code": null,
"e": 26814,
"s": 26660,
"text": "When some of the people will cross the river and reached the right side then only the fastest people(smallest integer) will come back to the left side. "
},
{
"code": null,
"e": 27084,
"s": 26814,
"text": "Person can only be present either left side or right side of the bridge. Thus, if we maintain the left mask, then right mask can easily be calculated by setting the bits ‘1’ which is not present in the left mask. For instance, Right_mask = ((2n) – 1) XOR (left_mask). "
},
{
"code": null,
"e": 27498,
"s": 27084,
"text": "Any person can easily be represented by bitmask(usually called as ‘mask’). When ith bit of ‘mask’ is set, that means that person is present at left side of the bridge otherwise it would be present at right side of bridge. For instance, let the mask of 6 people is 100101, which represents the person 1, 4, 6 are present at left side of bridge and the person 2, 3 and 5 are present at the right side of the bridge."
},
{
"code": null,
"e": 27502,
"s": 27498,
"text": "cpp"
},
{
"code": "// C++ program to find minimum time required to// send people on other side of bridge#include <bits/stdc++.h>using namespace std; /* Global dp[2^20][2] array, in dp[i][j]-- 'i' denotes mask in which 'set bits' denotes total people standing at left side of bridge and 'j' denotes the turn that represent on which side we have to send people either from left to right(0) or from right to left(1) */int dp[1 << 20][2]; /* Utility function to find total time required to send people to other side of bridge */int findMinTime(int leftmask, bool turn, int arr[], int& n){ // If all people has been transferred if (!leftmask) return 0; int& res = dp[leftmask][turn]; // If we already have solved this subproblem, // return the answer. if (~res) return res; // Calculate mask of right side of people int rightmask = ((1 << n) - 1) ^ leftmask; /* if turn == 1 means currently people are at right side, thus we need to transfer people to the left side */ if (turn == 1) { int minRow = INT_MAX, person; for (int i = 0; i < n; ++i) { // Select one people whose time is less // among all others present at right // side if (rightmask & (1 << i)) { if (minRow > arr[i]) { person = i; minRow = arr[i]; } } } // Add that person to answer and recurse for next turn // after initializing that person at left side res = arr[person] + findMinTime(leftmask | (1 << person), turn ^ 1, arr, n); } else { // __builtin_popcount() is inbuilt gcc function // which will count total set bits in 'leftmask' if (__builtin_popcount(leftmask) == 1) { for (int i = 0; i < n; ++i) { // Since one person is present at left // side, thus return that person only if (leftmask & (1 << i)) { res = arr[i]; break; } } } else { // try for every pair of people by // sending them to right side // Initialize the result with maximum value res = INT_MAX; for (int i = 0; i < n; ++i) { // If ith person is not present then // skip the rest loop if (!(leftmask & (1 << i))) continue; for (int j = i + 1; j < n; ++j) { if (leftmask & (1 << j)) { // Find maximum integer(slowest // person's time) int val = max(arr[i], arr[j]); // Recurse for other people after un-setting // the ith and jth bit of left-mask val += findMinTime(leftmask ^ (1 << i) ^ (1 << j), turn ^ 1, arr, n); // Find minimum answer among // all chosen values res = min(res, val); } } } } } return res;} // Utility function to find minimum timeint findTime(int arr[], int n){ // Find the mask of 'n' peoples int mask = (1 << n) - 1; // Initialize all entries in dp as -1 memset(dp, -1, sizeof(dp)); return findMinTime(mask, 0, arr, n);} // Driver programint main(){ int arr[] = { 10, 20, 30 }; int n = sizeof(arr)/sizeof(arr[0]); cout << findTime(arr, n); return 0;}",
"e": 31138,
"s": 27502,
"text": null
},
{
"code": null,
"e": 31149,
"s": 31138,
"text": "Output \n60"
},
{
"code": null,
"e": 31184,
"s": 31149,
"text": "Time complexity: Auxiliary space: "
},
{
"code": null,
"e": 31200,
"s": 31184,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 31214,
"s": 31200,
"text": "sumitgumber28"
},
{
"code": null,
"e": 31232,
"s": 31214,
"text": "germanshephered48"
},
{
"code": null,
"e": 31241,
"s": 31232,
"text": "sweetyty"
},
{
"code": null,
"e": 31248,
"s": 31241,
"text": "Arrays"
},
{
"code": null,
"e": 31268,
"s": 31248,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 31275,
"s": 31268,
"text": "Arrays"
},
{
"code": null,
"e": 31295,
"s": 31275,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 31393,
"s": 31295,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31402,
"s": 31393,
"text": "Comments"
},
{
"code": null,
"e": 31415,
"s": 31402,
"text": "Old Comments"
},
{
"code": null,
"e": 31436,
"s": 31415,
"text": "Next Greater Element"
},
{
"code": null,
"e": 31461,
"s": 31436,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 31488,
"s": 31461,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 31537,
"s": 31488,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 31575,
"s": 31537,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 31604,
"s": 31575,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 31634,
"s": 31604,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 31668,
"s": 31634,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 31699,
"s": 31668,
"text": "Bellman–Ford Algorithm | DP-23"
}
] |
Scala Collections - ListMap
|
Scala map is a collection of key/value pairs. Any value can be retrieved based on its key. Keys are unique in the Map, but values need not be unique. ListMap implements immutable map and uses list to implement the same. It is used with small number of elements.
The following is the syntax for declaring an ListMap variable.
val colors = ListMap("red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F")
Here, colors is declared as an hash-map of Strings, Int which has three key-value pairs. Values can be added by using commands like the following −
var myMap1: ListMap[Char, Int] = colors + ("black" -> "#000000");
Below is an example program of showing how to create, initialize and process ListMap −
import scala.collection.immutable.ListMap
object Demo {
def main(args: Array[String]) = {
var myMap: ListMap[String,String] = ListMap(
"red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F"
);
// Add an element
var myMap1: ListMap[String,String] = myMap + ("white" -> "#FFFFFF");
// Print key values
myMap.keys.foreach{
i =>
print( "Key = " + i )
println(" Value = " + myMap(i) )
}
if( myMap.contains( "red" )) {
println("Red key exists with value :" + myMap("red"))
} else {
println("Red key does not exist")
}
if( myMap.contains( "maroon" )) {
println("Maroon key exists with value :" + myMap("maroon"))
} else {
println("Maroon key does not exist")
}
//removing element
var myMap2: ListMap[String,String] = myMap - ("white");
// Create empty map
var myMap3: ListMap[String,String] = ListMap.empty[String, String];
println(myMap1);
println(myMap2);
println(myMap3);
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
Key = red Value = #FF0000
Key = azure Value = #F0FFFF
Key = peru Value = #CD853F
Red key exists with value :#FF0000
Maroon key does not exist
ListMap(red -> #FF0000, azure -> #F0FFFF, peru -> #CD853F, white -> #FFFFFF)
ListMap(red -> #FF0000, azure -> #F0FFFF, peru -> #CD853F)
ListMap()
82 Lectures
7 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
52 Lectures
1.5 hours
Bigdata Engineer
76 Lectures
5.5 hours
Bigdata Engineer
69 Lectures
7.5 hours
Bigdata Engineer
46 Lectures
4.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3144,
"s": 2882,
"text": "Scala map is a collection of key/value pairs. Any value can be retrieved based on its key. Keys are unique in the Map, but values need not be unique. ListMap implements immutable map and uses list to implement the same. It is used with small number of elements."
},
{
"code": null,
"e": 3207,
"s": 3144,
"text": "The following is the syntax for declaring an ListMap variable."
},
{
"code": null,
"e": 3292,
"s": 3207,
"text": "val colors = ListMap(\"red\" -> \"#FF0000\", \"azure\" -> \"#F0FFFF\", \"peru\" -> \"#CD853F\")\n"
},
{
"code": null,
"e": 3440,
"s": 3292,
"text": "Here, colors is declared as an hash-map of Strings, Int which has three key-value pairs. Values can be added by using commands like the following −"
},
{
"code": null,
"e": 3507,
"s": 3440,
"text": "var myMap1: ListMap[Char, Int] = colors + (\"black\" -> \"#000000\");\n"
},
{
"code": null,
"e": 3594,
"s": 3507,
"text": "Below is an example program of showing how to create, initialize and process ListMap −"
},
{
"code": null,
"e": 4683,
"s": 3594,
"text": "import scala.collection.immutable.ListMap\n\nobject Demo {\n def main(args: Array[String]) = {\n var myMap: ListMap[String,String] = ListMap(\n \"red\" -> \"#FF0000\", \"azure\" -> \"#F0FFFF\", \"peru\" -> \"#CD853F\"\n );\n // Add an element\n var myMap1: ListMap[String,String] = myMap + (\"white\" -> \"#FFFFFF\");\n // Print key values\n myMap.keys.foreach{ \n i => \n print( \"Key = \" + i )\n println(\" Value = \" + myMap(i) ) \n }\n if( myMap.contains( \"red\" )) {\n println(\"Red key exists with value :\" + myMap(\"red\"))\n } else {\n println(\"Red key does not exist\")\n }\n if( myMap.contains( \"maroon\" )) {\n println(\"Maroon key exists with value :\" + myMap(\"maroon\"))\n } else {\n println(\"Maroon key does not exist\")\n }\n //removing element\n var myMap2: ListMap[String,String] = myMap - (\"white\");\n // Create empty map\n var myMap3: ListMap[String,String] = ListMap.empty[String, String];\n println(myMap1);\n println(myMap2);\t\n println(myMap3);\t\t \n }\n}"
},
{
"code": null,
"e": 4790,
"s": 4683,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 4824,
"s": 4790,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 5113,
"s": 4824,
"text": "Key = red Value = #FF0000\nKey = azure Value = #F0FFFF\nKey = peru Value = #CD853F\nRed key exists with value :#FF0000\nMaroon key does not exist\nListMap(red -> #FF0000, azure -> #F0FFFF, peru -> #CD853F, white -> #FFFFFF)\nListMap(red -> #FF0000, azure -> #F0FFFF, peru -> #CD853F)\nListMap()\n"
},
{
"code": null,
"e": 5146,
"s": 5113,
"text": "\n 82 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5165,
"s": 5146,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5200,
"s": 5165,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5221,
"s": 5200,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 5256,
"s": 5221,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5274,
"s": 5256,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5309,
"s": 5274,
"text": "\n 76 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5327,
"s": 5309,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5362,
"s": 5327,
"text": "\n 69 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 5380,
"s": 5362,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5415,
"s": 5380,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5438,
"s": 5415,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 5445,
"s": 5438,
"text": " Print"
},
{
"code": null,
"e": 5456,
"s": 5445,
"text": " Add Notes"
}
] |
How to use Chip Component in ReactJS? - GeeksforGeeks
|
05 Mar, 2021
Chips are compact elements that represent an input, attribute, or action. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Chip Component in ReactJS using the following approach.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command.
npm install @material-ui/core
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from "react";import Chip from "@material-ui/core/Chip";import Avatar from "@material-ui/core/Avatar"; export default function App() { const handleClick = () => { alert("Clicked!!"); }; return ( <div style={{ display: "block", padding: 30 }}> <h4>How to use Chip Component in ReactJS?</h4> <Chip label="Simple Basic Chip" /> <Chip label="Disabled Chip" disabled /> <Chip avatar={<Avatar>M</Avatar>} label="Simple Clickable Chip" onClick={handleClick} /> </div> );}
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
Reference: https://material-ui.com/components/chips/
Material-UI
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to set background images in ReactJS ?
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
How to create a multi-page website using React.js ?
How to build a basic CRUD app with Node.js and ReactJS ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 24397,
"s": 24369,
"text": "\n05 Mar, 2021"
},
{
"code": null,
"e": 24635,
"s": 24397,
"text": "Chips are compact elements that represent an input, attribute, or action. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Chip Component in ReactJS using the following approach."
},
{
"code": null,
"e": 24685,
"s": 24635,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 24749,
"s": 24685,
"text": "Step 1: Create a React application using the following command."
},
{
"code": null,
"e": 24781,
"s": 24749,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 24881,
"s": 24781,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command."
},
{
"code": null,
"e": 24895,
"s": 24881,
"text": "cd foldername"
},
{
"code": null,
"e": 25004,
"s": 24895,
"text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command."
},
{
"code": null,
"e": 25034,
"s": 25004,
"text": "npm install @material-ui/core"
},
{
"code": null,
"e": 25086,
"s": 25034,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 25104,
"s": 25086,
"text": "Project Structure"
},
{
"code": null,
"e": 25234,
"s": 25104,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 25241,
"s": 25234,
"text": "App.js"
},
{
"code": "import React from \"react\";import Chip from \"@material-ui/core/Chip\";import Avatar from \"@material-ui/core/Avatar\"; export default function App() { const handleClick = () => { alert(\"Clicked!!\"); }; return ( <div style={{ display: \"block\", padding: 30 }}> <h4>How to use Chip Component in ReactJS?</h4> <Chip label=\"Simple Basic Chip\" /> <Chip label=\"Disabled Chip\" disabled /> <Chip avatar={<Avatar>M</Avatar>} label=\"Simple Clickable Chip\" onClick={handleClick} /> </div> );}",
"e": 25780,
"s": 25241,
"text": null
},
{
"code": null,
"e": 25893,
"s": 25780,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project."
},
{
"code": null,
"e": 25903,
"s": 25893,
"text": "npm start"
},
{
"code": null,
"e": 26002,
"s": 25903,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output."
},
{
"code": null,
"e": 26055,
"s": 26002,
"text": "Reference: https://material-ui.com/components/chips/"
},
{
"code": null,
"e": 26067,
"s": 26055,
"text": "Material-UI"
},
{
"code": null,
"e": 26083,
"s": 26067,
"text": "React-Questions"
},
{
"code": null,
"e": 26091,
"s": 26083,
"text": "ReactJS"
},
{
"code": null,
"e": 26108,
"s": 26091,
"text": "Web Technologies"
},
{
"code": null,
"e": 26206,
"s": 26108,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26215,
"s": 26206,
"text": "Comments"
},
{
"code": null,
"e": 26228,
"s": 26215,
"text": "Old Comments"
},
{
"code": null,
"e": 26270,
"s": 26228,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 26305,
"s": 26270,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 26363,
"s": 26305,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 26415,
"s": 26363,
"text": "How to create a multi-page website using React.js ?"
},
{
"code": null,
"e": 26472,
"s": 26415,
"text": "How to build a basic CRUD app with Node.js and ReactJS ?"
},
{
"code": null,
"e": 26528,
"s": 26472,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 26561,
"s": 26528,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26623,
"s": 26561,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26673,
"s": 26623,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Sublime Text - Quick Guide
|
Sublime Text Editor is a full featured Text editor for editing local files or a code base. It includes various features for editing code base which helps developers to keep track of changes. Various features that are supported by Sublime are as follows −
Syntax Highlight
Auto Indentation
File Type Recognition
Sidebar with files of mentioned directory
Macros
Plug-in and Packages
Sublime Text editor is used as an Integrated Development Editor (IDE) like Visual Studio code and NetBeans. The current version of Sublime Text editor is 3.0 and is compatible with various operating systems like Windows, Linux and MacOS.
When you use a suitable Text editor, you can enjoy its rich beneficial features. Sublime Text offers its users the following benefits −
Ability to solve linker errors.
Keeping track of all files and folders to work with.
Connectivity with version control systems like Git, Mercurial.
Problem solving capabilities.
Keeping color combination for syntax combination.
You can download Sublime Text from its official Website − www.sublimetext.com. In the next chapter, we will learn about installation procedure of Sublime Text editor in various operating systems.
Sublime Text editor is supported by the following major operating systems −
Windows
Linux and its distributions
OS X
You can download Sublime Text from its official website − www.sublimetext.com
In this chapter, you will learn about the installation of Sublime Text on various operating systems.
You will have to go follow the steps shown below to install Sublime Text on Windows −
Step 1 − Download the .exe package from the official website as shown below −
https://www.sublimetext.com/3
Step 2 − Now, run the executable file. This defines the environment variables. When you run the executable file, you can observe the following window on your screen. Click Next.
Step 3 − Now, choose a destination location to install Sublime Text3 and click Next.
Step 4 − Verify the destination folder and click Install.
Step 5 − Now, click Finish to complete the installation.
Step 6 − Upon a successful installation, your editor will appear as shown below −
You will have to follow the steps shown below to install Sublime Text on Linux distributions −
Step 1 − Using the command line terminal, install the packages for Sublime Text editor, using the command given below −
sudo add-apt-repository ppa:webupd8team/Sublime-Text-3
Step 2 − Update the packages using the following command −
sudo apt-get update
Step 3 − Install the Sublime Text repository using the following command −
sudo apt-get install Sublime-Text
After the successful execution of above mentioned commands, you will find that Sublime Text editor is installed on the system.
For OSX operating systems,
Download the .dmg file of Sublime Text Editor.
Download the .dmg file of Sublime Text Editor.
Open it and drag-and-drop in the Applications folder.
Open it and drag-and-drop in the Applications folder.
Follow the steps that you have seen in above two cases.
Follow the steps that you have seen in above two cases.
Launch the application.
Launch the application.
Throughout this tutorial, we will be focusing on using the subversion control system, Git and bit bucket in combination with Sublime Text editor.
As with any other Text editor, working on a specific repository is the key aspect of Sublime Text. It is shown in detail in the steps given below −
Step 1 − Consider a repository to be cloned from the bit bucket. Please note that we will be working with Python scripts throughout this tutorial.
Step 2 − Include the repository in Sublime Text editor using the Open Folder option, as shown below.
Step 3 − After including the repository, the screen of Sublime Text editor will be as shown below −
You can choose the file you wish to open from the list that is displayed in the left hand side of the screen, as shown in the image below −
Note that the color combination gives recognition of keywords and packages included in the code.
In this chapter, you will learn step by step how to create a file in Sublime Text.
Step 1 − Use the option New File to create a file in Sublime Text editor.
Step 2 − Once the new file is available, you can insert the code, similar to any other text editor, and save the file in your working repository.
Step 3 − Once you save the associated file, Sublime Text editor provides a variety of options based on the type of file, for example .php for PHP scripts, .py for Python scripts and .java for Java code base.
Step 4 − As our code repository is on Python project, we will save the file as demo1.py, as shown below −
Code editors allow the users to edit the code scripts and text documents with various shortcut keys. In this chapter, let us understand through various examples about editing options of first text document in Sublime Text.
In this example, you will see how to add print statements at two locations.
Step 1 − Consider the first script of Python with the following code in it −
Step 2 − Let us suppose that, in the given script you want to mention the starting and ending points of the loop, using simple statements. You can write the print statement wherever required, however, in Sublime Text editor you can simultaneously add comments and statements in two places with a shortcut of Ctrl+cursor point for Windows or Linux, and Cmd+cursor point for Mac. Then, you can see the cursor points as mentioned below −
Step 3 − Now, you can insert the print statements at both the locations of the mentioned cursor points, as shown in the image below.
Sublime Text editor includes a feature to find the occurrences of the keywords included in the scripts. The shortcut key for finding occurrences of the keyword is Ctrl+D after highlighting the associated keyword.
If you want to search for a keyword, say print from the given code, you can use Ctrl+D or Cmd+D to get the count of occurrences of the associated keyword.
We can append comments at the end of line using the shortcut key Ctrl+Shift+L for Windows and Cmd+Shift+L for Mac operating system after selecting the code section where you actually need the comment.
There are various types of code editing and shortcut keys used in Sublime Text editor −
Splitting the selection into lines
Wrapping the complete paragraph in HTML file
Finding all occurrences
This chapter discusses each of them in detail.
The key combination Ctrl+Shift+L allows you to select the blocks of lines and split them, on Windows. The screenshot given below explains this −
The key combination Alt+Shift+w for Windows and Cmd+Shift+w for Mac, allows the user to split the sections of code and create various paragraphs. It is referred as a wrap selection with html tag. This also allows you to include HTML tags using Sublime editor.
The screenshot given below explains wrapping text with a HTML tag −
After wrapping the text, the text wrapped with a HTML tag will be seen as shown below −
The key pattern Ctrl+Shift+f allows you to find a keyword in a given project. The screenshot given below explains this −
The shortcut key opens a window with three options included in it, namely find, where and replace,
where,
find refers to the search of the particular keyword,
find refers to the search of the particular keyword,
where mentions the section as to which repository is searched, and
where mentions the section as to which repository is searched, and
replace mentions the keyword which is replaced instead of find keyword.
replace mentions the keyword which is replaced instead of find keyword.
Linting is the process of flagging suspicious constructs and likely to be bugs in any programming language.
Sublime Linter is the package of Sublime Text that helps you to perform linting in Sublime. It helps in creating files in different modes for the manipulation of code base. It is not an in built package and you need to install it manually.
You can install any package control in Sublime Text editor using the shortcut key combination Ctrl+Shift+P, and selecting the Package Control: Install Package option.
Select the associated package to install in Sublime Text editor. To install Sublime Linter, you need to select the option of SublimeLinter plugin.
On successful installation, your screen will look as shown below −
Sublime Linter runs in four different modes as mentioned below −
When the Sublime Linter key is set to true, linting is performed in the background constantly each time the file is modified.
When the Sublime Linter key is set to , linting load savewill be performed when a file is loaded from the repository.
When the Sublime Linter key is set to save only mode, linting is performed while saving the particular file in working repository.
In the on-demand mode, the Sublime Linter will be set to true, using the shortcut Ctrl+Alt+L, which sets up the linter to detect bugs, if any present in the code.
Sublime Text editor includes shortcuts and methods for manipulating the output. This chapter discusses in detail about these shortcuts with the help of suitable illustrations.
Command palette in Sublime Text editor includes options for installing packages and console. The shortcut key for this purpose is Ctrl+Shift+P for Windows and Cmd+Shift+P for Mac. The screenshot given below shows opening the command palette using this shortcut.
Sublime text editor includes a side bar which displays the scripts or the file names. You can use the shortcut key Ctrl+KB on Windows and Cmd+KB for Mac for this purpose.
The shortcut key Ctrl+Shift+Alt+P for Windows and Ctrl+Shift+P for Mac displays scope in the status bar. The following screenshot shows an illustration of this shortcut.
When you are working with Python scripts using Sublime Text editor, you can use Ctrl+` for Windows or Control + ` for Windows, to operate the Python console.
Snippets are the smart templates which can be reused whenever needed. Sublime text editor includes snippets feature for HTML templates. In this chapter, you will learn about them in detail.
Snippets are simple XML supported files with various attributes. They include an extension called sublime-snippet. The root tag of XML element will be the <snippet> tag. Snippets created are saved in the Packages folder and are considered to live in this folder.
The file format and syntax of snippets are discussed in detail as follows −
Content −This section includes description of the snippet.
Content −This section includes description of the snippet.
tabTrigger − It includes a sequence of characters which trigger when the snippet is written.
tabTrigger − It includes a sequence of characters which trigger when the snippet is written.
Scope − It defines the scope in which the snippet remains active.
Scope − It defines the scope in which the snippet remains active.
Description − It includes all the meta description. It will be displayed when snippet’s menu is open.
Description − It includes all the meta description. It will be displayed when snippet’s menu is open.
You can create the default snippet using Tools → Developer → Snippet option.
Then, a demo snippet with the associated tags will be created as shown below −
To create a first snippet in Sublime Text editor, click the Tools menu and select the Snippets option from the drop down window, as shown in the screenshot here.
Now, choose Snippet:html from the options displayed.
This creates a default snippet on the specified html file as shown below.
Note that there are various snippets for different types of files. For html files in the code base, there are three snippets defined in Sublime Text editor, as shown below.
Control snippets are primarily used for product development. With install packages option in Sublime editor, you can download any snippet needed for web development and install it.
You may need the following packages for web development −
EverCodeLab Sublime supports for Ruby on Rails
Additional PHP snippets for PHP
HTML snippets for HTML files
Twitter Bootstrap snippets for Twitter Bootstrap
JavaScript snippets for JS files
jQuery snippets pack for jQuery
Macros are the basic automation facility that includes a sequence of commands. You can use macros whenever you need to perform an operation which includes same steps.
Macro files are JSON files with an extension called .sublime-micro and are considered to be very helpful.
Recording a macro defines the procedure to keep a set of commands needed for the given file. You can record a macro in two ways −
Use the shortcut key Ctrl+Q for recording a macro in Windows and Cmd+Q in Mac.
Use the shortcut key Ctrl+Q for recording a macro in Windows and Cmd+Q in Mac.
Use the record option in Tools → Record Macro.
Use the record option in Tools → Record Macro.
Once the macro has started recording, you can see the following message in Sublime Text editor −
You can use the shortcut key Ctrl+Shift+Q on Windows and Cmd+Shift+Q for Mac, to play a macro recorded by the user in Sublime Text. Note that this shortcut plays the last recorded macro in Sublime.
You can save a recorded macro using the option Tools → Save Macro. The following screenshot shows how to save a macro using this option.
You can also redefine the macros using various options in Tool menu bar, as shown below −
Key bindings in Sublime Text helps a user to process and map the sequences of key presses to actions. They are defined in the JSON format and are stored in .sublime-keymap files.
For better integration, it is important to keep separate key map files for Linux, OSX and Windows. Key maps of the corresponding platform will be loaded in the Sublime Text editor.
A user can open the keymap file or default key bindings using the option Preferences → Key Bindings.
The following example shows how to perform key bindings in Windows −
[
{ "keys": ["ctrl+shift+n"], "command": "new_window" },
{ "keys": ["ctrl+shift+w"], "command": "close_window" }
]
Sublime Text editor includes an option to define a key map. The key bindings defined in the file .sublime-keymap includes all the key value combinations.
You can include the following key binding set into this file and save them to check the execution, with the help of the code shown below −
[
{
"keys": ["super+alt+;"], "command": "run_macro_file",
"args":
{"file": "Packages/User/semicolon.sublime-macro"}
}
]
Here super is the Winkey in Windows or Linux, and a command on OSX operating system. Note that this code will run the macro that is located in Packages/User and is named semicolon.sublime-macro on pressing the Super+Alt+ keys.
In this chapter, you will learn various shortcuts keys to move and select the columns of a file in Sublime Text.
You can use the shortcut Ctrl+Home to move the pointer to the beginning of the code in Sublime Text editor.
Observe the sample code shown here.
The screenshot given below shows the same code where the cursor is moved to its beginning.
You can use the shortcut Ctrl+L to extend a specified column. This shortcut will select the column which includes the pointer. The following screenshot explains this in a detailed manner −
You can use the shortcut Ctrl+K to trim the specified column of the file. For OSX, you will have to use the key combination Cmd+K for this purpose.
The example shown here displays the code where the line mentioned in the fifth column is trimmed.
You can use the shortcut Ctrl+Shift+K to split a selected block of text into two selections.
Note − The difference in key combinations from the previous key combination is that columns are visible. Ctrl+Shift+K removes the column number from the specified code, whereas Ctrl+K keeps the column number intact after trimming the entire column.
Indentation is the process of maintaining the code blocks of programming languages to maintain a systematic structure. It helps to convey the developers a better structure of program. This chapter explains you in detail about indentation in Sublime Text editor.
Indentation helps to maintain the code structure such that it is easily understood by anyone who accesses it. Proper indentation imparts the following features to the code −
Readability
User-friendliness
Adaptability
Ease of maintenance
Sublime Text editor provides various options for code indentation as shown in the following screenshot −
The usage of these options is discussed in detail here −
Indent option helps to create indentation of the specified code. You have to select the code specified and select the Indent option. You can also use the shortcut Ctrl+[ after selecting the required code that is to be indented. Refer to the following screenshot for a better understanding −
Unindent option works in the reverse of indent procedure. The shortcut for the unindent option is Ctrl+]. Refer to the following screenshot for a better understanding −
Reindent option is used to undo the unindent option and revert the code back to the same condition. Refer to the following screenshot for a better understanding −
Proper indentation offers various benefits to the code and developers. They are discussed below −
Code blocks will be visible without much effort.
Code blocks will be visible without much effort.
Developer can focus on lines of code that are necessary and easily ignore the irrelevant ones.
Developer can focus on lines of code that are necessary and easily ignore the irrelevant ones.
A developer using the same kind of code structure multiple times need not focus on the start of block and end of block statements.
A developer using the same kind of code structure multiple times need not focus on the start of block and end of block statements.
Any misplaced lines of code can be easily identified.
Any misplaced lines of code can be easily identified.
Base settings of the Sublime Text editor are the configuration needed for editor such as font size, display of line numbers or color scheme of the editor.
All the base settings are configured in JSON format. To view the list of settings, go to menu of Preferences -> Settings.
The settings include two types of configurations namely −
Default
User
Default includes all the default configurations and user defines the customized settings for base settings.
For the scenario mentioned above, the customized settings are as mentioned below −
"font_size": 15,
"ignored_packages":
[
"Vintage"
]
Various categories of the settings in Sublime Text are as follows −
These include the basic settings for editing the files of the code base. Examples include font_face, font_size and tab_size. The settings are present in the default configuration.
These include the general settings which specifically focus on background, theme and various color combinations. These settings are appended in the second section of the default configuration.
These settings focus on behavior of the application included in Sublime Text editor across open windows. These settings are included in the third section of default configuration settings.
These settings are used for designing the syntax of Sublime Text editor. To get the list of syntax specific settings, the user needs to use option Preferences − Syntax-Specific.
Theme management in Sublime text editor implies enhancing the appearance of editor with colors and attractive backgrounds. Themes are JSON formatted values with .sublime-theme extension and manage the appearance of the user interface of the editor by changing the colors of elements of the IDE.
The following steps will guide you about installing and applying themes in Sublime Text editor −
Step 1 − Use the Install Package of the Sublime Text to install package for themes, as shown in the screenshot here −
Step 2 − You can see a list of options with Install Package option and you can download them and install in Sublime Text editor.
Step 3 − Once you select a theme, activate it.
Step 4 − Now select your desired theme from the list of installed theme list. This automatically changes the appearance of the editor.
Color schemes are XML formatted files located at the Packages folder with color schemes. They are an awesome way for the customization of Sublime text colors, unlike themes which are specific to UI elements.
You can choose color schemes using option Preferences → Color Scheme. Refer to the following screenshot that shows the same.
Color schemes include various options such as Breakers, Mariana, Monokai, and Sixteen. The appearance of the editor depends on the color scheme that you choose. Note that these patterns will only focus on color syntax.
Vintage mode in Sublime text editor is a package that includes a combination of editing features of vi. Vintage Mode lets you to use a list of vi commands in the Sublime editor.
Vintage mode is an open source project and you can download it from the link −
https://github.com/sublimehq/Vintage
Sublime includes vim, which is an advanced section of vi editor, and includes customization of macros, snippets and plugins.
You can enable Vintage mode through the following steps −
Select the option Preferences → Settings
Select the option Preferences → Settings
Edit the json file of the settings configuration with key name as ignored_packages. Vintage package is included in the ignored_packages section.
Edit the json file of the settings configuration with key name as ignored_packages. Vintage package is included in the ignored_packages section.
Remove the attribute of Vintage from the configurations to enable Vintage property in Sublime text editor.
Remove the attribute of Vintage from the configurations to enable Vintage property in Sublime text editor.
"ignored_packages": []
Your vintage mode editor will appear as shown in the following screenshot −
Your vintage mode editor will appear as shown in the following screenshot −
Vintage mode includes a variety of commands similar to the vi editor. This includes the basic settings of Sublime Text editor as shown in the code given below −
{
"color_scheme": "Packages/Color Scheme - Default/Monokai.tmTheme",
"font_size": 15,
"ignored_packages":
[
],
"vintage_start_in_command_mode": true,
"theme": "Soda Dark.sublime-theme"
}
Vintageous is the package used for the descriptive analysis of vi editor. It can be downloaded using package control as mentioned below −
Once you successfully install the vintageous package, your screen will look like as shown in the following screenshot −
Sublime Editor includes testing modules for various programming languages. This helps in unit testing of files and scripts and helps developers to analyze bugs, errors and issues, if any.
Sublime Text editor includes 3 modules which are necessary for testing and deployment of JavaScript. This chapter discusses them in detail.
JsFormat is a JavaScript plugin used for formatting the script lines which eases the unit testing process. Behind the scenes, it uses JS beautifier (http://jsbeautifier.org/) to format the full JS or portions of JS files. JSFormat can be installed using the Install Package option of Sublime editor.
JsFormat offers the following features to the script −
Eases JS and JSON file formatting.
Offers full text formatting and selected formatting.
Provides customizable settings for formatting options.
JSHint is a community driven tool used for analyzing the mistakes through hints. This helps to detect errors and potential problems. JSHint is an open source package, simple and easy to understand. You can install JSHine in Sublime Text editor through Install Package mode.
To implement JSHint plugin in Sublime Text Editor, you can use the shortcut Alt+J on Windows and Cmd+j on OSX systems.
This script is used to highlight the syntax of JS file and its associated meaning. It includes a feature of syntax highlight with various modules, arrow functions, classes and generators.
You can perform syntax check on a file using the syntax list as shown in the screenshot below −
Python offers unittest, an official unit testing framework for unit testing the scripts designed before deployment. It is also called as PyUnit. Python unit tests used in Sublime Text editor are called as sublime-unittests and they are available in the following link −
https://github.com/martinsam/sublime-unittest
These unit tests contain a number of useful snippets to ease the writing of unit test cases.
The package control of Sublime manages the installation of unittests and the following steps describe it in detail −
Step 1 − Use the command palette of Sublime Editor Ctrl+Shift+P for installation of the package, as shown in the screenshots given below −
Step 2 − The installed packages use the following two main snippets −
testclass which is used to create a new test class
testclass which is used to create a new test class
testfunc which is used to create a new test function for us to fill out
testfunc which is used to create a new test function for us to fill out
Step 3 − The console computes test results as shown in the screenshot below. Note that the result depends on the success or failure of the test.
Success Result
Failure Result
Note − Unit test cases work as a compiler for computing scripts in python.
Sublime Text Editor uses Hunspell for spell checking process. Hunspell is the spell checker of LibreOffice, Mozilla Thunderbird, Google chrome and many proprietary packages. Sublime Text editor includes dictionary support for proper spell check of words.
Sublime Text includes UTF-8 encoded dictionaries. To implement a dictionary with Sublime Text editor, it should be first converted into UTF-8. If the user has UTF-8 encoded dictionary, it can be installed using the Preferences option in Sublime Text editor.
You can select the dictionary from View → Dictionary menu as shown in the given screenshot −
There are two settings defined for the spell check of Sublime Text Editor −
Spell_check
Dictionary
// Set to true to turn spell checking on by default
"spell_check": false,
// Word list to use for spell checking
"dictionary": "Packages/Language - English/en_US.dic"
These configurations are included in the settings file. Added and ignored words are stored in the user settings under the added_words and ignored_words keys, respectively.
Software packages are installed in Sublime Text for additional functionalities. You can see the list of software packages through the shortcut key Ctrl+Shift+P on Windows and Cmd+Shift+P on Mac. Observe the following screenshots for a better understanding −
These packages are installed in the Packages → User directory which includes the entire necessary configuration. To browse the packages, select Preferences → Browse Packages option, as shown in the screenshot below −
These files are the customized configuration which can be changed as and when needed. The packages are created in JSON format.
Consider the sublime-keymap package created which includes following code −
[
{
"keys": ["super+alt+;"],
"command": "run_macro_file",
"args": {"file": "Packages/User/semicolon.sublime-macro"}
}
]
In this chapter, you will learn about the primary options of File, Edit and Goto menus of Sublime Text editor.
This option is included in the File menu which helps in saving the scripts and file with appropriate encoding. Sublime Text Editor includes a variety of options for encoding Python scripts, as shown in the following screenshot −
Encoding process helps the scripts to be secured from third-party attacks and allows the perceived item of use or interest which to be converted into a construct.
Convert case helps in the conversion of upper case to lower case and vice versa. Refer to the following screenshot for a better understanding −
For example, consider a keyword Monica included in the file and let us convert it to uppercase. Refer to the following screenshot for a better understanding −
With this option, a user can search or get the appropriate keyword or any function. This option is very beneficial when we have more than 1000 lines of code and user got to search a unique line or annotation.
The following screenshot shows the demonstration of Goto Symbol −
The previous chapters discussed various options related to the Preferences menu. In this chapter, you will learn in detail about the Font settings of Sublime Text editor.
Sublime Editor offers three dimensions of font sizes − Larger, Smaller and Reset option to undo the particular changes made. Implementing the specified font is possible once the user selects the appropriate paragraph or text in editor.
Consider a selected text in the file functions.py where the you need to make desired changes −
Observe that after the implementation of larger font, the dimensions and font size of the scripts will be automatically changed to larger dimension.
Every editor includes plugin for the development, that triggers set of activities and default packages. Sublime Text editor includes a feature for developing your own customized plugin. This chapter discusses in detail about developing your own plugin in Sublime Text.
The following steps show you in detail how to develop a plugin in Sublime Text −
Step 1 − Select the New Plugin option by navigating through Tools → Developer → New Plugin as shown below −
Step 2 − The basic code of a plugin includes import of two main libraries: sublime and sublime_plugin.
The code for the plugin is −
import sublime
import sublime_plugin
class ExampleCommand(sublime_plugin.TextCommand):
def run(self, edit):
self.view.insert(edit, 0, "Hello, World!")
Step 3 − The customized plugins are saved in Packages → User folder. Refer to the following screenshot that gives you the complete understanding of the plugins saved in Sublime Text editor.
When you have created a plugin and saved it, open the console using the shortcut key Ctrl+` on Windows and Cmd+` on OSX, and execute the command shown here −
view.run_command(plugin-name)
This command will execute the plugin defined by the user with the list of activities included in it.
Command Palette includes a list of items or commands which are used frequently. The entries of commands are included in the .sublime-commands file.
To open a command palette in Sublime Text editor, you can use the shortcut key combination Ctrl+Shift+P on Windows and Cmd+Shift+P on OSX.
The commonly used commands from the palette are −
Build with Python
Install Packages
This will generate all the dependencies and build the specified code of a given Python file.
With this command, we get list of packages which can be installed which is not included earlier.
All the commands included in the command palette are stored in the Packages directory. The basic example of command declared inside the Default.sublime-commands file is shown in the code given below −
[
{ "caption": "Project: Save As", "command": "save_project_as" },
{ "caption": "Project: Close", "command": "close_project" },
{ "caption": "Project: Add Folder", "command": "prompt_add_folder" },
]
Note − The JSON file includes 3 main keys for every command −
Name/Caption
Location
Content
Debugging is the process of finding errors and bugs in the given code and fixing them. Sublime editor includes various plugins that have debugging features, which helps in finding errors easily.
In this chapter, you will learn how to debug a PHP web application. Sublime uses Sublime TestX debug plugin for this purpose. The features of this plugin are −
It is an extension used for debugging the PHP files and scripts.
It is an extension used for debugging the PHP files and scripts.
Provides a list of debugging and profiling capabilities.
Provides a list of debugging and profiling capabilities.
Maintains stack traces and real time parameters like display and functionalities.
Maintains stack traces and real time parameters like display and functionalities.
To install Sublime Text Xdebug plugin, you will have to take the following steps −
Step 1 − Install package control palette installation with the shortcut of Ctrl+Shift+P or Cmd+shift+P.
Step 2 − After the successful installation of Xdebug client, the configuration file will be kept in the Installed Packages folder. The configuration file is the JSON file which includes the parameters for debugging a PHP web application.
Step 3 − Start the debug session of PHP file using the shortcut Ctrl+F9. You can also do it using the Start Debug option using command palette.
Step 4 − The split windows of XdebugClient will show the output of PHP file. It keeps a process of debugging code line by line. Refer to the following screenshot for a better understanding −
Sublime Text Editor has a plugin Web Inspector for debugging JavaScript code. It helps us to set breakpoints, examine the console and evaluate sections of code. In this chapter, you will learn in detail about this plugin.
The following steps show the installation of Sublime Web Inspector −
Use the menu option Preferences → Browse Packages to get the path of installed packages as shown in the given screenshot.
With the help of git command prompt, clone the packages of Debugging Javascript web application using the git repository, as shown in the command given below −
git clone -b ST3 "git://github.com/sokolovstas/SublimeWebInspector.git"
To test the installation, open a command palette and start the web inspector. You can use the shortcut key for web inspector Ctrl+Shift+R on Windows and Cmd+Shift+R on OSX systems. You can see all the breakpoints needed for JavaScript application, as shown below −
Batch processing in Sublime Text also refers to Build systems. Build systems helps user to run files through external programs such as make, tidy and interpreters.
The following points are worth notable while working with Build systems −
They are JSON files and have the extension .sublime-build.
They are JSON files and have the extension .sublime-build.
To initiate the build process, you can select the option Tools → Build or the shortcut Ctrl+B on Windows and Cmd+B for OSX system.
To initiate the build process, you can select the option Tools → Build or the shortcut Ctrl+B on Windows and Cmd+B for OSX system.
Recall that throughout this tutorial, we are focusing on Python files. Sublime text includes two build modes for python files.
Once the build for Python is completed, you can observe the following output on the editor −
You can see the list of build results created for the specific project in Sublime Text editor using the option Tools → Build Results → Show Build Results.
Note that build systems and the complete files associated with batch processing must be located under the Packages folder (Packages/user). Many packages in Sublime Editor include their own build systems.
Distraction Free Mode in Sublime Text editor allows displaying the code and files full screen. You can enter distraction free mode via option View → Enter distraction mode menu item.
Once the distraction mode is enabled in the Sublime Text editor, the output will be visible as below −
All UI chrome accessible items are hidden, but accessible in distraction mode.
All the properties of customization of distraction free mode of Sublime Text editor are included in Distraction Free.sublime-settings JSON file as shown in the screenshot given below.
The following screenshot shows the properties included in Distraction free mode of Sublime editor −
Note that the attributes like line_numbers, gutter, draw_centered, wrap_width, word_wrap and scroll_past_end are such that they enable attractive distraction free mode.
SublimeCodeIntel is an important plugin for the Sublime Text editor. It offers the following features −
Jump to symbol feature, which helps the user to jump to the file and the specified line of the symbol.
Jump to symbol feature, which helps the user to jump to the file and the specified line of the symbol.
Includes library of autocomplete and displays the modules/symbols in real time.
Includes library of autocomplete and displays the modules/symbols in real time.
Tooltips display information in the status bar about the associated function.
Tooltips display information in the status bar about the associated function.
You can install the SublimeCodeIntel plugin through the following steps −
Step 1 − Get the install package functionality of Sublime Text editor using the shortcut Ctrl+Shift+P on Windows and Cmd+Shift+P for OSX system. Refer to the following screenshot for better understanding −
Step 2 − Now, select the plugin SublimeCodeIntel for installation and restart the Sublime Text editor.
Step 3 − On successful installation of SublimeCodeIntel plugin, your screen will look like this −
There are two in built configurations of SublimeCodeIntel −
Settings − Default
Settings − User
Refer to the following screenshot that shows these configurations −
The configuration for SublimeCodeIntel is included in the JSON file called SublimeCodeIntel.sublime-settings. The configuration needed for each language is included in SublimeCodeIntel plugin as below −
/*
Defines a configuration for each language.
*/
"codeintel_language_settings": {
"Python3": {
"python3": "/usr/local/bin/python3.3",
"codeintel_scan_extra_dir": [
"/Applications/Sublime Text.app/Contents/MacOS",
"~/Library/Application Support/Sublime Text 3/Packages/SublimeCodeIntel/arch",
"~/Library/Application Support/Sublime Text 3/Packages/SublimeCodeIntel/libs"
],
"codeintel_scan_files_in_project": true,
"codeintel_selected_catalogs": []
},
"JavaScript": {
"codeintel_scan_extra_dir": [],
"codeintel_scan_exclude_dir":["/build/", "/min/"],
"codeintel_scan_files_in_project": false,
"codeintel_max_recursive_dir_depth": 2,
"codeintel_selected_catalogs": ["jQuery"]
},
"PHP": {
"php": "/Applications/MAMP/bin/php/php5.5.3/bin/php",
"codeintel_scan_extra_dir": [],
"codeintel_scan_files_in_project": true,
"codeintel_max_recursive_dir_depth": 15,
"codeintel_scan_exclude_dir":["/Applications/MAMP/bin/php/php5.5.3/"]
}
}
These configurations can be customized as and when needed. It depends on the number of modules/libraries installed by the user with various parameters such as the size and complexity of the project a user is working on.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2712,
"s": 2457,
"text": "Sublime Text Editor is a full featured Text editor for editing local files or a code base. It includes various features for editing code base which helps developers to keep track of changes. Various features that are supported by Sublime are as follows −"
},
{
"code": null,
"e": 2729,
"s": 2712,
"text": "Syntax Highlight"
},
{
"code": null,
"e": 2746,
"s": 2729,
"text": "Auto Indentation"
},
{
"code": null,
"e": 2768,
"s": 2746,
"text": "File Type Recognition"
},
{
"code": null,
"e": 2810,
"s": 2768,
"text": "Sidebar with files of mentioned directory"
},
{
"code": null,
"e": 2817,
"s": 2810,
"text": "Macros"
},
{
"code": null,
"e": 2838,
"s": 2817,
"text": "Plug-in and Packages"
},
{
"code": null,
"e": 3076,
"s": 2838,
"text": "Sublime Text editor is used as an Integrated Development Editor (IDE) like Visual Studio code and NetBeans. The current version of Sublime Text editor is 3.0 and is compatible with various operating systems like Windows, Linux and MacOS."
},
{
"code": null,
"e": 3212,
"s": 3076,
"text": "When you use a suitable Text editor, you can enjoy its rich beneficial features. Sublime Text offers its users the following benefits −"
},
{
"code": null,
"e": 3244,
"s": 3212,
"text": "Ability to solve linker errors."
},
{
"code": null,
"e": 3297,
"s": 3244,
"text": "Keeping track of all files and folders to work with."
},
{
"code": null,
"e": 3360,
"s": 3297,
"text": "Connectivity with version control systems like Git, Mercurial."
},
{
"code": null,
"e": 3390,
"s": 3360,
"text": "Problem solving capabilities."
},
{
"code": null,
"e": 3440,
"s": 3390,
"text": "Keeping color combination for syntax combination."
},
{
"code": null,
"e": 3636,
"s": 3440,
"text": "You can download Sublime Text from its official Website − www.sublimetext.com. In the next chapter, we will learn about installation procedure of Sublime Text editor in various operating systems."
},
{
"code": null,
"e": 3712,
"s": 3636,
"text": "Sublime Text editor is supported by the following major operating systems −"
},
{
"code": null,
"e": 3720,
"s": 3712,
"text": "Windows"
},
{
"code": null,
"e": 3748,
"s": 3720,
"text": "Linux and its distributions"
},
{
"code": null,
"e": 3753,
"s": 3748,
"text": "OS X"
},
{
"code": null,
"e": 3831,
"s": 3753,
"text": "You can download Sublime Text from its official website − www.sublimetext.com"
},
{
"code": null,
"e": 3932,
"s": 3831,
"text": "In this chapter, you will learn about the installation of Sublime Text on various operating systems."
},
{
"code": null,
"e": 4018,
"s": 3932,
"text": "You will have to go follow the steps shown below to install Sublime Text on Windows −"
},
{
"code": null,
"e": 4096,
"s": 4018,
"text": "Step 1 − Download the .exe package from the official website as shown below −"
},
{
"code": null,
"e": 4126,
"s": 4096,
"text": "https://www.sublimetext.com/3"
},
{
"code": null,
"e": 4304,
"s": 4126,
"text": "Step 2 − Now, run the executable file. This defines the environment variables. When you run the executable file, you can observe the following window on your screen. Click Next."
},
{
"code": null,
"e": 4389,
"s": 4304,
"text": "Step 3 − Now, choose a destination location to install Sublime Text3 and click Next."
},
{
"code": null,
"e": 4447,
"s": 4389,
"text": "Step 4 − Verify the destination folder and click Install."
},
{
"code": null,
"e": 4504,
"s": 4447,
"text": "Step 5 − Now, click Finish to complete the installation."
},
{
"code": null,
"e": 4586,
"s": 4504,
"text": "Step 6 − Upon a successful installation, your editor will appear as shown below −"
},
{
"code": null,
"e": 4681,
"s": 4586,
"text": "You will have to follow the steps shown below to install Sublime Text on Linux distributions −"
},
{
"code": null,
"e": 4801,
"s": 4681,
"text": "Step 1 − Using the command line terminal, install the packages for Sublime Text editor, using the command given below −"
},
{
"code": null,
"e": 4857,
"s": 4801,
"text": "sudo add-apt-repository ppa:webupd8team/Sublime-Text-3\n"
},
{
"code": null,
"e": 4916,
"s": 4857,
"text": "Step 2 − Update the packages using the following command −"
},
{
"code": null,
"e": 4937,
"s": 4916,
"text": "sudo apt-get update\n"
},
{
"code": null,
"e": 5012,
"s": 4937,
"text": "Step 3 − Install the Sublime Text repository using the following command −"
},
{
"code": null,
"e": 5047,
"s": 5012,
"text": "sudo apt-get install Sublime-Text\n"
},
{
"code": null,
"e": 5174,
"s": 5047,
"text": "After the successful execution of above mentioned commands, you will find that Sublime Text editor is installed on the system."
},
{
"code": null,
"e": 5201,
"s": 5174,
"text": "For OSX operating systems,"
},
{
"code": null,
"e": 5248,
"s": 5201,
"text": "Download the .dmg file of Sublime Text Editor."
},
{
"code": null,
"e": 5295,
"s": 5248,
"text": "Download the .dmg file of Sublime Text Editor."
},
{
"code": null,
"e": 5349,
"s": 5295,
"text": "Open it and drag-and-drop in the Applications folder."
},
{
"code": null,
"e": 5403,
"s": 5349,
"text": "Open it and drag-and-drop in the Applications folder."
},
{
"code": null,
"e": 5459,
"s": 5403,
"text": "Follow the steps that you have seen in above two cases."
},
{
"code": null,
"e": 5515,
"s": 5459,
"text": "Follow the steps that you have seen in above two cases."
},
{
"code": null,
"e": 5539,
"s": 5515,
"text": "Launch the application."
},
{
"code": null,
"e": 5563,
"s": 5539,
"text": "Launch the application."
},
{
"code": null,
"e": 5709,
"s": 5563,
"text": "Throughout this tutorial, we will be focusing on using the subversion control system, Git and bit bucket in combination with Sublime Text editor."
},
{
"code": null,
"e": 5857,
"s": 5709,
"text": "As with any other Text editor, working on a specific repository is the key aspect of Sublime Text. It is shown in detail in the steps given below −"
},
{
"code": null,
"e": 6004,
"s": 5857,
"text": "Step 1 − Consider a repository to be cloned from the bit bucket. Please note that we will be working with Python scripts throughout this tutorial."
},
{
"code": null,
"e": 6105,
"s": 6004,
"text": "Step 2 − Include the repository in Sublime Text editor using the Open Folder option, as shown below."
},
{
"code": null,
"e": 6205,
"s": 6105,
"text": "Step 3 − After including the repository, the screen of Sublime Text editor will be as shown below −"
},
{
"code": null,
"e": 6345,
"s": 6205,
"text": "You can choose the file you wish to open from the list that is displayed in the left hand side of the screen, as shown in the image below −"
},
{
"code": null,
"e": 6442,
"s": 6345,
"text": "Note that the color combination gives recognition of keywords and packages included in the code."
},
{
"code": null,
"e": 6525,
"s": 6442,
"text": "In this chapter, you will learn step by step how to create a file in Sublime Text."
},
{
"code": null,
"e": 6599,
"s": 6525,
"text": "Step 1 − Use the option New File to create a file in Sublime Text editor."
},
{
"code": null,
"e": 6745,
"s": 6599,
"text": "Step 2 − Once the new file is available, you can insert the code, similar to any other text editor, and save the file in your working repository."
},
{
"code": null,
"e": 6953,
"s": 6745,
"text": "Step 3 − Once you save the associated file, Sublime Text editor provides a variety of options based on the type of file, for example .php for PHP scripts, .py for Python scripts and .java for Java code base."
},
{
"code": null,
"e": 7059,
"s": 6953,
"text": "Step 4 − As our code repository is on Python project, we will save the file as demo1.py, as shown below −"
},
{
"code": null,
"e": 7282,
"s": 7059,
"text": "Code editors allow the users to edit the code scripts and text documents with various shortcut keys. In this chapter, let us understand through various examples about editing options of first text document in Sublime Text."
},
{
"code": null,
"e": 7358,
"s": 7282,
"text": "In this example, you will see how to add print statements at two locations."
},
{
"code": null,
"e": 7435,
"s": 7358,
"text": "Step 1 − Consider the first script of Python with the following code in it −"
},
{
"code": null,
"e": 7870,
"s": 7435,
"text": "Step 2 − Let us suppose that, in the given script you want to mention the starting and ending points of the loop, using simple statements. You can write the print statement wherever required, however, in Sublime Text editor you can simultaneously add comments and statements in two places with a shortcut of Ctrl+cursor point for Windows or Linux, and Cmd+cursor point for Mac. Then, you can see the cursor points as mentioned below −"
},
{
"code": null,
"e": 8003,
"s": 7870,
"text": "Step 3 − Now, you can insert the print statements at both the locations of the mentioned cursor points, as shown in the image below."
},
{
"code": null,
"e": 8216,
"s": 8003,
"text": "Sublime Text editor includes a feature to find the occurrences of the keywords included in the scripts. The shortcut key for finding occurrences of the keyword is Ctrl+D after highlighting the associated keyword."
},
{
"code": null,
"e": 8371,
"s": 8216,
"text": "If you want to search for a keyword, say print from the given code, you can use Ctrl+D or Cmd+D to get the count of occurrences of the associated keyword."
},
{
"code": null,
"e": 8572,
"s": 8371,
"text": "We can append comments at the end of line using the shortcut key Ctrl+Shift+L for Windows and Cmd+Shift+L for Mac operating system after selecting the code section where you actually need the comment."
},
{
"code": null,
"e": 8660,
"s": 8572,
"text": "There are various types of code editing and shortcut keys used in Sublime Text editor −"
},
{
"code": null,
"e": 8695,
"s": 8660,
"text": "Splitting the selection into lines"
},
{
"code": null,
"e": 8740,
"s": 8695,
"text": "Wrapping the complete paragraph in HTML file"
},
{
"code": null,
"e": 8764,
"s": 8740,
"text": "Finding all occurrences"
},
{
"code": null,
"e": 8811,
"s": 8764,
"text": "This chapter discusses each of them in detail."
},
{
"code": null,
"e": 8956,
"s": 8811,
"text": "The key combination Ctrl+Shift+L allows you to select the blocks of lines and split them, on Windows. The screenshot given below explains this −"
},
{
"code": null,
"e": 9216,
"s": 8956,
"text": "The key combination Alt+Shift+w for Windows and Cmd+Shift+w for Mac, allows the user to split the sections of code and create various paragraphs. It is referred as a wrap selection with html tag. This also allows you to include HTML tags using Sublime editor."
},
{
"code": null,
"e": 9284,
"s": 9216,
"text": "The screenshot given below explains wrapping text with a HTML tag −"
},
{
"code": null,
"e": 9372,
"s": 9284,
"text": "After wrapping the text, the text wrapped with a HTML tag will be seen as shown below −"
},
{
"code": null,
"e": 9493,
"s": 9372,
"text": "The key pattern Ctrl+Shift+f allows you to find a keyword in a given project. The screenshot given below explains this −"
},
{
"code": null,
"e": 9592,
"s": 9493,
"text": "The shortcut key opens a window with three options included in it, namely find, where and replace,"
},
{
"code": null,
"e": 9599,
"s": 9592,
"text": "where,"
},
{
"code": null,
"e": 9652,
"s": 9599,
"text": "find refers to the search of the particular keyword,"
},
{
"code": null,
"e": 9705,
"s": 9652,
"text": "find refers to the search of the particular keyword,"
},
{
"code": null,
"e": 9772,
"s": 9705,
"text": "where mentions the section as to which repository is searched, and"
},
{
"code": null,
"e": 9839,
"s": 9772,
"text": "where mentions the section as to which repository is searched, and"
},
{
"code": null,
"e": 9911,
"s": 9839,
"text": "replace mentions the keyword which is replaced instead of find keyword."
},
{
"code": null,
"e": 9983,
"s": 9911,
"text": "replace mentions the keyword which is replaced instead of find keyword."
},
{
"code": null,
"e": 10091,
"s": 9983,
"text": "Linting is the process of flagging suspicious constructs and likely to be bugs in any programming language."
},
{
"code": null,
"e": 10331,
"s": 10091,
"text": "Sublime Linter is the package of Sublime Text that helps you to perform linting in Sublime. It helps in creating files in different modes for the manipulation of code base. It is not an in built package and you need to install it manually."
},
{
"code": null,
"e": 10498,
"s": 10331,
"text": "You can install any package control in Sublime Text editor using the shortcut key combination Ctrl+Shift+P, and selecting the Package Control: Install Package option."
},
{
"code": null,
"e": 10645,
"s": 10498,
"text": "Select the associated package to install in Sublime Text editor. To install Sublime Linter, you need to select the option of SublimeLinter plugin."
},
{
"code": null,
"e": 10712,
"s": 10645,
"text": "On successful installation, your screen will look as shown below −"
},
{
"code": null,
"e": 10777,
"s": 10712,
"text": "Sublime Linter runs in four different modes as mentioned below −"
},
{
"code": null,
"e": 10903,
"s": 10777,
"text": "When the Sublime Linter key is set to true, linting is performed in the background constantly each time the file is modified."
},
{
"code": null,
"e": 11021,
"s": 10903,
"text": "When the Sublime Linter key is set to , linting load savewill be performed when a file is loaded from the repository."
},
{
"code": null,
"e": 11152,
"s": 11021,
"text": "When the Sublime Linter key is set to save only mode, linting is performed while saving the particular file in working repository."
},
{
"code": null,
"e": 11315,
"s": 11152,
"text": "In the on-demand mode, the Sublime Linter will be set to true, using the shortcut Ctrl+Alt+L, which sets up the linter to detect bugs, if any present in the code."
},
{
"code": null,
"e": 11491,
"s": 11315,
"text": "Sublime Text editor includes shortcuts and methods for manipulating the output. This chapter discusses in detail about these shortcuts with the help of suitable illustrations."
},
{
"code": null,
"e": 11753,
"s": 11491,
"text": "Command palette in Sublime Text editor includes options for installing packages and console. The shortcut key for this purpose is Ctrl+Shift+P for Windows and Cmd+Shift+P for Mac. The screenshot given below shows opening the command palette using this shortcut."
},
{
"code": null,
"e": 11924,
"s": 11753,
"text": "Sublime text editor includes a side bar which displays the scripts or the file names. You can use the shortcut key Ctrl+KB on Windows and Cmd+KB for Mac for this purpose."
},
{
"code": null,
"e": 12094,
"s": 11924,
"text": "The shortcut key Ctrl+Shift+Alt+P for Windows and Ctrl+Shift+P for Mac displays scope in the status bar. The following screenshot shows an illustration of this shortcut."
},
{
"code": null,
"e": 12252,
"s": 12094,
"text": "When you are working with Python scripts using Sublime Text editor, you can use Ctrl+` for Windows or Control + ` for Windows, to operate the Python console."
},
{
"code": null,
"e": 12442,
"s": 12252,
"text": "Snippets are the smart templates which can be reused whenever needed. Sublime text editor includes snippets feature for HTML templates. In this chapter, you will learn about them in detail."
},
{
"code": null,
"e": 12705,
"s": 12442,
"text": "Snippets are simple XML supported files with various attributes. They include an extension called sublime-snippet. The root tag of XML element will be the <snippet> tag. Snippets created are saved in the Packages folder and are considered to live in this folder."
},
{
"code": null,
"e": 12781,
"s": 12705,
"text": "The file format and syntax of snippets are discussed in detail as follows −"
},
{
"code": null,
"e": 12840,
"s": 12781,
"text": "Content −This section includes description of the snippet."
},
{
"code": null,
"e": 12899,
"s": 12840,
"text": "Content −This section includes description of the snippet."
},
{
"code": null,
"e": 12992,
"s": 12899,
"text": "tabTrigger − It includes a sequence of characters which trigger when the snippet is written."
},
{
"code": null,
"e": 13085,
"s": 12992,
"text": "tabTrigger − It includes a sequence of characters which trigger when the snippet is written."
},
{
"code": null,
"e": 13151,
"s": 13085,
"text": "Scope − It defines the scope in which the snippet remains active."
},
{
"code": null,
"e": 13217,
"s": 13151,
"text": "Scope − It defines the scope in which the snippet remains active."
},
{
"code": null,
"e": 13319,
"s": 13217,
"text": "Description − It includes all the meta description. It will be displayed when snippet’s menu is open."
},
{
"code": null,
"e": 13421,
"s": 13319,
"text": "Description − It includes all the meta description. It will be displayed when snippet’s menu is open."
},
{
"code": null,
"e": 13498,
"s": 13421,
"text": "You can create the default snippet using Tools → Developer → Snippet option."
},
{
"code": null,
"e": 13577,
"s": 13498,
"text": "Then, a demo snippet with the associated tags will be created as shown below −"
},
{
"code": null,
"e": 13739,
"s": 13577,
"text": "To create a first snippet in Sublime Text editor, click the Tools menu and select the Snippets option from the drop down window, as shown in the screenshot here."
},
{
"code": null,
"e": 13792,
"s": 13739,
"text": "Now, choose Snippet:html from the options displayed."
},
{
"code": null,
"e": 13866,
"s": 13792,
"text": "This creates a default snippet on the specified html file as shown below."
},
{
"code": null,
"e": 14039,
"s": 13866,
"text": "Note that there are various snippets for different types of files. For html files in the code base, there are three snippets defined in Sublime Text editor, as shown below."
},
{
"code": null,
"e": 14220,
"s": 14039,
"text": "Control snippets are primarily used for product development. With install packages option in Sublime editor, you can download any snippet needed for web development and install it."
},
{
"code": null,
"e": 14278,
"s": 14220,
"text": "You may need the following packages for web development −"
},
{
"code": null,
"e": 14325,
"s": 14278,
"text": "EverCodeLab Sublime supports for Ruby on Rails"
},
{
"code": null,
"e": 14357,
"s": 14325,
"text": "Additional PHP snippets for PHP"
},
{
"code": null,
"e": 14386,
"s": 14357,
"text": "HTML snippets for HTML files"
},
{
"code": null,
"e": 14435,
"s": 14386,
"text": "Twitter Bootstrap snippets for Twitter Bootstrap"
},
{
"code": null,
"e": 14468,
"s": 14435,
"text": "JavaScript snippets for JS files"
},
{
"code": null,
"e": 14500,
"s": 14468,
"text": "jQuery snippets pack for jQuery"
},
{
"code": null,
"e": 14667,
"s": 14500,
"text": "Macros are the basic automation facility that includes a sequence of commands. You can use macros whenever you need to perform an operation which includes same steps."
},
{
"code": null,
"e": 14773,
"s": 14667,
"text": "Macro files are JSON files with an extension called .sublime-micro and are considered to be very helpful."
},
{
"code": null,
"e": 14903,
"s": 14773,
"text": "Recording a macro defines the procedure to keep a set of commands needed for the given file. You can record a macro in two ways −"
},
{
"code": null,
"e": 14982,
"s": 14903,
"text": "Use the shortcut key Ctrl+Q for recording a macro in Windows and Cmd+Q in Mac."
},
{
"code": null,
"e": 15061,
"s": 14982,
"text": "Use the shortcut key Ctrl+Q for recording a macro in Windows and Cmd+Q in Mac."
},
{
"code": null,
"e": 15108,
"s": 15061,
"text": "Use the record option in Tools → Record Macro."
},
{
"code": null,
"e": 15155,
"s": 15108,
"text": "Use the record option in Tools → Record Macro."
},
{
"code": null,
"e": 15252,
"s": 15155,
"text": "Once the macro has started recording, you can see the following message in Sublime Text editor −"
},
{
"code": null,
"e": 15450,
"s": 15252,
"text": "You can use the shortcut key Ctrl+Shift+Q on Windows and Cmd+Shift+Q for Mac, to play a macro recorded by the user in Sublime Text. Note that this shortcut plays the last recorded macro in Sublime."
},
{
"code": null,
"e": 15587,
"s": 15450,
"text": "You can save a recorded macro using the option Tools → Save Macro. The following screenshot shows how to save a macro using this option."
},
{
"code": null,
"e": 15677,
"s": 15587,
"text": "You can also redefine the macros using various options in Tool menu bar, as shown below −"
},
{
"code": null,
"e": 15856,
"s": 15677,
"text": "Key bindings in Sublime Text helps a user to process and map the sequences of key presses to actions. They are defined in the JSON format and are stored in .sublime-keymap files."
},
{
"code": null,
"e": 16037,
"s": 15856,
"text": "For better integration, it is important to keep separate key map files for Linux, OSX and Windows. Key maps of the corresponding platform will be loaded in the Sublime Text editor."
},
{
"code": null,
"e": 16138,
"s": 16037,
"text": "A user can open the keymap file or default key bindings using the option Preferences → Key Bindings."
},
{
"code": null,
"e": 16207,
"s": 16138,
"text": "The following example shows how to perform key bindings in Windows −"
},
{
"code": null,
"e": 16328,
"s": 16207,
"text": "[\n { \"keys\": [\"ctrl+shift+n\"], \"command\": \"new_window\" },\n { \"keys\": [\"ctrl+shift+w\"], \"command\": \"close_window\" }\n]"
},
{
"code": null,
"e": 16482,
"s": 16328,
"text": "Sublime Text editor includes an option to define a key map. The key bindings defined in the file .sublime-keymap includes all the key value combinations."
},
{
"code": null,
"e": 16621,
"s": 16482,
"text": "You can include the following key binding set into this file and save them to check the execution, with the help of the code shown below −"
},
{
"code": null,
"e": 16768,
"s": 16621,
"text": "[\n { \n \"keys\": [\"super+alt+;\"], \"command\": \"run_macro_file\",\n \"args\": \n {\"file\": \"Packages/User/semicolon.sublime-macro\"} \n }\n]"
},
{
"code": null,
"e": 16995,
"s": 16768,
"text": "Here super is the Winkey in Windows or Linux, and a command on OSX operating system. Note that this code will run the macro that is located in Packages/User and is named semicolon.sublime-macro on pressing the Super+Alt+ keys."
},
{
"code": null,
"e": 17108,
"s": 16995,
"text": "In this chapter, you will learn various shortcuts keys to move and select the columns of a file in Sublime Text."
},
{
"code": null,
"e": 17216,
"s": 17108,
"text": "You can use the shortcut Ctrl+Home to move the pointer to the beginning of the code in Sublime Text editor."
},
{
"code": null,
"e": 17252,
"s": 17216,
"text": "Observe the sample code shown here."
},
{
"code": null,
"e": 17343,
"s": 17252,
"text": "The screenshot given below shows the same code where the cursor is moved to its beginning."
},
{
"code": null,
"e": 17532,
"s": 17343,
"text": "You can use the shortcut Ctrl+L to extend a specified column. This shortcut will select the column which includes the pointer. The following screenshot explains this in a detailed manner −"
},
{
"code": null,
"e": 17680,
"s": 17532,
"text": "You can use the shortcut Ctrl+K to trim the specified column of the file. For OSX, you will have to use the key combination Cmd+K for this purpose."
},
{
"code": null,
"e": 17778,
"s": 17680,
"text": "The example shown here displays the code where the line mentioned in the fifth column is trimmed."
},
{
"code": null,
"e": 17871,
"s": 17778,
"text": "You can use the shortcut Ctrl+Shift+K to split a selected block of text into two selections."
},
{
"code": null,
"e": 18120,
"s": 17871,
"text": "Note − The difference in key combinations from the previous key combination is that columns are visible. Ctrl+Shift+K removes the column number from the specified code, whereas Ctrl+K keeps the column number intact after trimming the entire column."
},
{
"code": null,
"e": 18382,
"s": 18120,
"text": "Indentation is the process of maintaining the code blocks of programming languages to maintain a systematic structure. It helps to convey the developers a better structure of program. This chapter explains you in detail about indentation in Sublime Text editor."
},
{
"code": null,
"e": 18556,
"s": 18382,
"text": "Indentation helps to maintain the code structure such that it is easily understood by anyone who accesses it. Proper indentation imparts the following features to the code −"
},
{
"code": null,
"e": 18568,
"s": 18556,
"text": "Readability"
},
{
"code": null,
"e": 18586,
"s": 18568,
"text": "User-friendliness"
},
{
"code": null,
"e": 18599,
"s": 18586,
"text": "Adaptability"
},
{
"code": null,
"e": 18619,
"s": 18599,
"text": "Ease of maintenance"
},
{
"code": null,
"e": 18724,
"s": 18619,
"text": "Sublime Text editor provides various options for code indentation as shown in the following screenshot −"
},
{
"code": null,
"e": 18781,
"s": 18724,
"text": "The usage of these options is discussed in detail here −"
},
{
"code": null,
"e": 19072,
"s": 18781,
"text": "Indent option helps to create indentation of the specified code. You have to select the code specified and select the Indent option. You can also use the shortcut Ctrl+[ after selecting the required code that is to be indented. Refer to the following screenshot for a better understanding −"
},
{
"code": null,
"e": 19241,
"s": 19072,
"text": "Unindent option works in the reverse of indent procedure. The shortcut for the unindent option is Ctrl+]. Refer to the following screenshot for a better understanding −"
},
{
"code": null,
"e": 19404,
"s": 19241,
"text": "Reindent option is used to undo the unindent option and revert the code back to the same condition. Refer to the following screenshot for a better understanding −"
},
{
"code": null,
"e": 19502,
"s": 19404,
"text": "Proper indentation offers various benefits to the code and developers. They are discussed below −"
},
{
"code": null,
"e": 19551,
"s": 19502,
"text": "Code blocks will be visible without much effort."
},
{
"code": null,
"e": 19600,
"s": 19551,
"text": "Code blocks will be visible without much effort."
},
{
"code": null,
"e": 19695,
"s": 19600,
"text": "Developer can focus on lines of code that are necessary and easily ignore the irrelevant ones."
},
{
"code": null,
"e": 19790,
"s": 19695,
"text": "Developer can focus on lines of code that are necessary and easily ignore the irrelevant ones."
},
{
"code": null,
"e": 19921,
"s": 19790,
"text": "A developer using the same kind of code structure multiple times need not focus on the start of block and end of block statements."
},
{
"code": null,
"e": 20052,
"s": 19921,
"text": "A developer using the same kind of code structure multiple times need not focus on the start of block and end of block statements."
},
{
"code": null,
"e": 20106,
"s": 20052,
"text": "Any misplaced lines of code can be easily identified."
},
{
"code": null,
"e": 20160,
"s": 20106,
"text": "Any misplaced lines of code can be easily identified."
},
{
"code": null,
"e": 20315,
"s": 20160,
"text": "Base settings of the Sublime Text editor are the configuration needed for editor such as font size, display of line numbers or color scheme of the editor."
},
{
"code": null,
"e": 20437,
"s": 20315,
"text": "All the base settings are configured in JSON format. To view the list of settings, go to menu of Preferences -> Settings."
},
{
"code": null,
"e": 20495,
"s": 20437,
"text": "The settings include two types of configurations namely −"
},
{
"code": null,
"e": 20503,
"s": 20495,
"text": "Default"
},
{
"code": null,
"e": 20508,
"s": 20503,
"text": "User"
},
{
"code": null,
"e": 20616,
"s": 20508,
"text": "Default includes all the default configurations and user defines the customized settings for base settings."
},
{
"code": null,
"e": 20699,
"s": 20616,
"text": "For the scenario mentioned above, the customized settings are as mentioned below −"
},
{
"code": null,
"e": 20766,
"s": 20699,
"text": "\"font_size\": 15,\n \"ignored_packages\":\n [\n \"Vintage\"\n ]\n"
},
{
"code": null,
"e": 20834,
"s": 20766,
"text": "Various categories of the settings in Sublime Text are as follows −"
},
{
"code": null,
"e": 21014,
"s": 20834,
"text": "These include the basic settings for editing the files of the code base. Examples include font_face, font_size and tab_size. The settings are present in the default configuration."
},
{
"code": null,
"e": 21207,
"s": 21014,
"text": "These include the general settings which specifically focus on background, theme and various color combinations. These settings are appended in the second section of the default configuration."
},
{
"code": null,
"e": 21396,
"s": 21207,
"text": "These settings focus on behavior of the application included in Sublime Text editor across open windows. These settings are included in the third section of default configuration settings."
},
{
"code": null,
"e": 21574,
"s": 21396,
"text": "These settings are used for designing the syntax of Sublime Text editor. To get the list of syntax specific settings, the user needs to use option Preferences − Syntax-Specific."
},
{
"code": null,
"e": 21869,
"s": 21574,
"text": "Theme management in Sublime text editor implies enhancing the appearance of editor with colors and attractive backgrounds. Themes are JSON formatted values with .sublime-theme extension and manage the appearance of the user interface of the editor by changing the colors of elements of the IDE."
},
{
"code": null,
"e": 21966,
"s": 21869,
"text": "The following steps will guide you about installing and applying themes in Sublime Text editor −"
},
{
"code": null,
"e": 22084,
"s": 21966,
"text": "Step 1 − Use the Install Package of the Sublime Text to install package for themes, as shown in the screenshot here −"
},
{
"code": null,
"e": 22213,
"s": 22084,
"text": "Step 2 − You can see a list of options with Install Package option and you can download them and install in Sublime Text editor."
},
{
"code": null,
"e": 22260,
"s": 22213,
"text": "Step 3 − Once you select a theme, activate it."
},
{
"code": null,
"e": 22395,
"s": 22260,
"text": "Step 4 − Now select your desired theme from the list of installed theme list. This automatically changes the appearance of the editor."
},
{
"code": null,
"e": 22603,
"s": 22395,
"text": "Color schemes are XML formatted files located at the Packages folder with color schemes. They are an awesome way for the customization of Sublime text colors, unlike themes which are specific to UI elements."
},
{
"code": null,
"e": 22728,
"s": 22603,
"text": "You can choose color schemes using option Preferences → Color Scheme. Refer to the following screenshot that shows the same."
},
{
"code": null,
"e": 22947,
"s": 22728,
"text": "Color schemes include various options such as Breakers, Mariana, Monokai, and Sixteen. The appearance of the editor depends on the color scheme that you choose. Note that these patterns will only focus on color syntax."
},
{
"code": null,
"e": 23125,
"s": 22947,
"text": "Vintage mode in Sublime text editor is a package that includes a combination of editing features of vi. Vintage Mode lets you to use a list of vi commands in the Sublime editor."
},
{
"code": null,
"e": 23204,
"s": 23125,
"text": "Vintage mode is an open source project and you can download it from the link −"
},
{
"code": null,
"e": 23241,
"s": 23204,
"text": "https://github.com/sublimehq/Vintage"
},
{
"code": null,
"e": 23366,
"s": 23241,
"text": "Sublime includes vim, which is an advanced section of vi editor, and includes customization of macros, snippets and plugins."
},
{
"code": null,
"e": 23424,
"s": 23366,
"text": "You can enable Vintage mode through the following steps −"
},
{
"code": null,
"e": 23465,
"s": 23424,
"text": "Select the option Preferences → Settings"
},
{
"code": null,
"e": 23506,
"s": 23465,
"text": "Select the option Preferences → Settings"
},
{
"code": null,
"e": 23651,
"s": 23506,
"text": "Edit the json file of the settings configuration with key name as ignored_packages. Vintage package is included in the ignored_packages section."
},
{
"code": null,
"e": 23796,
"s": 23651,
"text": "Edit the json file of the settings configuration with key name as ignored_packages. Vintage package is included in the ignored_packages section."
},
{
"code": null,
"e": 23903,
"s": 23796,
"text": "Remove the attribute of Vintage from the configurations to enable Vintage property in Sublime text editor."
},
{
"code": null,
"e": 24010,
"s": 23903,
"text": "Remove the attribute of Vintage from the configurations to enable Vintage property in Sublime text editor."
},
{
"code": null,
"e": 24034,
"s": 24010,
"text": "\"ignored_packages\": []\n"
},
{
"code": null,
"e": 24110,
"s": 24034,
"text": "Your vintage mode editor will appear as shown in the following screenshot −"
},
{
"code": null,
"e": 24186,
"s": 24110,
"text": "Your vintage mode editor will appear as shown in the following screenshot −"
},
{
"code": null,
"e": 24347,
"s": 24186,
"text": "Vintage mode includes a variety of commands similar to the vi editor. This includes the basic settings of Sublime Text editor as shown in the code given below −"
},
{
"code": null,
"e": 24559,
"s": 24347,
"text": "{\n \"color_scheme\": \"Packages/Color Scheme - Default/Monokai.tmTheme\",\n \"font_size\": 15,\n \"ignored_packages\":\n [\n \n ],\n \"vintage_start_in_command_mode\": true,\n \"theme\": \"Soda Dark.sublime-theme\"\n}"
},
{
"code": null,
"e": 24697,
"s": 24559,
"text": "Vintageous is the package used for the descriptive analysis of vi editor. It can be downloaded using package control as mentioned below −"
},
{
"code": null,
"e": 24817,
"s": 24697,
"text": "Once you successfully install the vintageous package, your screen will look like as shown in the following screenshot −"
},
{
"code": null,
"e": 25005,
"s": 24817,
"text": "Sublime Editor includes testing modules for various programming languages. This helps in unit testing of files and scripts and helps developers to analyze bugs, errors and issues, if any."
},
{
"code": null,
"e": 25145,
"s": 25005,
"text": "Sublime Text editor includes 3 modules which are necessary for testing and deployment of JavaScript. This chapter discusses them in detail."
},
{
"code": null,
"e": 25445,
"s": 25145,
"text": "JsFormat is a JavaScript plugin used for formatting the script lines which eases the unit testing process. Behind the scenes, it uses JS beautifier (http://jsbeautifier.org/) to format the full JS or portions of JS files. JSFormat can be installed using the Install Package option of Sublime editor."
},
{
"code": null,
"e": 25500,
"s": 25445,
"text": "JsFormat offers the following features to the script −"
},
{
"code": null,
"e": 25535,
"s": 25500,
"text": "Eases JS and JSON file formatting."
},
{
"code": null,
"e": 25588,
"s": 25535,
"text": "Offers full text formatting and selected formatting."
},
{
"code": null,
"e": 25643,
"s": 25588,
"text": "Provides customizable settings for formatting options."
},
{
"code": null,
"e": 25917,
"s": 25643,
"text": "JSHint is a community driven tool used for analyzing the mistakes through hints. This helps to detect errors and potential problems. JSHint is an open source package, simple and easy to understand. You can install JSHine in Sublime Text editor through Install Package mode."
},
{
"code": null,
"e": 26036,
"s": 25917,
"text": "To implement JSHint plugin in Sublime Text Editor, you can use the shortcut Alt+J on Windows and Cmd+j on OSX systems."
},
{
"code": null,
"e": 26224,
"s": 26036,
"text": "This script is used to highlight the syntax of JS file and its associated meaning. It includes a feature of syntax highlight with various modules, arrow functions, classes and generators."
},
{
"code": null,
"e": 26320,
"s": 26224,
"text": "You can perform syntax check on a file using the syntax list as shown in the screenshot below −"
},
{
"code": null,
"e": 26590,
"s": 26320,
"text": "Python offers unittest, an official unit testing framework for unit testing the scripts designed before deployment. It is also called as PyUnit. Python unit tests used in Sublime Text editor are called as sublime-unittests and they are available in the following link −"
},
{
"code": null,
"e": 26636,
"s": 26590,
"text": "https://github.com/martinsam/sublime-unittest"
},
{
"code": null,
"e": 26729,
"s": 26636,
"text": "These unit tests contain a number of useful snippets to ease the writing of unit test cases."
},
{
"code": null,
"e": 26846,
"s": 26729,
"text": "The package control of Sublime manages the installation of unittests and the following steps describe it in detail −"
},
{
"code": null,
"e": 26985,
"s": 26846,
"text": "Step 1 − Use the command palette of Sublime Editor Ctrl+Shift+P for installation of the package, as shown in the screenshots given below −"
},
{
"code": null,
"e": 27055,
"s": 26985,
"text": "Step 2 − The installed packages use the following two main snippets −"
},
{
"code": null,
"e": 27106,
"s": 27055,
"text": "testclass which is used to create a new test class"
},
{
"code": null,
"e": 27157,
"s": 27106,
"text": "testclass which is used to create a new test class"
},
{
"code": null,
"e": 27229,
"s": 27157,
"text": "testfunc which is used to create a new test function for us to fill out"
},
{
"code": null,
"e": 27301,
"s": 27229,
"text": "testfunc which is used to create a new test function for us to fill out"
},
{
"code": null,
"e": 27446,
"s": 27301,
"text": "Step 3 − The console computes test results as shown in the screenshot below. Note that the result depends on the success or failure of the test."
},
{
"code": null,
"e": 27461,
"s": 27446,
"text": "Success Result"
},
{
"code": null,
"e": 27476,
"s": 27461,
"text": "Failure Result"
},
{
"code": null,
"e": 27551,
"s": 27476,
"text": "Note − Unit test cases work as a compiler for computing scripts in python."
},
{
"code": null,
"e": 27806,
"s": 27551,
"text": "Sublime Text Editor uses Hunspell for spell checking process. Hunspell is the spell checker of LibreOffice, Mozilla Thunderbird, Google chrome and many proprietary packages. Sublime Text editor includes dictionary support for proper spell check of words."
},
{
"code": null,
"e": 28064,
"s": 27806,
"text": "Sublime Text includes UTF-8 encoded dictionaries. To implement a dictionary with Sublime Text editor, it should be first converted into UTF-8. If the user has UTF-8 encoded dictionary, it can be installed using the Preferences option in Sublime Text editor."
},
{
"code": null,
"e": 28157,
"s": 28064,
"text": "You can select the dictionary from View → Dictionary menu as shown in the given screenshot −"
},
{
"code": null,
"e": 28233,
"s": 28157,
"text": "There are two settings defined for the spell check of Sublime Text Editor −"
},
{
"code": null,
"e": 28245,
"s": 28233,
"text": "Spell_check"
},
{
"code": null,
"e": 28256,
"s": 28245,
"text": "Dictionary"
},
{
"code": null,
"e": 28425,
"s": 28256,
"text": "// Set to true to turn spell checking on by default\n\"spell_check\": false,\n\n// Word list to use for spell checking\n\"dictionary\": \"Packages/Language - English/en_US.dic\"\n"
},
{
"code": null,
"e": 28597,
"s": 28425,
"text": "These configurations are included in the settings file. Added and ignored words are stored in the user settings under the added_words and ignored_words keys, respectively."
},
{
"code": null,
"e": 28855,
"s": 28597,
"text": "Software packages are installed in Sublime Text for additional functionalities. You can see the list of software packages through the shortcut key Ctrl+Shift+P on Windows and Cmd+Shift+P on Mac. Observe the following screenshots for a better understanding −"
},
{
"code": null,
"e": 29072,
"s": 28855,
"text": "These packages are installed in the Packages → User directory which includes the entire necessary configuration. To browse the packages, select Preferences → Browse Packages option, as shown in the screenshot below −"
},
{
"code": null,
"e": 29199,
"s": 29072,
"text": "These files are the customized configuration which can be changed as and when needed. The packages are created in JSON format."
},
{
"code": null,
"e": 29275,
"s": 29199,
"text": "Consider the sublime-keymap package created which includes following code −"
},
{
"code": null,
"e": 29421,
"s": 29275,
"text": "[\n { \n \"keys\": [\"super+alt+;\"],\n \"command\": \"run_macro_file\",\n \"args\": {\"file\": \"Packages/User/semicolon.sublime-macro\"}\n }\n]\n"
},
{
"code": null,
"e": 29532,
"s": 29421,
"text": "In this chapter, you will learn about the primary options of File, Edit and Goto menus of Sublime Text editor."
},
{
"code": null,
"e": 29761,
"s": 29532,
"text": "This option is included in the File menu which helps in saving the scripts and file with appropriate encoding. Sublime Text Editor includes a variety of options for encoding Python scripts, as shown in the following screenshot −"
},
{
"code": null,
"e": 29924,
"s": 29761,
"text": "Encoding process helps the scripts to be secured from third-party attacks and allows the perceived item of use or interest which to be converted into a construct."
},
{
"code": null,
"e": 30068,
"s": 29924,
"text": "Convert case helps in the conversion of upper case to lower case and vice versa. Refer to the following screenshot for a better understanding −"
},
{
"code": null,
"e": 30227,
"s": 30068,
"text": "For example, consider a keyword Monica included in the file and let us convert it to uppercase. Refer to the following screenshot for a better understanding −"
},
{
"code": null,
"e": 30436,
"s": 30227,
"text": "With this option, a user can search or get the appropriate keyword or any function. This option is very beneficial when we have more than 1000 lines of code and user got to search a unique line or annotation."
},
{
"code": null,
"e": 30502,
"s": 30436,
"text": "The following screenshot shows the demonstration of Goto Symbol −"
},
{
"code": null,
"e": 30673,
"s": 30502,
"text": "The previous chapters discussed various options related to the Preferences menu. In this chapter, you will learn in detail about the Font settings of Sublime Text editor."
},
{
"code": null,
"e": 30909,
"s": 30673,
"text": "Sublime Editor offers three dimensions of font sizes − Larger, Smaller and Reset option to undo the particular changes made. Implementing the specified font is possible once the user selects the appropriate paragraph or text in editor."
},
{
"code": null,
"e": 31004,
"s": 30909,
"text": "Consider a selected text in the file functions.py where the you need to make desired changes −"
},
{
"code": null,
"e": 31153,
"s": 31004,
"text": "Observe that after the implementation of larger font, the dimensions and font size of the scripts will be automatically changed to larger dimension."
},
{
"code": null,
"e": 31422,
"s": 31153,
"text": "Every editor includes plugin for the development, that triggers set of activities and default packages. Sublime Text editor includes a feature for developing your own customized plugin. This chapter discusses in detail about developing your own plugin in Sublime Text."
},
{
"code": null,
"e": 31503,
"s": 31422,
"text": "The following steps show you in detail how to develop a plugin in Sublime Text −"
},
{
"code": null,
"e": 31611,
"s": 31503,
"text": "Step 1 − Select the New Plugin option by navigating through Tools → Developer → New Plugin as shown below −"
},
{
"code": null,
"e": 31714,
"s": 31611,
"text": "Step 2 − The basic code of a plugin includes import of two main libraries: sublime and sublime_plugin."
},
{
"code": null,
"e": 31743,
"s": 31714,
"text": "The code for the plugin is −"
},
{
"code": null,
"e": 31903,
"s": 31743,
"text": "import sublime\nimport sublime_plugin\nclass ExampleCommand(sublime_plugin.TextCommand):\n def run(self, edit):\n self.view.insert(edit, 0, \"Hello, World!\")"
},
{
"code": null,
"e": 32093,
"s": 31903,
"text": "Step 3 − The customized plugins are saved in Packages → User folder. Refer to the following screenshot that gives you the complete understanding of the plugins saved in Sublime Text editor."
},
{
"code": null,
"e": 32251,
"s": 32093,
"text": "When you have created a plugin and saved it, open the console using the shortcut key Ctrl+` on Windows and Cmd+` on OSX, and execute the command shown here −"
},
{
"code": null,
"e": 32282,
"s": 32251,
"text": "view.run_command(plugin-name)\n"
},
{
"code": null,
"e": 32383,
"s": 32282,
"text": "This command will execute the plugin defined by the user with the list of activities included in it."
},
{
"code": null,
"e": 32531,
"s": 32383,
"text": "Command Palette includes a list of items or commands which are used frequently. The entries of commands are included in the .sublime-commands file."
},
{
"code": null,
"e": 32670,
"s": 32531,
"text": "To open a command palette in Sublime Text editor, you can use the shortcut key combination Ctrl+Shift+P on Windows and Cmd+Shift+P on OSX."
},
{
"code": null,
"e": 32720,
"s": 32670,
"text": "The commonly used commands from the palette are −"
},
{
"code": null,
"e": 32738,
"s": 32720,
"text": "Build with Python"
},
{
"code": null,
"e": 32755,
"s": 32738,
"text": "Install Packages"
},
{
"code": null,
"e": 32848,
"s": 32755,
"text": "This will generate all the dependencies and build the specified code of a given Python file."
},
{
"code": null,
"e": 32945,
"s": 32848,
"text": "With this command, we get list of packages which can be installed which is not included earlier."
},
{
"code": null,
"e": 33146,
"s": 32945,
"text": "All the commands included in the command palette are stored in the Packages directory. The basic example of command declared inside the Default.sublime-commands file is shown in the code given below −"
},
{
"code": null,
"e": 33363,
"s": 33146,
"text": "[\n { \"caption\": \"Project: Save As\", \"command\": \"save_project_as\" },\n \n { \"caption\": \"Project: Close\", \"command\": \"close_project\" },\n \n { \"caption\": \"Project: Add Folder\", \"command\": \"prompt_add_folder\" },\n]"
},
{
"code": null,
"e": 33425,
"s": 33363,
"text": "Note − The JSON file includes 3 main keys for every command −"
},
{
"code": null,
"e": 33438,
"s": 33425,
"text": "Name/Caption"
},
{
"code": null,
"e": 33447,
"s": 33438,
"text": "Location"
},
{
"code": null,
"e": 33455,
"s": 33447,
"text": "Content"
},
{
"code": null,
"e": 33650,
"s": 33455,
"text": "Debugging is the process of finding errors and bugs in the given code and fixing them. Sublime editor includes various plugins that have debugging features, which helps in finding errors easily."
},
{
"code": null,
"e": 33810,
"s": 33650,
"text": "In this chapter, you will learn how to debug a PHP web application. Sublime uses Sublime TestX debug plugin for this purpose. The features of this plugin are −"
},
{
"code": null,
"e": 33875,
"s": 33810,
"text": "It is an extension used for debugging the PHP files and scripts."
},
{
"code": null,
"e": 33940,
"s": 33875,
"text": "It is an extension used for debugging the PHP files and scripts."
},
{
"code": null,
"e": 33997,
"s": 33940,
"text": "Provides a list of debugging and profiling capabilities."
},
{
"code": null,
"e": 34054,
"s": 33997,
"text": "Provides a list of debugging and profiling capabilities."
},
{
"code": null,
"e": 34136,
"s": 34054,
"text": "Maintains stack traces and real time parameters like display and functionalities."
},
{
"code": null,
"e": 34218,
"s": 34136,
"text": "Maintains stack traces and real time parameters like display and functionalities."
},
{
"code": null,
"e": 34301,
"s": 34218,
"text": "To install Sublime Text Xdebug plugin, you will have to take the following steps −"
},
{
"code": null,
"e": 34405,
"s": 34301,
"text": "Step 1 − Install package control palette installation with the shortcut of Ctrl+Shift+P or Cmd+shift+P."
},
{
"code": null,
"e": 34643,
"s": 34405,
"text": "Step 2 − After the successful installation of Xdebug client, the configuration file will be kept in the Installed Packages folder. The configuration file is the JSON file which includes the parameters for debugging a PHP web application."
},
{
"code": null,
"e": 34787,
"s": 34643,
"text": "Step 3 − Start the debug session of PHP file using the shortcut Ctrl+F9. You can also do it using the Start Debug option using command palette."
},
{
"code": null,
"e": 34978,
"s": 34787,
"text": "Step 4 − The split windows of XdebugClient will show the output of PHP file. It keeps a process of debugging code line by line. Refer to the following screenshot for a better understanding −"
},
{
"code": null,
"e": 35200,
"s": 34978,
"text": "Sublime Text Editor has a plugin Web Inspector for debugging JavaScript code. It helps us to set breakpoints, examine the console and evaluate sections of code. In this chapter, you will learn in detail about this plugin."
},
{
"code": null,
"e": 35269,
"s": 35200,
"text": "The following steps show the installation of Sublime Web Inspector −"
},
{
"code": null,
"e": 35391,
"s": 35269,
"text": "Use the menu option Preferences → Browse Packages to get the path of installed packages as shown in the given screenshot."
},
{
"code": null,
"e": 35551,
"s": 35391,
"text": "With the help of git command prompt, clone the packages of Debugging Javascript web application using the git repository, as shown in the command given below −"
},
{
"code": null,
"e": 35624,
"s": 35551,
"text": "git clone -b ST3 \"git://github.com/sokolovstas/SublimeWebInspector.git\"\n"
},
{
"code": null,
"e": 35889,
"s": 35624,
"text": "To test the installation, open a command palette and start the web inspector. You can use the shortcut key for web inspector Ctrl+Shift+R on Windows and Cmd+Shift+R on OSX systems. You can see all the breakpoints needed for JavaScript application, as shown below −"
},
{
"code": null,
"e": 36053,
"s": 35889,
"text": "Batch processing in Sublime Text also refers to Build systems. Build systems helps user to run files through external programs such as make, tidy and interpreters."
},
{
"code": null,
"e": 36127,
"s": 36053,
"text": "The following points are worth notable while working with Build systems −"
},
{
"code": null,
"e": 36186,
"s": 36127,
"text": "They are JSON files and have the extension .sublime-build."
},
{
"code": null,
"e": 36245,
"s": 36186,
"text": "They are JSON files and have the extension .sublime-build."
},
{
"code": null,
"e": 36376,
"s": 36245,
"text": "To initiate the build process, you can select the option Tools → Build or the shortcut Ctrl+B on Windows and Cmd+B for OSX system."
},
{
"code": null,
"e": 36507,
"s": 36376,
"text": "To initiate the build process, you can select the option Tools → Build or the shortcut Ctrl+B on Windows and Cmd+B for OSX system."
},
{
"code": null,
"e": 36634,
"s": 36507,
"text": "Recall that throughout this tutorial, we are focusing on Python files. Sublime text includes two build modes for python files."
},
{
"code": null,
"e": 36727,
"s": 36634,
"text": "Once the build for Python is completed, you can observe the following output on the editor −"
},
{
"code": null,
"e": 36882,
"s": 36727,
"text": "You can see the list of build results created for the specific project in Sublime Text editor using the option Tools → Build Results → Show Build Results."
},
{
"code": null,
"e": 37086,
"s": 36882,
"text": "Note that build systems and the complete files associated with batch processing must be located under the Packages folder (Packages/user). Many packages in Sublime Editor include their own build systems."
},
{
"code": null,
"e": 37270,
"s": 37086,
"text": "Distraction Free Mode in Sublime Text editor allows displaying the code and files full screen. You can enter distraction free mode via option View → Enter distraction mode menu item.\n"
},
{
"code": null,
"e": 37373,
"s": 37270,
"text": "Once the distraction mode is enabled in the Sublime Text editor, the output will be visible as below −"
},
{
"code": null,
"e": 37452,
"s": 37373,
"text": "All UI chrome accessible items are hidden, but accessible in distraction mode."
},
{
"code": null,
"e": 37636,
"s": 37452,
"text": "All the properties of customization of distraction free mode of Sublime Text editor are included in Distraction Free.sublime-settings JSON file as shown in the screenshot given below."
},
{
"code": null,
"e": 37736,
"s": 37636,
"text": "The following screenshot shows the properties included in Distraction free mode of Sublime editor −"
},
{
"code": null,
"e": 37905,
"s": 37736,
"text": "Note that the attributes like line_numbers, gutter, draw_centered, wrap_width, word_wrap and scroll_past_end are such that they enable attractive distraction free mode."
},
{
"code": null,
"e": 38009,
"s": 37905,
"text": "SublimeCodeIntel is an important plugin for the Sublime Text editor. It offers the following features −"
},
{
"code": null,
"e": 38112,
"s": 38009,
"text": "Jump to symbol feature, which helps the user to jump to the file and the specified line of the symbol."
},
{
"code": null,
"e": 38215,
"s": 38112,
"text": "Jump to symbol feature, which helps the user to jump to the file and the specified line of the symbol."
},
{
"code": null,
"e": 38295,
"s": 38215,
"text": "Includes library of autocomplete and displays the modules/symbols in real time."
},
{
"code": null,
"e": 38375,
"s": 38295,
"text": "Includes library of autocomplete and displays the modules/symbols in real time."
},
{
"code": null,
"e": 38453,
"s": 38375,
"text": "Tooltips display information in the status bar about the associated function."
},
{
"code": null,
"e": 38531,
"s": 38453,
"text": "Tooltips display information in the status bar about the associated function."
},
{
"code": null,
"e": 38605,
"s": 38531,
"text": "You can install the SublimeCodeIntel plugin through the following steps −"
},
{
"code": null,
"e": 38811,
"s": 38605,
"text": "Step 1 − Get the install package functionality of Sublime Text editor using the shortcut Ctrl+Shift+P on Windows and Cmd+Shift+P for OSX system. Refer to the following screenshot for better understanding −"
},
{
"code": null,
"e": 38914,
"s": 38811,
"text": "Step 2 − Now, select the plugin SublimeCodeIntel for installation and restart the Sublime Text editor."
},
{
"code": null,
"e": 39012,
"s": 38914,
"text": "Step 3 − On successful installation of SublimeCodeIntel plugin, your screen will look like this −"
},
{
"code": null,
"e": 39072,
"s": 39012,
"text": "There are two in built configurations of SublimeCodeIntel −"
},
{
"code": null,
"e": 39091,
"s": 39072,
"text": "Settings − Default"
},
{
"code": null,
"e": 39107,
"s": 39091,
"text": "Settings − User"
},
{
"code": null,
"e": 39175,
"s": 39107,
"text": "Refer to the following screenshot that shows these configurations −"
},
{
"code": null,
"e": 39378,
"s": 39175,
"text": "The configuration for SublimeCodeIntel is included in the JSON file called SublimeCodeIntel.sublime-settings. The configuration needed for each language is included in SublimeCodeIntel plugin as below −"
},
{
"code": null,
"e": 40453,
"s": 39378,
"text": "/*\n Defines a configuration for each language.\n*/\n\n\"codeintel_language_settings\": {\n \"Python3\": {\n \"python3\": \"/usr/local/bin/python3.3\",\n \"codeintel_scan_extra_dir\": [\n \"/Applications/Sublime Text.app/Contents/MacOS\",\n \"~/Library/Application Support/Sublime Text 3/Packages/SublimeCodeIntel/arch\",\n \"~/Library/Application Support/Sublime Text 3/Packages/SublimeCodeIntel/libs\"\n ],\n \"codeintel_scan_files_in_project\": true,\n \"codeintel_selected_catalogs\": []\n },\n \n \"JavaScript\": {\n \"codeintel_scan_extra_dir\": [],\n \"codeintel_scan_exclude_dir\":[\"/build/\", \"/min/\"],\n \"codeintel_scan_files_in_project\": false,\n \"codeintel_max_recursive_dir_depth\": 2,\n \"codeintel_selected_catalogs\": [\"jQuery\"]\n },\n \n \"PHP\": {\n \"php\": \"/Applications/MAMP/bin/php/php5.5.3/bin/php\",\n \"codeintel_scan_extra_dir\": [],\n \"codeintel_scan_files_in_project\": true,\n \"codeintel_max_recursive_dir_depth\": 15,\n \"codeintel_scan_exclude_dir\":[\"/Applications/MAMP/bin/php/php5.5.3/\"]\n }\n}"
},
{
"code": null,
"e": 40673,
"s": 40453,
"text": "These configurations can be customized as and when needed. It depends on the number of modules/libraries installed by the user with various parameters such as the size and complexity of the project a user is working on."
},
{
"code": null,
"e": 40680,
"s": 40673,
"text": " Print"
},
{
"code": null,
"e": 40691,
"s": 40680,
"text": " Add Notes"
}
] |
How can Keras be used with a pre-trained model using Python?
|
Tensorflow is a machine learning framework that is provided by Google. It is an open-source framework used in conjunction with Python to implement algorithms, deep learning applications, and much more. It is used in research and for production purposes.
Keras means ‘horn’ in Greek. Keras was developed as a part of the research for the project ONEIROS (Open ended Neuro-Electronic Intelligent Robot Operating System). Keras is a deep learning API, which is written in Python. It is a high-level API that has a productive interface that helps solve machine learning problems.
It runs on top of Tensorflow framework. It was built to help experiment in a quick manner. It provides essential abstractions and building blocks that are essential in developing and encapsulating machine learning solutions.
It is highly scalable and comes with cross-platform abilities. This means Keras can be run on TPU or clusters of GPUs. Keras models can also be exported to run in a web browser or a mobile phone as well.
Keras is already present within the Tensorflow package. It can be accessed using the below line of code.
import tensorflow
from tensorflow import keras
We are using the Google Colaboratory to run the below code. Google Colab or Colaboratory helps run Python code over the browser and requires zero configuration and free access to GPUs (Graphical Processing Units). Colaboratory has been built on top of Jupyter Notebook. Following is the code snippet −
print("A convolutional model with pre-trained weights is loaded")
base_model = keras.applications.Xception(
weights='imagenet',
include_top=False,
pooling='avg')
print("This model is freezed")
base_model.trainable = False
print("A sequential model is used to add a trainable classifier on top of the base")
model = keras.Sequential([
base_model,
layers.Dense(1000),
])
print("Compile the model")
print("Fit the model to the test data")
model.compile(...)
model.fit(...)
Code credit − https://www.tensorflow.org/guide/keras/sequential_model
A convolutional model with pre-trained weights is loaded
Downloading data from https://storage.googleapis.com/tensorflow/kerasapplications/xception/xception_weights_tf_dim_ordering_tf_kernels_notop.h583689472/83683744 [==============================] - 1s 0us/step
This model is freezed
A sequential model is used to add a trainable classifier on top of the base
Compile the model
Fit the model to the test data
A sequential model stack can be used, along with the help of a pre-trained model to initialize
classification layers.
A sequential model stack can be used, along with the help of a pre-trained model to initialize
classification layers.
Once this model has been built, it is compiled.
Once this model has been built, it is compiled.
Once the compilation is complete, this model can be fit to the training data.
Once the compilation is complete, this model can be fit to the training data.
|
[
{
"code": null,
"e": 1316,
"s": 1062,
"text": "Tensorflow is a machine learning framework that is provided by Google. It is an open-source framework used in conjunction with Python to implement algorithms, deep learning applications, and much more. It is used in research and for production purposes."
},
{
"code": null,
"e": 1638,
"s": 1316,
"text": "Keras means ‘horn’ in Greek. Keras was developed as a part of the research for the project ONEIROS (Open ended Neuro-Electronic Intelligent Robot Operating System). Keras is a deep learning API, which is written in Python. It is a high-level API that has a productive interface that helps solve machine learning problems."
},
{
"code": null,
"e": 1863,
"s": 1638,
"text": "It runs on top of Tensorflow framework. It was built to help experiment in a quick manner. It provides essential abstractions and building blocks that are essential in developing and encapsulating machine learning solutions."
},
{
"code": null,
"e": 2067,
"s": 1863,
"text": "It is highly scalable and comes with cross-platform abilities. This means Keras can be run on TPU or clusters of GPUs. Keras models can also be exported to run in a web browser or a mobile phone as well."
},
{
"code": null,
"e": 2172,
"s": 2067,
"text": "Keras is already present within the Tensorflow package. It can be accessed using the below line of code."
},
{
"code": null,
"e": 2219,
"s": 2172,
"text": "import tensorflow\nfrom tensorflow import keras"
},
{
"code": null,
"e": 2521,
"s": 2219,
"text": "We are using the Google Colaboratory to run the below code. Google Colab or Colaboratory helps run Python code over the browser and requires zero configuration and free access to GPUs (Graphical Processing Units). Colaboratory has been built on top of Jupyter Notebook. Following is the code snippet −"
},
{
"code": null,
"e": 3006,
"s": 2521,
"text": "print(\"A convolutional model with pre-trained weights is loaded\")\nbase_model = keras.applications.Xception(\n weights='imagenet',\n include_top=False,\n pooling='avg')\nprint(\"This model is freezed\")\nbase_model.trainable = False\nprint(\"A sequential model is used to add a trainable classifier on top of the base\")\nmodel = keras.Sequential([\n base_model,\n layers.Dense(1000),\n])\nprint(\"Compile the model\")\nprint(\"Fit the model to the test data\")\nmodel.compile(...)\nmodel.fit(...)"
},
{
"code": null,
"e": 3076,
"s": 3006,
"text": "Code credit − https://www.tensorflow.org/guide/keras/sequential_model"
},
{
"code": null,
"e": 3488,
"s": 3076,
"text": "A convolutional model with pre-trained weights is loaded\nDownloading data from https://storage.googleapis.com/tensorflow/kerasapplications/xception/xception_weights_tf_dim_ordering_tf_kernels_notop.h583689472/83683744 [==============================] - 1s 0us/step\nThis model is freezed\nA sequential model is used to add a trainable classifier on top of the base\nCompile the model\nFit the model to the test data"
},
{
"code": null,
"e": 3606,
"s": 3488,
"text": "A sequential model stack can be used, along with the help of a pre-trained model to initialize\nclassification layers."
},
{
"code": null,
"e": 3724,
"s": 3606,
"text": "A sequential model stack can be used, along with the help of a pre-trained model to initialize\nclassification layers."
},
{
"code": null,
"e": 3772,
"s": 3724,
"text": "Once this model has been built, it is compiled."
},
{
"code": null,
"e": 3820,
"s": 3772,
"text": "Once this model has been built, it is compiled."
},
{
"code": null,
"e": 3898,
"s": 3820,
"text": "Once the compilation is complete, this model can be fit to the training data."
},
{
"code": null,
"e": 3976,
"s": 3898,
"text": "Once the compilation is complete, this model can be fit to the training data."
}
] |
Java program to print the fibonacci series of a given number using while loop
|
Fibonacci Series generates subsequent number by adding two previous numbers. Fibonacci series starts from two numbers − F0 & F1. The initial values of F0 & F1 can be taken 0, 1 or 1, 1 respectively.
Live Demo
public class FibonacciSeriesWithWhileLoop{
public static void main(String args[]) {
int a, b, c, i = 1, n;
n = 10;
a = b = 1; System.out.print(a+" "+b);
while(i<n) {
c = a + b; System.out.print(" ");
System.out.print(c);
a = b;
b = c;
i++;
}
}
}
1 1 2 3 5 8 13 21 34 55 89
|
[
{
"code": null,
"e": 1269,
"s": 1062,
"text": "Fibonacci Series generates subsequent number by adding two previous numbers. Fibonacci series starts from two numbers − F0 & F1. The initial values of F0 & F1 can be taken 0, 1 or 1, 1 respectively."
},
{
"code": null,
"e": 1279,
"s": 1269,
"text": "Live Demo"
},
{
"code": null,
"e": 1607,
"s": 1279,
"text": "public class FibonacciSeriesWithWhileLoop{\n public static void main(String args[]) {\n int a, b, c, i = 1, n;\n n = 10;\n a = b = 1; System.out.print(a+\" \"+b);\n\n while(i<n) {\n c = a + b; System.out.print(\" \");\n System.out.print(c);\n a = b;\n b = c;\n i++;\n }\n }\n}"
},
{
"code": null,
"e": 1634,
"s": 1607,
"text": "1 1 2 3 5 8 13 21 34 55 89"
}
] |
AWT BasicStroke Class
|
The BasicStroke class states colors in the default sRGB color space or colors in arbitrary color spaces identified by a ColorSpace.
Following is the declaration for java.awt.BasicStroke class:
public class BasicStroke
extends Object
implements Stroke
Following are the fields for java.awt.geom.Arc2D class:
static int CAP_BUTT -- Ends unclosed subpaths and dash segments with no added decoration.
static int CAP_BUTT -- Ends unclosed subpaths and dash segments with no added decoration.
static int CAP_ROUND -- Ends unclosed subpaths and dash segments with a round decoration that has a radius equal to half of the width of the pen.
static int CAP_ROUND -- Ends unclosed subpaths and dash segments with a round decoration that has a radius equal to half of the width of the pen.
static int CAP_SQUARE -- Ends unclosed subpaths and dash segments with a square projection that extends beyond the end of the segment to a distance equal to half of the line width.
static int CAP_SQUARE -- Ends unclosed subpaths and dash segments with a square projection that extends beyond the end of the segment to a distance equal to half of the line width.
static int JOIN_BEVEL -- Joins path segments by connecting the outer corners of their wide outlines with a straight segment.
static int JOIN_BEVEL -- Joins path segments by connecting the outer corners of their wide outlines with a straight segment.
static int JOIN_MITER -- Joins path segments by extending their outside edges until they meet.
static int JOIN_MITER -- Joins path segments by extending their outside edges until they meet.
static int JOIN_ROUND -- Joins path segments by rounding off the corner at a radius of half the line width.
static int JOIN_ROUND -- Joins path segments by rounding off the corner at a radius of half the line width.
BasicStroke()
Constructs a new BasicStroke with defaults for all attributes.
BasicStroke(float width)
Constructs a solid BasicStroke with the specified line width and with default values for the cap and join styles.
BasicStroke(float width, int cap, int join)
Constructs a solid BasicStroke with the specified attributes.
BasicStroke(float width, int cap, int join, float miterlimit)
Constructs a solid BasicStroke with the specified attributes.
BasicStroke(float width, int cap, int join, float miterlimit, float[] dash, float dash_phase)
Constructs a new BasicStroke with the specified attributes.
Shape createStrokedShape(Shape s)
Returns a Shape whose interior defines the stroked outline of a specified Shape.
boolean equals(Object obj)
Tests if a specified object is equal to this BasicStroke by first testing if it is a BasicStroke and then comparing its width, join, cap, miter limit, dash, and dash phase attributes with those of this BasicStroke.
float[] getDashArray()
Returns the array representing the lengths of the dash segments.
float getDashPhase()
Returns the current dash phase.
int getEndCap()
Returns the end cap style.
int getLineJoin()
Returns the line join style.
float getLineWidth()
Returns the line width.
float getMiterLimit()
Returns the limit of miter joins.
int hashCode()
Returns the hashcode for this stroke.
This class inherits methods from the following classes:
java.lang.Object
java.lang.Object
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public class AWTGraphicsDemo extends Frame {
public AWTGraphicsDemo(){
super("Java AWT Examples");
prepareGUI();
}
public static void main(String[] args){
AWTGraphicsDemo awtGraphicsDemo = new AWTGraphicsDemo();
awtGraphicsDemo.setVisible(true);
}
private void prepareGUI(){
setSize(400,400);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
}
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setStroke(new BasicStroke(3.0f));
g2.setPaint(Color.blue);
Rectangle2D shape = new Rectangle2D.Float();
shape.setFrame(100, 150, 200,100);
g2.draw(shape);
Rectangle2D shape1 = new Rectangle2D.Float();
shape1.setFrame(110, 160, 180,80);
g2.setStroke(new BasicStroke(1.0f));
g2.draw(shape1);
Font plainFont = new Font("Serif", Font.PLAIN, 24);
g2.setFont(plainFont);
g2.setColor(Color.DARK_GRAY);
g2.drawString("TutorialsPoint", 130, 200);
}
}
Compile the program using command prompt. Go to D:/ > AWT and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtGraphicsDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtGraphicsDemo
Verify the following output
13 Lectures
2 hours
EduOLC
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1879,
"s": 1747,
"text": "The BasicStroke class states colors in the default sRGB color space or colors in arbitrary color spaces identified by a ColorSpace."
},
{
"code": null,
"e": 1940,
"s": 1879,
"text": "Following is the declaration for java.awt.BasicStroke class:"
},
{
"code": null,
"e": 2007,
"s": 1940,
"text": "public class BasicStroke\n extends Object\n implements Stroke"
},
{
"code": null,
"e": 2063,
"s": 2007,
"text": "Following are the fields for java.awt.geom.Arc2D class:"
},
{
"code": null,
"e": 2154,
"s": 2063,
"text": "static int CAP_BUTT -- Ends unclosed subpaths and dash segments with no added decoration."
},
{
"code": null,
"e": 2245,
"s": 2154,
"text": "static int CAP_BUTT -- Ends unclosed subpaths and dash segments with no added decoration."
},
{
"code": null,
"e": 2392,
"s": 2245,
"text": "static int CAP_ROUND -- Ends unclosed subpaths and dash segments with a round decoration that has a radius equal to half of the width of the pen."
},
{
"code": null,
"e": 2539,
"s": 2392,
"text": "static int CAP_ROUND -- Ends unclosed subpaths and dash segments with a round decoration that has a radius equal to half of the width of the pen."
},
{
"code": null,
"e": 2721,
"s": 2539,
"text": "static int CAP_SQUARE -- Ends unclosed subpaths and dash segments with a square projection that extends beyond the end of the segment to a distance equal to half of the line width."
},
{
"code": null,
"e": 2903,
"s": 2721,
"text": "static int CAP_SQUARE -- Ends unclosed subpaths and dash segments with a square projection that extends beyond the end of the segment to a distance equal to half of the line width."
},
{
"code": null,
"e": 3029,
"s": 2903,
"text": "static int JOIN_BEVEL -- Joins path segments by connecting the outer corners of their wide outlines with a straight segment."
},
{
"code": null,
"e": 3155,
"s": 3029,
"text": "static int JOIN_BEVEL -- Joins path segments by connecting the outer corners of their wide outlines with a straight segment."
},
{
"code": null,
"e": 3251,
"s": 3155,
"text": "static int JOIN_MITER -- Joins path segments by extending their outside edges until they meet."
},
{
"code": null,
"e": 3347,
"s": 3251,
"text": "static int JOIN_MITER -- Joins path segments by extending their outside edges until they meet."
},
{
"code": null,
"e": 3456,
"s": 3347,
"text": "static int JOIN_ROUND -- Joins path segments by rounding off the corner at a radius of half the line width."
},
{
"code": null,
"e": 3565,
"s": 3456,
"text": "static int JOIN_ROUND -- Joins path segments by rounding off the corner at a radius of half the line width."
},
{
"code": null,
"e": 3581,
"s": 3565,
"text": "BasicStroke() "
},
{
"code": null,
"e": 3644,
"s": 3581,
"text": "Constructs a new BasicStroke with defaults for all attributes."
},
{
"code": null,
"e": 3670,
"s": 3644,
"text": "BasicStroke(float width) "
},
{
"code": null,
"e": 3784,
"s": 3670,
"text": "Constructs a solid BasicStroke with the specified line width and with default values for the cap and join styles."
},
{
"code": null,
"e": 3828,
"s": 3784,
"text": "BasicStroke(float width, int cap, int join)"
},
{
"code": null,
"e": 3890,
"s": 3828,
"text": "Constructs a solid BasicStroke with the specified attributes."
},
{
"code": null,
"e": 3952,
"s": 3890,
"text": "BasicStroke(float width, int cap, int join, float miterlimit)"
},
{
"code": null,
"e": 4014,
"s": 3952,
"text": "Constructs a solid BasicStroke with the specified attributes."
},
{
"code": null,
"e": 4109,
"s": 4014,
"text": "BasicStroke(float width, int cap, int join, float miterlimit, float[] dash, float dash_phase) "
},
{
"code": null,
"e": 4169,
"s": 4109,
"text": "Constructs a new BasicStroke with the specified attributes."
},
{
"code": null,
"e": 4204,
"s": 4169,
"text": "Shape createStrokedShape(Shape s) "
},
{
"code": null,
"e": 4285,
"s": 4204,
"text": "Returns a Shape whose interior defines the stroked outline of a specified Shape."
},
{
"code": null,
"e": 4313,
"s": 4285,
"text": "boolean equals(Object obj) "
},
{
"code": null,
"e": 4528,
"s": 4313,
"text": "Tests if a specified object is equal to this BasicStroke by first testing if it is a BasicStroke and then comparing its width, join, cap, miter limit, dash, and dash phase attributes with those of this BasicStroke."
},
{
"code": null,
"e": 4552,
"s": 4528,
"text": "float[] getDashArray() "
},
{
"code": null,
"e": 4617,
"s": 4552,
"text": "Returns the array representing the lengths of the dash segments."
},
{
"code": null,
"e": 4639,
"s": 4617,
"text": "float getDashPhase() "
},
{
"code": null,
"e": 4671,
"s": 4639,
"text": "Returns the current dash phase."
},
{
"code": null,
"e": 4688,
"s": 4671,
"text": "int getEndCap() "
},
{
"code": null,
"e": 4715,
"s": 4688,
"text": "Returns the end cap style."
},
{
"code": null,
"e": 4734,
"s": 4715,
"text": "int getLineJoin() "
},
{
"code": null,
"e": 4763,
"s": 4734,
"text": "Returns the line join style."
},
{
"code": null,
"e": 4785,
"s": 4763,
"text": "float getLineWidth() "
},
{
"code": null,
"e": 4809,
"s": 4785,
"text": "Returns the line width."
},
{
"code": null,
"e": 4832,
"s": 4809,
"text": "float getMiterLimit() "
},
{
"code": null,
"e": 4866,
"s": 4832,
"text": "Returns the limit of miter joins."
},
{
"code": null,
"e": 4882,
"s": 4866,
"text": "int hashCode() "
},
{
"code": null,
"e": 4920,
"s": 4882,
"text": "Returns the hashcode for this stroke."
},
{
"code": null,
"e": 4976,
"s": 4920,
"text": "This class inherits methods from the following classes:"
},
{
"code": null,
"e": 4993,
"s": 4976,
"text": "java.lang.Object"
},
{
"code": null,
"e": 5010,
"s": 4993,
"text": "java.lang.Object"
},
{
"code": null,
"e": 5124,
"s": 5010,
"text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >"
},
{
"code": null,
"e": 6385,
"s": 5124,
"text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\nimport java.awt.geom.*;\n\npublic class AWTGraphicsDemo extends Frame {\n \n public AWTGraphicsDemo(){\n super(\"Java AWT Examples\");\n prepareGUI();\n }\n\n public static void main(String[] args){\n AWTGraphicsDemo awtGraphicsDemo = new AWTGraphicsDemo(); \n awtGraphicsDemo.setVisible(true);\n }\n\n private void prepareGUI(){\n setSize(400,400);\n addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n } \n\n @Override\n public void paint(Graphics g) {\n Graphics2D g2 = (Graphics2D)g; \n g2.setStroke(new BasicStroke(3.0f));\n g2.setPaint(Color.blue);\n\n Rectangle2D shape = new Rectangle2D.Float();\n shape.setFrame(100, 150, 200,100);\n g2.draw(shape);\n\n Rectangle2D shape1 = new Rectangle2D.Float();\n shape1.setFrame(110, 160, 180,80);\n g2.setStroke(new BasicStroke(1.0f));\n \n g2.draw(shape1);\n Font plainFont = new Font(\"Serif\", Font.PLAIN, 24); \n g2.setFont(plainFont);\n g2.setColor(Color.DARK_GRAY);\n g2.drawString(\"TutorialsPoint\", 130, 200);\n }\n}"
},
{
"code": null,
"e": 6476,
"s": 6385,
"text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command."
},
{
"code": null,
"e": 6533,
"s": 6476,
"text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AwtGraphicsDemo.java"
},
{
"code": null,
"e": 6630,
"s": 6533,
"text": "If no error comes that means compilation is successful. Run the program using following command."
},
{
"code": null,
"e": 6681,
"s": 6630,
"text": "D:\\AWT>java com.tutorialspoint.gui.AwtGraphicsDemo"
},
{
"code": null,
"e": 6709,
"s": 6681,
"text": "Verify the following output"
},
{
"code": null,
"e": 6742,
"s": 6709,
"text": "\n 13 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6750,
"s": 6742,
"text": " EduOLC"
},
{
"code": null,
"e": 6757,
"s": 6750,
"text": " Print"
},
{
"code": null,
"e": 6768,
"s": 6757,
"text": " Add Notes"
}
] |
HTML - <form> Tag
|
The HTML <form> tag is used for creating a form for user input. A form can contain textfields, checkboxes, radio-buttons and more. Forms are used to pass user-data to a specified URL.
<!DOCTYPE html>
<html>
<head>
<title>HTML form Tag</title>
</head>
<body>
<form action = "/cgi-bin/hello_get.cgi" method = "get">
First name:
<input type = "text" name = "first_name" value = "" maxlength = "100" />
<br />
Last name:
<input type = "text" name = "last_name" value = "" maxlength = "100" />
<input type = "submit" value ="Submit" />
</form>
</body>
</html>
This will produce the following result −
This tag supports all the global attributes described in HTML Attribute Reference
The HTML <form> tag also supports the following additional attributes −
get (the form data is appended to the URL when submitted)
post (the form data is not appended to the URL)
Target to open the given URL.
_blank − the target URL will open in a new window.
_self − the target URL will open in the same frame as it was clicked.
_parent − the target URL will open in the parent frameset.
_top − the target URL will open in the full body of the window.
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": 2558,
"s": 2374,
"text": "The HTML <form> tag is used for creating a form for user input. A form can contain textfields, checkboxes, radio-buttons and more. Forms are used to pass user-data to a specified URL."
},
{
"code": null,
"e": 3034,
"s": 2558,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML form Tag</title>\n </head>\n\n <body>\n <form action = \"/cgi-bin/hello_get.cgi\" method = \"get\">\n First name: \n <input type = \"text\" name = \"first_name\" value = \"\" maxlength = \"100\" />\n <br />\n \n Last name: \n <input type = \"text\" name = \"last_name\" value = \"\" maxlength = \"100\" />\n <input type = \"submit\" value =\"Submit\" />\n </form>\n </body>\n\n</html>"
},
{
"code": null,
"e": 3075,
"s": 3034,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3157,
"s": 3075,
"text": "This tag supports all the global attributes described in HTML Attribute Reference"
},
{
"code": null,
"e": 3230,
"s": 3157,
"text": "The HTML <form> tag also supports the following additional attributes −"
},
{
"code": null,
"e": 3288,
"s": 3230,
"text": "get (the form data is appended to the URL when submitted)"
},
{
"code": null,
"e": 3336,
"s": 3288,
"text": "post (the form data is not appended to the URL)"
},
{
"code": null,
"e": 3366,
"s": 3336,
"text": "Target to open the given URL."
},
{
"code": null,
"e": 3417,
"s": 3366,
"text": "_blank − the target URL will open in a new window."
},
{
"code": null,
"e": 3487,
"s": 3417,
"text": "_self − the target URL will open in the same frame as it was clicked."
},
{
"code": null,
"e": 3546,
"s": 3487,
"text": "_parent − the target URL will open in the parent frameset."
},
{
"code": null,
"e": 3610,
"s": 3546,
"text": "_top − the target URL will open in the full body of the window."
},
{
"code": null,
"e": 3688,
"s": 3610,
"text": "This tag supports all the event attributes described in HTML Events Reference"
},
{
"code": null,
"e": 3721,
"s": 3688,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3735,
"s": 3721,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3770,
"s": 3735,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3784,
"s": 3770,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3819,
"s": 3784,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3836,
"s": 3819,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3871,
"s": 3836,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3902,
"s": 3871,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3935,
"s": 3902,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3966,
"s": 3935,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4001,
"s": 3966,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4032,
"s": 4001,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4039,
"s": 4032,
"text": " Print"
},
{
"code": null,
"e": 4050,
"s": 4039,
"text": " Add Notes"
}
] |
Count top 10 most occurring values in a column in MySQL?
|
To count the top 10 most occurring values in a column in MySQL, The syntax is as follows −
SELECT yourColumnName, count(*)
FROM yourTableName
GROUP BY yourColumnName
ORDER BY count(*) DESC
LIMIT 10;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table countTop10Demo
-> (
-> Value int
-> );
Query OK, 0 rows affected (0.74 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into countTop10Demo values(10);
Query OK, 1 row affected (0.12 sec)
mysql> insert into countTop10Demo values(1100);
Query OK, 1 row affected (0.11 sec)
mysql> insert into countTop10Demo values(200);
Query OK, 1 row affected (0.11 sec)
mysql> insert into countTop10Demo values(2100);
Query OK, 1 row affected (0.10 sec)
mysql> insert into countTop10Demo values(1100);
Query OK, 1 row affected (0.11 sec)
mysql> insert into countTop10Demo values(450);
Query OK, 1 row affected (0.28 sec)
mysql> insert into countTop10Demo values(600);
Query OK, 1 row affected (0.12 sec)
mysql> insert into countTop10Demo values(2100);
Query OK, 1 row affected (0.16 sec)
mysql> insert into countTop10Demo values(150);
Query OK, 1 row affected (0.16 sec)
mysql> insert into countTop10Demo values(16454);
Query OK, 1 row affected (0.10 sec)
mysql> insert into countTop10Demo values(450);
Query OK, 1 row affected (0.12 sec)
mysql> insert into countTop10Demo values(2350);
Query OK, 1 row affected (0.10 sec)
mysql> insert into countTop10Demo values(1780);
Query OK, 1 row affected (0.15 sec)
mysql> insert into countTop10Demo values(1345);
Query OK, 1 row affected (0.22 sec)
mysql> insert into countTop10Demo values(34);
Query OK, 1 row affected (0.15 sec)
mysql> insert into countTop10Demo values(2100);
Query OK, 1 row affected (0.08 sec)
mysql> insert into countTop10Demo values(19034);
Query OK, 1 row affected (0.12 sec)
mysql> insert into countTop10Demo values(1844);
Query OK, 1 row affected (0.11 sec)
mysql> insert into countTop10Demo values(34);
Query OK, 1 row affected (0.08 sec)
mysql> insert into countTop10Demo values(16454);
Query OK, 1 row affected (0.19 sec)
Now you can Display all records from the table using select statement. The query is as follows −
mysql> select *from countTop10Demo;
Here is the output −
+-------+
| Value |
+-------+
| 10 |
| 1100 |
| 200 |
| 2100 |
| 1100 |
| 450 |
| 600 |
| 2100 |
| 150 |
| 16454 |
| 450 |
| 2350 |
| 1780 |
| 1345 |
| 34 |
| 2100 |
| 19034 |
| 1844 |
| 34 |
| 16454 |
+-------+
20 rows in set (0.00 sec)
The following is the query to select top 10 most occurring values in a column in MySQL −
mysql> SELECT Value, count(*)
-> FROM countTop10Demo
-> GROUP BY Value
-> ORDER BY count(*) DESC
-> LIMIT 10;
Here is the output −
+-------+----------+
| Value | count(*) |
+-------+----------+
| 2100 | 3 |
| 1100 | 2 |
| 34 | 2 |
| 450 | 2 |
| 16454 | 2 |
| 1780 | 1 |
| 200 | 1 |
| 1345 | 1 |
| 19034 | 1 |
| 600 | 1 |
+-------+----------+
10 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1153,
"s": 1062,
"text": "To count the top 10 most occurring values in a column in MySQL, The syntax is as follows −"
},
{
"code": null,
"e": 1273,
"s": 1153,
"text": "SELECT yourColumnName, count(*)\n FROM yourTableName\n GROUP BY yourColumnName\n ORDER BY count(*) DESC\n LIMIT 10;"
},
{
"code": null,
"e": 1372,
"s": 1273,
"text": "To understand the above syntax, let us create a table. The query to create a table is as follows −"
},
{
"code": null,
"e": 1477,
"s": 1372,
"text": "mysql> create table countTop10Demo\n -> (\n -> Value int\n -> );\nQuery OK, 0 rows affected (0.74 sec)"
},
{
"code": null,
"e": 1558,
"s": 1477,
"text": "Insert some records in the table using insert command. The query is as follows −"
},
{
"code": null,
"e": 3230,
"s": 1558,
"text": "mysql> insert into countTop10Demo values(10);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into countTop10Demo values(1100);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into countTop10Demo values(200);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into countTop10Demo values(2100);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into countTop10Demo values(1100);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into countTop10Demo values(450);\nQuery OK, 1 row affected (0.28 sec)\nmysql> insert into countTop10Demo values(600);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into countTop10Demo values(2100);\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into countTop10Demo values(150);\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into countTop10Demo values(16454);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into countTop10Demo values(450);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into countTop10Demo values(2350);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into countTop10Demo values(1780);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into countTop10Demo values(1345);\nQuery OK, 1 row affected (0.22 sec)\nmysql> insert into countTop10Demo values(34);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into countTop10Demo values(2100);\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into countTop10Demo values(19034);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into countTop10Demo values(1844);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into countTop10Demo values(34);\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into countTop10Demo values(16454);\nQuery OK, 1 row affected (0.19 sec)"
},
{
"code": null,
"e": 3327,
"s": 3230,
"text": "Now you can Display all records from the table using select statement. The query is as follows −"
},
{
"code": null,
"e": 3363,
"s": 3327,
"text": "mysql> select *from countTop10Demo;"
},
{
"code": null,
"e": 3384,
"s": 3363,
"text": "Here is the output −"
},
{
"code": null,
"e": 3650,
"s": 3384,
"text": "+-------+\n| Value |\n+-------+\n| 10 |\n| 1100 |\n| 200 |\n| 2100 |\n| 1100 |\n| 450 |\n| 600 |\n| 2100 |\n| 150 |\n| 16454 |\n| 450 |\n| 2350 |\n| 1780 |\n| 1345 |\n| 34 |\n| 2100 |\n| 19034 |\n| 1844 |\n| 34 |\n| 16454 |\n+-------+\n20 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3739,
"s": 3650,
"text": "The following is the query to select top 10 most occurring values in a column in MySQL −"
},
{
"code": null,
"e": 3861,
"s": 3739,
"text": "mysql> SELECT Value, count(*)\n -> FROM countTop10Demo\n -> GROUP BY Value\n -> ORDER BY count(*) DESC\n -> LIMIT 10;"
},
{
"code": null,
"e": 3882,
"s": 3861,
"text": "Here is the output −"
},
{
"code": null,
"e": 4202,
"s": 3882,
"text": "+-------+----------+\n| Value | count(*) |\n+-------+----------+\n| 2100 | 3 |\n| 1100 | 2 |\n| 34 | 2 |\n| 450 | 2 |\n| 16454 | 2 |\n| 1780 | 1 |\n| 200 | 1 |\n| 1345 | 1 |\n| 19034 | 1 |\n| 600 | 1 |\n+-------+----------+\n10 rows in set (0.00 sec)"
}
] |
Scrape IMDB movie rating and details using Python - GeeksforGeeks
|
01 Jun, 2021
We can scrape the IMDb movie ratings and their details with the help of the BeautifulSoup library of Python.
Below is the list of modules required to scrape from IMDB.
requests: Requests library is an integral part of Python for making HTTP requests to a specified URL. Whether it be REST APIs or Web Scrapping, requests is must to be learned for proceeding further with these technologies. When one makes a request to a URI, it returns a response.
html5lib: A pure-python library for parsing HTML. It is designed to conform to the WHATWG HTML specification, as is implemented by all major web browsers.
bs4: BeautifulSoup object is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster.
Steps to implement web scraping in python to extract IMDb movie ratings and its ratings:
Import the required modules.
Python3
from bs4 import BeautifulSoupimport requestsimport re
Access the HTML content from the webpage by assigning the URL and creating a soap object.
Python3
# Downloading imdb top 250 movie's dataurl = 'http://www.imdb.com/chart/top'response = requests.get(url)soup = BeautifulSoup(response.text, 'lxml')
Extract the movie ratings and their details. Here, we are extracting data from BeautifulSoup object using Html tags like href, title, etc.
Python3
movies = soup.select('td.titleColumn')links = [a.attrs.get('href') for a in soup.select('td.titleColumn a')]crew = [a.attrs.get('title') for a in soup.select('td.titleColumn a')]ratings = [b.attrs.get('data-value') for b in soup.select('td.posterColumn span[name=ir]')]votes = [b.attrs.get('data-value') for b in soup.select('td.ratingColumn strong')]
After extracting the movie details, create an empty list and store the details in a dictionary, and then adding them to a list.
Python3
# create a empty list for storing# movie informationlist = [] # Iterating over movies to extract# each movie's detailsfor index in range(0, len(movies)): # Separating movie into: 'place', # 'title', 'year' movie_string = movies[index].get_text() movie = (' '.join(movie_string.split()).replace('.', '')) movie_title = movie[len(str(index))+1:-7] year = re.search('\((.*?)\)', movie_string).group(1) place = movie[:len(str(index))-(len(movie))] data = {"movie_title": movie_title, "year": year, "place": place, "star_cast": crew[index], "rating": ratings[index], "vote": votes[index], "link": links[index]} list.append(data)
Now or list is filled with top IMBD movies along with their details. Finally display the list of movie details
Python3
for movie in list: print(movie['place'], '-', movie['movie_title'], '('+movie['year'] + ') -', 'Starring:', moive['star_cast'], movie['rating'])
Complete Code:
Python3
from bs4 import BeautifulSoupimport requestsimport re # Downloading imdb top 250 movie's dataurl = 'http://www.imdb.com/chart/top'response = requests.get(url)soup = BeautifulSoup(response.text, 'lxml') movies = soup.select('td.titleColumn')links = [a.attrs.get('href') for a in soup.select('td.titleColumn a')]crew = [a.attrs.get('title') for a in soup.select('td.titleColumn a')] ratings = [b.attrs.get('data-value') for b in soup.select('td.posterColumn span[name=ir]')] votes = [b.attrs.get('data-value') for b in soup.select('td.ratingColumn strong')] list = [] # create a empty list for storing# movie informationlist = [] # Iterating over movies to extract# each movie's detailsfor index in range(0, len(movies)): # Separating movie into: 'place', # 'title', 'year' movie_string = movies[index].get_text() movie = (' '.join(movie_string.split()).replace('.', '')) movie_title = movie[len(str(index))+1:-7] year = re.search('\((.*?)\)', movie_string).group(1) place = movie[:len(str(index))-(len(movie))] data = {"movie_title": movie_title, "year": year, "place": place, "star_cast": crew[index], "rating": ratings[index], "vote": votes[index], "link": links[index]} list.append(data) # printing movie details with its rating.for movie in list: print(movie['place'], '-', movie['movie_title'], '('+movie['year'] + ') -', 'Starring:', movie['star_cast'], movie['rating'])
Output:
gabaa406
Picked
Python BeautifulSoup
Python bs4-Exercises
Python web-scraping-exercises
Python-requests
Web-scraping
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
|
[
{
"code": null,
"e": 23927,
"s": 23899,
"text": "\n01 Jun, 2021"
},
{
"code": null,
"e": 24037,
"s": 23927,
"text": "We can scrape the IMDb movie ratings and their details with the help of the BeautifulSoup library of Python. "
},
{
"code": null,
"e": 24096,
"s": 24037,
"text": "Below is the list of modules required to scrape from IMDB."
},
{
"code": null,
"e": 24377,
"s": 24096,
"text": "requests: Requests library is an integral part of Python for making HTTP requests to a specified URL. Whether it be REST APIs or Web Scrapping, requests is must to be learned for proceeding further with these technologies. When one makes a request to a URI, it returns a response."
},
{
"code": null,
"e": 24532,
"s": 24377,
"text": "html5lib: A pure-python library for parsing HTML. It is designed to conform to the WHATWG HTML specification, as is implemented by all major web browsers."
},
{
"code": null,
"e": 24748,
"s": 24532,
"text": "bs4: BeautifulSoup object is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster."
},
{
"code": null,
"e": 24837,
"s": 24748,
"text": "Steps to implement web scraping in python to extract IMDb movie ratings and its ratings:"
},
{
"code": null,
"e": 24866,
"s": 24837,
"text": "Import the required modules."
},
{
"code": null,
"e": 24874,
"s": 24866,
"text": "Python3"
},
{
"code": "from bs4 import BeautifulSoupimport requestsimport re",
"e": 24928,
"s": 24874,
"text": null
},
{
"code": null,
"e": 25021,
"s": 24931,
"text": "Access the HTML content from the webpage by assigning the URL and creating a soap object."
},
{
"code": null,
"e": 25031,
"s": 25023,
"text": "Python3"
},
{
"code": "# Downloading imdb top 250 movie's dataurl = 'http://www.imdb.com/chart/top'response = requests.get(url)soup = BeautifulSoup(response.text, 'lxml')",
"e": 25179,
"s": 25031,
"text": null
},
{
"code": null,
"e": 25318,
"s": 25179,
"text": "Extract the movie ratings and their details. Here, we are extracting data from BeautifulSoup object using Html tags like href, title, etc."
},
{
"code": null,
"e": 25326,
"s": 25318,
"text": "Python3"
},
{
"code": "movies = soup.select('td.titleColumn')links = [a.attrs.get('href') for a in soup.select('td.titleColumn a')]crew = [a.attrs.get('title') for a in soup.select('td.titleColumn a')]ratings = [b.attrs.get('data-value') for b in soup.select('td.posterColumn span[name=ir]')]votes = [b.attrs.get('data-value') for b in soup.select('td.ratingColumn strong')]",
"e": 25678,
"s": 25326,
"text": null
},
{
"code": null,
"e": 25809,
"s": 25681,
"text": "After extracting the movie details, create an empty list and store the details in a dictionary, and then adding them to a list."
},
{
"code": null,
"e": 25819,
"s": 25811,
"text": "Python3"
},
{
"code": "# create a empty list for storing# movie informationlist = [] # Iterating over movies to extract# each movie's detailsfor index in range(0, len(movies)): # Separating movie into: 'place', # 'title', 'year' movie_string = movies[index].get_text() movie = (' '.join(movie_string.split()).replace('.', '')) movie_title = movie[len(str(index))+1:-7] year = re.search('\\((.*?)\\)', movie_string).group(1) place = movie[:len(str(index))-(len(movie))] data = {\"movie_title\": movie_title, \"year\": year, \"place\": place, \"star_cast\": crew[index], \"rating\": ratings[index], \"vote\": votes[index], \"link\": links[index]} list.append(data)",
"e": 26545,
"s": 25819,
"text": null
},
{
"code": null,
"e": 26656,
"s": 26545,
"text": "Now or list is filled with top IMBD movies along with their details. Finally display the list of movie details"
},
{
"code": null,
"e": 26664,
"s": 26656,
"text": "Python3"
},
{
"code": "for movie in list: print(movie['place'], '-', movie['movie_title'], '('+movie['year'] + ') -', 'Starring:', moive['star_cast'], movie['rating'])",
"e": 26821,
"s": 26664,
"text": null
},
{
"code": null,
"e": 26836,
"s": 26821,
"text": "Complete Code:"
},
{
"code": null,
"e": 26844,
"s": 26836,
"text": "Python3"
},
{
"code": "from bs4 import BeautifulSoupimport requestsimport re # Downloading imdb top 250 movie's dataurl = 'http://www.imdb.com/chart/top'response = requests.get(url)soup = BeautifulSoup(response.text, 'lxml') movies = soup.select('td.titleColumn')links = [a.attrs.get('href') for a in soup.select('td.titleColumn a')]crew = [a.attrs.get('title') for a in soup.select('td.titleColumn a')] ratings = [b.attrs.get('data-value') for b in soup.select('td.posterColumn span[name=ir]')] votes = [b.attrs.get('data-value') for b in soup.select('td.ratingColumn strong')] list = [] # create a empty list for storing# movie informationlist = [] # Iterating over movies to extract# each movie's detailsfor index in range(0, len(movies)): # Separating movie into: 'place', # 'title', 'year' movie_string = movies[index].get_text() movie = (' '.join(movie_string.split()).replace('.', '')) movie_title = movie[len(str(index))+1:-7] year = re.search('\\((.*?)\\)', movie_string).group(1) place = movie[:len(str(index))-(len(movie))] data = {\"movie_title\": movie_title, \"year\": year, \"place\": place, \"star_cast\": crew[index], \"rating\": ratings[index], \"vote\": votes[index], \"link\": links[index]} list.append(data) # printing movie details with its rating.for movie in list: print(movie['place'], '-', movie['movie_title'], '('+movie['year'] + ') -', 'Starring:', movie['star_cast'], movie['rating'])",
"e": 28350,
"s": 26844,
"text": null
},
{
"code": null,
"e": 28358,
"s": 28350,
"text": "Output:"
},
{
"code": null,
"e": 28367,
"s": 28358,
"text": "gabaa406"
},
{
"code": null,
"e": 28374,
"s": 28367,
"text": "Picked"
},
{
"code": null,
"e": 28395,
"s": 28374,
"text": "Python BeautifulSoup"
},
{
"code": null,
"e": 28416,
"s": 28395,
"text": "Python bs4-Exercises"
},
{
"code": null,
"e": 28446,
"s": 28416,
"text": "Python web-scraping-exercises"
},
{
"code": null,
"e": 28462,
"s": 28446,
"text": "Python-requests"
},
{
"code": null,
"e": 28475,
"s": 28462,
"text": "Web-scraping"
},
{
"code": null,
"e": 28482,
"s": 28475,
"text": "Python"
},
{
"code": null,
"e": 28580,
"s": 28482,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28589,
"s": 28580,
"text": "Comments"
},
{
"code": null,
"e": 28602,
"s": 28589,
"text": "Old Comments"
},
{
"code": null,
"e": 28634,
"s": 28602,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28690,
"s": 28634,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28732,
"s": 28690,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28774,
"s": 28732,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28810,
"s": 28774,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 28832,
"s": 28810,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28871,
"s": 28832,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28898,
"s": 28871,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28929,
"s": 28898,
"text": "Python | os.path.join() method"
}
] |
Replace the Elements of a Vector in R Programming - replace() Function - GeeksforGeeks
|
01 Jun, 2020
replace() function in R Language is used to replace the values in the specified string vector x with indices given in list by those given in values.
Syntax: replace(x, list, values)
Parameters:x: vectorlist: indicesvalues: replacement values
Example 1:
# R program to illustrate# replace function # Initializing a string vectorx <- c("GFG", "gfg", "Geeks") # Getting the stringsx # Calling replace() function to replace# the word gfg at index 2 with the # GeeksforGeeks elementy <- replace(x, 2, "GeeksforGeeks") # Getting the new replaced stringsy
Output :
[1] "GFG" "gfg" "Geeks"
[1] "GFG" "GeeksforGeeks" "Geeks"
Example 2:
# R program to illustrate# replace function # Initializing a string vectorx <- c("GFG", "gfg", "Geeks") # Getting the stringsx # Calling replace() function to replace# the word GFG at index 1 and Geeks at# index 3 with the A and B elements# respectivelyy <- replace(x, c(1, 3), c("A", "B")) # Getting the new replaced stringsy
Output:
[1] "GFG" "gfg" "Geeks"
[1] "A" "gfg" "B"
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
Loops in R (for, while, repeat)
Printing Output of an R Program
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
|
[
{
"code": null,
"e": 24383,
"s": 24355,
"text": "\n01 Jun, 2020"
},
{
"code": null,
"e": 24532,
"s": 24383,
"text": "replace() function in R Language is used to replace the values in the specified string vector x with indices given in list by those given in values."
},
{
"code": null,
"e": 24565,
"s": 24532,
"text": "Syntax: replace(x, list, values)"
},
{
"code": null,
"e": 24625,
"s": 24565,
"text": "Parameters:x: vectorlist: indicesvalues: replacement values"
},
{
"code": null,
"e": 24636,
"s": 24625,
"text": "Example 1:"
},
{
"code": "# R program to illustrate# replace function # Initializing a string vectorx <- c(\"GFG\", \"gfg\", \"Geeks\") # Getting the stringsx # Calling replace() function to replace# the word gfg at index 2 with the # GeeksforGeeks elementy <- replace(x, 2, \"GeeksforGeeks\") # Getting the new replaced stringsy",
"e": 24936,
"s": 24636,
"text": null
},
{
"code": null,
"e": 24945,
"s": 24936,
"text": "Output :"
},
{
"code": null,
"e": 25012,
"s": 24945,
"text": "[1] \"GFG\" \"gfg\" \"Geeks\"\n[1] \"GFG\" \"GeeksforGeeks\" \"Geeks\" \n"
},
{
"code": null,
"e": 25023,
"s": 25012,
"text": "Example 2:"
},
{
"code": "# R program to illustrate# replace function # Initializing a string vectorx <- c(\"GFG\", \"gfg\", \"Geeks\") # Getting the stringsx # Calling replace() function to replace# the word GFG at index 1 and Geeks at# index 3 with the A and B elements# respectivelyy <- replace(x, c(1, 3), c(\"A\", \"B\")) # Getting the new replaced stringsy",
"e": 25354,
"s": 25023,
"text": null
},
{
"code": null,
"e": 25362,
"s": 25354,
"text": "Output:"
},
{
"code": null,
"e": 25413,
"s": 25362,
"text": "[1] \"GFG\" \"gfg\" \"Geeks\"\n[1] \"A\" \"gfg\" \"B\" \n"
},
{
"code": null,
"e": 25431,
"s": 25413,
"text": "R Vector-Function"
},
{
"code": null,
"e": 25442,
"s": 25431,
"text": "R Language"
},
{
"code": null,
"e": 25540,
"s": 25442,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25549,
"s": 25540,
"text": "Comments"
},
{
"code": null,
"e": 25562,
"s": 25549,
"text": "Old Comments"
},
{
"code": null,
"e": 25620,
"s": 25562,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 25664,
"s": 25620,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 25716,
"s": 25664,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 25768,
"s": 25716,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 25800,
"s": 25768,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 25832,
"s": 25800,
"text": "Printing Output of an R Program"
},
{
"code": null,
"e": 25870,
"s": 25832,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 25905,
"s": 25870,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 25963,
"s": 25905,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
}
] |
AVRO - Quick Guide
|
To transfer data over a network or for its persistent storage, you need to serialize the
data. Prior to the serialization APIs provided by Java and Hadoop, we have a special utility, called Avro, a schema-based serialization technique.
This tutorial teaches you how to serialize and deserialize the data using Avro. Avro provides
libraries for various programming languages. In this tutorial, we demonstrate the examples using Java library.
Apache Avro is a language-neutral data serialization system. It was developed by Doug Cutting, the father of Hadoop. Since Hadoop writable classes lack language portability, Avro becomes quite helpful, as it deals with data formats that can be processed by multiple languages. Avro is a preferred tool to serialize data in Hadoop.
Avro has a schema-based system. A language-independent schema is associated with its read and write operations. Avro serializes the data which has a built-in schema. Avro serializes the data into a compact binary format, which can be deserialized by any application.
Avro uses JSON format to declare the data structures. Presently, it supports languages such as Java, C, C++, C#, Python, and Ruby.
Avro depends heavily on its schema. It allows every data to be written with no prior knowledge of the schema. It serializes fast and the resulting serialized data is lesser in size. Schema is stored along with the Avro data in a file for any further processing.
In RPC, the client and the server exchange schemas during the connection. This exchange helps in the communication between same named fields, missing fields, extra fields, etc.
Avro schemas are defined with JSON that simplifies its implementation in languages with JSON libraries.
Like Avro, there are other serialization mechanisms in Hadoop such as Sequence Files, Protocol Buffers, and Thrift.
Thrift and Protocol Buffers are the most competent libraries with Avro. Avro differs from these frameworks in the following ways −
Avro supports both dynamic and static types as per the requirement. Protocol Buffers and Thrift use Interface Definition Languages (IDLs) to specify schemas and their types. These IDLs are used to generate code for serialization and deserialization.
Avro supports both dynamic and static types as per the requirement. Protocol Buffers and Thrift use Interface Definition Languages (IDLs) to specify schemas and their types. These IDLs are used to generate code for serialization and deserialization.
Avro is built in the Hadoop ecosystem. Thrift and Protocol Buffers are not built in Hadoop ecosystem.
Avro is built in the Hadoop ecosystem. Thrift and Protocol Buffers are not built in Hadoop ecosystem.
Unlike Thrift and Protocol Buffer, Avro's schema definition is in JSON and not in any proprietary IDL.
Listed below are some of the prominent features of Avro −
Avro is a language-neutral data serialization system.
Avro is a language-neutral data serialization system.
It can be processed by many languages (currently C, C++, C#, Java, Python, and Ruby).
It can be processed by many languages (currently C, C++, C#, Java, Python, and Ruby).
Avro creates binary structured format that is both compressible and splittable. Hence it can be efficiently used as the input to Hadoop MapReduce jobs.
Avro creates binary structured format that is both compressible and splittable. Hence it can be efficiently used as the input to Hadoop MapReduce jobs.
Avro provides rich data structures. For example, you can create a record that contains an array, an enumerated type, and a sub record. These datatypes can be created in any language, can be processed in Hadoop, and the results can be fed to a third language.
Avro provides rich data structures. For example, you can create a record that contains an array, an enumerated type, and a sub record. These datatypes can be created in any language, can be processed in Hadoop, and the results can be fed to a third language.
Avro schemas defined in JSON, facilitate implementation in the languages that already have JSON libraries.
Avro schemas defined in JSON, facilitate implementation in the languages that already have JSON libraries.
Avro creates a self-describing file named Avro Data File, in which it stores data along with its schema in the metadata section.
Avro creates a self-describing file named Avro Data File, in which it stores data along with its schema in the metadata section.
Avro is also used in Remote Procedure Calls (RPCs). During RPC, client and server exchange schemas in the connection handshake.
Avro is also used in Remote Procedure Calls (RPCs). During RPC, client and server exchange schemas in the connection handshake.
To use Avro, you need to follow the given workflow −
Step 1 − Create schemas. Here you need to design Avro schema according to your data.
Step 1 − Create schemas. Here you need to design Avro schema according to your data.
Step 2 − Read the schemas into your program. It is done in two ways −
By Generating a Class Corresponding to Schema − Compile the schema using Avro. This generates a class file corresponding to the schema
By Using Parsers Library − You can directly read the schema using parsers library.
Step 2 − Read the schemas into your program. It is done in two ways −
By Generating a Class Corresponding to Schema − Compile the schema using Avro. This generates a class file corresponding to the schema
By Generating a Class Corresponding to Schema − Compile the schema using Avro. This generates a class file corresponding to the schema
By Using Parsers Library − You can directly read the schema using parsers library.
By Using Parsers Library − You can directly read the schema using parsers library.
Step 3 − Serialize the data using the serialization API provided for Avro, which is found in the package org.apache.avro.specific.
Step 3 − Serialize the data using the serialization API provided for Avro, which is found in the package org.apache.avro.specific.
Step 4 − Deserialize the data using deserialization API provided for Avro, which is found in the package org.apache.avro.specific.
Step 4 − Deserialize the data using deserialization API provided for Avro, which is found in the package org.apache.avro.specific.
Data is serialized for two objectives −
For persistent storage
For persistent storage
To transport the data over network
To transport the data over network
Serialization is the process of translating data structures or objects state into binary or textual form to transport the data over network or to store on some persisten storage. Once the data is transported over network or retrieved from the persistent storage, it needs to be deserialized again. Serialization is termed as marshalling and deserialization is termed as unmarshalling.
Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.
After a serialized object is written into a file, it can be read from the file and deserialized. That is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.
ObjectInputStream and ObjectOutputStream classes are used to serialize and deserialize an object respectively in Java.
Generally in distributed systems like Hadoop, the concept of serialization is used for Interprocess Communication and Persistent Storage.
To establish the interprocess communication between the nodes connected in a network, RPC technique was used.
To establish the interprocess communication between the nodes connected in a network, RPC technique was used.
RPC used internal serialization to convert the message into binary format before sending it to the remote node via network. At the other end the remote system deserializes the binary stream into the original message.
RPC used internal serialization to convert the message into binary format before sending it to the remote node via network. At the other end the remote system deserializes the binary stream into the original message.
The RPC serialization format is required to be as follows −
Compact − To make the best use of network bandwidth, which is the most scarce resource in a data center.
Fast − Since the communication between the nodes is crucial in distributed systems, the serialization and deserialization process should be quick, producing less overhead.
Extensible − Protocols change over time to meet new requirements, so it should be straightforward to evolve the protocol in a controlled manner for clients and servers.
Interoperable − The message format should support the nodes that are written in different languages.
The RPC serialization format is required to be as follows −
Compact − To make the best use of network bandwidth, which is the most scarce resource in a data center.
Compact − To make the best use of network bandwidth, which is the most scarce resource in a data center.
Fast − Since the communication between the nodes is crucial in distributed systems, the serialization and deserialization process should be quick, producing less overhead.
Fast − Since the communication between the nodes is crucial in distributed systems, the serialization and deserialization process should be quick, producing less overhead.
Extensible − Protocols change over time to meet new requirements, so it should be straightforward to evolve the protocol in a controlled manner for clients and servers.
Extensible − Protocols change over time to meet new requirements, so it should be straightforward to evolve the protocol in a controlled manner for clients and servers.
Interoperable − The message format should support the nodes that are written in different languages.
Interoperable − The message format should support the nodes that are written in different languages.
Persistent Storage is a digital storage facility that does not lose its data with the loss of
power supply. Files, folders, databases are the examples of persistent storage.
This is the interface in Hadoop which provides methods for serialization and deserialization. The following table describes the methods −
void readFields(DataInput in)
This method is used to deserialize the fields of the given object.
void write(DataOutput out)
This method is used to serialize the fields of the given object.
It is the combination of Writable and Comparable interfaces. This interface inherits Writable interface of Hadoop as well as Comparable interface of Java. Therefore it provides methods for data serialization, deserialization, and comparison.
int compareTo(class obj)
This method compares current object with the given object obj.
In addition to these classes, Hadoop supports a number of wrapper classes that implement WritableComparable interface. Each class wraps a Java primitive type. The class hierarchy of Hadoop serialization is given below −
These classes are useful to serialize various types of data in Hadoop. For instance, let us consider the IntWritable class. Let us see how this class is used to serialize and deserialize the data in Hadoop.
This class implements Writable, Comparable, and WritableComparable interfaces. It wraps an integer data type in it. This class provides methods used to serialize and deserialize integer type of data.
int get()
Using this method you can get the integer value present in the current object.
void readFields(DataInput in)
This method is used to deserialize the data in the given DataInput object.
void set(int value)
This method is used to set the value of the current IntWritable object.
void write(DataOutput out)
This method is used to serialize the data in the current object to the given DataOutput object.
The procedure to serialize the integer type of data is discussed below.
Instantiate IntWritable class by wrapping an integer value in it.
Instantiate IntWritable class by wrapping an integer value in it.
Instantiate ByteArrayOutputStream class.
Instantiate ByteArrayOutputStream class.
Instantiate DataOutputStream class and pass the object of ByteArrayOutputStream class to it.
Instantiate DataOutputStream class and pass the object of ByteArrayOutputStream class to it.
Serialize the integer value in IntWritable object using write() method. This method needs an object of DataOutputStream class.
Serialize the integer value in IntWritable object using write() method. This method needs an object of DataOutputStream class.
The serialized data will be stored in the byte array object which is passed as parameter to the DataOutputStream class at the time of instantiation. Convert the data in the object to byte array.
The serialized data will be stored in the byte array object which is passed as parameter to the DataOutputStream class at the time of instantiation. Convert the data in the object to byte array.
The following example shows how to serialize data of integer type in Hadoop −
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
public class Serialization {
public byte[] serialize() throws IOException{
//Instantiating the IntWritable object
IntWritable intwritable = new IntWritable(12);
//Instantiating ByteArrayOutputStream object
ByteArrayOutputStream byteoutputStream = new ByteArrayOutputStream();
//Instantiating DataOutputStream object
DataOutputStream dataOutputStream = new
DataOutputStream(byteoutputStream);
//Serializing the data
intwritable.write(dataOutputStream);
//storing the serialized object in bytearray
byte[] byteArray = byteoutputStream.toByteArray();
//Closing the OutputStream
dataOutputStream.close();
return(byteArray);
}
public static void main(String args[]) throws IOException{
Serialization serialization= new Serialization();
serialization.serialize();
System.out.println();
}
}
The procedure to deserialize the integer type of data is discussed below −
Instantiate IntWritable class by wrapping an integer value in it.
Instantiate IntWritable class by wrapping an integer value in it.
Instantiate ByteArrayOutputStream class.
Instantiate ByteArrayOutputStream class.
Instantiate DataOutputStream class and pass the object of ByteArrayOutputStream class to it.
Instantiate DataOutputStream class and pass the object of ByteArrayOutputStream class to it.
Deserialize the data in the object of DataInputStream using readFields() method of IntWritable class.
Deserialize the data in the object of DataInputStream using readFields() method of IntWritable class.
The deserialized data will be stored in the object of IntWritable class. You can retrieve this data using get() method of this class.
The deserialized data will be stored in the object of IntWritable class. You can retrieve this data using get() method of this class.
The following example shows how to deserialize the data of integer type in Hadoop −
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import org.apache.hadoop.io.IntWritable;
public class Deserialization {
public void deserialize(byte[]byteArray) throws Exception{
//Instantiating the IntWritable class
IntWritable intwritable =new IntWritable();
//Instantiating ByteArrayInputStream object
ByteArrayInputStream InputStream = new ByteArrayInputStream(byteArray);
//Instantiating DataInputStream object
DataInputStream datainputstream=new DataInputStream(InputStream);
//deserializing the data in DataInputStream
intwritable.readFields(datainputstream);
//printing the serialized data
System.out.println((intwritable).get());
}
public static void main(String args[]) throws Exception {
Deserialization dese = new Deserialization();
dese.deserialize(new Serialization().serialize());
}
}
Hadoop’s Writable-based serialization is capable of reducing the object-creation overhead by reusing the Writable objects, which is not possible with the Java’s native serialization framework.
To serialize Hadoop data, there are two ways −
You can use the Writable classes, provided by Hadoop’s native library.
You can use the Writable classes, provided by Hadoop’s native library.
You can also use Sequence Files which store the data in binary format.
You can also use Sequence Files which store the data in binary format.
The main drawback of these two mechanisms is that Writables and SequenceFiles have only a Java API and they cannot be written or read in any other language.
Therefore any of the files created in Hadoop with above two mechanisms cannot be read by any other third language, which makes Hadoop as a limited box. To address this drawback, Doug Cutting created Avro, which is a language independent data structure.
Apache software foundation provides Avro with various releases. You can download the required release from Apache mirrors. Let us see, how to set up the environment to work with Avro −
To download Apache Avro, proceed with the following −
Open the web page Apache.org. You will see the homepage of Apache Avro as shown below −
Open the web page Apache.org. You will see the homepage of Apache Avro as shown below −
Click on project → releases. You will get a list of releases.
Click on project → releases. You will get a list of releases.
Select the latest release which leads you to a download link.
Select the latest release which leads you to a download link.
mirror.nexcess is one of the links where you can find the list of all libraries of different languages that Avro supports as shown below −
mirror.nexcess is one of the links where you can find the list of all libraries of different languages that Avro supports as shown below −
You can select and download the library for any of the languages provided. In this tutorial, we use Java. Hence download the jar files avro-1.7.7.jar and avro-tools-1.7.7.jar.
To use Avro in Eclipse environment, you need to follow the steps given below −
Step 1. Open eclipse.
Step 1. Open eclipse.
Step 2. Create a project.
Step 2. Create a project.
Step 3. Right-click on the project name. You will get a shortcut menu.
Step 3. Right-click on the project name. You will get a shortcut menu.
Step 4. Click on Build Path. It leads you to another shortcut menu.
Step 4. Click on Build Path. It leads you to another shortcut menu.
Step 5. Click on Configure Build Path... You can see Properties window of your project as shown below −
Step 5. Click on Configure Build Path... You can see Properties window of your project as shown below −
Step 6. Under libraries tab, click on ADD EXternal JARs... button.
Step 6. Under libraries tab, click on ADD EXternal JARs... button.
Step 7. Select the jar file avro-1.77.jar you have downloaded.
Step 7. Select the jar file avro-1.77.jar you have downloaded.
Step 8. Click on OK.
Step 8. Click on OK.
You can also get the Avro library into your project using Maven. Given below is the pom.xml file for Avro.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Test</groupId>
<artifactId>Test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.avro</groupId>
<artifactId>avro</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.apache.avro</groupId>
<artifactId>avro-tools</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.0-beta9</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.0-beta9</version>
</dependency>
</dependencies>
</project>
To work with Avro in Linux environment, download the following jar files −
avro-1.77.jar
avro-tools-1.77.jar
log4j-api-2.0-beta9.jar
og4j-core-2.0.beta9.jar.
Copy these files into a folder and set the classpath to the folder, in the ./bashrc file as shown below.
#class path for Avro
export CLASSPATH=$CLASSPATH://home/Hadoop/Avro_Work/jars/*
Avro, being a schema-based serialization utility, accepts schemas as input. In spite of various schemas being available, Avro follows its own standards of defining schemas. These schemas describe the following details −
type of file (record by default)
location of record
name of the record
fields in the record with their corresponding data types
Using these schemas, you can store serialized values in binary format using less space. These values are stored without any metadata.
The Avro schema is created in JavaScript Object Notation (JSON) document format, which is a lightweight text-based data interchange format. It is created in one of the following ways −
A JSON string
A JSON object
A JSON array
Example − The following example shows a schema, which defines a document, under the name space Tutorialspoint, with name Employee, having fields name and age.
{
"type" : "record",
"namespace" : "Tutorialspoint",
"name" : "Employee",
"fields" : [
{ "name" : "Name" , "type" : "string" },
{ "name" : "Age" , "type" : "int" }
]
}
In this example, you can observe that there are four fields for each record −
type − This field comes under the document as well as the under the field named fields.
In case of document, it shows the type of the document, generally a record because there are multiple fields.
When it is field, the type describes data type.
type − This field comes under the document as well as the under the field named fields.
In case of document, it shows the type of the document, generally a record because there are multiple fields.
In case of document, it shows the type of the document, generally a record because there are multiple fields.
When it is field, the type describes data type.
When it is field, the type describes data type.
namespace − This field describes the name of the namespace in which the object resides.
namespace − This field describes the name of the namespace in which the object resides.
name − This field comes under the document as well as the under the field named fields.
In case of document, it describes the schema name. This schema name together with the namespace, uniquely identifies the schema within the store (Namespace.schema name). In the above example, the full name of the schema will be Tutorialspoint.Employee.
In case of fields, it describes name of the field.
name − This field comes under the document as well as the under the field named fields.
In case of document, it describes the schema name. This schema name together with the namespace, uniquely identifies the schema within the store (Namespace.schema name). In the above example, the full name of the schema will be Tutorialspoint.Employee.
In case of document, it describes the schema name. This schema name together with the namespace, uniquely identifies the schema within the store (Namespace.schema name). In the above example, the full name of the schema will be Tutorialspoint.Employee.
In case of fields, it describes name of the field.
In case of fields, it describes name of the field.
Avro schema is having primitive data types as well as complex data types. The following table describes the primitive data types of Avro −
Along with primitive data types, Avro provides six complex data types namely Records, Enums, Arrays, Maps, Unions, and Fixed.
A record data type in Avro is a collection of multiple attributes. It supports the following
attributes −
name − The value of this field holds the name of the record.
name − The value of this field holds the name of the record.
namespace − The value of this field holds the name of the namespace where the
object is stored.
namespace − The value of this field holds the name of the namespace where the
object is stored.
type − The value of this attribute holds either the type of the document (record) or the datatype of the field in the schema.
type − The value of this attribute holds either the type of the document (record) or the datatype of the field in the schema.
fields − This field holds a JSON array, which have the list of all of the fields in the schema, each having name and the type attributes.
fields − This field holds a JSON array, which have the list of all of the fields in the schema, each having name and the type attributes.
Example
Given below is the example of a record.
{
" type " : "record",
" namespace " : "Tutorialspoint",
" name " : "Employee",
" fields " : [
{ "name" : " Name" , "type" : "string" },
{ "name" : "age" , "type" : "int" }
]
}
An enumeration is a list of items in a collection, Avro enumeration supports the following attributes −
name − The value of this field holds the name of the enumeration.
name − The value of this field holds the name of the enumeration.
namespace − The value of this field contains the string that qualifies the name of the Enumeration.
namespace − The value of this field contains the string that qualifies the name of the Enumeration.
symbols − The value of this field holds the enum's symbols as an array of names.
symbols − The value of this field holds the enum's symbols as an array of names.
Example
Given below is the example of an enumeration.
{
"type" : "enum",
"name" : "Numbers",
"namespace": "data",
"symbols" : [ "ONE", "TWO", "THREE", "FOUR" ]
}
This data type defines an array field having a single attribute items. This items attribute specifies the type of items in the array.
Example
{ " type " : " array ", " items " : " int " }
The map data type is an array of key-value pairs, it organizes data as key-value pairs. The
key for an Avro map must be a string. The values of a map hold the data type of the content of map.
Example
{"type" : "map", "values" : "int"}
A union datatype is used whenever the field has one or more datatypes. They are represented as JSON arrays. For example, if a field that could be either an int or null, then the union is represented as ["int", "null"].
Example
Given below is an example document using unions −
{
"type" : "record",
"namespace" : "tutorialspoint",
"name" : "empdetails ",
"fields" :
[
{ "name" : "experience", "type": ["int", "null"] }, { "name" : "age", "type": "int" }
]
}
This data type is used to declare a fixed-sized field that can be used for storing binary data. It has field name and data as attributes. Name holds the name of the field, and size holds the size of the field.
Example
{ "type" : "fixed" , "name" : "bdata", "size" : 1048576}
In the previous chapter, we described the input type of Avro, i.e., Avro schemas. In this chapter, we will explain the classes and methods used in the serialization and deserialization of Avro schemas.
This class belongs to the package org.apache.avro.specific. It implements the DatumWriter interface which converts Java objects into an in-memory serialized format.
SpecificData getSpecificData()
Returns the SpecificData implementation used by this writer.
This class belongs to the package org.apache.avro.specific. It implements the DatumReader interface which reads the data of a schema and determines in-memory data representation. SpecificDatumReader is the class which supports generated java classes.
SpecificDatumReader(Schema schema)
Construct where the writer's and reader's schemas are the same.
SpecificData getSpecificData()
Returns the contained SpecificData.
void setSchema(Schema actual)
This method is used to set the writer's schema.
Instantiates DataFileWrite for emp class. This class writes a sequence serialized records of data conforming to a schema, along with the schema in a file.
void append(D datum)
Appends a datum to a file.
DataFileWriter<D> appendTo(File file)
This method is used to open a writer appending to an existing file.
This class provides random access to files written with DataFileWriter. It inherits the class DataFileStream.
next()
Reads the next datum in the file.
Boolean hasNext()
Returns true if more entries remain in this file.
This class is a parser for JSON-format schemas. It contains methods to parse the schema. It belongs to org.apache.avro package.
parse (File file)
Parses the schema provided in the given file.
parse (InputStream in)
Parses the schema provided in the given InputStream.
parse (String s)
Parses the schema provided in the given String.
This interface provides methods to access the fields by name as well as index.
Object get(String key)
Returns the value of a field given.
void put(String key, Object v)
Sets the value of a field given its name.
Object get(String key)
Returns the value of a field of the given name.
Schema getSchema()
Returns the schema of this instance.
void put(int i, Object v)
Sets the value of a field given its position in the schema.
void put(String key, Object value)
Sets the value of a field given its name.
One can read an Avro schema into the program either by generating a class corresponding to a schema or by using the parsers library. This chapter describes how to read the schema by generating a class and Serializing the data using Avr.
To serialize the data using Avro, follow the steps as given below −
Write an Avro schema.
Write an Avro schema.
Compile the schema using Avro utility. You get the Java code corresponding to that
schema.
Compile the schema using Avro utility. You get the Java code corresponding to that
schema.
Populate the schema with the data.
Populate the schema with the data.
Serialize it using Avro library.
Serialize it using Avro library.
Suppose you want a schema with the following details −
Create an Avro schema as shown below.
Save it as emp.avsc.
{
"namespace": "tutorialspoint.com",
"type": "record",
"name": "emp",
"fields": [
{"name": "name", "type": "string"},
{"name": "id", "type": "int"},
{"name": "salary", "type": "int"},
{"name": "age", "type": "int"},
{"name": "address", "type": "string"}
]
}
After creating an Avro schema, you need to compile the created schema using Avro tools.
avro-tools-1.7.7.jar is the jar containing the tools.
java -jar <path/to/avro-tools-1.7.7.jar> compile schema <path/to/schema-file> <destination-folder>
Open the terminal in the home folder.
Create a new directory to work with Avro as shown below −
$ mkdir Avro_Work
In the newly created directory, create three sub-directories −
First named schema, to place the schema.
First named schema, to place the schema.
Second named with_code_gen, to place the generated code.
Second named with_code_gen, to place the generated code.
Third named jars, to place the jar files.
Third named jars, to place the jar files.
$ mkdir schema
$ mkdir with_code_gen
$ mkdir jars
The following screenshot shows how your Avro_work folder should look like after creating all the directories.
Now /home/Hadoop/Avro_work/jars/avro-tools-1.7.7.jar is the path for the directory where you have downloaded avro-tools-1.7.7.jar file.
Now /home/Hadoop/Avro_work/jars/avro-tools-1.7.7.jar is the path for the directory where you have downloaded avro-tools-1.7.7.jar file.
/home/Hadoop/Avro_work/schema/ is the path for the directory where your schema file emp.avsc is stored.
/home/Hadoop/Avro_work/schema/ is the path for the directory where your schema file emp.avsc is stored.
/home/Hadoop/Avro_work/with_code_gen is the directory where you want the generated class files to be stored.
/home/Hadoop/Avro_work/with_code_gen is the directory where you want the generated class files to be stored.
Now compile the schema as shown below −
$ java -jar /home/Hadoop/Avro_work/jars/avro-tools-1.7.7.jar compile schema /home/Hadoop/Avro_work/schema/emp.avsc /home/Hadoop/Avro/with_code_gen
After compiling, a package according to the name space of the schema is created in the
destination directory. Within this package, the Java source code with schema name is created. This generated source code is the Java code of the given schema which can be used in the applications directly.
For example, in this instance a package/folder, named tutorialspoint is created which contains another folder named com (since the name space is tutorialspoint.com) and within it, you can observe the generated file emp.java. The following snapshot shows emp.java −
This class is useful to create data according to schema.
The generated class contains −
Default constructor, and parameterized constructor which accept all the variables of the schema.
The setter and getter methods for all variables in the schema.
Get() method which returns the schema.
Builder methods.
First of all, copy the generated java file used in this project into the current directory or import it from where it is located.
Now we can write a new Java file and instantiate the class in the generated file (emp) to add employee data to the schema.
Let us see the procedure to create data according to the schema using apache Avro.
Instantiate the generated emp class.
emp e1=new emp( );
Using setter methods, insert the data of first employee. For example, we have created the details of the employee named Omar.
e1.setName("omar");
e1.setAge(21);
e1.setSalary(30000);
e1.setAddress("Hyderabad");
e1.setId(001);
Similarly, fill in all employee details using setter methods.
Create an object of DatumWriter interface using the SpecificDatumWriter class. This converts Java objects into in-memory serialized format. The following example instantiates SpecificDatumWriter class object for emp class.
DatumWriter<emp> empDatumWriter = new SpecificDatumWriter<emp>(emp.class);
Instantiate DataFileWriter for emp class. This class writes a sequence serialized records of data conforming to a schema, along with the schema itself, in a file. This class requires the DatumWriter object, as a parameter to the constructor.
DataFileWriter<emp> empFileWriter = new DataFileWriter<emp>(empDatumWriter);
Open a new file to store the data matching to the given schema using create() method. This method requires the schema, and the path of the file where the data is to be stored, as parameters.
In the following example, schema is passed using getSchema() method, and the data file is stored in the path − /home/Hadoop/Avro/serialized_file/emp.avro.
empFileWriter.create(e1.getSchema(),new File("/home/Hadoop/Avro/serialized_file/emp.avro"));
Add all the created records to the file using append() method as shown below −
empFileWriter.append(e1);
empFileWriter.append(e2);
empFileWriter.append(e3);
The following complete program shows how to serialize data into a file using Apache Avro −
import java.io.File;
import java.io.IOException;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.specific.SpecificDatumWriter;
public class Serialize {
public static void main(String args[]) throws IOException{
//Instantiating generated emp class
emp e1=new emp();
//Creating values according the schema
e1.setName("omar");
e1.setAge(21);
e1.setSalary(30000);
e1.setAddress("Hyderabad");
e1.setId(001);
emp e2=new emp();
e2.setName("ram");
e2.setAge(30);
e2.setSalary(40000);
e2.setAddress("Hyderabad");
e2.setId(002);
emp e3=new emp();
e3.setName("robbin");
e3.setAge(25);
e3.setSalary(35000);
e3.setAddress("Hyderabad");
e3.setId(003);
//Instantiate DatumWriter class
DatumWriter<emp> empDatumWriter = new SpecificDatumWriter<emp>(emp.class);
DataFileWriter<emp> empFileWriter = new DataFileWriter<emp>(empDatumWriter);
empFileWriter.create(e1.getSchema(), new File("/home/Hadoop/Avro_Work/with_code_gen/emp.avro"));
empFileWriter.append(e1);
empFileWriter.append(e2);
empFileWriter.append(e3);
empFileWriter.close();
System.out.println("data successfully serialized");
}
}
Browse through the directory where the generated code is placed. In this case, at home/Hadoop/Avro_work/with_code_gen.
In Terminal −
$ cd home/Hadoop/Avro_work/with_code_gen/
In GUI −
Now copy and save the above program in the file named Serialize.java
Compile and execute it as shown below −
$ javac Serialize.java
$ java Serialize
data successfully serialized
If you verify the path given in the program, you can find the generated serialized file as shown below.
As described earlier, one can read an Avro schema into a program either by generating a class corresponding to the schema or by using the parsers library. This chapter describes how to read the schema by generating a class and Deserialize the data using Avro.
The serialized data is stored in the file emp.avro. You can deserialize and read it using Avro.
Follow the procedure given below to deserialize the serialized data from a file.
Create an object of DatumReader interface using SpecificDatumReader class.
DatumReader<emp>empDatumReader = new SpecificDatumReader<emp>(emp.class);
Instantiate DataFileReader for emp class. This class reads serialized data from a file. It requires the Dataumeader object, and path of the file where the serialized data is existing, as a parameters to the constructor.
DataFileReader<emp> dataFileReader = new DataFileReader(new File("/path/to/emp.avro"), empDatumReader);
Print the deserialized data, using the methods of DataFileReader.
The hasNext() method will return a boolean if there are any elements in the Reader.
The hasNext() method will return a boolean if there are any elements in the Reader.
The next() method of DataFileReader returns the data in the Reader.
The next() method of DataFileReader returns the data in the Reader.
while(dataFileReader.hasNext()){
em=dataFileReader.next(em);
System.out.println(em);
}
The following complete program shows how to deserialize the data in a file using Avro.
import java.io.File;
import java.io.IOException;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.io.DatumReader;
import org.apache.avro.specific.SpecificDatumReader;
public class Deserialize {
public static void main(String args[]) throws IOException{
//DeSerializing the objects
DatumReader<emp> empDatumReader = new SpecificDatumReader<emp>(emp.class);
//Instantiating DataFileReader
DataFileReader<emp> dataFileReader = new DataFileReader<emp>(new
File("/home/Hadoop/Avro_Work/with_code_genfile/emp.avro"), empDatumReader);
emp em=null;
while(dataFileReader.hasNext()){
em=dataFileReader.next(em);
System.out.println(em);
}
}
}
Browse into the directory where the generated code is placed. In this case, at home/Hadoop/Avro_work/with_code_gen.
$ cd home/Hadoop/Avro_work/with_code_gen/
Now, copy and save the above program in the file named DeSerialize.java. Compile and execute it as shown below −
$ javac Deserialize.java
$ java Deserialize
{"name": "omar", "id": 1, "salary": 30000, "age": 21, "address": "Hyderabad"}
{"name": "ram", "id": 2, "salary": 40000, "age": 30, "address": "Hyderabad"}
{"name": "robbin", "id": 3, "salary": 35000, "age": 25, "address": "Hyderabad"}
One can read an Avro schema into a program either by generating a class corresponding to a schema or by using the parsers library. In Avro, data is always stored with its corresponding schema. Therefore, we can always read a schema without code generation.
This chapter describes how to read the schema by using parsers library and to serialize the data using Avro.
To serialize the data, we need to read the schema, create data according to the schema, and serialize the schema using the Avro API. The following procedure serializes the data without generating any code −
First of all, read the schema from the file. To do so, use Schema.Parser class. This class provides methods to parse the schema in different formats.
Instantiate the Schema.Parser class by passing the file path where the schema is stored.
Schema schema = new Schema.Parser().parse(new File("/path/to/emp.avsc"));
Create the object of GenericRecord interface, by instantiating GenericData.Record class as shown below. Pass the above created schema object to its constructor.
GenericRecord e1 = new GenericData.Record(schema);
Insert the values in the schema using the put() method of the GenericData class.
e1.put("name", "ramu");
e1.put("id", 001);
e1.put("salary",30000);
e1.put("age", 25);
e1.put("address", "chennai");
Create an object of DatumWriter interface using the SpecificDatumWriter class. It converts Java objects into in-memory serialized format. The following example instantiates SpecificDatumWriter class object for emp class −
DatumWriter<emp> empDatumWriter = new SpecificDatumWriter<emp>(emp.class);
Instantiate DataFileWriter for emp class. This class writes serialized records of data conforming to a schema, along with the schema itself, in a file. This class requires the DatumWriter object, as a parameter to the constructor.
DataFileWriter<emp> dataFileWriter = new DataFileWriter<emp>(empDatumWriter);
Open a new file to store the data matching to the given schema using create() method. This method requires the schema, and the path of the file where the data is to be stored, as parameters.
In the example given below, schema is passed using getSchema() method and the data file is stored in the path
/home/Hadoop/Avro/serialized_file/emp.avro.
empFileWriter.create(e1.getSchema(), new
File("/home/Hadoop/Avro/serialized_file/emp.avro"));
Add all the created records to the file using append( ) method as shown below.
empFileWriter.append(e1);
empFileWriter.append(e2);
empFileWriter.append(e3);
The following complete program shows how to serialize the data using parsers −
import java.io.File;
import java.io.IOException;
import org.apache.avro.Schema;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.io.DatumWriter;
public class Seriali {
public static void main(String args[]) throws IOException{
//Instantiating the Schema.Parser class.
Schema schema = new Schema.Parser().parse(new File("/home/Hadoop/Avro/schema/emp.avsc"));
//Instantiating the GenericRecord class.
GenericRecord e1 = new GenericData.Record(schema);
//Insert data according to schema
e1.put("name", "ramu");
e1.put("id", 001);
e1.put("salary",30000);
e1.put("age", 25);
e1.put("address", "chenni");
GenericRecord e2 = new GenericData.Record(schema);
e2.put("name", "rahman");
e2.put("id", 002);
e2.put("salary", 35000);
e2.put("age", 30);
e2.put("address", "Delhi");
DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<GenericRecord>(schema);
DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<GenericRecord>(datumWriter);
dataFileWriter.create(schema, new File("/home/Hadoop/Avro_work/without_code_gen/mydata.txt"));
dataFileWriter.append(e1);
dataFileWriter.append(e2);
dataFileWriter.close();
System.out.println(“data successfully serialized”);
}
}
Browse into the directory where the generated code is placed. In this case, at home/Hadoop/Avro_work/without_code_gen.
$ cd home/Hadoop/Avro_work/without_code_gen/
Now copy and save the above program in the file named Serialize.java. Compile and execute it as shown below −
$ javac Serialize.java
$ java Serialize
data successfully serialized
If you verify the path given in the program, you can find the generated serialized file as shown below.
As mentioned earlier, one can read an Avro schema into a program either by generating a class corresponding to a schema or by using the parsers library. In Avro, data is always stored with its corresponding schema. Therefore, we can always read a serialized item without code generation.
This chapter describes how to read the schema using parsers library and Deserializing the data using Avro.
The serialized data is stored in the file mydata.txt. You can deserialize and read it using Avro.
Follow the procedure given below to deserialize the serialized data from a file.
First of all, read the schema from the file. To do so, use Schema.Parser class. This class provides methods to parse the schema in different formats.
Instantiate the Schema.Parser class by passing the file path where the schema is stored.
Schema schema = new Schema.Parser().parse(new File("/path/to/emp.avsc"));
Create an object of DatumReader interface using SpecificDatumReader class.
DatumReader<emp>empDatumReader = new SpecificDatumReader<emp>(emp.class);
Instantiate DataFileReader class. This class reads serialized data from a file. It requires the DatumReader object, and path of the file where the serialized data exists, as a parameters to the constructor.
DataFileReader<GenericRecord> dataFileReader = new DataFileReader<GenericRecord>(new File("/path/to/mydata.txt"), datumReader);
Print the deserialized data, using the methods of DataFileReader.
The hasNext() method returns a boolean if there are any elements in the Reader
.
The hasNext() method returns a boolean if there are any elements in the Reader
.
The next() method of DataFileReader returns the data in the Reader.
The next() method of DataFileReader returns the data in the Reader.
while(dataFileReader.hasNext()){
em=dataFileReader.next(em);
System.out.println(em);
}
The following complete program shows how to deserialize the serialized data using Parsers library −
public class Deserialize {
public static void main(String args[]) throws Exception{
//Instantiating the Schema.Parser class.
Schema schema = new Schema.Parser().parse(new File("/home/Hadoop/Avro/schema/emp.avsc"));
DatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>(schema);
DataFileReader<GenericRecord> dataFileReader = new DataFileReader<GenericRecord>(new File("/home/Hadoop/Avro_Work/without_code_gen/mydata.txt"), datumReader);
GenericRecord emp = null;
while (dataFileReader.hasNext()) {
emp = dataFileReader.next(emp);
System.out.println(emp);
}
System.out.println("hello");
}
}
Browse into the directory where the generated code is placed. In this case, it is at home/Hadoop/Avro_work/without_code_gen.
$ cd home/Hadoop/Avro_work/without_code_gen/
Now copy and save the above program in the file named DeSerialize.java. Compile and execute it as shown below −
$ javac Deserialize.java
$ java Deserialize
{"name": "ramu", "id": 1, "salary": 30000, "age": 25, "address": "chennai"}
{"name": "rahman", "id": 2, "salary": 35000, "age": 30, "address": "Delhi"}
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2097,
"s": 1861,
"text": "To transfer data over a network or for its persistent storage, you need to serialize the\ndata. Prior to the serialization APIs provided by Java and Hadoop, we have a special utility, called Avro, a schema-based serialization technique."
},
{
"code": null,
"e": 2302,
"s": 2097,
"text": "This tutorial teaches you how to serialize and deserialize the data using Avro. Avro provides\nlibraries for various programming languages. In this tutorial, we demonstrate the examples using Java library."
},
{
"code": null,
"e": 2633,
"s": 2302,
"text": "Apache Avro is a language-neutral data serialization system. It was developed by Doug Cutting, the father of Hadoop. Since Hadoop writable classes lack language portability, Avro becomes quite helpful, as it deals with data formats that can be processed by multiple languages. Avro is a preferred tool to serialize data in Hadoop."
},
{
"code": null,
"e": 2900,
"s": 2633,
"text": "Avro has a schema-based system. A language-independent schema is associated with its read and write operations. Avro serializes the data which has a built-in schema. Avro serializes the data into a compact binary format, which can be deserialized by any application."
},
{
"code": null,
"e": 3031,
"s": 2900,
"text": "Avro uses JSON format to declare the data structures. Presently, it supports languages such as Java, C, C++, C#, Python, and Ruby."
},
{
"code": null,
"e": 3293,
"s": 3031,
"text": "Avro depends heavily on its schema. It allows every data to be written with no prior knowledge of the schema. It serializes fast and the resulting serialized data is lesser in size. Schema is stored along with the Avro data in a file for any further processing."
},
{
"code": null,
"e": 3470,
"s": 3293,
"text": "In RPC, the client and the server exchange schemas during the connection. This exchange helps in the communication between same named fields, missing fields, extra fields, etc."
},
{
"code": null,
"e": 3574,
"s": 3470,
"text": "Avro schemas are defined with JSON that simplifies its implementation in languages with JSON libraries."
},
{
"code": null,
"e": 3690,
"s": 3574,
"text": "Like Avro, there are other serialization mechanisms in Hadoop such as Sequence Files, Protocol Buffers, and Thrift."
},
{
"code": null,
"e": 3821,
"s": 3690,
"text": "Thrift and Protocol Buffers are the most competent libraries with Avro. Avro differs from these frameworks in the following ways −"
},
{
"code": null,
"e": 4071,
"s": 3821,
"text": "Avro supports both dynamic and static types as per the requirement. Protocol Buffers and Thrift use Interface Definition Languages (IDLs) to specify schemas and their types. These IDLs are used to generate code for serialization and deserialization."
},
{
"code": null,
"e": 4321,
"s": 4071,
"text": "Avro supports both dynamic and static types as per the requirement. Protocol Buffers and Thrift use Interface Definition Languages (IDLs) to specify schemas and their types. These IDLs are used to generate code for serialization and deserialization."
},
{
"code": null,
"e": 4423,
"s": 4321,
"text": "Avro is built in the Hadoop ecosystem. Thrift and Protocol Buffers are not built in Hadoop ecosystem."
},
{
"code": null,
"e": 4525,
"s": 4423,
"text": "Avro is built in the Hadoop ecosystem. Thrift and Protocol Buffers are not built in Hadoop ecosystem."
},
{
"code": null,
"e": 4628,
"s": 4525,
"text": "Unlike Thrift and Protocol Buffer, Avro's schema definition is in JSON and not in any proprietary IDL."
},
{
"code": null,
"e": 4686,
"s": 4628,
"text": "Listed below are some of the prominent features of Avro −"
},
{
"code": null,
"e": 4740,
"s": 4686,
"text": "Avro is a language-neutral data serialization system."
},
{
"code": null,
"e": 4794,
"s": 4740,
"text": "Avro is a language-neutral data serialization system."
},
{
"code": null,
"e": 4880,
"s": 4794,
"text": "It can be processed by many languages (currently C, C++, C#, Java, Python, and Ruby)."
},
{
"code": null,
"e": 4966,
"s": 4880,
"text": "It can be processed by many languages (currently C, C++, C#, Java, Python, and Ruby)."
},
{
"code": null,
"e": 5118,
"s": 4966,
"text": "Avro creates binary structured format that is both compressible and splittable. Hence it can be efficiently used as the input to Hadoop MapReduce jobs."
},
{
"code": null,
"e": 5270,
"s": 5118,
"text": "Avro creates binary structured format that is both compressible and splittable. Hence it can be efficiently used as the input to Hadoop MapReduce jobs."
},
{
"code": null,
"e": 5529,
"s": 5270,
"text": "Avro provides rich data structures. For example, you can create a record that contains an array, an enumerated type, and a sub record. These datatypes can be created in any language, can be processed in Hadoop, and the results can be fed to a third language."
},
{
"code": null,
"e": 5788,
"s": 5529,
"text": "Avro provides rich data structures. For example, you can create a record that contains an array, an enumerated type, and a sub record. These datatypes can be created in any language, can be processed in Hadoop, and the results can be fed to a third language."
},
{
"code": null,
"e": 5895,
"s": 5788,
"text": "Avro schemas defined in JSON, facilitate implementation in the languages that already have JSON libraries."
},
{
"code": null,
"e": 6002,
"s": 5895,
"text": "Avro schemas defined in JSON, facilitate implementation in the languages that already have JSON libraries."
},
{
"code": null,
"e": 6131,
"s": 6002,
"text": "Avro creates a self-describing file named Avro Data File, in which it stores data along with its schema in the metadata section."
},
{
"code": null,
"e": 6260,
"s": 6131,
"text": "Avro creates a self-describing file named Avro Data File, in which it stores data along with its schema in the metadata section."
},
{
"code": null,
"e": 6388,
"s": 6260,
"text": "Avro is also used in Remote Procedure Calls (RPCs). During RPC, client and server exchange schemas in the connection handshake."
},
{
"code": null,
"e": 6516,
"s": 6388,
"text": "Avro is also used in Remote Procedure Calls (RPCs). During RPC, client and server exchange schemas in the connection handshake."
},
{
"code": null,
"e": 6569,
"s": 6516,
"text": "To use Avro, you need to follow the given workflow −"
},
{
"code": null,
"e": 6654,
"s": 6569,
"text": "Step 1 − Create schemas. Here you need to design Avro schema according to your data."
},
{
"code": null,
"e": 6739,
"s": 6654,
"text": "Step 1 − Create schemas. Here you need to design Avro schema according to your data."
},
{
"code": null,
"e": 7030,
"s": 6739,
"text": "Step 2 − Read the schemas into your program. It is done in two ways −\n\nBy Generating a Class Corresponding to Schema − Compile the schema using Avro. This generates a class file corresponding to the schema\nBy Using Parsers Library − You can directly read the schema using parsers library.\n\n"
},
{
"code": null,
"e": 7100,
"s": 7030,
"text": "Step 2 − Read the schemas into your program. It is done in two ways −"
},
{
"code": null,
"e": 7235,
"s": 7100,
"text": "By Generating a Class Corresponding to Schema − Compile the schema using Avro. This generates a class file corresponding to the schema"
},
{
"code": null,
"e": 7370,
"s": 7235,
"text": "By Generating a Class Corresponding to Schema − Compile the schema using Avro. This generates a class file corresponding to the schema"
},
{
"code": null,
"e": 7453,
"s": 7370,
"text": "By Using Parsers Library − You can directly read the schema using parsers library."
},
{
"code": null,
"e": 7536,
"s": 7453,
"text": "By Using Parsers Library − You can directly read the schema using parsers library."
},
{
"code": null,
"e": 7667,
"s": 7536,
"text": "Step 3 − Serialize the data using the serialization API provided for Avro, which is found in the package org.apache.avro.specific."
},
{
"code": null,
"e": 7798,
"s": 7667,
"text": "Step 3 − Serialize the data using the serialization API provided for Avro, which is found in the package org.apache.avro.specific."
},
{
"code": null,
"e": 7929,
"s": 7798,
"text": "Step 4 − Deserialize the data using deserialization API provided for Avro, which is found in the package org.apache.avro.specific."
},
{
"code": null,
"e": 8060,
"s": 7929,
"text": "Step 4 − Deserialize the data using deserialization API provided for Avro, which is found in the package org.apache.avro.specific."
},
{
"code": null,
"e": 8100,
"s": 8060,
"text": "Data is serialized for two objectives −"
},
{
"code": null,
"e": 8123,
"s": 8100,
"text": "For persistent storage"
},
{
"code": null,
"e": 8146,
"s": 8123,
"text": "For persistent storage"
},
{
"code": null,
"e": 8181,
"s": 8146,
"text": "To transport the data over network"
},
{
"code": null,
"e": 8216,
"s": 8181,
"text": "To transport the data over network"
},
{
"code": null,
"e": 8601,
"s": 8216,
"text": "Serialization is the process of translating data structures or objects state into binary or textual form to transport the data over network or to store on some persisten storage. Once the data is transported over network or retrieved from the persistent storage, it needs to be deserialized again. Serialization is termed as marshalling and deserialization is termed as unmarshalling."
},
{
"code": null,
"e": 8837,
"s": 8601,
"text": "Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object."
},
{
"code": null,
"e": 9059,
"s": 8837,
"text": "After a serialized object is written into a file, it can be read from the file and deserialized. That is, the type information and bytes that represent the object and its data can be used to recreate the object in memory."
},
{
"code": null,
"e": 9178,
"s": 9059,
"text": "ObjectInputStream and ObjectOutputStream classes are used to serialize and deserialize an object respectively in Java."
},
{
"code": null,
"e": 9316,
"s": 9178,
"text": "Generally in distributed systems like Hadoop, the concept of serialization is used for Interprocess Communication and Persistent Storage."
},
{
"code": null,
"e": 9426,
"s": 9316,
"text": "To establish the interprocess communication between the nodes connected in a network, RPC technique was used."
},
{
"code": null,
"e": 9536,
"s": 9426,
"text": "To establish the interprocess communication between the nodes connected in a network, RPC technique was used."
},
{
"code": null,
"e": 9753,
"s": 9536,
"text": "RPC used internal serialization to convert the message into binary format before sending it to the remote node via network. At the other end the remote system deserializes the binary stream into the original message."
},
{
"code": null,
"e": 9970,
"s": 9753,
"text": "RPC used internal serialization to convert the message into binary format before sending it to the remote node via network. At the other end the remote system deserializes the binary stream into the original message."
},
{
"code": null,
"e": 10580,
"s": 9970,
"text": "The RPC serialization format is required to be as follows −\n\nCompact − To make the best use of network bandwidth, which is the most scarce resource in a data center.\nFast − Since the communication between the nodes is crucial in distributed systems, the serialization and deserialization process should be quick, producing less overhead.\nExtensible − Protocols change over time to meet new requirements, so it should be straightforward to evolve the protocol in a controlled manner for clients and servers.\nInteroperable − The message format should support the nodes that are written in different languages.\n\n"
},
{
"code": null,
"e": 10640,
"s": 10580,
"text": "The RPC serialization format is required to be as follows −"
},
{
"code": null,
"e": 10745,
"s": 10640,
"text": "Compact − To make the best use of network bandwidth, which is the most scarce resource in a data center."
},
{
"code": null,
"e": 10850,
"s": 10745,
"text": "Compact − To make the best use of network bandwidth, which is the most scarce resource in a data center."
},
{
"code": null,
"e": 11022,
"s": 10850,
"text": "Fast − Since the communication between the nodes is crucial in distributed systems, the serialization and deserialization process should be quick, producing less overhead."
},
{
"code": null,
"e": 11194,
"s": 11022,
"text": "Fast − Since the communication between the nodes is crucial in distributed systems, the serialization and deserialization process should be quick, producing less overhead."
},
{
"code": null,
"e": 11363,
"s": 11194,
"text": "Extensible − Protocols change over time to meet new requirements, so it should be straightforward to evolve the protocol in a controlled manner for clients and servers."
},
{
"code": null,
"e": 11532,
"s": 11363,
"text": "Extensible − Protocols change over time to meet new requirements, so it should be straightforward to evolve the protocol in a controlled manner for clients and servers."
},
{
"code": null,
"e": 11633,
"s": 11532,
"text": "Interoperable − The message format should support the nodes that are written in different languages."
},
{
"code": null,
"e": 11734,
"s": 11633,
"text": "Interoperable − The message format should support the nodes that are written in different languages."
},
{
"code": null,
"e": 11908,
"s": 11734,
"text": "Persistent Storage is a digital storage facility that does not lose its data with the loss of\npower supply. Files, folders, databases are the examples of persistent storage."
},
{
"code": null,
"e": 12046,
"s": 11908,
"text": "This is the interface in Hadoop which provides methods for serialization and deserialization. The following table describes the methods −"
},
{
"code": null,
"e": 12076,
"s": 12046,
"text": "void readFields(DataInput in)"
},
{
"code": null,
"e": 12143,
"s": 12076,
"text": "This method is used to deserialize the fields of the given object."
},
{
"code": null,
"e": 12170,
"s": 12143,
"text": "void write(DataOutput out)"
},
{
"code": null,
"e": 12235,
"s": 12170,
"text": "This method is used to serialize the fields of the given object."
},
{
"code": null,
"e": 12477,
"s": 12235,
"text": "It is the combination of Writable and Comparable interfaces. This interface inherits Writable interface of Hadoop as well as Comparable interface of Java. Therefore it provides methods for data serialization, deserialization, and comparison."
},
{
"code": null,
"e": 12502,
"s": 12477,
"text": "int compareTo(class obj)"
},
{
"code": null,
"e": 12565,
"s": 12502,
"text": "This method compares current object with the given object obj."
},
{
"code": null,
"e": 12785,
"s": 12565,
"text": "In addition to these classes, Hadoop supports a number of wrapper classes that implement WritableComparable interface. Each class wraps a Java primitive type. The class hierarchy of Hadoop serialization is given below −"
},
{
"code": null,
"e": 12992,
"s": 12785,
"text": "These classes are useful to serialize various types of data in Hadoop. For instance, let us consider the IntWritable class. Let us see how this class is used to serialize and deserialize the data in Hadoop."
},
{
"code": null,
"e": 13192,
"s": 12992,
"text": "This class implements Writable, Comparable, and WritableComparable interfaces. It wraps an integer data type in it. This class provides methods used to serialize and deserialize integer type of data."
},
{
"code": null,
"e": 13202,
"s": 13192,
"text": "int get()"
},
{
"code": null,
"e": 13281,
"s": 13202,
"text": "Using this method you can get the integer value present in the current object."
},
{
"code": null,
"e": 13311,
"s": 13281,
"text": "void readFields(DataInput in)"
},
{
"code": null,
"e": 13386,
"s": 13311,
"text": "This method is used to deserialize the data in the given DataInput object."
},
{
"code": null,
"e": 13406,
"s": 13386,
"text": "void set(int value)"
},
{
"code": null,
"e": 13478,
"s": 13406,
"text": "This method is used to set the value of the current IntWritable object."
},
{
"code": null,
"e": 13505,
"s": 13478,
"text": "void write(DataOutput out)"
},
{
"code": null,
"e": 13601,
"s": 13505,
"text": "This method is used to serialize the data in the current object to the given DataOutput object."
},
{
"code": null,
"e": 13673,
"s": 13601,
"text": "The procedure to serialize the integer type of data is discussed below."
},
{
"code": null,
"e": 13739,
"s": 13673,
"text": "Instantiate IntWritable class by wrapping an integer value in it."
},
{
"code": null,
"e": 13805,
"s": 13739,
"text": "Instantiate IntWritable class by wrapping an integer value in it."
},
{
"code": null,
"e": 13846,
"s": 13805,
"text": "Instantiate ByteArrayOutputStream class."
},
{
"code": null,
"e": 13887,
"s": 13846,
"text": "Instantiate ByteArrayOutputStream class."
},
{
"code": null,
"e": 13980,
"s": 13887,
"text": "Instantiate DataOutputStream class and pass the object of ByteArrayOutputStream class to it."
},
{
"code": null,
"e": 14073,
"s": 13980,
"text": "Instantiate DataOutputStream class and pass the object of ByteArrayOutputStream class to it."
},
{
"code": null,
"e": 14200,
"s": 14073,
"text": "Serialize the integer value in IntWritable object using write() method. This method needs an object of DataOutputStream class."
},
{
"code": null,
"e": 14327,
"s": 14200,
"text": "Serialize the integer value in IntWritable object using write() method. This method needs an object of DataOutputStream class."
},
{
"code": null,
"e": 14522,
"s": 14327,
"text": "The serialized data will be stored in the byte array object which is passed as parameter to the DataOutputStream class at the time of instantiation. Convert the data in the object to byte array."
},
{
"code": null,
"e": 14717,
"s": 14522,
"text": "The serialized data will be stored in the byte array object which is passed as parameter to the DataOutputStream class at the time of instantiation. Convert the data in the object to byte array."
},
{
"code": null,
"e": 14795,
"s": 14717,
"text": "The following example shows how to serialize data of integer type in Hadoop −"
},
{
"code": null,
"e": 15861,
"s": 14795,
"text": "import java.io.ByteArrayOutputStream;\nimport java.io.DataOutputStream;\n\nimport java.io.IOException;\n\nimport org.apache.hadoop.io.IntWritable;\n\npublic class Serialization {\n public byte[] serialize() throws IOException{\n\t\t\n //Instantiating the IntWritable object\n IntWritable intwritable = new IntWritable(12);\n \n //Instantiating ByteArrayOutputStream object\n ByteArrayOutputStream byteoutputStream = new ByteArrayOutputStream();\n \n //Instantiating DataOutputStream object\n DataOutputStream dataOutputStream = new\n DataOutputStream(byteoutputStream);\n \n //Serializing the data\n intwritable.write(dataOutputStream);\n \n //storing the serialized object in bytearray\n byte[] byteArray = byteoutputStream.toByteArray();\n \n //Closing the OutputStream\n dataOutputStream.close();\n return(byteArray);\n }\n\t\n public static void main(String args[]) throws IOException{\n Serialization serialization= new Serialization();\n serialization.serialize();\n System.out.println();\n }\n}"
},
{
"code": null,
"e": 15936,
"s": 15861,
"text": "The procedure to deserialize the integer type of data is discussed below −"
},
{
"code": null,
"e": 16002,
"s": 15936,
"text": "Instantiate IntWritable class by wrapping an integer value in it."
},
{
"code": null,
"e": 16068,
"s": 16002,
"text": "Instantiate IntWritable class by wrapping an integer value in it."
},
{
"code": null,
"e": 16109,
"s": 16068,
"text": "Instantiate ByteArrayOutputStream class."
},
{
"code": null,
"e": 16150,
"s": 16109,
"text": "Instantiate ByteArrayOutputStream class."
},
{
"code": null,
"e": 16243,
"s": 16150,
"text": "Instantiate DataOutputStream class and pass the object of ByteArrayOutputStream class to it."
},
{
"code": null,
"e": 16336,
"s": 16243,
"text": "Instantiate DataOutputStream class and pass the object of ByteArrayOutputStream class to it."
},
{
"code": null,
"e": 16438,
"s": 16336,
"text": "Deserialize the data in the object of DataInputStream using readFields() method of IntWritable class."
},
{
"code": null,
"e": 16540,
"s": 16438,
"text": "Deserialize the data in the object of DataInputStream using readFields() method of IntWritable class."
},
{
"code": null,
"e": 16674,
"s": 16540,
"text": "The deserialized data will be stored in the object of IntWritable class. You can retrieve this data using get() method of this class."
},
{
"code": null,
"e": 16808,
"s": 16674,
"text": "The deserialized data will be stored in the object of IntWritable class. You can retrieve this data using get() method of this class."
},
{
"code": null,
"e": 16892,
"s": 16808,
"text": "The following example shows how to deserialize the data of integer type in Hadoop −"
},
{
"code": null,
"e": 17836,
"s": 16892,
"text": "import java.io.ByteArrayInputStream;\nimport java.io.DataInputStream;\n\nimport org.apache.hadoop.io.IntWritable;\n\npublic class Deserialization {\n\n public void deserialize(byte[]byteArray) throws Exception{\n \n //Instantiating the IntWritable class\n IntWritable intwritable =new IntWritable();\n \n //Instantiating ByteArrayInputStream object\n ByteArrayInputStream InputStream = new ByteArrayInputStream(byteArray);\n \n //Instantiating DataInputStream object\n DataInputStream datainputstream=new DataInputStream(InputStream);\n \n //deserializing the data in DataInputStream\n intwritable.readFields(datainputstream);\n \n //printing the serialized data\n System.out.println((intwritable).get());\n }\n \n public static void main(String args[]) throws Exception {\n Deserialization dese = new Deserialization();\n dese.deserialize(new Serialization().serialize());\n }\n}"
},
{
"code": null,
"e": 18029,
"s": 17836,
"text": "Hadoop’s Writable-based serialization is capable of reducing the object-creation overhead by reusing the Writable objects, which is not possible with the Java’s native serialization framework."
},
{
"code": null,
"e": 18076,
"s": 18029,
"text": "To serialize Hadoop data, there are two ways −"
},
{
"code": null,
"e": 18147,
"s": 18076,
"text": "You can use the Writable classes, provided by Hadoop’s native library."
},
{
"code": null,
"e": 18218,
"s": 18147,
"text": "You can use the Writable classes, provided by Hadoop’s native library."
},
{
"code": null,
"e": 18289,
"s": 18218,
"text": "You can also use Sequence Files which store the data in binary format."
},
{
"code": null,
"e": 18360,
"s": 18289,
"text": "You can also use Sequence Files which store the data in binary format."
},
{
"code": null,
"e": 18517,
"s": 18360,
"text": "The main drawback of these two mechanisms is that Writables and SequenceFiles have only a Java API and they cannot be written or read in any other language."
},
{
"code": null,
"e": 18770,
"s": 18517,
"text": "Therefore any of the files created in Hadoop with above two mechanisms cannot be read by any other third language, which makes Hadoop as a limited box. To address this drawback, Doug Cutting created Avro, which is a language independent data structure."
},
{
"code": null,
"e": 18955,
"s": 18770,
"text": "Apache software foundation provides Avro with various releases. You can download the required release from Apache mirrors. Let us see, how to set up the environment to work with Avro −"
},
{
"code": null,
"e": 19009,
"s": 18955,
"text": "To download Apache Avro, proceed with the following −"
},
{
"code": null,
"e": 19097,
"s": 19009,
"text": "Open the web page Apache.org. You will see the homepage of Apache Avro as shown below −"
},
{
"code": null,
"e": 19185,
"s": 19097,
"text": "Open the web page Apache.org. You will see the homepage of Apache Avro as shown below −"
},
{
"code": null,
"e": 19247,
"s": 19185,
"text": "Click on project → releases. You will get a list of releases."
},
{
"code": null,
"e": 19309,
"s": 19247,
"text": "Click on project → releases. You will get a list of releases."
},
{
"code": null,
"e": 19371,
"s": 19309,
"text": "Select the latest release which leads you to a download link."
},
{
"code": null,
"e": 19433,
"s": 19371,
"text": "Select the latest release which leads you to a download link."
},
{
"code": null,
"e": 19572,
"s": 19433,
"text": "mirror.nexcess is one of the links where you can find the list of all libraries of different languages that Avro supports as shown below −"
},
{
"code": null,
"e": 19711,
"s": 19572,
"text": "mirror.nexcess is one of the links where you can find the list of all libraries of different languages that Avro supports as shown below −"
},
{
"code": null,
"e": 19887,
"s": 19711,
"text": "You can select and download the library for any of the languages provided. In this tutorial, we use Java. Hence download the jar files avro-1.7.7.jar and avro-tools-1.7.7.jar."
},
{
"code": null,
"e": 19966,
"s": 19887,
"text": "To use Avro in Eclipse environment, you need to follow the steps given below −"
},
{
"code": null,
"e": 19988,
"s": 19966,
"text": "Step 1. Open eclipse."
},
{
"code": null,
"e": 20010,
"s": 19988,
"text": "Step 1. Open eclipse."
},
{
"code": null,
"e": 20036,
"s": 20010,
"text": "Step 2. Create a project."
},
{
"code": null,
"e": 20062,
"s": 20036,
"text": "Step 2. Create a project."
},
{
"code": null,
"e": 20133,
"s": 20062,
"text": "Step 3. Right-click on the project name. You will get a shortcut menu."
},
{
"code": null,
"e": 20204,
"s": 20133,
"text": "Step 3. Right-click on the project name. You will get a shortcut menu."
},
{
"code": null,
"e": 20272,
"s": 20204,
"text": "Step 4. Click on Build Path. It leads you to another shortcut menu."
},
{
"code": null,
"e": 20340,
"s": 20272,
"text": "Step 4. Click on Build Path. It leads you to another shortcut menu."
},
{
"code": null,
"e": 20444,
"s": 20340,
"text": "Step 5. Click on Configure Build Path... You can see Properties window of your project as shown below −"
},
{
"code": null,
"e": 20548,
"s": 20444,
"text": "Step 5. Click on Configure Build Path... You can see Properties window of your project as shown below −"
},
{
"code": null,
"e": 20615,
"s": 20548,
"text": "Step 6. Under libraries tab, click on ADD EXternal JARs... button."
},
{
"code": null,
"e": 20682,
"s": 20615,
"text": "Step 6. Under libraries tab, click on ADD EXternal JARs... button."
},
{
"code": null,
"e": 20745,
"s": 20682,
"text": "Step 7. Select the jar file avro-1.77.jar you have downloaded."
},
{
"code": null,
"e": 20808,
"s": 20745,
"text": "Step 7. Select the jar file avro-1.77.jar you have downloaded."
},
{
"code": null,
"e": 20829,
"s": 20808,
"text": "Step 8. Click on OK."
},
{
"code": null,
"e": 20850,
"s": 20829,
"text": "Step 8. Click on OK."
},
{
"code": null,
"e": 20957,
"s": 20850,
"text": "You can also get the Avro library into your project using Maven. Given below is the pom.xml file for Avro."
},
{
"code": null,
"e": 22394,
"s": 20957,
"text": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\" http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\n <modelVersion>4.0.0</modelVersion>\n <groupId>Test</groupId>\n <artifactId>Test</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n\n <build>\n <sourceDirectory>src</sourceDirectory>\n <plugins>\n <plugin>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>3.1</version>\n\t\t\n <configuration>\n <source>1.7</source>\n <target>1.7</target>\n </configuration>\n\t\t\n </plugin>\n </plugins>\n </build>\n\n <dependencies>\n <dependency>\n <groupId>org.apache.avro</groupId>\n <artifactId>avro</artifactId>\n <version>1.7.7</version>\n </dependency>\n\t\n <dependency>\n <groupId>org.apache.avro</groupId>\n <artifactId>avro-tools</artifactId>\n <version>1.7.7</version>\n </dependency>\n\t\n <dependency>\n <groupId>org.apache.logging.log4j</groupId>\n <artifactId>log4j-api</artifactId>\n <version>2.0-beta9</version>\n </dependency>\n\t\n <dependency>\n <groupId>org.apache.logging.log4j</groupId>\n <artifactId>log4j-core</artifactId>\n <version>2.0-beta9</version>\n </dependency>\n\t\n </dependencies>\n\n</project>"
},
{
"code": null,
"e": 22469,
"s": 22394,
"text": "To work with Avro in Linux environment, download the following jar files −"
},
{
"code": null,
"e": 22483,
"s": 22469,
"text": "avro-1.77.jar"
},
{
"code": null,
"e": 22503,
"s": 22483,
"text": "avro-tools-1.77.jar"
},
{
"code": null,
"e": 22527,
"s": 22503,
"text": "log4j-api-2.0-beta9.jar"
},
{
"code": null,
"e": 22552,
"s": 22527,
"text": "og4j-core-2.0.beta9.jar."
},
{
"code": null,
"e": 22657,
"s": 22552,
"text": "Copy these files into a folder and set the classpath to the folder, in the ./bashrc file as shown below."
},
{
"code": null,
"e": 22738,
"s": 22657,
"text": "#class path for Avro\nexport CLASSPATH=$CLASSPATH://home/Hadoop/Avro_Work/jars/*\n"
},
{
"code": null,
"e": 22958,
"s": 22738,
"text": "Avro, being a schema-based serialization utility, accepts schemas as input. In spite of various schemas being available, Avro follows its own standards of defining schemas. These schemas describe the following details −"
},
{
"code": null,
"e": 22991,
"s": 22958,
"text": "type of file (record by default)"
},
{
"code": null,
"e": 23010,
"s": 22991,
"text": "location of record"
},
{
"code": null,
"e": 23029,
"s": 23010,
"text": "name of the record"
},
{
"code": null,
"e": 23086,
"s": 23029,
"text": "fields in the record with their corresponding data types"
},
{
"code": null,
"e": 23220,
"s": 23086,
"text": "Using these schemas, you can store serialized values in binary format using less space. These values are stored without any metadata."
},
{
"code": null,
"e": 23405,
"s": 23220,
"text": "The Avro schema is created in JavaScript Object Notation (JSON) document format, which is a lightweight text-based data interchange format. It is created in one of the following ways −"
},
{
"code": null,
"e": 23419,
"s": 23405,
"text": "A JSON string"
},
{
"code": null,
"e": 23433,
"s": 23419,
"text": "A JSON object"
},
{
"code": null,
"e": 23446,
"s": 23433,
"text": "A JSON array"
},
{
"code": null,
"e": 23605,
"s": 23446,
"text": "Example − The following example shows a schema, which defines a document, under the name space Tutorialspoint, with name Employee, having fields name and age."
},
{
"code": null,
"e": 23801,
"s": 23605,
"text": "{\n \"type\" : \"record\",\n \"namespace\" : \"Tutorialspoint\",\n \"name\" : \"Employee\",\n \"fields\" : [\n { \"name\" : \"Name\" , \"type\" : \"string\" },\n { \"name\" : \"Age\" , \"type\" : \"int\" }\n ]\n}\n"
},
{
"code": null,
"e": 23879,
"s": 23801,
"text": "In this example, you can observe that there are four fields for each record −"
},
{
"code": null,
"e": 24128,
"s": 23879,
"text": "type − This field comes under the document as well as the under the field named fields.\n\nIn case of document, it shows the type of the document, generally a record because there are multiple fields.\nWhen it is field, the type describes data type. \n"
},
{
"code": null,
"e": 24216,
"s": 24128,
"text": "type − This field comes under the document as well as the under the field named fields."
},
{
"code": null,
"e": 24326,
"s": 24216,
"text": "In case of document, it shows the type of the document, generally a record because there are multiple fields."
},
{
"code": null,
"e": 24436,
"s": 24326,
"text": "In case of document, it shows the type of the document, generally a record because there are multiple fields."
},
{
"code": null,
"e": 24485,
"s": 24436,
"text": "When it is field, the type describes data type. "
},
{
"code": null,
"e": 24534,
"s": 24485,
"text": "When it is field, the type describes data type. "
},
{
"code": null,
"e": 24622,
"s": 24534,
"text": "namespace − This field describes the name of the namespace in which the object resides."
},
{
"code": null,
"e": 24710,
"s": 24622,
"text": "namespace − This field describes the name of the namespace in which the object resides."
},
{
"code": null,
"e": 25104,
"s": 24710,
"text": "name − This field comes under the document as well as the under the field named fields.\n\nIn case of document, it describes the schema name. This schema name together with the namespace, uniquely identifies the schema within the store (Namespace.schema name). In the above example, the full name of the schema will be Tutorialspoint.Employee.\nIn case of fields, it describes name of the field.\n"
},
{
"code": null,
"e": 25192,
"s": 25104,
"text": "name − This field comes under the document as well as the under the field named fields."
},
{
"code": null,
"e": 25445,
"s": 25192,
"text": "In case of document, it describes the schema name. This schema name together with the namespace, uniquely identifies the schema within the store (Namespace.schema name). In the above example, the full name of the schema will be Tutorialspoint.Employee."
},
{
"code": null,
"e": 25698,
"s": 25445,
"text": "In case of document, it describes the schema name. This schema name together with the namespace, uniquely identifies the schema within the store (Namespace.schema name). In the above example, the full name of the schema will be Tutorialspoint.Employee."
},
{
"code": null,
"e": 25749,
"s": 25698,
"text": "In case of fields, it describes name of the field."
},
{
"code": null,
"e": 25800,
"s": 25749,
"text": "In case of fields, it describes name of the field."
},
{
"code": null,
"e": 25939,
"s": 25800,
"text": "Avro schema is having primitive data types as well as complex data types. The following table describes the primitive data types of Avro −"
},
{
"code": null,
"e": 26065,
"s": 25939,
"text": "Along with primitive data types, Avro provides six complex data types namely Records, Enums, Arrays, Maps, Unions, and Fixed."
},
{
"code": null,
"e": 26171,
"s": 26065,
"text": "A record data type in Avro is a collection of multiple attributes. It supports the following\nattributes −"
},
{
"code": null,
"e": 26232,
"s": 26171,
"text": "name − The value of this field holds the name of the record."
},
{
"code": null,
"e": 26293,
"s": 26232,
"text": "name − The value of this field holds the name of the record."
},
{
"code": null,
"e": 26389,
"s": 26293,
"text": "namespace − The value of this field holds the name of the namespace where the\nobject is stored."
},
{
"code": null,
"e": 26485,
"s": 26389,
"text": "namespace − The value of this field holds the name of the namespace where the\nobject is stored."
},
{
"code": null,
"e": 26611,
"s": 26485,
"text": "type − The value of this attribute holds either the type of the document (record) or the datatype of the field in the schema."
},
{
"code": null,
"e": 26737,
"s": 26611,
"text": "type − The value of this attribute holds either the type of the document (record) or the datatype of the field in the schema."
},
{
"code": null,
"e": 26875,
"s": 26737,
"text": "fields − This field holds a JSON array, which have the list of all of the fields in the schema, each having name and the type attributes."
},
{
"code": null,
"e": 27013,
"s": 26875,
"text": "fields − This field holds a JSON array, which have the list of all of the fields in the schema, each having name and the type attributes."
},
{
"code": null,
"e": 27021,
"s": 27013,
"text": "Example"
},
{
"code": null,
"e": 27061,
"s": 27021,
"text": "Given below is the example of a record."
},
{
"code": null,
"e": 27242,
"s": 27061,
"text": "{\n\" type \" : \"record\",\n\" namespace \" : \"Tutorialspoint\",\n\" name \" : \"Employee\",\n\" fields \" : [\n { \"name\" : \" Name\" , \"type\" : \"string\" },\n { \"name\" : \"age\" , \"type\" : \"int\" }\n ]\n}\n"
},
{
"code": null,
"e": 27346,
"s": 27242,
"text": "An enumeration is a list of items in a collection, Avro enumeration supports the following attributes −"
},
{
"code": null,
"e": 27412,
"s": 27346,
"text": "name − The value of this field holds the name of the enumeration."
},
{
"code": null,
"e": 27478,
"s": 27412,
"text": "name − The value of this field holds the name of the enumeration."
},
{
"code": null,
"e": 27578,
"s": 27478,
"text": "namespace − The value of this field contains the string that qualifies the name of the Enumeration."
},
{
"code": null,
"e": 27678,
"s": 27578,
"text": "namespace − The value of this field contains the string that qualifies the name of the Enumeration."
},
{
"code": null,
"e": 27759,
"s": 27678,
"text": "symbols − The value of this field holds the enum's symbols as an array of names."
},
{
"code": null,
"e": 27840,
"s": 27759,
"text": "symbols − The value of this field holds the enum's symbols as an array of names."
},
{
"code": null,
"e": 27848,
"s": 27840,
"text": "Example"
},
{
"code": null,
"e": 27894,
"s": 27848,
"text": "Given below is the example of an enumeration."
},
{
"code": null,
"e": 28017,
"s": 27894,
"text": "{\n \"type\" : \"enum\",\n \"name\" : \"Numbers\", \n \"namespace\": \"data\", \n \"symbols\" : [ \"ONE\", \"TWO\", \"THREE\", \"FOUR\" ]\n}\n"
},
{
"code": null,
"e": 28151,
"s": 28017,
"text": "This data type defines an array field having a single attribute items. This items attribute specifies the type of items in the array."
},
{
"code": null,
"e": 28159,
"s": 28151,
"text": "Example"
},
{
"code": null,
"e": 28206,
"s": 28159,
"text": "{ \" type \" : \" array \", \" items \" : \" int \" }\n"
},
{
"code": null,
"e": 28398,
"s": 28206,
"text": "The map data type is an array of key-value pairs, it organizes data as key-value pairs. The\nkey for an Avro map must be a string. The values of a map hold the data type of the content of map."
},
{
"code": null,
"e": 28406,
"s": 28398,
"text": "Example"
},
{
"code": null,
"e": 28442,
"s": 28406,
"text": "{\"type\" : \"map\", \"values\" : \"int\"}\n"
},
{
"code": null,
"e": 28661,
"s": 28442,
"text": "A union datatype is used whenever the field has one or more datatypes. They are represented as JSON arrays. For example, if a field that could be either an int or null, then the union is represented as [\"int\", \"null\"]."
},
{
"code": null,
"e": 28669,
"s": 28661,
"text": "Example"
},
{
"code": null,
"e": 28719,
"s": 28669,
"text": "Given below is an example document using unions −"
},
{
"code": null,
"e": 28932,
"s": 28719,
"text": "{ \n \"type\" : \"record\", \n \"namespace\" : \"tutorialspoint\", \n \"name\" : \"empdetails \", \n \"fields\" : \n [ \n { \"name\" : \"experience\", \"type\": [\"int\", \"null\"] }, { \"name\" : \"age\", \"type\": \"int\" } \n ] \n}\n"
},
{
"code": null,
"e": 29142,
"s": 28932,
"text": "This data type is used to declare a fixed-sized field that can be used for storing binary data. It has field name and data as attributes. Name holds the name of the field, and size holds the size of the field."
},
{
"code": null,
"e": 29150,
"s": 29142,
"text": "Example"
},
{
"code": null,
"e": 29208,
"s": 29150,
"text": "{ \"type\" : \"fixed\" , \"name\" : \"bdata\", \"size\" : 1048576}\n"
},
{
"code": null,
"e": 29410,
"s": 29208,
"text": "In the previous chapter, we described the input type of Avro, i.e., Avro schemas. In this chapter, we will explain the classes and methods used in the serialization and deserialization of Avro schemas."
},
{
"code": null,
"e": 29575,
"s": 29410,
"text": "This class belongs to the package org.apache.avro.specific. It implements the DatumWriter interface which converts Java objects into an in-memory serialized format."
},
{
"code": null,
"e": 29606,
"s": 29575,
"text": "SpecificData getSpecificData()"
},
{
"code": null,
"e": 29667,
"s": 29606,
"text": "Returns the SpecificData implementation used by this writer."
},
{
"code": null,
"e": 29918,
"s": 29667,
"text": "This class belongs to the package org.apache.avro.specific. It implements the DatumReader interface which reads the data of a schema and determines in-memory data representation. SpecificDatumReader is the class which supports generated java classes."
},
{
"code": null,
"e": 29953,
"s": 29918,
"text": "SpecificDatumReader(Schema schema)"
},
{
"code": null,
"e": 30017,
"s": 29953,
"text": "Construct where the writer's and reader's schemas are the same."
},
{
"code": null,
"e": 30048,
"s": 30017,
"text": "SpecificData getSpecificData()"
},
{
"code": null,
"e": 30084,
"s": 30048,
"text": "Returns the contained SpecificData."
},
{
"code": null,
"e": 30114,
"s": 30084,
"text": "void setSchema(Schema actual)"
},
{
"code": null,
"e": 30162,
"s": 30114,
"text": "This method is used to set the writer's schema."
},
{
"code": null,
"e": 30317,
"s": 30162,
"text": "Instantiates DataFileWrite for emp class. This class writes a sequence serialized records of data conforming to a schema, along with the schema in a file."
},
{
"code": null,
"e": 30338,
"s": 30317,
"text": "void append(D datum)"
},
{
"code": null,
"e": 30365,
"s": 30338,
"text": "Appends a datum to a file."
},
{
"code": null,
"e": 30403,
"s": 30365,
"text": "DataFileWriter<D> appendTo(File file)"
},
{
"code": null,
"e": 30471,
"s": 30403,
"text": "This method is used to open a writer appending to an existing file."
},
{
"code": null,
"e": 30581,
"s": 30471,
"text": "This class provides random access to files written with DataFileWriter. It inherits the class DataFileStream."
},
{
"code": null,
"e": 30588,
"s": 30581,
"text": "next()"
},
{
"code": null,
"e": 30622,
"s": 30588,
"text": "Reads the next datum in the file."
},
{
"code": null,
"e": 30640,
"s": 30622,
"text": "Boolean hasNext()"
},
{
"code": null,
"e": 30690,
"s": 30640,
"text": "Returns true if more entries remain in this file."
},
{
"code": null,
"e": 30818,
"s": 30690,
"text": "This class is a parser for JSON-format schemas. It contains methods to parse the schema. It belongs to org.apache.avro package."
},
{
"code": null,
"e": 30836,
"s": 30818,
"text": "parse (File file)"
},
{
"code": null,
"e": 30882,
"s": 30836,
"text": "Parses the schema provided in the given file."
},
{
"code": null,
"e": 30905,
"s": 30882,
"text": "parse (InputStream in)"
},
{
"code": null,
"e": 30958,
"s": 30905,
"text": "Parses the schema provided in the given InputStream."
},
{
"code": null,
"e": 30975,
"s": 30958,
"text": "parse (String s)"
},
{
"code": null,
"e": 31023,
"s": 30975,
"text": "Parses the schema provided in the given String."
},
{
"code": null,
"e": 31102,
"s": 31023,
"text": "This interface provides methods to access the fields by name as well as index."
},
{
"code": null,
"e": 31125,
"s": 31102,
"text": "Object get(String key)"
},
{
"code": null,
"e": 31161,
"s": 31125,
"text": "Returns the value of a field given."
},
{
"code": null,
"e": 31192,
"s": 31161,
"text": "void put(String key, Object v)"
},
{
"code": null,
"e": 31234,
"s": 31192,
"text": "Sets the value of a field given its name."
},
{
"code": null,
"e": 31257,
"s": 31234,
"text": "Object get(String key)"
},
{
"code": null,
"e": 31305,
"s": 31257,
"text": "Returns the value of a field of the given name."
},
{
"code": null,
"e": 31324,
"s": 31305,
"text": "Schema getSchema()"
},
{
"code": null,
"e": 31361,
"s": 31324,
"text": "Returns the schema of this instance."
},
{
"code": null,
"e": 31387,
"s": 31361,
"text": "void put(int i, Object v)"
},
{
"code": null,
"e": 31447,
"s": 31387,
"text": "Sets the value of a field given its position in the schema."
},
{
"code": null,
"e": 31482,
"s": 31447,
"text": "void put(String key, Object value)"
},
{
"code": null,
"e": 31524,
"s": 31482,
"text": "Sets the value of a field given its name."
},
{
"code": null,
"e": 31761,
"s": 31524,
"text": "One can read an Avro schema into the program either by generating a class corresponding to a schema or by using the parsers library. This chapter describes how to read the schema by generating a class and Serializing the data using Avr."
},
{
"code": null,
"e": 31829,
"s": 31761,
"text": "To serialize the data using Avro, follow the steps as given below −"
},
{
"code": null,
"e": 31851,
"s": 31829,
"text": "Write an Avro schema."
},
{
"code": null,
"e": 31873,
"s": 31851,
"text": "Write an Avro schema."
},
{
"code": null,
"e": 31964,
"s": 31873,
"text": "Compile the schema using Avro utility. You get the Java code corresponding to that\nschema."
},
{
"code": null,
"e": 32055,
"s": 31964,
"text": "Compile the schema using Avro utility. You get the Java code corresponding to that\nschema."
},
{
"code": null,
"e": 32090,
"s": 32055,
"text": "Populate the schema with the data."
},
{
"code": null,
"e": 32125,
"s": 32090,
"text": "Populate the schema with the data."
},
{
"code": null,
"e": 32158,
"s": 32125,
"text": "Serialize it using Avro library."
},
{
"code": null,
"e": 32191,
"s": 32158,
"text": "Serialize it using Avro library."
},
{
"code": null,
"e": 32246,
"s": 32191,
"text": "Suppose you want a schema with the following details −"
},
{
"code": null,
"e": 32284,
"s": 32246,
"text": "Create an Avro schema as shown below."
},
{
"code": null,
"e": 32305,
"s": 32284,
"text": "Save it as emp.avsc."
},
{
"code": null,
"e": 32609,
"s": 32305,
"text": "{\n \"namespace\": \"tutorialspoint.com\",\n \"type\": \"record\",\n \"name\": \"emp\",\n \"fields\": [\n {\"name\": \"name\", \"type\": \"string\"},\n {\"name\": \"id\", \"type\": \"int\"},\n {\"name\": \"salary\", \"type\": \"int\"},\n {\"name\": \"age\", \"type\": \"int\"},\n {\"name\": \"address\", \"type\": \"string\"}\n ]\n}\n"
},
{
"code": null,
"e": 32751,
"s": 32609,
"text": "After creating an Avro schema, you need to compile the created schema using Avro tools.\navro-tools-1.7.7.jar is the jar containing the tools."
},
{
"code": null,
"e": 32851,
"s": 32751,
"text": "java -jar <path/to/avro-tools-1.7.7.jar> compile schema <path/to/schema-file> <destination-folder>\n"
},
{
"code": null,
"e": 32889,
"s": 32851,
"text": "Open the terminal in the home folder."
},
{
"code": null,
"e": 32947,
"s": 32889,
"text": "Create a new directory to work with Avro as shown below −"
},
{
"code": null,
"e": 32966,
"s": 32947,
"text": "$ mkdir Avro_Work\n"
},
{
"code": null,
"e": 33029,
"s": 32966,
"text": "In the newly created directory, create three sub-directories −"
},
{
"code": null,
"e": 33070,
"s": 33029,
"text": "First named schema, to place the schema."
},
{
"code": null,
"e": 33111,
"s": 33070,
"text": "First named schema, to place the schema."
},
{
"code": null,
"e": 33168,
"s": 33111,
"text": "Second named with_code_gen, to place the generated code."
},
{
"code": null,
"e": 33225,
"s": 33168,
"text": "Second named with_code_gen, to place the generated code."
},
{
"code": null,
"e": 33267,
"s": 33225,
"text": "Third named jars, to place the jar files."
},
{
"code": null,
"e": 33309,
"s": 33267,
"text": "Third named jars, to place the jar files."
},
{
"code": null,
"e": 33360,
"s": 33309,
"text": "$ mkdir schema\n$ mkdir with_code_gen\n$ mkdir jars\n"
},
{
"code": null,
"e": 33470,
"s": 33360,
"text": "The following screenshot shows how your Avro_work folder should look like after creating all the directories."
},
{
"code": null,
"e": 33606,
"s": 33470,
"text": "Now /home/Hadoop/Avro_work/jars/avro-tools-1.7.7.jar is the path for the directory where you have downloaded avro-tools-1.7.7.jar file."
},
{
"code": null,
"e": 33742,
"s": 33606,
"text": "Now /home/Hadoop/Avro_work/jars/avro-tools-1.7.7.jar is the path for the directory where you have downloaded avro-tools-1.7.7.jar file."
},
{
"code": null,
"e": 33846,
"s": 33742,
"text": "/home/Hadoop/Avro_work/schema/ is the path for the directory where your schema file emp.avsc is stored."
},
{
"code": null,
"e": 33950,
"s": 33846,
"text": "/home/Hadoop/Avro_work/schema/ is the path for the directory where your schema file emp.avsc is stored."
},
{
"code": null,
"e": 34059,
"s": 33950,
"text": "/home/Hadoop/Avro_work/with_code_gen is the directory where you want the generated class files to be stored."
},
{
"code": null,
"e": 34168,
"s": 34059,
"text": "/home/Hadoop/Avro_work/with_code_gen is the directory where you want the generated class files to be stored."
},
{
"code": null,
"e": 34208,
"s": 34168,
"text": "Now compile the schema as shown below −"
},
{
"code": null,
"e": 34356,
"s": 34208,
"text": "$ java -jar /home/Hadoop/Avro_work/jars/avro-tools-1.7.7.jar compile schema /home/Hadoop/Avro_work/schema/emp.avsc /home/Hadoop/Avro/with_code_gen\n"
},
{
"code": null,
"e": 34649,
"s": 34356,
"text": "After compiling, a package according to the name space of the schema is created in the\ndestination directory. Within this package, the Java source code with schema name is created. This generated source code is the Java code of the given schema which can be used in the applications directly."
},
{
"code": null,
"e": 34915,
"s": 34649,
"text": "For example, in this instance a package/folder, named tutorialspoint is created which contains another folder named com (since the name space is tutorialspoint.com) and within it, you can observe the generated file emp.java. The following snapshot shows emp.java − "
},
{
"code": null,
"e": 34972,
"s": 34915,
"text": "This class is useful to create data according to schema."
},
{
"code": null,
"e": 35003,
"s": 34972,
"text": "The generated class contains −"
},
{
"code": null,
"e": 35100,
"s": 35003,
"text": "Default constructor, and parameterized constructor which accept all the variables of the schema."
},
{
"code": null,
"e": 35163,
"s": 35100,
"text": "The setter and getter methods for all variables in the schema."
},
{
"code": null,
"e": 35202,
"s": 35163,
"text": "Get() method which returns the schema."
},
{
"code": null,
"e": 35219,
"s": 35202,
"text": "Builder methods."
},
{
"code": null,
"e": 35349,
"s": 35219,
"text": "First of all, copy the generated java file used in this project into the current directory or import it from where it is located."
},
{
"code": null,
"e": 35472,
"s": 35349,
"text": "Now we can write a new Java file and instantiate the class in the generated file (emp) to add employee data to the schema."
},
{
"code": null,
"e": 35555,
"s": 35472,
"text": "Let us see the procedure to create data according to the schema using apache Avro."
},
{
"code": null,
"e": 35592,
"s": 35555,
"text": "Instantiate the generated emp class."
},
{
"code": null,
"e": 35612,
"s": 35592,
"text": "emp e1=new emp( );\n"
},
{
"code": null,
"e": 35738,
"s": 35612,
"text": "Using setter methods, insert the data of first employee. For example, we have created the details of the employee named Omar."
},
{
"code": null,
"e": 35838,
"s": 35738,
"text": "e1.setName(\"omar\");\ne1.setAge(21);\ne1.setSalary(30000);\ne1.setAddress(\"Hyderabad\");\ne1.setId(001);\n"
},
{
"code": null,
"e": 35900,
"s": 35838,
"text": "Similarly, fill in all employee details using setter methods."
},
{
"code": null,
"e": 36123,
"s": 35900,
"text": "Create an object of DatumWriter interface using the SpecificDatumWriter class. This converts Java objects into in-memory serialized format. The following example instantiates SpecificDatumWriter class object for emp class."
},
{
"code": null,
"e": 36199,
"s": 36123,
"text": "DatumWriter<emp> empDatumWriter = new SpecificDatumWriter<emp>(emp.class);\n"
},
{
"code": null,
"e": 36441,
"s": 36199,
"text": "Instantiate DataFileWriter for emp class. This class writes a sequence serialized records of data conforming to a schema, along with the schema itself, in a file. This class requires the DatumWriter object, as a parameter to the constructor."
},
{
"code": null,
"e": 36519,
"s": 36441,
"text": "DataFileWriter<emp> empFileWriter = new DataFileWriter<emp>(empDatumWriter);\n"
},
{
"code": null,
"e": 36710,
"s": 36519,
"text": "Open a new file to store the data matching to the given schema using create() method. This method requires the schema, and the path of the file where the data is to be stored, as parameters."
},
{
"code": null,
"e": 36865,
"s": 36710,
"text": "In the following example, schema is passed using getSchema() method, and the data file is stored in the path − /home/Hadoop/Avro/serialized_file/emp.avro."
},
{
"code": null,
"e": 36958,
"s": 36865,
"text": "empFileWriter.create(e1.getSchema(),new File(\"/home/Hadoop/Avro/serialized_file/emp.avro\"));"
},
{
"code": null,
"e": 37037,
"s": 36958,
"text": "Add all the created records to the file using append() method as shown below −"
},
{
"code": null,
"e": 37116,
"s": 37037,
"text": "empFileWriter.append(e1);\nempFileWriter.append(e2);\nempFileWriter.append(e3);\n"
},
{
"code": null,
"e": 37207,
"s": 37116,
"text": "The following complete program shows how to serialize data into a file using Apache Avro −"
},
{
"code": null,
"e": 38545,
"s": 37207,
"text": "import java.io.File;\nimport java.io.IOException;\n\nimport org.apache.avro.file.DataFileWriter;\nimport org.apache.avro.io.DatumWriter;\nimport org.apache.avro.specific.SpecificDatumWriter;\n\npublic class Serialize {\n public static void main(String args[]) throws IOException{\n\t\n //Instantiating generated emp class\n emp e1=new emp();\n\t\n //Creating values according the schema\n e1.setName(\"omar\");\n e1.setAge(21);\n e1.setSalary(30000);\n e1.setAddress(\"Hyderabad\");\n e1.setId(001);\n\t\n emp e2=new emp();\n\t\n e2.setName(\"ram\");\n e2.setAge(30);\n e2.setSalary(40000);\n e2.setAddress(\"Hyderabad\");\n e2.setId(002);\n\t\n emp e3=new emp();\n\t\n e3.setName(\"robbin\");\n e3.setAge(25);\n e3.setSalary(35000);\n e3.setAddress(\"Hyderabad\");\n e3.setId(003);\n\t\n //Instantiate DatumWriter class\n DatumWriter<emp> empDatumWriter = new SpecificDatumWriter<emp>(emp.class);\n DataFileWriter<emp> empFileWriter = new DataFileWriter<emp>(empDatumWriter);\n\t\n empFileWriter.create(e1.getSchema(), new File(\"/home/Hadoop/Avro_Work/with_code_gen/emp.avro\"));\n\t\n empFileWriter.append(e1);\n empFileWriter.append(e2);\n empFileWriter.append(e3);\n\t\n empFileWriter.close();\n\t\n System.out.println(\"data successfully serialized\");\n }\n}"
},
{
"code": null,
"e": 38664,
"s": 38545,
"text": "Browse through the directory where the generated code is placed. In this case, at home/Hadoop/Avro_work/with_code_gen."
},
{
"code": null,
"e": 38678,
"s": 38664,
"text": "In Terminal −"
},
{
"code": null,
"e": 38721,
"s": 38678,
"text": "$ cd home/Hadoop/Avro_work/with_code_gen/\n"
},
{
"code": null,
"e": 38730,
"s": 38721,
"text": "In GUI −"
},
{
"code": null,
"e": 38799,
"s": 38730,
"text": "Now copy and save the above program in the file named Serialize.java"
},
{
"code": null,
"e": 38839,
"s": 38799,
"text": "Compile and execute it as shown below −"
},
{
"code": null,
"e": 38880,
"s": 38839,
"text": "$ javac Serialize.java\n$ java Serialize\n"
},
{
"code": null,
"e": 38910,
"s": 38880,
"text": "data successfully serialized\n"
},
{
"code": null,
"e": 39014,
"s": 38910,
"text": "If you verify the path given in the program, you can find the generated serialized file as shown below."
},
{
"code": null,
"e": 39274,
"s": 39014,
"text": "As described earlier, one can read an Avro schema into a program either by generating a class corresponding to the schema or by using the parsers library. This chapter describes how to read the schema by generating a class and Deserialize the data using Avro."
},
{
"code": null,
"e": 39370,
"s": 39274,
"text": "The serialized data is stored in the file emp.avro. You can deserialize and read it using Avro."
},
{
"code": null,
"e": 39451,
"s": 39370,
"text": "Follow the procedure given below to deserialize the serialized data from a file."
},
{
"code": null,
"e": 39526,
"s": 39451,
"text": "Create an object of DatumReader interface using SpecificDatumReader class."
},
{
"code": null,
"e": 39601,
"s": 39526,
"text": "DatumReader<emp>empDatumReader = new SpecificDatumReader<emp>(emp.class);\n"
},
{
"code": null,
"e": 39821,
"s": 39601,
"text": "Instantiate DataFileReader for emp class. This class reads serialized data from a file. It requires the Dataumeader object, and path of the file where the serialized data is existing, as a parameters to the constructor."
},
{
"code": null,
"e": 39926,
"s": 39821,
"text": "DataFileReader<emp> dataFileReader = new DataFileReader(new File(\"/path/to/emp.avro\"), empDatumReader);\n"
},
{
"code": null,
"e": 39992,
"s": 39926,
"text": "Print the deserialized data, using the methods of DataFileReader."
},
{
"code": null,
"e": 40076,
"s": 39992,
"text": "The hasNext() method will return a boolean if there are any elements in the Reader."
},
{
"code": null,
"e": 40160,
"s": 40076,
"text": "The hasNext() method will return a boolean if there are any elements in the Reader."
},
{
"code": null,
"e": 40228,
"s": 40160,
"text": "The next() method of DataFileReader returns the data in the Reader."
},
{
"code": null,
"e": 40296,
"s": 40228,
"text": "The next() method of DataFileReader returns the data in the Reader."
},
{
"code": null,
"e": 40390,
"s": 40296,
"text": "while(dataFileReader.hasNext()){\n\n em=dataFileReader.next(em);\n System.out.println(em);\n}"
},
{
"code": null,
"e": 40477,
"s": 40390,
"text": "The following complete program shows how to deserialize the data in a file using Avro."
},
{
"code": null,
"e": 41219,
"s": 40477,
"text": "import java.io.File;\nimport java.io.IOException;\n\nimport org.apache.avro.file.DataFileReader;\nimport org.apache.avro.io.DatumReader;\nimport org.apache.avro.specific.SpecificDatumReader;\n\npublic class Deserialize {\n public static void main(String args[]) throws IOException{\n\t\n //DeSerializing the objects\n DatumReader<emp> empDatumReader = new SpecificDatumReader<emp>(emp.class);\n\t\t\n //Instantiating DataFileReader\n DataFileReader<emp> dataFileReader = new DataFileReader<emp>(new\n File(\"/home/Hadoop/Avro_Work/with_code_genfile/emp.avro\"), empDatumReader);\n emp em=null;\n\t\t\n while(dataFileReader.hasNext()){\n \n em=dataFileReader.next(em);\n System.out.println(em);\n }\n }\n}"
},
{
"code": null,
"e": 41335,
"s": 41219,
"text": "Browse into the directory where the generated code is placed. In this case, at home/Hadoop/Avro_work/with_code_gen."
},
{
"code": null,
"e": 41378,
"s": 41335,
"text": "$ cd home/Hadoop/Avro_work/with_code_gen/\n"
},
{
"code": null,
"e": 41491,
"s": 41378,
"text": "Now, copy and save the above program in the file named DeSerialize.java. Compile and execute it as shown below −"
},
{
"code": null,
"e": 41536,
"s": 41491,
"text": "$ javac Deserialize.java\n$ java Deserialize\n"
},
{
"code": null,
"e": 41772,
"s": 41536,
"text": "{\"name\": \"omar\", \"id\": 1, \"salary\": 30000, \"age\": 21, \"address\": \"Hyderabad\"}\n{\"name\": \"ram\", \"id\": 2, \"salary\": 40000, \"age\": 30, \"address\": \"Hyderabad\"}\n{\"name\": \"robbin\", \"id\": 3, \"salary\": 35000, \"age\": 25, \"address\": \"Hyderabad\"}\n"
},
{
"code": null,
"e": 42029,
"s": 41772,
"text": "One can read an Avro schema into a program either by generating a class corresponding to a schema or by using the parsers library. In Avro, data is always stored with its corresponding schema. Therefore, we can always read a schema without code generation."
},
{
"code": null,
"e": 42138,
"s": 42029,
"text": "This chapter describes how to read the schema by using parsers library and to serialize the data using Avro."
},
{
"code": null,
"e": 42345,
"s": 42138,
"text": "To serialize the data, we need to read the schema, create data according to the schema, and serialize the schema using the Avro API. The following procedure serializes the data without generating any code −"
},
{
"code": null,
"e": 42495,
"s": 42345,
"text": "First of all, read the schema from the file. To do so, use Schema.Parser class. This class provides methods to parse the schema in different formats."
},
{
"code": null,
"e": 42584,
"s": 42495,
"text": "Instantiate the Schema.Parser class by passing the file path where the schema is stored."
},
{
"code": null,
"e": 42659,
"s": 42584,
"text": "Schema schema = new Schema.Parser().parse(new File(\"/path/to/emp.avsc\"));\n"
},
{
"code": null,
"e": 42820,
"s": 42659,
"text": "Create the object of GenericRecord interface, by instantiating GenericData.Record class as shown below. Pass the above created schema object to its constructor."
},
{
"code": null,
"e": 42872,
"s": 42820,
"text": "GenericRecord e1 = new GenericData.Record(schema);\n"
},
{
"code": null,
"e": 42953,
"s": 42872,
"text": "Insert the values in the schema using the put() method of the GenericData class."
},
{
"code": null,
"e": 43070,
"s": 42953,
"text": "e1.put(\"name\", \"ramu\");\ne1.put(\"id\", 001);\ne1.put(\"salary\",30000);\ne1.put(\"age\", 25);\ne1.put(\"address\", \"chennai\");\n"
},
{
"code": null,
"e": 43292,
"s": 43070,
"text": "Create an object of DatumWriter interface using the SpecificDatumWriter class. It converts Java objects into in-memory serialized format. The following example instantiates SpecificDatumWriter class object for emp class −"
},
{
"code": null,
"e": 43368,
"s": 43292,
"text": "DatumWriter<emp> empDatumWriter = new SpecificDatumWriter<emp>(emp.class);\n"
},
{
"code": null,
"e": 43599,
"s": 43368,
"text": "Instantiate DataFileWriter for emp class. This class writes serialized records of data conforming to a schema, along with the schema itself, in a file. This class requires the DatumWriter object, as a parameter to the constructor."
},
{
"code": null,
"e": 43678,
"s": 43599,
"text": "DataFileWriter<emp> dataFileWriter = new DataFileWriter<emp>(empDatumWriter);\n"
},
{
"code": null,
"e": 43869,
"s": 43678,
"text": "Open a new file to store the data matching to the given schema using create() method. This method requires the schema, and the path of the file where the data is to be stored, as parameters."
},
{
"code": null,
"e": 43979,
"s": 43869,
"text": "In the example given below, schema is passed using getSchema() method and the data file is stored in the path"
},
{
"code": null,
"e": 44023,
"s": 43979,
"text": "/home/Hadoop/Avro/serialized_file/emp.avro."
},
{
"code": null,
"e": 44118,
"s": 44023,
"text": "empFileWriter.create(e1.getSchema(), new\nFile(\"/home/Hadoop/Avro/serialized_file/emp.avro\"));\n"
},
{
"code": null,
"e": 44197,
"s": 44118,
"text": "Add all the created records to the file using append( ) method as shown below."
},
{
"code": null,
"e": 44276,
"s": 44197,
"text": "empFileWriter.append(e1);\nempFileWriter.append(e2);\nempFileWriter.append(e3);\n"
},
{
"code": null,
"e": 44355,
"s": 44276,
"text": "The following complete program shows how to serialize the data using parsers −"
},
{
"code": null,
"e": 45867,
"s": 44355,
"text": "import java.io.File;\nimport java.io.IOException;\n\nimport org.apache.avro.Schema;\nimport org.apache.avro.file.DataFileWriter;\n\nimport org.apache.avro.generic.GenericData;\nimport org.apache.avro.generic.GenericDatumWriter;\nimport org.apache.avro.generic.GenericRecord;\n\nimport org.apache.avro.io.DatumWriter;\n\npublic class Seriali {\n public static void main(String args[]) throws IOException{\n\t\n //Instantiating the Schema.Parser class.\n Schema schema = new Schema.Parser().parse(new File(\"/home/Hadoop/Avro/schema/emp.avsc\"));\n\t\t\n //Instantiating the GenericRecord class.\n GenericRecord e1 = new GenericData.Record(schema);\n\t\t\n //Insert data according to schema\n e1.put(\"name\", \"ramu\");\n e1.put(\"id\", 001);\n e1.put(\"salary\",30000);\n e1.put(\"age\", 25);\n e1.put(\"address\", \"chenni\");\n\t\t\n GenericRecord e2 = new GenericData.Record(schema);\n\t\t\n e2.put(\"name\", \"rahman\");\n e2.put(\"id\", 002);\n e2.put(\"salary\", 35000);\n e2.put(\"age\", 30);\n e2.put(\"address\", \"Delhi\");\n\t\t\n DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<GenericRecord>(schema);\n\t\t\n DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<GenericRecord>(datumWriter);\n dataFileWriter.create(schema, new File(\"/home/Hadoop/Avro_work/without_code_gen/mydata.txt\"));\n\t\t\n dataFileWriter.append(e1);\n dataFileWriter.append(e2);\n dataFileWriter.close();\n\t\t\n System.out.println(“data successfully serialized”);\n }\n}"
},
{
"code": null,
"e": 45986,
"s": 45867,
"text": "Browse into the directory where the generated code is placed. In this case, at home/Hadoop/Avro_work/without_code_gen."
},
{
"code": null,
"e": 46032,
"s": 45986,
"text": "$ cd home/Hadoop/Avro_work/without_code_gen/\n"
},
{
"code": null,
"e": 46142,
"s": 46032,
"text": "Now copy and save the above program in the file named Serialize.java. Compile and execute it as shown below −"
},
{
"code": null,
"e": 46183,
"s": 46142,
"text": "$ javac Serialize.java\n$ java Serialize\n"
},
{
"code": null,
"e": 46213,
"s": 46183,
"text": "data successfully serialized\n"
},
{
"code": null,
"e": 46317,
"s": 46213,
"text": "If you verify the path given in the program, you can find the generated serialized file as shown below."
},
{
"code": null,
"e": 46605,
"s": 46317,
"text": "As mentioned earlier, one can read an Avro schema into a program either by generating a class corresponding to a schema or by using the parsers library. In Avro, data is always stored with its corresponding schema. Therefore, we can always read a serialized item without code generation."
},
{
"code": null,
"e": 46712,
"s": 46605,
"text": "This chapter describes how to read the schema using parsers library and Deserializing the data using Avro."
},
{
"code": null,
"e": 46810,
"s": 46712,
"text": "The serialized data is stored in the file mydata.txt. You can deserialize and read it using Avro."
},
{
"code": null,
"e": 46891,
"s": 46810,
"text": "Follow the procedure given below to deserialize the serialized data from a file."
},
{
"code": null,
"e": 47041,
"s": 46891,
"text": "First of all, read the schema from the file. To do so, use Schema.Parser class. This class provides methods to parse the schema in different formats."
},
{
"code": null,
"e": 47130,
"s": 47041,
"text": "Instantiate the Schema.Parser class by passing the file path where the schema is stored."
},
{
"code": null,
"e": 47205,
"s": 47130,
"text": "Schema schema = new Schema.Parser().parse(new File(\"/path/to/emp.avsc\"));\n"
},
{
"code": null,
"e": 47280,
"s": 47205,
"text": "Create an object of DatumReader interface using SpecificDatumReader class."
},
{
"code": null,
"e": 47355,
"s": 47280,
"text": "DatumReader<emp>empDatumReader = new SpecificDatumReader<emp>(emp.class);\n"
},
{
"code": null,
"e": 47562,
"s": 47355,
"text": "Instantiate DataFileReader class. This class reads serialized data from a file. It requires the DatumReader object, and path of the file where the serialized data exists, as a parameters to the constructor."
},
{
"code": null,
"e": 47691,
"s": 47562,
"text": "DataFileReader<GenericRecord> dataFileReader = new DataFileReader<GenericRecord>(new File(\"/path/to/mydata.txt\"), datumReader);\n"
},
{
"code": null,
"e": 47757,
"s": 47691,
"text": "Print the deserialized data, using the methods of DataFileReader."
},
{
"code": null,
"e": 47838,
"s": 47757,
"text": "The hasNext() method returns a boolean if there are any elements in the Reader\n."
},
{
"code": null,
"e": 47919,
"s": 47838,
"text": "The hasNext() method returns a boolean if there are any elements in the Reader\n."
},
{
"code": null,
"e": 47987,
"s": 47919,
"text": "The next() method of DataFileReader returns the data in the Reader."
},
{
"code": null,
"e": 48055,
"s": 47987,
"text": "The next() method of DataFileReader returns the data in the Reader."
},
{
"code": null,
"e": 48149,
"s": 48055,
"text": "while(dataFileReader.hasNext()){\n\n em=dataFileReader.next(em);\n System.out.println(em);\n}"
},
{
"code": null,
"e": 48249,
"s": 48149,
"text": "The following complete program shows how to deserialize the serialized data using Parsers library −"
},
{
"code": null,
"e": 48941,
"s": 48249,
"text": "public class Deserialize {\n public static void main(String args[]) throws Exception{\n\t\n //Instantiating the Schema.Parser class.\n Schema schema = new Schema.Parser().parse(new File(\"/home/Hadoop/Avro/schema/emp.avsc\"));\n DatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>(schema);\n DataFileReader<GenericRecord> dataFileReader = new DataFileReader<GenericRecord>(new File(\"/home/Hadoop/Avro_Work/without_code_gen/mydata.txt\"), datumReader);\n GenericRecord emp = null;\n\t\t\n while (dataFileReader.hasNext()) {\n emp = dataFileReader.next(emp);\n System.out.println(emp);\n }\n System.out.println(\"hello\");\n }\n}"
},
{
"code": null,
"e": 49066,
"s": 48941,
"text": "Browse into the directory where the generated code is placed. In this case, it is at home/Hadoop/Avro_work/without_code_gen."
},
{
"code": null,
"e": 49112,
"s": 49066,
"text": "$ cd home/Hadoop/Avro_work/without_code_gen/\n"
},
{
"code": null,
"e": 49224,
"s": 49112,
"text": "Now copy and save the above program in the file named DeSerialize.java. Compile and execute it as shown below −"
},
{
"code": null,
"e": 49269,
"s": 49224,
"text": "$ javac Deserialize.java\n$ java Deserialize\n"
},
{
"code": null,
"e": 49422,
"s": 49269,
"text": "{\"name\": \"ramu\", \"id\": 1, \"salary\": 30000, \"age\": 25, \"address\": \"chennai\"}\n{\"name\": \"rahman\", \"id\": 2, \"salary\": 35000, \"age\": 30, \"address\": \"Delhi\"}\n"
},
{
"code": null,
"e": 49429,
"s": 49422,
"text": " Print"
},
{
"code": null,
"e": 49440,
"s": 49429,
"text": " Add Notes"
}
] |
Predicting Wine Quality with Several Classification Techniques | by Terence Shin | Towards Data Science
|
Be sure to subscribe here or to my personal newsletter to never miss another article on data science guides, tricks and tips, life lessons, and more!
IntroductionSetupExploring VariablesConvert to a Classification ProblemPreparing Data for ModellingModellingFeature Importance
Introduction
Setup
Exploring Variables
Convert to a Classification Problem
Preparing Data for Modelling
Modelling
Feature Importance
As the quarantine continues, I’ve picked up a number of hobbies and interests... including WINE. Recently, I’ve acquired a taste for wines, although I don’t really know what makes a good wine. Therefore, I decided to apply some machine learning models to figure out what makes a good quality wine!
For this project, I used Kaggle’s Red Wine Quality dataset to build various classification models to predict whether a particular red wine is “good quality” or not. Each wine in this dataset is given a “quality” score between 0 and 10. For the purpose of this project, I converted the output to a binary output where each wine is either “good quality” (a score of 7 or higher) or not (a score below 7). The quality of a wine is determined by 11 input variables:
Fixed acidityVolatile acidityCitric acidResidual sugarChloridesFree sulfur dioxideTotal sulfur dioxideDensitypHSulfatesAlcohol
Fixed acidity
Volatile acidity
Citric acid
Residual sugar
Chlorides
Free sulfur dioxide
Total sulfur dioxide
Density
pH
Sulfates
Alcohol
The objectives of this project are as follows
To experiment with different classification methods to see which yields the highest accuracyTo determine which features are the most indicative of a good quality wine
To experiment with different classification methods to see which yields the highest accuracy
To determine which features are the most indicative of a good quality wine
With that said, here we go!
Be sure to subscribe here or to my personal newsletter to never miss another article on data science guides, tricks and tips, life lessons, and more!
First, I imported all of the relevant libraries that I’ll be using as well as the data itself.
import numpy as npimport pandas as pdimport matplotlib as pltimport seaborn as snsimport plotly.express as px
df = pd.read_csv("../input/red-wine-quality-cortez-et-al-2009/winequality-red.csv")
Next, I wanted to get a better idea of what I was working with.
# See the number of rows and columnsprint("Rows, columns: " + str(df.shape))# See the first five rows of the datasetdf.head()
There are a total of 1599 rows and 12 columns. The data looks very clean by looking at the first five rows, but I still wanted to make sure that there were no missing values.
# Missing Valuesprint(df.isna().sum())
This is a very beginner-friendly dataset. I did not have to deal with any missing values, and there isn’t much flexibility to conduct some feature engineering given these variables. Next, I wanted to explore my data a little bit more.
First, I wanted to see the distribution of the quality variable. I wanted to make sure that I had enough ‘good quality’ wines in my dataset — you’ll see later how I defined ‘good quality’.
fig = px.histogram(df,x='quality')fig.show()
Next I wanted to see the correlations between the variables that I’m working with. This allows me to get a much better understanding of the relationships between my variables in a quick glimpse.
Immediately, I can see that there are some variables that are strongly correlated to quality. It’s likely that these variables are also the most important features in our machine learning model, but we’ll take a look at that later.
corr = df.corr()matplotlib.pyplot.subplots(figsize=(15,10))sns.heatmap(corr, xticklabels=corr.columns, yticklabels=corr.columns, annot=True, cmap=sns.diverging_palette(220, 20, as_cmap=True))
Be sure to subscribe here or to my personal newsletter to never miss another article on data science guides, tricks and tips, life lessons, and more!
Going back to my objective, I wanted to compare the effectiveness of different classification techniques, so I needed to change the output variable to a binary output.
For this problem, I defined a bottle of wine as ‘good quality’ if it had a quality score of 7 or higher, and if it had a score of less than 7, it was deemed ‘bad quality’.
Once I converted the output variable to a binary output, I separated my feature variables (X) and the target variable (y) into separate dataframes.
# Create Classification version of target variabledf['goodquality'] = [1 if x >= 7 else 0 for x in df['quality']]# Separate feature variables and target variableX = df.drop(['quality','goodquality'], axis = 1)y = df['goodquality']
I wanted to make sure that there was a reasonable number of good quality wines. Based on the results below, it seemed like a fair enough number. In some applications, resampling may be required if the data was extremely imbalanced, but I assumed that it was okay for this purpose.
# See proportion of good vs bad winesdf['goodquality'].value_counts()
At this point, I felt that I was ready to prepare the data for modelling. The first thing that I did was standardize the data. Standardizing the data means that it will transform the data so that its distribution will have a mean of 0 and a standard deviation of 1. It’s important to standardize your data in order to equalize the range of the data.
For example, imagine a dataset with two input features: height in millimeters and weight in pounds. Because the values of ‘height’ are much higher due to its measurement, a greater emphasis will automatically be placed on height than weight, creating a bias.
# Normalize feature variablesfrom sklearn.preprocessing import StandardScalerX_features = XX = StandardScaler().fit_transform(X)
Next I split the data into a training and test set so that I could cross-validate my models and determine their effectiveness.
# Splitting the datafrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.25, random_state=0)
Now, comes the fun part!
For this project, I wanted to compare five different machine learning models: decision trees, random forests, AdaBoost, Gradient Boost, and XGBoost. For the purpose of this project, I wanted to compare these models by their accuracy.
Decision trees are a popular model, used in operations research, strategic planning, and machine learning. Each square above is called a node, and the more nodes you have, the more accurate your decision tree will be (generally). The last nodes of the decision tree, where a decision is made, are called the leaves of the tree. Decision trees are intuitive and easy to build but fall short when it comes to accuracy.
from sklearn.metrics import classification_reportfrom sklearn.tree import DecisionTreeClassifiermodel1 = DecisionTreeClassifier(random_state=1)model1.fit(X_train, y_train)y_pred1 = model1.predict(X_test)print(classification_report(y_test, y_pred1))
Random forests are an ensemble learning technique that builds off of decision trees. Random forests involve creating multiple decision trees using bootstrapped datasets of the original data and randomly selecting a subset of variables at each step of the decision tree. The model then selects the mode of all of the predictions of each decision tree. What’s the point of this? By relying on a “majority wins” model, it reduces the risk of error from an individual tree.
For example, if we created one decision tree, the third one, it would predict 0. But if we relied on the mode of all 4 decision trees, the predicted value would be 1. This is the power of random forests.
from sklearn.ensemble import RandomForestClassifiermodel2 = RandomForestClassifier(random_state=1)model2.fit(X_train, y_train)y_pred2 = model2.predict(X_test)print(classification_report(y_test, y_pred2))
The next three models are boosting algorithms that take weak learners and turn them into strong ones. I don’t want to get sidetracked and explain the differences between the three because it’s quite complicated and intricate. That being said, I’ll leave some resources where you can learn about AdaBoost, Gradient Boosting, and XGBoosting.
StatQuest: AdaBoost
StatQuest: Gradient Boost
StatQuest: XGBoost
from sklearn.ensemble import AdaBoostClassifiermodel3 = AdaBoostClassifier(random_state=1)model3.fit(X_train, y_train)y_pred3 = model3.predict(X_test)print(classification_report(y_test, y_pred3))
from sklearn.ensemble import GradientBoostingClassifiermodel4 = GradientBoostingClassifier(random_state=1)model4.fit(X_train, y_train)y_pred4 = model4.predict(X_test)print(classification_report(y_test, y_pred4))
import xgboost as xgbmodel5 = xgb.XGBClassifier(random_state=1)model5.fit(X_train, y_train)y_pred5 = model5.predict(X_test)print(classification_report(y_test, y_pred5))
By comparing the five models, the random forest and XGBoost seems to yield the highest level of accuracy. However, since XGBoost has a better f1-score for predicting good quality wines (1), I’m concluding that the XGBoost is the winner of the five models.
Below, I graphed the feature importance based on the Random Forest model and the XGBoost model. While they slightly vary, the top 3 features are the same: alcohol, volatile acidity, and sulphates. If you look below the graphs, I split the dataset into good quality and bad quality to compare these variables in more detail.
feat_importances = pd.Series(model2.feature_importances_, index=X_features.columns)feat_importances.nlargest(25).plot(kind='barh',figsize=(10,10))
feat_importances = pd.Series(model5.feature_importances_, index=X_features.columns)feat_importances.nlargest(25).plot(kind='barh',figsize=(10,10))
# Filtering df for only good qualitydf_temp = df[df['goodquality']==1]df_temp.describe()# Filtering df for only bad qualitydf_temp2 = df[df['goodquality']==0]df_temp2.describe()
By looking into the details, we can see that good quality wines have higher levels of alcohol on average, have a lower volatile acidity on average, higher levels of sulphates on average, and higher levels of residual sugar on average.
If you like my work and want to support me, I’d greatly appreciate if you followed me on my social media channels:
The BEST way to support me is by following me on Medium here.Follow me on Twitter here.Subscribe to my new YouTube channel here.Follow me on LinkedIn here.Sign up on my email list here.Check out my website terenceshin.com.
The BEST way to support me is by following me on Medium here.
Follow me on Twitter here.
Subscribe to my new YouTube channel here.
Follow me on LinkedIn here.
Sign up on my email list here.
Check out my website terenceshin.com.
|
[
{
"code": null,
"e": 321,
"s": 171,
"text": "Be sure to subscribe here or to my personal newsletter to never miss another article on data science guides, tricks and tips, life lessons, and more!"
},
{
"code": null,
"e": 448,
"s": 321,
"text": "IntroductionSetupExploring VariablesConvert to a Classification ProblemPreparing Data for ModellingModellingFeature Importance"
},
{
"code": null,
"e": 461,
"s": 448,
"text": "Introduction"
},
{
"code": null,
"e": 467,
"s": 461,
"text": "Setup"
},
{
"code": null,
"e": 487,
"s": 467,
"text": "Exploring Variables"
},
{
"code": null,
"e": 523,
"s": 487,
"text": "Convert to a Classification Problem"
},
{
"code": null,
"e": 552,
"s": 523,
"text": "Preparing Data for Modelling"
},
{
"code": null,
"e": 562,
"s": 552,
"text": "Modelling"
},
{
"code": null,
"e": 581,
"s": 562,
"text": "Feature Importance"
},
{
"code": null,
"e": 879,
"s": 581,
"text": "As the quarantine continues, I’ve picked up a number of hobbies and interests... including WINE. Recently, I’ve acquired a taste for wines, although I don’t really know what makes a good wine. Therefore, I decided to apply some machine learning models to figure out what makes a good quality wine!"
},
{
"code": null,
"e": 1341,
"s": 879,
"text": "For this project, I used Kaggle’s Red Wine Quality dataset to build various classification models to predict whether a particular red wine is “good quality” or not. Each wine in this dataset is given a “quality” score between 0 and 10. For the purpose of this project, I converted the output to a binary output where each wine is either “good quality” (a score of 7 or higher) or not (a score below 7). The quality of a wine is determined by 11 input variables:"
},
{
"code": null,
"e": 1468,
"s": 1341,
"text": "Fixed acidityVolatile acidityCitric acidResidual sugarChloridesFree sulfur dioxideTotal sulfur dioxideDensitypHSulfatesAlcohol"
},
{
"code": null,
"e": 1482,
"s": 1468,
"text": "Fixed acidity"
},
{
"code": null,
"e": 1499,
"s": 1482,
"text": "Volatile acidity"
},
{
"code": null,
"e": 1511,
"s": 1499,
"text": "Citric acid"
},
{
"code": null,
"e": 1526,
"s": 1511,
"text": "Residual sugar"
},
{
"code": null,
"e": 1536,
"s": 1526,
"text": "Chlorides"
},
{
"code": null,
"e": 1556,
"s": 1536,
"text": "Free sulfur dioxide"
},
{
"code": null,
"e": 1577,
"s": 1556,
"text": "Total sulfur dioxide"
},
{
"code": null,
"e": 1585,
"s": 1577,
"text": "Density"
},
{
"code": null,
"e": 1588,
"s": 1585,
"text": "pH"
},
{
"code": null,
"e": 1597,
"s": 1588,
"text": "Sulfates"
},
{
"code": null,
"e": 1605,
"s": 1597,
"text": "Alcohol"
},
{
"code": null,
"e": 1651,
"s": 1605,
"text": "The objectives of this project are as follows"
},
{
"code": null,
"e": 1818,
"s": 1651,
"text": "To experiment with different classification methods to see which yields the highest accuracyTo determine which features are the most indicative of a good quality wine"
},
{
"code": null,
"e": 1911,
"s": 1818,
"text": "To experiment with different classification methods to see which yields the highest accuracy"
},
{
"code": null,
"e": 1986,
"s": 1911,
"text": "To determine which features are the most indicative of a good quality wine"
},
{
"code": null,
"e": 2014,
"s": 1986,
"text": "With that said, here we go!"
},
{
"code": null,
"e": 2164,
"s": 2014,
"text": "Be sure to subscribe here or to my personal newsletter to never miss another article on data science guides, tricks and tips, life lessons, and more!"
},
{
"code": null,
"e": 2259,
"s": 2164,
"text": "First, I imported all of the relevant libraries that I’ll be using as well as the data itself."
},
{
"code": null,
"e": 2369,
"s": 2259,
"text": "import numpy as npimport pandas as pdimport matplotlib as pltimport seaborn as snsimport plotly.express as px"
},
{
"code": null,
"e": 2453,
"s": 2369,
"text": "df = pd.read_csv(\"../input/red-wine-quality-cortez-et-al-2009/winequality-red.csv\")"
},
{
"code": null,
"e": 2517,
"s": 2453,
"text": "Next, I wanted to get a better idea of what I was working with."
},
{
"code": null,
"e": 2643,
"s": 2517,
"text": "# See the number of rows and columnsprint(\"Rows, columns: \" + str(df.shape))# See the first five rows of the datasetdf.head()"
},
{
"code": null,
"e": 2818,
"s": 2643,
"text": "There are a total of 1599 rows and 12 columns. The data looks very clean by looking at the first five rows, but I still wanted to make sure that there were no missing values."
},
{
"code": null,
"e": 2857,
"s": 2818,
"text": "# Missing Valuesprint(df.isna().sum())"
},
{
"code": null,
"e": 3092,
"s": 2857,
"text": "This is a very beginner-friendly dataset. I did not have to deal with any missing values, and there isn’t much flexibility to conduct some feature engineering given these variables. Next, I wanted to explore my data a little bit more."
},
{
"code": null,
"e": 3281,
"s": 3092,
"text": "First, I wanted to see the distribution of the quality variable. I wanted to make sure that I had enough ‘good quality’ wines in my dataset — you’ll see later how I defined ‘good quality’."
},
{
"code": null,
"e": 3326,
"s": 3281,
"text": "fig = px.histogram(df,x='quality')fig.show()"
},
{
"code": null,
"e": 3521,
"s": 3326,
"text": "Next I wanted to see the correlations between the variables that I’m working with. This allows me to get a much better understanding of the relationships between my variables in a quick glimpse."
},
{
"code": null,
"e": 3753,
"s": 3521,
"text": "Immediately, I can see that there are some variables that are strongly correlated to quality. It’s likely that these variables are also the most important features in our machine learning model, but we’ll take a look at that later."
},
{
"code": null,
"e": 3945,
"s": 3753,
"text": "corr = df.corr()matplotlib.pyplot.subplots(figsize=(15,10))sns.heatmap(corr, xticklabels=corr.columns, yticklabels=corr.columns, annot=True, cmap=sns.diverging_palette(220, 20, as_cmap=True))"
},
{
"code": null,
"e": 4095,
"s": 3945,
"text": "Be sure to subscribe here or to my personal newsletter to never miss another article on data science guides, tricks and tips, life lessons, and more!"
},
{
"code": null,
"e": 4263,
"s": 4095,
"text": "Going back to my objective, I wanted to compare the effectiveness of different classification techniques, so I needed to change the output variable to a binary output."
},
{
"code": null,
"e": 4435,
"s": 4263,
"text": "For this problem, I defined a bottle of wine as ‘good quality’ if it had a quality score of 7 or higher, and if it had a score of less than 7, it was deemed ‘bad quality’."
},
{
"code": null,
"e": 4583,
"s": 4435,
"text": "Once I converted the output variable to a binary output, I separated my feature variables (X) and the target variable (y) into separate dataframes."
},
{
"code": null,
"e": 4814,
"s": 4583,
"text": "# Create Classification version of target variabledf['goodquality'] = [1 if x >= 7 else 0 for x in df['quality']]# Separate feature variables and target variableX = df.drop(['quality','goodquality'], axis = 1)y = df['goodquality']"
},
{
"code": null,
"e": 5095,
"s": 4814,
"text": "I wanted to make sure that there was a reasonable number of good quality wines. Based on the results below, it seemed like a fair enough number. In some applications, resampling may be required if the data was extremely imbalanced, but I assumed that it was okay for this purpose."
},
{
"code": null,
"e": 5165,
"s": 5095,
"text": "# See proportion of good vs bad winesdf['goodquality'].value_counts()"
},
{
"code": null,
"e": 5515,
"s": 5165,
"text": "At this point, I felt that I was ready to prepare the data for modelling. The first thing that I did was standardize the data. Standardizing the data means that it will transform the data so that its distribution will have a mean of 0 and a standard deviation of 1. It’s important to standardize your data in order to equalize the range of the data."
},
{
"code": null,
"e": 5774,
"s": 5515,
"text": "For example, imagine a dataset with two input features: height in millimeters and weight in pounds. Because the values of ‘height’ are much higher due to its measurement, a greater emphasis will automatically be placed on height than weight, creating a bias."
},
{
"code": null,
"e": 5903,
"s": 5774,
"text": "# Normalize feature variablesfrom sklearn.preprocessing import StandardScalerX_features = XX = StandardScaler().fit_transform(X)"
},
{
"code": null,
"e": 6030,
"s": 5903,
"text": "Next I split the data into a training and test set so that I could cross-validate my models and determine their effectiveness."
},
{
"code": null,
"e": 6191,
"s": 6030,
"text": "# Splitting the datafrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.25, random_state=0)"
},
{
"code": null,
"e": 6216,
"s": 6191,
"text": "Now, comes the fun part!"
},
{
"code": null,
"e": 6450,
"s": 6216,
"text": "For this project, I wanted to compare five different machine learning models: decision trees, random forests, AdaBoost, Gradient Boost, and XGBoost. For the purpose of this project, I wanted to compare these models by their accuracy."
},
{
"code": null,
"e": 6867,
"s": 6450,
"text": "Decision trees are a popular model, used in operations research, strategic planning, and machine learning. Each square above is called a node, and the more nodes you have, the more accurate your decision tree will be (generally). The last nodes of the decision tree, where a decision is made, are called the leaves of the tree. Decision trees are intuitive and easy to build but fall short when it comes to accuracy."
},
{
"code": null,
"e": 7116,
"s": 6867,
"text": "from sklearn.metrics import classification_reportfrom sklearn.tree import DecisionTreeClassifiermodel1 = DecisionTreeClassifier(random_state=1)model1.fit(X_train, y_train)y_pred1 = model1.predict(X_test)print(classification_report(y_test, y_pred1))"
},
{
"code": null,
"e": 7586,
"s": 7116,
"text": "Random forests are an ensemble learning technique that builds off of decision trees. Random forests involve creating multiple decision trees using bootstrapped datasets of the original data and randomly selecting a subset of variables at each step of the decision tree. The model then selects the mode of all of the predictions of each decision tree. What’s the point of this? By relying on a “majority wins” model, it reduces the risk of error from an individual tree."
},
{
"code": null,
"e": 7790,
"s": 7586,
"text": "For example, if we created one decision tree, the third one, it would predict 0. But if we relied on the mode of all 4 decision trees, the predicted value would be 1. This is the power of random forests."
},
{
"code": null,
"e": 7994,
"s": 7790,
"text": "from sklearn.ensemble import RandomForestClassifiermodel2 = RandomForestClassifier(random_state=1)model2.fit(X_train, y_train)y_pred2 = model2.predict(X_test)print(classification_report(y_test, y_pred2))"
},
{
"code": null,
"e": 8334,
"s": 7994,
"text": "The next three models are boosting algorithms that take weak learners and turn them into strong ones. I don’t want to get sidetracked and explain the differences between the three because it’s quite complicated and intricate. That being said, I’ll leave some resources where you can learn about AdaBoost, Gradient Boosting, and XGBoosting."
},
{
"code": null,
"e": 8354,
"s": 8334,
"text": "StatQuest: AdaBoost"
},
{
"code": null,
"e": 8380,
"s": 8354,
"text": "StatQuest: Gradient Boost"
},
{
"code": null,
"e": 8399,
"s": 8380,
"text": "StatQuest: XGBoost"
},
{
"code": null,
"e": 8595,
"s": 8399,
"text": "from sklearn.ensemble import AdaBoostClassifiermodel3 = AdaBoostClassifier(random_state=1)model3.fit(X_train, y_train)y_pred3 = model3.predict(X_test)print(classification_report(y_test, y_pred3))"
},
{
"code": null,
"e": 8807,
"s": 8595,
"text": "from sklearn.ensemble import GradientBoostingClassifiermodel4 = GradientBoostingClassifier(random_state=1)model4.fit(X_train, y_train)y_pred4 = model4.predict(X_test)print(classification_report(y_test, y_pred4))"
},
{
"code": null,
"e": 8976,
"s": 8807,
"text": "import xgboost as xgbmodel5 = xgb.XGBClassifier(random_state=1)model5.fit(X_train, y_train)y_pred5 = model5.predict(X_test)print(classification_report(y_test, y_pred5))"
},
{
"code": null,
"e": 9232,
"s": 8976,
"text": "By comparing the five models, the random forest and XGBoost seems to yield the highest level of accuracy. However, since XGBoost has a better f1-score for predicting good quality wines (1), I’m concluding that the XGBoost is the winner of the five models."
},
{
"code": null,
"e": 9556,
"s": 9232,
"text": "Below, I graphed the feature importance based on the Random Forest model and the XGBoost model. While they slightly vary, the top 3 features are the same: alcohol, volatile acidity, and sulphates. If you look below the graphs, I split the dataset into good quality and bad quality to compare these variables in more detail."
},
{
"code": null,
"e": 9703,
"s": 9556,
"text": "feat_importances = pd.Series(model2.feature_importances_, index=X_features.columns)feat_importances.nlargest(25).plot(kind='barh',figsize=(10,10))"
},
{
"code": null,
"e": 9850,
"s": 9703,
"text": "feat_importances = pd.Series(model5.feature_importances_, index=X_features.columns)feat_importances.nlargest(25).plot(kind='barh',figsize=(10,10))"
},
{
"code": null,
"e": 10028,
"s": 9850,
"text": "# Filtering df for only good qualitydf_temp = df[df['goodquality']==1]df_temp.describe()# Filtering df for only bad qualitydf_temp2 = df[df['goodquality']==0]df_temp2.describe()"
},
{
"code": null,
"e": 10263,
"s": 10028,
"text": "By looking into the details, we can see that good quality wines have higher levels of alcohol on average, have a lower volatile acidity on average, higher levels of sulphates on average, and higher levels of residual sugar on average."
},
{
"code": null,
"e": 10378,
"s": 10263,
"text": "If you like my work and want to support me, I’d greatly appreciate if you followed me on my social media channels:"
},
{
"code": null,
"e": 10601,
"s": 10378,
"text": "The BEST way to support me is by following me on Medium here.Follow me on Twitter here.Subscribe to my new YouTube channel here.Follow me on LinkedIn here.Sign up on my email list here.Check out my website terenceshin.com."
},
{
"code": null,
"e": 10663,
"s": 10601,
"text": "The BEST way to support me is by following me on Medium here."
},
{
"code": null,
"e": 10690,
"s": 10663,
"text": "Follow me on Twitter here."
},
{
"code": null,
"e": 10732,
"s": 10690,
"text": "Subscribe to my new YouTube channel here."
},
{
"code": null,
"e": 10760,
"s": 10732,
"text": "Follow me on LinkedIn here."
},
{
"code": null,
"e": 10791,
"s": 10760,
"text": "Sign up on my email list here."
}
] |
How can we get the total number of rows affected by MySQL query?
|
MySQL ROW_COUNT() can be used to get the total number of rows affected by MySQL query. To illustrate it we are creating a procedure with the help of which we can insert records in a table and it will show us how many rows have been affected.
mysql> Delimiter //
mysql> CREATE PROCEDURE `query`.`row_cnt` (IN command VarChar(60000))
-> BEGIN
-> SET @query = command;
-> PREPARE stmt FROM @query;
-> EXECUTE stmt;
-> SELECT ROW_COUNT() AS 'Affected rows';
-> END //
Query OK, 0 rows affected (0.00 sec)
mysql> Delimiter ;
mysql> Create table Testing123(First Varchar(20), Second Varchar(20));
Query OK, 0 rows affected (0.48 sec)
mysql> CALL row_cnt("INSERT INTO testing123(First,Second) Values('Testing First','Testing Second');");
+---------------+
| Affected rows |
+---------------+
| 1 |
+---------------+
1 row in set (0.10 sec)
Query OK, 0 rows affected (0.11 sec)
The above result set shows that I row is affected after inserting the data into the ‘testing123’ table.
|
[
{
"code": null,
"e": 1304,
"s": 1062,
"text": "MySQL ROW_COUNT() can be used to get the total number of rows affected by MySQL query. To illustrate it we are creating a procedure with the help of which we can insert records in a table and it will show us how many rows have been affected."
},
{
"code": null,
"e": 1983,
"s": 1304,
"text": "mysql> Delimiter //\nmysql> CREATE PROCEDURE `query`.`row_cnt` (IN command VarChar(60000))\n -> BEGIN\n -> SET @query = command;\n -> PREPARE stmt FROM @query;\n -> EXECUTE stmt;\n -> SELECT ROW_COUNT() AS 'Affected rows';\n -> END //\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> Delimiter ;\nmysql> Create table Testing123(First Varchar(20), Second Varchar(20));\nQuery OK, 0 rows affected (0.48 sec)\n\nmysql> CALL row_cnt(\"INSERT INTO testing123(First,Second) Values('Testing First','Testing Second');\");\n+---------------+\n| Affected rows |\n+---------------+\n| 1 |\n+---------------+\n1 row in set (0.10 sec)\n\nQuery OK, 0 rows affected (0.11 sec)"
},
{
"code": null,
"e": 2087,
"s": 1983,
"text": "The above result set shows that I row is affected after inserting the data into the ‘testing123’ table."
}
] |
Find the Level of a Binary Tree with Width K - GeeksforGeeks
|
22 Jun, 2021
Given a Binary Tree and an integer K, the task is to find the level of the Binary Tree with width K. If multiple levels exists with width K, print the lowest level. If no such level exists, print -1.
The width of a level of a Binary tree is defined as the number of nodes between leftmost and the rightmost node at that level, including the NULL nodes in between them as well.
Examples:
Input: K = 4
5 --------- 1st level width = 1 => (5)
/ \
6 2 -------- 2nd level width = 2 => (6, 2)
/ \ \
7 3 8 -------3rd level width = 4 => (7, 3, NULL, 8)
/ \
5 4 -----------4th level width = 4 => (5, NULL, NULL, 4)
Output: 3 Explanation: For the given tree, the levels having width K( = 4) are 3 and 4. Since 3 is the minimum of the two, print the minimum.
Input: K = 7
1 --------- 1st level width = 1 => (1)
/ \
2 9 -------- 2nd level width = 2 => (2, 9)
/ \
7 8 ---------3rd level width = 4 => (7, NULL, NULL, 8)
/ /
5 9 -----------4th level width = 7 => (5, NULL, NULL,
/ NULL, NULL, NULL, 9)
2 -----------5th level width = 1 => (2)
/
1 -----------6th level width = 1 => (1)
Output: 4 Explanation: For the given tree, the level having width K( = 7) is 4.
Approach: The basic idea to solve the problem is to add a label to each node. If a parent has a label i, then assign a label 2*i to it’s left child and 2*i+1 to its right child. This will help in including the NULL nodes in the calculation. Follow the steps below:
Perform Level Order Traversal on the given tree using a Queue.
Queue contains a pair of {Node, Label}. Initially insert {rootNode, 0} to queue.
If parent has label i, then for a left child, insert {leftChild, 2*i} to queue and for right child, insert{rightChild, 2*i+1} into the queue.
For each level assume a as label of leftmost node and b as label of rightmost node, then (b-a+1) gives the width of that level.
Check whether the width is equal to K. If so, return level.
If none of the levels have width K, then return -1.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Structure of a Tree nodestruct Node { int key; struct Node *left, *right;}; // Utility function to create// and initialize a new nodeNode* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp);} // Function returns required level// of width k, if found else -1int findLevel(Node* root, int k, int level){ // To store the node and the label // and perform traversal queue<pair<Node*, int> > qt; qt.push(make_pair(root, 0)); int count = 1, b, a = 0; while (!qt.empty()) { pair<Node*, int> temp = qt.front(); qt.pop(); // Taking the last label // of each level of the tree if (count == 1) { b = temp.second; } if ((temp.first)->left) { qt.push(make_pair( temp.first->left, 2 * temp.second)); } if (temp.first->right) { qt.push(make_pair( temp.first->right, 2 * temp.second + 1)); } count--; // Check width of current level if (count == 0) { // If the width is equal to k // then return that level if (b - a + 1 == k) return level; pair<Node*, int> secondLabel = qt.front(); // Taking the first label // of each level of the tree a = secondLabel.second; level += 1; count = qt.size(); } } // If any level does not has // width equal to k, return -1 return -1;} // Driver Codeint main(){ Node* root = newNode(5); root->left = newNode(6); root->right = newNode(2); root->right->right = newNode(8); root->left->left = newNode(7); root->left->left->left = newNode(5); root->left->right = newNode(3); root->left->right->right = newNode(4); int k = 4; cout << findLevel(root, k, 1) << endl; return 0;}
// Java program to implement// the above approachimport java.util.*; class GFG{ // Structure of// binary tree nodestatic class Node{ int data; Node left, right;}; static class pair{ Node first; int second; pair(Node first, int second) { this.first = first; this.second = second; }} // Function to create new nodestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Function returns required level// of width k, if found else -1static int findLevel(Node root, int k, int level){ // To store the node and the label // and perform traversal Queue<pair> qt = new LinkedList<>(); qt.add(new pair(root, 0)); int count = 1, b = 0, a = 0; while (!qt.isEmpty()) { pair temp = qt.peek(); qt.poll(); // Taking the last label // of each level of the tree if (count == 1) { b = temp.second; } if (temp.first.left != null) { qt.add(new pair( temp.first.left, 2 * temp.second)); } if (temp.first.right != null) { qt.add(new pair( temp.first.right, 2 * temp.second + 1)); } count--; // Check width of current level if (count == 0) { // If the width is equal to k // then return that level if ((b - a + 1) == k) return level; pair secondLabel = qt.peek(); // Taking the first label // of each level of the tree a = secondLabel.second; level += 1; count = qt.size(); } } // If any level does not has // width equal to k, return -1 return -1;} // Driver codepublic static void main(String[] args){ Node root = newNode(5); root.left = newNode(6); root.right = newNode(2); root.right.right = newNode(8); root.left.left = newNode(7); root.left.left.left = newNode(5); root.left.right = newNode(3); root.left.right.right = newNode(4); int k = 4; System.out.println(findLevel(root, k, 1));}} // This code is contributed by offbeat
# Python3 program to implement# the above approachfrom collections import deque # Structure of a Tree nodeclass Node: def __init__(self, key): self.key = key self.left = None self.right = None # Function returns required level# of width k, if found else -1def findLevel(root: Node, k: int, level: int) -> int: # To store the node and the label # and perform traversal qt = deque() qt.append([root, 0]) count = 1 b = 0 a = 0 while qt: temp = qt.popleft() # Taking the last label # of each level of the tree if (count == 1): b = temp[1] if (temp[0].left): qt.append([temp[0].left, 2 * temp[1]]) if (temp[0].right): qt.append([temp[0].right, 2 * temp[1] + 1]) count -= 1 # Check width of current level if (count == 0): # If the width is equal to k # then return that level if (b - a + 1 == k): return level secondLabel = qt[0] # Taking the first label # of each level of the tree a = secondLabel[1] level += 1 count = len(qt) # If any level does not has # width equal to k, return -1 return -1 # Driver Codeif __name__ == "__main__": root = Node(5) root.left = Node(6) root.right = Node(2) root.right.right = Node(8) root.left.left = Node(7) root.left.left.left = Node(5) root.left.right = Node(3) root.left.right.right = Node(4) k = 4 print(findLevel(root, k, 1)) # This code is contributed by sanjeev2552
// C# program to implement// the above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Structure of// binary tree nodeclass Node{ public int data; public Node left, right;}; class pair{ public Node first; public int second; public pair(Node first, int second) { this.first = first; this.second = second; }} // Function to create new nodestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Function returns required level// of width k, if found else -1static int findLevel(Node root, int k, int level){ // To store the node and the label // and perform traversal Queue qt = new Queue(); qt.Enqueue(new pair(root, 0)); int count = 1, b = 0, a = 0; while (qt.Count!=0) { pair temp = (pair)qt.Dequeue(); // Taking the last label // of each level of the tree if (count == 1) { b = temp.second; } if (temp.first.left != null) { qt.Enqueue(new pair( temp.first.left, 2 * temp.second)); } if (temp.first.right != null) { qt.Enqueue(new pair( temp.first.right, 2 * temp.second + 1)); } count--; // Check width of current level if (count == 0) { // If the width is equal to k // then return that level if ((b - a + 1) == k) return level; pair secondLabel = (pair)qt.Peek(); // Taking the first label // of each level of the tree a = secondLabel.second; level += 1; count = qt.Count; } } // If any level does not has // width equal to k, return -1 return -1;} // Driver codepublic static void Main(string[] args){ Node root = newNode(5); root.left = newNode(6); root.right = newNode(2); root.right.right = newNode(8); root.left.left = newNode(7); root.left.left.left = newNode(5); root.left.right = newNode(3); root.left.right.right = newNode(4); int k = 4; Console.Write(findLevel(root, k, 1));}} // This code is contributed by rutvik_56
<script> // Javascript program to implement// the above approach // Structure of// binary tree nodeclass Node{ constructor() { this.data = 0; this.left = null; this.right = null; }}; class pair{ constructor(first, second) { this.first = first; this.second = second; }} // Function to create new nodefunction newNode(data){ var temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Function returns required level// of width k, if found else -1function findLevel(root, k, level){ // To store the node and the label // and perform traversal var qt = []; qt.push(new pair(root, 0)); var count = 1, b = 0, a = 0; while (qt.length!=0) { var temp = qt.shift(); // Taking the last label // of each level of the tree if (count == 1) { b = temp.second; } if (temp.first.left != null) { qt.push(new pair( temp.first.left, 2 * temp.second)); } if (temp.first.right != null) { qt.push(new pair( temp.first.right, 2 * temp.second + 1)); } count--; // Check width of current level if (count == 0) { // If the width is equal to k // then return that level if ((b - a + 1) == k) return level; var secondLabel = qt[0]; // Taking the first label // of each level of the tree a = secondLabel.second; level += 1; count = qt.length; } } // If any level does not has // width equal to k, return -1 return -1;} // Driver codevar root = newNode(5);root.left = newNode(6);root.right = newNode(2);root.right.right = newNode(8); root.left.left = newNode(7);root.left.left.left = newNode(5);root.left.right = newNode(3);root.left.right.right = newNode(4); var k = 4; document.write(findLevel(root, k, 1)); </script>
3
Time Complexity : O(N) Auxiliary Space : O(N)
offbeat
sanjeev2552
rutvik_56
famously
cpp-queue
Tree Traversals
Data Structures
Searching
Tree
Data Structures
Searching
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Tree Data Structure
Program to implement Singly Linked List in C++ using class
Hash Functions and list/types of Hash functions
Insertion in a B+ tree
TCS NQT Coding Sheet
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
Find the Missing Number
K'th Smallest/Largest Element in Unsorted Array | Set 1
|
[
{
"code": null,
"e": 25028,
"s": 25000,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 25228,
"s": 25028,
"text": "Given a Binary Tree and an integer K, the task is to find the level of the Binary Tree with width K. If multiple levels exists with width K, print the lowest level. If no such level exists, print -1."
},
{
"code": null,
"e": 25405,
"s": 25228,
"text": "The width of a level of a Binary tree is defined as the number of nodes between leftmost and the rightmost node at that level, including the NULL nodes in between them as well."
},
{
"code": null,
"e": 25415,
"s": 25405,
"text": "Examples:"
},
{
"code": null,
"e": 25430,
"s": 25415,
"text": "Input: K = 4 "
},
{
"code": null,
"e": 25708,
"s": 25430,
"text": " 5 --------- 1st level width = 1 => (5)\n / \\\n 6 2 -------- 2nd level width = 2 => (6, 2)\n / \\ \\ \n 7 3 8 -------3rd level width = 4 => (7, 3, NULL, 8)\n / \\\n 5 4 -----------4th level width = 4 => (5, NULL, NULL, 4)"
},
{
"code": null,
"e": 25850,
"s": 25708,
"text": "Output: 3 Explanation: For the given tree, the levels having width K( = 4) are 3 and 4. Since 3 is the minimum of the two, print the minimum."
},
{
"code": null,
"e": 25864,
"s": 25850,
"text": "Input: K = 7 "
},
{
"code": null,
"e": 26341,
"s": 25864,
"text": " 1 --------- 1st level width = 1 => (1)\n / \\\n 2 9 -------- 2nd level width = 2 => (2, 9)\n / \\ \n 7 8 ---------3rd level width = 4 => (7, NULL, NULL, 8)\n / /\n 5 9 -----------4th level width = 7 => (5, NULL, NULL, \n / NULL, NULL, NULL, 9)\n 2 -----------5th level width = 1 => (2)\n /\n 1 -----------6th level width = 1 => (1)"
},
{
"code": null,
"e": 26423,
"s": 26341,
"text": "Output: 4 Explanation: For the given tree, the level having width K( = 7) is 4. "
},
{
"code": null,
"e": 26690,
"s": 26423,
"text": "Approach: The basic idea to solve the problem is to add a label to each node. If a parent has a label i, then assign a label 2*i to it’s left child and 2*i+1 to its right child. This will help in including the NULL nodes in the calculation. Follow the steps below: "
},
{
"code": null,
"e": 26753,
"s": 26690,
"text": "Perform Level Order Traversal on the given tree using a Queue."
},
{
"code": null,
"e": 26834,
"s": 26753,
"text": "Queue contains a pair of {Node, Label}. Initially insert {rootNode, 0} to queue."
},
{
"code": null,
"e": 26976,
"s": 26834,
"text": "If parent has label i, then for a left child, insert {leftChild, 2*i} to queue and for right child, insert{rightChild, 2*i+1} into the queue."
},
{
"code": null,
"e": 27104,
"s": 26976,
"text": "For each level assume a as label of leftmost node and b as label of rightmost node, then (b-a+1) gives the width of that level."
},
{
"code": null,
"e": 27164,
"s": 27104,
"text": "Check whether the width is equal to K. If so, return level."
},
{
"code": null,
"e": 27216,
"s": 27164,
"text": "If none of the levels have width K, then return -1."
},
{
"code": null,
"e": 27267,
"s": 27216,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27271,
"s": 27267,
"text": "C++"
},
{
"code": null,
"e": 27276,
"s": 27271,
"text": "Java"
},
{
"code": null,
"e": 27284,
"s": 27276,
"text": "Python3"
},
{
"code": null,
"e": 27287,
"s": 27284,
"text": "C#"
},
{
"code": null,
"e": 27298,
"s": 27287,
"text": "Javascript"
},
{
"code": "// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Structure of a Tree nodestruct Node { int key; struct Node *left, *right;}; // Utility function to create// and initialize a new nodeNode* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp);} // Function returns required level// of width k, if found else -1int findLevel(Node* root, int k, int level){ // To store the node and the label // and perform traversal queue<pair<Node*, int> > qt; qt.push(make_pair(root, 0)); int count = 1, b, a = 0; while (!qt.empty()) { pair<Node*, int> temp = qt.front(); qt.pop(); // Taking the last label // of each level of the tree if (count == 1) { b = temp.second; } if ((temp.first)->left) { qt.push(make_pair( temp.first->left, 2 * temp.second)); } if (temp.first->right) { qt.push(make_pair( temp.first->right, 2 * temp.second + 1)); } count--; // Check width of current level if (count == 0) { // If the width is equal to k // then return that level if (b - a + 1 == k) return level; pair<Node*, int> secondLabel = qt.front(); // Taking the first label // of each level of the tree a = secondLabel.second; level += 1; count = qt.size(); } } // If any level does not has // width equal to k, return -1 return -1;} // Driver Codeint main(){ Node* root = newNode(5); root->left = newNode(6); root->right = newNode(2); root->right->right = newNode(8); root->left->left = newNode(7); root->left->left->left = newNode(5); root->left->right = newNode(3); root->left->right->right = newNode(4); int k = 4; cout << findLevel(root, k, 1) << endl; return 0;}",
"e": 29353,
"s": 27298,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*; class GFG{ // Structure of// binary tree nodestatic class Node{ int data; Node left, right;}; static class pair{ Node first; int second; pair(Node first, int second) { this.first = first; this.second = second; }} // Function to create new nodestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Function returns required level// of width k, if found else -1static int findLevel(Node root, int k, int level){ // To store the node and the label // and perform traversal Queue<pair> qt = new LinkedList<>(); qt.add(new pair(root, 0)); int count = 1, b = 0, a = 0; while (!qt.isEmpty()) { pair temp = qt.peek(); qt.poll(); // Taking the last label // of each level of the tree if (count == 1) { b = temp.second; } if (temp.first.left != null) { qt.add(new pair( temp.first.left, 2 * temp.second)); } if (temp.first.right != null) { qt.add(new pair( temp.first.right, 2 * temp.second + 1)); } count--; // Check width of current level if (count == 0) { // If the width is equal to k // then return that level if ((b - a + 1) == k) return level; pair secondLabel = qt.peek(); // Taking the first label // of each level of the tree a = secondLabel.second; level += 1; count = qt.size(); } } // If any level does not has // width equal to k, return -1 return -1;} // Driver codepublic static void main(String[] args){ Node root = newNode(5); root.left = newNode(6); root.right = newNode(2); root.right.right = newNode(8); root.left.left = newNode(7); root.left.left.left = newNode(5); root.left.right = newNode(3); root.left.right.right = newNode(4); int k = 4; System.out.println(findLevel(root, k, 1));}} // This code is contributed by offbeat",
"e": 31619,
"s": 29353,
"text": null
},
{
"code": "# Python3 program to implement# the above approachfrom collections import deque # Structure of a Tree nodeclass Node: def __init__(self, key): self.key = key self.left = None self.right = None # Function returns required level# of width k, if found else -1def findLevel(root: Node, k: int, level: int) -> int: # To store the node and the label # and perform traversal qt = deque() qt.append([root, 0]) count = 1 b = 0 a = 0 while qt: temp = qt.popleft() # Taking the last label # of each level of the tree if (count == 1): b = temp[1] if (temp[0].left): qt.append([temp[0].left, 2 * temp[1]]) if (temp[0].right): qt.append([temp[0].right, 2 * temp[1] + 1]) count -= 1 # Check width of current level if (count == 0): # If the width is equal to k # then return that level if (b - a + 1 == k): return level secondLabel = qt[0] # Taking the first label # of each level of the tree a = secondLabel[1] level += 1 count = len(qt) # If any level does not has # width equal to k, return -1 return -1 # Driver Codeif __name__ == \"__main__\": root = Node(5) root.left = Node(6) root.right = Node(2) root.right.right = Node(8) root.left.left = Node(7) root.left.left.left = Node(5) root.left.right = Node(3) root.left.right.right = Node(4) k = 4 print(findLevel(root, k, 1)) # This code is contributed by sanjeev2552",
"e": 33303,
"s": 31619,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Structure of// binary tree nodeclass Node{ public int data; public Node left, right;}; class pair{ public Node first; public int second; public pair(Node first, int second) { this.first = first; this.second = second; }} // Function to create new nodestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Function returns required level// of width k, if found else -1static int findLevel(Node root, int k, int level){ // To store the node and the label // and perform traversal Queue qt = new Queue(); qt.Enqueue(new pair(root, 0)); int count = 1, b = 0, a = 0; while (qt.Count!=0) { pair temp = (pair)qt.Dequeue(); // Taking the last label // of each level of the tree if (count == 1) { b = temp.second; } if (temp.first.left != null) { qt.Enqueue(new pair( temp.first.left, 2 * temp.second)); } if (temp.first.right != null) { qt.Enqueue(new pair( temp.first.right, 2 * temp.second + 1)); } count--; // Check width of current level if (count == 0) { // If the width is equal to k // then return that level if ((b - a + 1) == k) return level; pair secondLabel = (pair)qt.Peek(); // Taking the first label // of each level of the tree a = secondLabel.second; level += 1; count = qt.Count; } } // If any level does not has // width equal to k, return -1 return -1;} // Driver codepublic static void Main(string[] args){ Node root = newNode(5); root.left = newNode(6); root.right = newNode(2); root.right.right = newNode(8); root.left.left = newNode(7); root.left.left.left = newNode(5); root.left.right = newNode(3); root.left.right.right = newNode(4); int k = 4; Console.Write(findLevel(root, k, 1));}} // This code is contributed by rutvik_56",
"e": 35661,
"s": 33303,
"text": null
},
{
"code": "<script> // Javascript program to implement// the above approach // Structure of// binary tree nodeclass Node{ constructor() { this.data = 0; this.left = null; this.right = null; }}; class pair{ constructor(first, second) { this.first = first; this.second = second; }} // Function to create new nodefunction newNode(data){ var temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Function returns required level// of width k, if found else -1function findLevel(root, k, level){ // To store the node and the label // and perform traversal var qt = []; qt.push(new pair(root, 0)); var count = 1, b = 0, a = 0; while (qt.length!=0) { var temp = qt.shift(); // Taking the last label // of each level of the tree if (count == 1) { b = temp.second; } if (temp.first.left != null) { qt.push(new pair( temp.first.left, 2 * temp.second)); } if (temp.first.right != null) { qt.push(new pair( temp.first.right, 2 * temp.second + 1)); } count--; // Check width of current level if (count == 0) { // If the width is equal to k // then return that level if ((b - a + 1) == k) return level; var secondLabel = qt[0]; // Taking the first label // of each level of the tree a = secondLabel.second; level += 1; count = qt.length; } } // If any level does not has // width equal to k, return -1 return -1;} // Driver codevar root = newNode(5);root.left = newNode(6);root.right = newNode(2);root.right.right = newNode(8); root.left.left = newNode(7);root.left.left.left = newNode(5);root.left.right = newNode(3);root.left.right.right = newNode(4); var k = 4; document.write(findLevel(root, k, 1)); </script>",
"e": 37755,
"s": 35661,
"text": null
},
{
"code": null,
"e": 37757,
"s": 37755,
"text": "3"
},
{
"code": null,
"e": 37806,
"s": 37759,
"text": "Time Complexity : O(N) Auxiliary Space : O(N) "
},
{
"code": null,
"e": 37814,
"s": 37806,
"text": "offbeat"
},
{
"code": null,
"e": 37826,
"s": 37814,
"text": "sanjeev2552"
},
{
"code": null,
"e": 37836,
"s": 37826,
"text": "rutvik_56"
},
{
"code": null,
"e": 37845,
"s": 37836,
"text": "famously"
},
{
"code": null,
"e": 37855,
"s": 37845,
"text": "cpp-queue"
},
{
"code": null,
"e": 37871,
"s": 37855,
"text": "Tree Traversals"
},
{
"code": null,
"e": 37887,
"s": 37871,
"text": "Data Structures"
},
{
"code": null,
"e": 37897,
"s": 37887,
"text": "Searching"
},
{
"code": null,
"e": 37902,
"s": 37897,
"text": "Tree"
},
{
"code": null,
"e": 37918,
"s": 37902,
"text": "Data Structures"
},
{
"code": null,
"e": 37928,
"s": 37918,
"text": "Searching"
},
{
"code": null,
"e": 37933,
"s": 37928,
"text": "Tree"
},
{
"code": null,
"e": 38031,
"s": 37933,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38067,
"s": 38031,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 38126,
"s": 38067,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 38174,
"s": 38126,
"text": "Hash Functions and list/types of Hash functions"
},
{
"code": null,
"e": 38197,
"s": 38174,
"text": "Insertion in a B+ tree"
},
{
"code": null,
"e": 38218,
"s": 38197,
"text": "TCS NQT Coding Sheet"
},
{
"code": null,
"e": 38232,
"s": 38218,
"text": "Binary Search"
},
{
"code": null,
"e": 38300,
"s": 38232,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 38314,
"s": 38300,
"text": "Linear Search"
},
{
"code": null,
"e": 38338,
"s": 38314,
"text": "Find the Missing Number"
}
] |
How to disable mouse event on certain elements using JavaScript?
|
Following is the code for disabling mouse event on certain elements using JavaScript −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 18px;
font-weight: 500;
color: rebeccapurple;
}
.size {
font-size: 30px;
}
</style>
</head>
<body>
<h1>Disable Mouse events using JavaScript</h1>
<div class="result">This is some text inside a div</div>
<button class="Btn">DISABLE</button>
<button class="Btn">ENABLE</button>
<h3>
Click on the above button to enable or disable mouse events
</h3>
<script>
let resEle = document.querySelector(".result");
let sampleEle = document.querySelector(".sample");
let BtnEle = document.querySelectorAll(".Btn");
resEle.addEventListener("click", () => {
resEle.classList.toggle("size");
});
BtnEle[0].addEventListener("click", () => {
resEle.style.pointerEvents = "none";
});
BtnEle[1].addEventListener("click", () => {
resEle.style.pointerEvents = "auto";
});
</script>
</body>
</html>
The above code will produce the following output −
On clicking the text in purple above −
On clicking the ‘DISABLE’ button and then clicking the text −
On clicking the ‘ENABLE’ button and then clicking on the text −
|
[
{
"code": null,
"e": 1149,
"s": 1062,
"text": "Following is the code for disabling mouse event on certain elements using JavaScript −"
},
{
"code": null,
"e": 1160,
"s": 1149,
"text": " Live Demo"
},
{
"code": null,
"e": 2292,
"s": 1160,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 18px;\n font-weight: 500;\n color: rebeccapurple;\n }\n .size {\n font-size: 30px;\n }\n</style>\n</head>\n<body>\n<h1>Disable Mouse events using JavaScript</h1>\n<div class=\"result\">This is some text inside a div</div>\n<button class=\"Btn\">DISABLE</button>\n<button class=\"Btn\">ENABLE</button>\n<h3>\nClick on the above button to enable or disable mouse events\n</h3>\n<script>\n let resEle = document.querySelector(\".result\");\n let sampleEle = document.querySelector(\".sample\");\n let BtnEle = document.querySelectorAll(\".Btn\");\n resEle.addEventListener(\"click\", () => {\n resEle.classList.toggle(\"size\");\n });\n BtnEle[0].addEventListener(\"click\", () => {\n resEle.style.pointerEvents = \"none\";\n });\n BtnEle[1].addEventListener(\"click\", () => {\n resEle.style.pointerEvents = \"auto\";\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2343,
"s": 2292,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 2382,
"s": 2343,
"text": "On clicking the text in purple above −"
},
{
"code": null,
"e": 2444,
"s": 2382,
"text": "On clicking the ‘DISABLE’ button and then clicking the text −"
},
{
"code": null,
"e": 2508,
"s": 2444,
"text": "On clicking the ‘ENABLE’ button and then clicking on the text −"
}
] |
Setting custom splash screen in Kivy android app - GeeksforGeeks
|
06 Jun, 2021
Kivy is a platform-independent GUI tool in Python. It can run on Android, IOS, Linux and Windows, etc. This is the only GUI library from python which can independently run on the android device even we can use it on Raspberry pi also. It is an open-source Python library for the rapid development of multitouch applications. Its graphic engine is built over OpenGL, and it also supports a fast graphics pipeline.
In this article, we will see how we can add a custom splashscreen in kivy android app!
Basically, our motive is to show you how you add a custom splash screen that’s why we haven’t added anything thing on the main screen of the app except a center green box which denotes the app is working properly. And we are using our geeksforgeeks logo as a custom splash screen for this application.
Python3
# importing Kivy Appfrom kivy.app import App # importing builder from kivyfrom kivy.lang import Builder # this is the main class which # will render the whole applicationclass uiApp(App): # method which will render our application def build(self): return Builder.load_string("""BoxLayout: BoxLayout: BoxLayout: canvas.before: Color: rgba:[0,1,0,1] Rectangle: pos:self.pos size:self.size BoxLayout: """) # running the applicationuiApp().run()
Step 1: Connect USB with your phone and pc and allow Transfer Files in the phone’s generated popup.
Step 2: Then go to the phone’s setting and unlock developers mode in your device (if you haven’t) you can make yourself a developer by clicking several times on the build number in your phone.
Step 3: Then goes to the developer option that you have unlocked recently allow the USB debugging option.
Now you can successfully transfer files from pc to android phone.
Step 1: create a .spec file using a bulldozer, you can create your .spec file using the command ‘buildozer init’.
Step 2: open that .spec file in the text editor, after opening that file remove # from the beginning of this line.
Step 3: Pass the image path in this line
Step 4: Now attach USB cable to your android device and pc
Make sure that you have turned on USB debugging mode in the android device, now run the command ‘buildozer android debug deploy run’
Now check the app icon in your device:
Python-kivy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Python - Call function from another file
loops in python
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
Python Lambda Functions
|
[
{
"code": null,
"e": 23927,
"s": 23899,
"text": "\n06 Jun, 2021"
},
{
"code": null,
"e": 24341,
"s": 23927,
"text": "Kivy is a platform-independent GUI tool in Python. It can run on Android, IOS, Linux and Windows, etc. This is the only GUI library from python which can independently run on the android device even we can use it on Raspberry pi also. It is an open-source Python library for the rapid development of multitouch applications. Its graphic engine is built over OpenGL, and it also supports a fast graphics pipeline."
},
{
"code": null,
"e": 24428,
"s": 24341,
"text": "In this article, we will see how we can add a custom splashscreen in kivy android app!"
},
{
"code": null,
"e": 24730,
"s": 24428,
"text": "Basically, our motive is to show you how you add a custom splash screen that’s why we haven’t added anything thing on the main screen of the app except a center green box which denotes the app is working properly. And we are using our geeksforgeeks logo as a custom splash screen for this application."
},
{
"code": null,
"e": 24738,
"s": 24730,
"text": "Python3"
},
{
"code": "# importing Kivy Appfrom kivy.app import App # importing builder from kivyfrom kivy.lang import Builder # this is the main class which # will render the whole applicationclass uiApp(App): # method which will render our application def build(self): return Builder.load_string(\"\"\"BoxLayout: BoxLayout: BoxLayout: canvas.before: Color: rgba:[0,1,0,1] Rectangle: pos:self.pos size:self.size BoxLayout: \"\"\") # running the applicationuiApp().run()",
"e": 25319,
"s": 24738,
"text": null
},
{
"code": null,
"e": 25419,
"s": 25319,
"text": "Step 1: Connect USB with your phone and pc and allow Transfer Files in the phone’s generated popup."
},
{
"code": null,
"e": 25612,
"s": 25419,
"text": "Step 2: Then go to the phone’s setting and unlock developers mode in your device (if you haven’t) you can make yourself a developer by clicking several times on the build number in your phone."
},
{
"code": null,
"e": 25718,
"s": 25612,
"text": "Step 3: Then goes to the developer option that you have unlocked recently allow the USB debugging option."
},
{
"code": null,
"e": 25784,
"s": 25718,
"text": "Now you can successfully transfer files from pc to android phone."
},
{
"code": null,
"e": 25898,
"s": 25784,
"text": "Step 1: create a .spec file using a bulldozer, you can create your .spec file using the command ‘buildozer init’."
},
{
"code": null,
"e": 26013,
"s": 25898,
"text": "Step 2: open that .spec file in the text editor, after opening that file remove # from the beginning of this line."
},
{
"code": null,
"e": 26054,
"s": 26013,
"text": "Step 3: Pass the image path in this line"
},
{
"code": null,
"e": 26113,
"s": 26054,
"text": "Step 4: Now attach USB cable to your android device and pc"
},
{
"code": null,
"e": 26246,
"s": 26113,
"text": "Make sure that you have turned on USB debugging mode in the android device, now run the command ‘buildozer android debug deploy run’"
},
{
"code": null,
"e": 26285,
"s": 26246,
"text": "Now check the app icon in your device:"
},
{
"code": null,
"e": 26297,
"s": 26285,
"text": "Python-kivy"
},
{
"code": null,
"e": 26304,
"s": 26297,
"text": "Python"
},
{
"code": null,
"e": 26402,
"s": 26304,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26411,
"s": 26402,
"text": "Comments"
},
{
"code": null,
"e": 26424,
"s": 26411,
"text": "Old Comments"
},
{
"code": null,
"e": 26460,
"s": 26424,
"text": "Box Plot in Python using Matplotlib"
},
{
"code": null,
"e": 26483,
"s": 26460,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 26522,
"s": 26483,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26555,
"s": 26522,
"text": "Python | Convert set into a list"
},
{
"code": null,
"e": 26604,
"s": 26555,
"text": "Ways to filter Pandas DataFrame by column values"
},
{
"code": null,
"e": 26645,
"s": 26604,
"text": "Python - Call function from another file"
},
{
"code": null,
"e": 26661,
"s": 26645,
"text": "loops in python"
},
{
"code": null,
"e": 26712,
"s": 26661,
"text": "Multithreading in Python | Set 2 (Synchronization)"
},
{
"code": null,
"e": 26744,
"s": 26712,
"text": "Python Dictionary keys() method"
}
] |
How to find the currently running applications programmatically in Android?
|
This example demonstrates how do I find the currently running applications programmatically in Android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textAlignment="center"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Bundle;
import android.widget.TextView;
import java.util.List;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
final ActivityManager activityManager = (ActivityManager)
getSystemService(Context.ACTIVITY_SERVICE);
final List<ActivityManager.RunningTaskInfo> recentTasks = Objects.requireNonNull(activityManager).getRunningTasks(Integer.MAX_VALUE);
for (int i = 0; i < recentTasks.size(); i++) {
textView.setText("Application executed: " + recentTasks.get(i).baseActivity.toShortString() + "\n\n ID: " + recentTasks.get(i).id + "");
}
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
|
[
{
"code": null,
"e": 1166,
"s": 1062,
"text": "This example demonstrates how do I find the currently running applications programmatically in Android."
},
{
"code": null,
"e": 1295,
"s": 1166,
"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": 1360,
"s": 1295,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1956,
"s": 1360,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\nxmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"16dp\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:textAlignment=\"center\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2013,
"s": 1956,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2984,
"s": 2013,
"text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.app.ActivityManager;\nimport android.content.Context;\nimport android.os.Bundle;\nimport android.widget.TextView;\nimport java.util.List;\nimport java.util.Objects;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.textView);\n final ActivityManager activityManager = (ActivityManager)\n getSystemService(Context.ACTIVITY_SERVICE);\n final List<ActivityManager.RunningTaskInfo> recentTasks = Objects.requireNonNull(activityManager).getRunningTasks(Integer.MAX_VALUE);\n for (int i = 0; i < recentTasks.size(); i++) {\n textView.setText(\"Application executed: \" + recentTasks.get(i).baseActivity.toShortString() + \"\\n\\n ID: \" + recentTasks.get(i).id + \"\");\n }\n }\n}"
},
{
"code": null,
"e": 3039,
"s": 2984,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3709,
"s": 3039,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4060,
"s": 3709,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 4101,
"s": 4060,
"text": "Click here to download the project code."
}
] |
Find Mean of a List of Numpy Array in Python
|
Numpy is a very powerful python library for numerical data processing. It mostly takes in the data in form of arrays and applies various functions including statistical functions to get the result out of the array. In this article we will see how to get the mean value of a given array.
The mean function can take in an array and give the mathematical mean value of all the elements in it. So we design a for loop to keep track of the length of the input and go through each array calculating its mean.
Live Demo
import numpy as np
# GIven Array
Arrays_In = [np.array([11, 5, 41]),
np.array([12, 13, 26]),
np.array([56, 20, 51])]
# Resultihg Array
Arrays_res = []
# With np.mean()
for x in range(len(Arrays_In)):
Arrays_res.append(np.mean(Arrays_In[x]))
# Result
print("The means of the arrays: \n",Arrays_res)
Running the above code gives us the following result −
The means of the arrays:
[19.0, 17.0, 42.333333333333336]
It is a very similar approach as above except that we use the average function instead of mean function. It gives the exact same result.
Live Demo
import numpy as np
# GIven Array
Arrays_In = [np.array([11, 5, 41]),
np.array([12, 13, 26]),
np.array([56, 20, 51])]
# Resultihg Array
Arrays_res = []
# With np.average()
for x in range(len(Arrays_In)):
Arrays_res.append(np.average(Arrays_In[x]))
# Result
print("The means of the arrays: \n",Arrays_res)
Running the above code gives us the following result −
The means of the arrays:
[19.0, 17.0, 42.333333333333336]
|
[
{
"code": null,
"e": 1349,
"s": 1062,
"text": "Numpy is a very powerful python library for numerical data processing. It mostly takes in the data in form of arrays and applies various functions including statistical functions to get the result out of the array. In this article we will see how to get the mean value of a given array."
},
{
"code": null,
"e": 1565,
"s": 1349,
"text": "The mean function can take in an array and give the mathematical mean value of all the elements in it. So we design a for loop to keep track of the length of the input and go through each array calculating its mean."
},
{
"code": null,
"e": 1576,
"s": 1565,
"text": " Live Demo"
},
{
"code": null,
"e": 1899,
"s": 1576,
"text": "import numpy as np\n\n# GIven Array\nArrays_In = [np.array([11, 5, 41]),\n np.array([12, 13, 26]),\n np.array([56, 20, 51])]\n\n# Resultihg Array\nArrays_res = []\n\n# With np.mean()\nfor x in range(len(Arrays_In)):\n Arrays_res.append(np.mean(Arrays_In[x]))\n\n# Result\nprint(\"The means of the arrays: \\n\",Arrays_res)"
},
{
"code": null,
"e": 1954,
"s": 1899,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2012,
"s": 1954,
"text": "The means of the arrays:\n[19.0, 17.0, 42.333333333333336]"
},
{
"code": null,
"e": 2149,
"s": 2012,
"text": "It is a very similar approach as above except that we use the average function instead of mean function. It gives the exact same result."
},
{
"code": null,
"e": 2160,
"s": 2149,
"text": " Live Demo"
},
{
"code": null,
"e": 2489,
"s": 2160,
"text": "import numpy as np\n\n# GIven Array\nArrays_In = [np.array([11, 5, 41]),\n np.array([12, 13, 26]),\n np.array([56, 20, 51])]\n\n# Resultihg Array\nArrays_res = []\n\n# With np.average()\nfor x in range(len(Arrays_In)):\n Arrays_res.append(np.average(Arrays_In[x]))\n\n# Result\nprint(\"The means of the arrays: \\n\",Arrays_res)"
},
{
"code": null,
"e": 2544,
"s": 2489,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2602,
"s": 2544,
"text": "The means of the arrays:\n[19.0, 17.0, 42.333333333333336]"
}
] |
What is the difference between a variable and StringVar() of Tkinter?
|
A variable in Tkinter is used to store the values of any data. For a Tkinter application, we can store the values in two ways −
by defining the value programmatically, or
by defining the value programmatically, or
by storing the value through user Input.
by storing the value through user Input.
A normal variable can be used to set the value for any application whenever it is required. However, we can take the user input by creating an instance of the StringVar() object. When we specify a Tkinter variable such as textvariable, for a widget (textvariable = myvar), the widget automatically gets updated whenever the value of the variable changes. However, there might be times when we want to modify the value of the widget through the variable.
In this program, we will update the Label Widget from the StringVar(value). Whenever we want to update the value of Tkinter StringVar(), we have to change its value.
#Import the required Libraries
from tkinter import *
from tkinter import ttk
#Create an instance of tkinter frame
win = Tk()
#Set the geometry of tkinter frame
win.geometry("750x250")
#Create a StringVar to accept user input
var= StringVar(value= "Hello World!")
#Create a Label
label= Label(win,textvariable=var, font= ('Mistral 28 bold'), background= 'blue', foreground="white")
label.pack(pady=20)
win.mainloop()
Running the above code will display a label text which has the same value as defined in StringVar().
|
[
{
"code": null,
"e": 1190,
"s": 1062,
"text": "A variable in Tkinter is used to store the values of any data. For a Tkinter application, we can store the values in two ways −"
},
{
"code": null,
"e": 1233,
"s": 1190,
"text": "by defining the value programmatically, or"
},
{
"code": null,
"e": 1276,
"s": 1233,
"text": "by defining the value programmatically, or"
},
{
"code": null,
"e": 1317,
"s": 1276,
"text": "by storing the value through user Input."
},
{
"code": null,
"e": 1358,
"s": 1317,
"text": "by storing the value through user Input."
},
{
"code": null,
"e": 1812,
"s": 1358,
"text": "A normal variable can be used to set the value for any application whenever it is required. However, we can take the user input by creating an instance of the StringVar() object. When we specify a Tkinter variable such as textvariable, for a widget (textvariable = myvar), the widget automatically gets updated whenever the value of the variable changes. However, there might be times when we want to modify the value of the widget through the variable."
},
{
"code": null,
"e": 1978,
"s": 1812,
"text": "In this program, we will update the Label Widget from the StringVar(value). Whenever we want to update the value of Tkinter StringVar(), we have to change its value."
},
{
"code": null,
"e": 2398,
"s": 1978,
"text": "#Import the required Libraries\nfrom tkinter import *\nfrom tkinter import ttk\n#Create an instance of tkinter frame\nwin = Tk()\n\n#Set the geometry of tkinter frame\nwin.geometry(\"750x250\")\n\n#Create a StringVar to accept user input\nvar= StringVar(value= \"Hello World!\")\n\n#Create a Label\nlabel= Label(win,textvariable=var, font= ('Mistral 28 bold'), background= 'blue', foreground=\"white\")\nlabel.pack(pady=20)\n\nwin.mainloop()"
},
{
"code": null,
"e": 2499,
"s": 2398,
"text": "Running the above code will display a label text which has the same value as defined in StringVar()."
}
] |
How to check whether a radio button is selected with JavaScript ? - GeeksforGeeks
|
26 Jul, 2021
Given a form containing radio button element and the task is to check whether a radio button is selected or not with the help of JavaScript. There are two methods to solve this problem which are discussed below:
Using Input Radio checked property: The Input Radio checked property is used to return the checked status of an Input Radio Button.Use document.getElementById(‘id’).checked method to check whether the element with selected id is check or not. If it is checked then display its corresponding result otherwise check the next statement. If no one radio button is selected then it returns ‘No one selected’.
Example:
<!DOCTYPE html><html> <head> <title> How to check whether a radio button is selected with JavaScript ? </title></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> Click on the button to check whether<br> a radio button is sected or not </h3> <form> <input type="radio" name="GFG" id="GFG" value="GeeksforGeeks">GeeksforGeeks<br> <input type="radio" name="GFG" id="HTML" value="HTML">HTML<br> <input type="radio" name="GFG" id="JS" value="JavaScript">JavaScript<br><br> <button type="button" onclick="display()"> Submit </button> </form> <br> <div id="disp" style= "color:green; font-size:18px; font-weight:bold;"> </div> </body> <script> function display() { if(document.getElementById('GFG').checked) { document.getElementById("disp").innerHTML = document.getElementById("GFG").value + " radio button checked"; } else if(document.getElementById('HTML').checked) { document.getElementById("disp").innerHTML = document.getElementById("HTML").value + " radio button checked"; } else if(document.getElementById('JS').checked) { document.getElementById("disp").innerHTML = document.getElementById("JS").value + " radio button checked"; } else { document.getElementById("disp").innerHTML = "No one selected"; } } </script></html>
Output:
Before click on submit button:
After click on submit button:
Using DOM querySelector() Method: The querySelector() method is used to return the first element that matches the specified CSS selectors in the document.Use document.querySelector(‘input[name=”GFG”]:checked’) method to check the checked element of radio button and dislapy its corresponding result. If no one radio button is selected then it returns ‘No one selected’
Example:
<!DOCTYPE html><html> <head> <title> How to check whether a radio button is selected with JavaScript ? </title></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> Click on the button to check whether<br> a radio button is sected or not </h3> <form> <input type="radio" name="GFG" id="GFG" value="GeeksforGeeks">GeeksforGeeks<br> <input type="radio" name="GFG" id="HTML" value="HTML">HTML<br> <input type="radio" name="GFG" id="JS" value="JavaScript">JavaScript<br><br> <button type="button" onclick="display()"> Submit </button> </form> <br> <div id="disp" style= "color:green; font-size:18px; font-weight:bold;"> </div> </body> <script> function display() { var checkRadio = document.querySelector( 'input[name="GFG"]:checked'); if(checkRadio != null) { document.getElementById("disp").innerHTML = checkRadio.value + " radio button checked"; } else { document.getElementById("disp").innerHTML = "No one selected"; } } </script></html>
Output:
Before click on submit button:
After click on submit button:
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24755,
"s": 24727,
"text": "\n26 Jul, 2021"
},
{
"code": null,
"e": 24967,
"s": 24755,
"text": "Given a form containing radio button element and the task is to check whether a radio button is selected or not with the help of JavaScript. There are two methods to solve this problem which are discussed below:"
},
{
"code": null,
"e": 25371,
"s": 24967,
"text": "Using Input Radio checked property: The Input Radio checked property is used to return the checked status of an Input Radio Button.Use document.getElementById(‘id’).checked method to check whether the element with selected id is check or not. If it is checked then display its corresponding result otherwise check the next statement. If no one radio button is selected then it returns ‘No one selected’."
},
{
"code": null,
"e": 25380,
"s": 25371,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to check whether a radio button is selected with JavaScript ? </title></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3> Click on the button to check whether<br> a radio button is sected or not </h3> <form> <input type=\"radio\" name=\"GFG\" id=\"GFG\" value=\"GeeksforGeeks\">GeeksforGeeks<br> <input type=\"radio\" name=\"GFG\" id=\"HTML\" value=\"HTML\">HTML<br> <input type=\"radio\" name=\"GFG\" id=\"JS\" value=\"JavaScript\">JavaScript<br><br> <button type=\"button\" onclick=\"display()\"> Submit </button> </form> <br> <div id=\"disp\" style= \"color:green; font-size:18px; font-weight:bold;\"> </div> </body> <script> function display() { if(document.getElementById('GFG').checked) { document.getElementById(\"disp\").innerHTML = document.getElementById(\"GFG\").value + \" radio button checked\"; } else if(document.getElementById('HTML').checked) { document.getElementById(\"disp\").innerHTML = document.getElementById(\"HTML\").value + \" radio button checked\"; } else if(document.getElementById('JS').checked) { document.getElementById(\"disp\").innerHTML = document.getElementById(\"JS\").value + \" radio button checked\"; } else { document.getElementById(\"disp\").innerHTML = \"No one selected\"; } } </script></html> ",
"e": 27134,
"s": 25380,
"text": null
},
{
"code": null,
"e": 27142,
"s": 27134,
"text": "Output:"
},
{
"code": null,
"e": 27173,
"s": 27142,
"text": "Before click on submit button:"
},
{
"code": null,
"e": 27203,
"s": 27173,
"text": "After click on submit button:"
},
{
"code": null,
"e": 27572,
"s": 27203,
"text": "Using DOM querySelector() Method: The querySelector() method is used to return the first element that matches the specified CSS selectors in the document.Use document.querySelector(‘input[name=”GFG”]:checked’) method to check the checked element of radio button and dislapy its corresponding result. If no one radio button is selected then it returns ‘No one selected’"
},
{
"code": null,
"e": 27581,
"s": 27572,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to check whether a radio button is selected with JavaScript ? </title></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3> Click on the button to check whether<br> a radio button is sected or not </h3> <form> <input type=\"radio\" name=\"GFG\" id=\"GFG\" value=\"GeeksforGeeks\">GeeksforGeeks<br> <input type=\"radio\" name=\"GFG\" id=\"HTML\" value=\"HTML\">HTML<br> <input type=\"radio\" name=\"GFG\" id=\"JS\" value=\"JavaScript\">JavaScript<br><br> <button type=\"button\" onclick=\"display()\"> Submit </button> </form> <br> <div id=\"disp\" style= \"color:green; font-size:18px; font-weight:bold;\"> </div> </body> <script> function display() { var checkRadio = document.querySelector( 'input[name=\"GFG\"]:checked'); if(checkRadio != null) { document.getElementById(\"disp\").innerHTML = checkRadio.value + \" radio button checked\"; } else { document.getElementById(\"disp\").innerHTML = \"No one selected\"; } } </script></html>",
"e": 28925,
"s": 27581,
"text": null
},
{
"code": null,
"e": 28933,
"s": 28925,
"text": "Output:"
},
{
"code": null,
"e": 28964,
"s": 28933,
"text": "Before click on submit button:"
},
{
"code": null,
"e": 28994,
"s": 28964,
"text": "After click on submit button:"
},
{
"code": null,
"e": 29213,
"s": 28994,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 29220,
"s": 29213,
"text": "Picked"
},
{
"code": null,
"e": 29231,
"s": 29220,
"text": "JavaScript"
},
{
"code": null,
"e": 29248,
"s": 29231,
"text": "Web Technologies"
},
{
"code": null,
"e": 29275,
"s": 29248,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29373,
"s": 29275,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29382,
"s": 29373,
"text": "Comments"
},
{
"code": null,
"e": 29395,
"s": 29382,
"text": "Old Comments"
},
{
"code": null,
"e": 29456,
"s": 29395,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29501,
"s": 29456,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29573,
"s": 29501,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29625,
"s": 29573,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 29671,
"s": 29625,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 29727,
"s": 29671,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 29760,
"s": 29727,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29822,
"s": 29760,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29865,
"s": 29822,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Sending an Intent to browser to open specific URL in Android?
|
This example demonstrates how do I send an Intent to browser to open specific URL in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp"
tools:context=".MainActivity">
<Button
android:onClick="GetUrlFromIntent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get URL from Intent"
android:layout_centerInParent="true"/>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void GetUrlFromIntent(View view) {
String url = "http://www.google.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
|
[
{
"code": null,
"e": 1156,
"s": 1062,
"text": "This example demonstrates how do I send an Intent to browser to open specific URL in android."
},
{
"code": null,
"e": 1285,
"s": 1156,
"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": 1350,
"s": 1285,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1893,
"s": 1350,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"8dp\"\n tools:context=\".MainActivity\">\n <Button\n android:onClick=\"GetUrlFromIntent\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Get URL from Intent\"\n android:layout_centerInParent=\"true\"/>\n</RelativeLayout>"
},
{
"code": null,
"e": 1950,
"s": 1893,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2524,
"s": 1950,
"text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.view.View;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n public void GetUrlFromIntent(View view) {\n String url = \"http://www.google.com\";\n Intent i = new Intent(Intent.ACTION_VIEW);\n i.setData(Uri.parse(url));\n startActivity(i);\n }\n}"
},
{
"code": null,
"e": 2579,
"s": 2524,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3314,
"s": 2579,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <uses-permission android:name=\"android.permission.INTERNET\"/>\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": 3661,
"s": 3314,
"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": 3702,
"s": 3661,
"text": "Click here to download the project code."
}
] |
Count triplets from a sorted array having difference between adjacent elements equal to D - GeeksforGeeks
|
25 May, 2021
Given a sorted array arr[] consisting of N positive integers and an integer D, the task is to find the number of triplets (i, j, k) such that arr[j] – arr[i] = D and arr[k] – arr[j] = D and 0 ≤ i < j < k < N.
Examples:
Input: arr[] = {1, 2, 4, 5, 7, 8, 10}, D = 3Output: 3Explanation:Following are the triplets having the difference between the adjacent elements is D(= 3) are:
{1, 4, 7}
{4, 7, 10}
{2, 5, 8}
{1, 4, 7}
{4, 7, 10}
{2, 5, 8}
Therefore, the total count of triplets is 3.
Input: arr[] = {1, 2, 4, 5, 7, 8, 10}, D = 1Output: 0
Naive Approach: The simplest approach to solve this problem is to generate all the triplets of the given array and count those triplets having the difference between the adjacent elements is D(= 3).
Time Complexity: O(N3)Auxiliary Space: O(1)
Efficient Approach: The above approach can also be optimized by considering every element of the array as the last element of the triplet and check for the previous two elements i.e., (arr[i] – D) and (arr[i] – 2 * D) exists in the array or not. Follow the steps below to solve the problem.
Initialize a HashMap, say M that stores the frequency of the array elements.
Initialize a variable, say ans as 0.
Traverse the given array arr[] and perform the following steps:
Increment the frequency of arr[i] by 1 in the HashMap M.
Now, check if the element (arr[i] – D) and (arr[i] – 2 * D) are present in the HashMap or not. If found to be true, then increment the value of ans by freq[arr[i] – D] * freq[arr[i] – 2 * D].
Increment the frequency of arr[i] by 1 in the HashMap M.
Now, check if the element (arr[i] – D) and (arr[i] – 2 * D) are present in the HashMap or not. If found to be true, then increment the value of ans by freq[arr[i] – D] * freq[arr[i] – 2 * D].
After completing the above steps, print the value of ans as the resultant count of triplets in the array.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to count the number of
// triplets having difference
// between adjacent elements equal to D
int countTriplets(int D, vector<int>& arr)
{
// Stores the frequency
// of array elements
unordered_map<int, int> freq;
// Stores the count of
// resultant triplets
int ans = 0;
// Traverse the array
for (int i = 0; i < arr.size(); i++) {
// Check if arr[i] - D and
// arr[i] - 2 * D exists
// in the Hashmap or not
if (freq.find(arr[i] - D)
!= freq.end()
&& freq.find(arr[i] - 2 * D)
!= freq.end()) {
// Update the value of ans
ans += freq[arr[i] - D]
* freq[arr[i] - 2 * D];
}
// Increase the frequency
// of the current element
freq[arr[i]]++;
}
// Return the resultant count
return ans;
}
// Driver Code
int main()
{
vector<int> arr{ 1, 2, 4, 5, 7, 8, 10 };
int D = 1;
cout << countTriplets(D, arr);
return 0;
}
// Java program for the above approach
import java.util.*;
class GFG{
// Function to count the number of
// triplets having difference
// between adjacent elements equal to D
static int countTriplets(int D, int []arr)
{
// Stores the frequency
// of array elements
HashMap<Integer,
Integer> freq = new HashMap<Integer,
Integer>();
// Stores the count of
// resultant triplets
int ans = 0;
// Traverse the array
for(int i = 0; i < arr.length; i++)
{
// Check if arr[i] - D and
// arr[i] - 2 * D exists
// in the Hashmap or not
if (freq.containsKey(arr[i] - D) &&
freq.containsKey(arr[i] - 2 * D))
{
// Update the value of ans
ans += freq.get(arr[i] - D) *
freq.get(arr[i] - 2 * D);
}
// Increase the frequency
// of the current element
if (freq.containsKey(arr[i]))
{
freq.put(arr[i], freq.get(arr[i]) + 1);
}
else
{
freq.put(arr[i], 1);
}
}
// Return the resultant count
return ans;
}
// Driver Code
public static void main(String[] args)
{
int []arr = { 1, 2, 4, 5, 7, 8, 10 };
int D = 1;
System.out.print(countTriplets(D, arr));
}
}
// This code is contributed by 29AjayKumar
# Python3 program for the above approach
# Function to count the number of
# triplets having difference
# between adjacent elements equal to D
def countTriplets(D, arr):
# Stores the frequency
# of array elements
freq = {}
# Stores the count of
# resultant triplets
ans = 0
# Traverse the array
for i in range(len(arr)):
# Check if arr[i] - D and
# arr[i] - 2 * D exists
# in the Hashmap or not
if (((arr[i] - D) in freq) and
(arr[i] - 2 * D) in freq):
# Update the value of ans
ans += (freq[arr[i] - D] *
freq[arr[i] - 2 * D])
# Increase the frequency
# of the current element
freq[arr[i]] = freq.get(arr[i], 0) + 1
# Return the resultant count
return ans
# Driver Code
if __name__ == '__main__':
arr = [ 1, 2, 4, 5, 7, 8, 10 ]
D = 1
print (countTriplets(D, arr))
# This code is contributed by mohit kumar 29
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to count the number of
// triplets having difference
// between adjacent elements equal to D
static int countTriplets(int D, int[] arr)
{
// Stores the frequency
// of array elements
Dictionary<int,
int> freq = new Dictionary<int,
int>();
// Stores the count of
// resultant triplets
int ans = 0;
// Traverse the array
for(int i = 0; i < arr.Length; i++)
{
// Check if arr[i] - D and
// arr[i] - 2 * D exists
// in the Hashmap or not
if (freq.ContainsKey(arr[i] - D) &&
freq.ContainsKey(arr[i] - 2 * D))
{
// Update the value of ans
ans += freq[arr[i] - D] *
freq[arr[i] - 2 * D];
}
// Increase the frequency
// of the current element
if (!freq.ContainsKey(arr[i]))
freq[arr[i]] = 0;
freq[arr[i]]++;
}
// Return the resultant count
return ans;
}
// Driver Code
public static void Main()
{
int[] arr = { 1, 2, 4, 5, 7, 8, 10 };
int D = 1;
Console.WriteLine(countTriplets(D, arr));
}
}
// This code is contributed by ukasp
<script>
// javascript program for the above approach
// Function to count the number of
// triplets having difference
// between adjacent elements equal to D
function countTriplets(D, arr)
{
// Stores the frequency
// of array elements
var freq = new Map();
// Stores the count of
// resultant triplets
var ans = 0;
var i;
// Traverse the array
for (i = 0; i < arr.length; i++) {
// Check if arr[i] - D and
// arr[i] - 2 * D exists
// in the Hashmap or not
if (freq.has(arr[i] - D) && freq.has(arr[i] - 2 * D)) {
// Update the value of ans
ans += freq.get(arr[i] - D) * freq.get(arr[i] - 2 * D);
}
// Increase the frequency
// of the current element
freq.set(arr[i],freq.get(arr[i])+1);
}
// Return the resultant count
return ans;
}
// Driver Code
var arr = [1, 2, 4, 5, 7, 8, 10];
var D = 1;
document.write(countTriplets(D, arr));
</script>
0
Time Complexity: O(N) Auxiliary Space: O(N)
mohit kumar 29
ukasp
29AjayKumar
SURENDRA_GANGWAR
frequency-counting
HashTable
Arrays
Hash
Mathematical
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Trapping Rain Water
Reversal algorithm for array rotation
Move all negative numbers to beginning and positive to end with constant extra space
Program to find sum of elements in a given array
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Count pairs with given sum
Hashing | Set 2 (Separate Chaining)
|
[
{
"code": null,
"e": 24870,
"s": 24839,
"text": " \n25 May, 2021\n"
},
{
"code": null,
"e": 25079,
"s": 24870,
"text": "Given a sorted array arr[] consisting of N positive integers and an integer D, the task is to find the number of triplets (i, j, k) such that arr[j] – arr[i] = D and arr[k] – arr[j] = D and 0 ≤ i < j < k < N."
},
{
"code": null,
"e": 25089,
"s": 25079,
"text": "Examples:"
},
{
"code": null,
"e": 25248,
"s": 25089,
"text": "Input: arr[] = {1, 2, 4, 5, 7, 8, 10}, D = 3Output: 3Explanation:Following are the triplets having the difference between the adjacent elements is D(= 3) are:"
},
{
"code": null,
"e": 25281,
"s": 25248,
"text": "\n{1, 4, 7}\n{4, 7, 10}\n{2, 5, 8}\n"
},
{
"code": null,
"e": 25291,
"s": 25281,
"text": "{1, 4, 7}"
},
{
"code": null,
"e": 25302,
"s": 25291,
"text": "{4, 7, 10}"
},
{
"code": null,
"e": 25312,
"s": 25302,
"text": "{2, 5, 8}"
},
{
"code": null,
"e": 25357,
"s": 25312,
"text": "Therefore, the total count of triplets is 3."
},
{
"code": null,
"e": 25411,
"s": 25357,
"text": "Input: arr[] = {1, 2, 4, 5, 7, 8, 10}, D = 1Output: 0"
},
{
"code": null,
"e": 25610,
"s": 25411,
"text": "Naive Approach: The simplest approach to solve this problem is to generate all the triplets of the given array and count those triplets having the difference between the adjacent elements is D(= 3)."
},
{
"code": null,
"e": 25654,
"s": 25610,
"text": "Time Complexity: O(N3)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 25945,
"s": 25654,
"text": "Efficient Approach: The above approach can also be optimized by considering every element of the array as the last element of the triplet and check for the previous two elements i.e., (arr[i] – D) and (arr[i] – 2 * D) exists in the array or not. Follow the steps below to solve the problem."
},
{
"code": null,
"e": 26022,
"s": 25945,
"text": "Initialize a HashMap, say M that stores the frequency of the array elements."
},
{
"code": null,
"e": 26059,
"s": 26022,
"text": "Initialize a variable, say ans as 0."
},
{
"code": null,
"e": 26376,
"s": 26059,
"text": "Traverse the given array arr[] and perform the following steps:\n\nIncrement the frequency of arr[i] by 1 in the HashMap M.\nNow, check if the element (arr[i] – D) and (arr[i] – 2 * D) are present in the HashMap or not. If found to be true, then increment the value of ans by freq[arr[i] – D] * freq[arr[i] – 2 * D].\n\n"
},
{
"code": null,
"e": 26433,
"s": 26376,
"text": "Increment the frequency of arr[i] by 1 in the HashMap M."
},
{
"code": null,
"e": 26626,
"s": 26433,
"text": "Now, check if the element (arr[i] – D) and (arr[i] – 2 * D) are present in the HashMap or not. If found to be true, then increment the value of ans by freq[arr[i] – D] * freq[arr[i] – 2 * D]."
},
{
"code": null,
"e": 26732,
"s": 26626,
"text": "After completing the above steps, print the value of ans as the resultant count of triplets in the array."
},
{
"code": null,
"e": 26783,
"s": 26732,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26787,
"s": 26783,
"text": "C++"
},
{
"code": null,
"e": 26792,
"s": 26787,
"text": "Java"
},
{
"code": null,
"e": 26800,
"s": 26792,
"text": "Python3"
},
{
"code": null,
"e": 26803,
"s": 26800,
"text": "C#"
},
{
"code": null,
"e": 26814,
"s": 26803,
"text": "Javascript"
},
{
"code": "\n\n\n\n\n\n\n// C++ program for the above approach\n \n#include <bits/stdc++.h>\nusing namespace std;\n \n// Function to count the number of\n// triplets having difference\n// between adjacent elements equal to D\nint countTriplets(int D, vector<int>& arr)\n{\n // Stores the frequency\n // of array elements\n unordered_map<int, int> freq;\n \n // Stores the count of\n // resultant triplets\n int ans = 0;\n \n // Traverse the array\n for (int i = 0; i < arr.size(); i++) {\n \n // Check if arr[i] - D and\n // arr[i] - 2 * D exists\n // in the Hashmap or not\n if (freq.find(arr[i] - D)\n != freq.end()\n && freq.find(arr[i] - 2 * D)\n != freq.end()) {\n \n // Update the value of ans\n ans += freq[arr[i] - D]\n * freq[arr[i] - 2 * D];\n }\n \n // Increase the frequency\n // of the current element\n freq[arr[i]]++;\n }\n \n // Return the resultant count\n return ans;\n}\n \n// Driver Code\nint main()\n{\n vector<int> arr{ 1, 2, 4, 5, 7, 8, 10 };\n int D = 1;\n cout << countTriplets(D, arr);\n \n return 0;\n}\n\n\n\n\n\n",
"e": 27978,
"s": 26824,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// Java program for the above approach\nimport java.util.*;\n \nclass GFG{\n \n// Function to count the number of\n// triplets having difference\n// between adjacent elements equal to D\nstatic int countTriplets(int D, int []arr)\n{\n \n // Stores the frequency\n // of array elements\n HashMap<Integer,\n Integer> freq = new HashMap<Integer,\n Integer>();\n \n // Stores the count of\n // resultant triplets\n int ans = 0;\n \n // Traverse the array\n for(int i = 0; i < arr.length; i++) \n {\n \n // Check if arr[i] - D and\n // arr[i] - 2 * D exists\n // in the Hashmap or not\n if (freq.containsKey(arr[i] - D) && \n freq.containsKey(arr[i] - 2 * D))\n {\n \n // Update the value of ans\n ans += freq.get(arr[i] - D) * \n freq.get(arr[i] - 2 * D);\n }\n \n // Increase the frequency\n // of the current element\n if (freq.containsKey(arr[i]))\n {\n freq.put(arr[i], freq.get(arr[i]) + 1);\n }\n else\n {\n freq.put(arr[i], 1);\n }\n }\n \n // Return the resultant count\n return ans;\n}\n \n// Driver Code\npublic static void main(String[] args)\n{\n int []arr = { 1, 2, 4, 5, 7, 8, 10 };\n int D = 1;\n \n System.out.print(countTriplets(D, arr));\n}\n}\n \n// This code is contributed by 29AjayKumar\n\n\n\n\n\n",
"e": 29439,
"s": 27988,
"text": null
},
{
"code": "\n\n\n\n\n\n\n# Python3 program for the above approach\n \n# Function to count the number of\n# triplets having difference\n# between adjacent elements equal to D\ndef countTriplets(D, arr):\n \n # Stores the frequency\n # of array elements\n freq = {}\n \n # Stores the count of\n # resultant triplets\n ans = 0\n \n # Traverse the array\n for i in range(len(arr)):\n \n # Check if arr[i] - D and\n # arr[i] - 2 * D exists\n # in the Hashmap or not\n if (((arr[i] - D) in freq) and\n (arr[i] - 2 * D) in freq):\n \n # Update the value of ans\n ans += (freq[arr[i] - D] *\n freq[arr[i] - 2 * D])\n \n # Increase the frequency\n # of the current element\n freq[arr[i]] = freq.get(arr[i], 0) + 1\n \n # Return the resultant count\n return ans\n \n# Driver Code\nif __name__ == '__main__':\n \n arr = [ 1, 2, 4, 5, 7, 8, 10 ]\n D = 1\n \n print (countTriplets(D, arr))\n \n# This code is contributed by mohit kumar 29\n\n\n\n\n\n",
"e": 30501,
"s": 29449,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// C# program for the above approach\nusing System;\nusing System.Collections.Generic;\n \nclass GFG{\n \n// Function to count the number of\n// triplets having difference\n// between adjacent elements equal to D\nstatic int countTriplets(int D, int[] arr)\n{\n \n // Stores the frequency\n // of array elements\n Dictionary<int, \n int> freq = new Dictionary<int, \n int>();\n \n // Stores the count of\n // resultant triplets\n int ans = 0;\n \n // Traverse the array\n for(int i = 0; i < arr.Length; i++) \n {\n \n // Check if arr[i] - D and\n // arr[i] - 2 * D exists\n // in the Hashmap or not\n if (freq.ContainsKey(arr[i] - D) && \n freq.ContainsKey(arr[i] - 2 * D))\n {\n \n // Update the value of ans\n ans += freq[arr[i] - D] * \n freq[arr[i] - 2 * D];\n }\n \n // Increase the frequency\n // of the current element\n if (!freq.ContainsKey(arr[i]))\n freq[arr[i]] = 0;\n \n freq[arr[i]]++;\n }\n \n // Return the resultant count\n return ans;\n}\n \n// Driver Code\npublic static void Main()\n{\n int[] arr = { 1, 2, 4, 5, 7, 8, 10 };\n int D = 1;\n \n Console.WriteLine(countTriplets(D, arr));\n}\n}\n \n// This code is contributed by ukasp\n\n\n\n\n\n",
"e": 31890,
"s": 30511,
"text": null
},
{
"code": "\n\n\n\n\n\n\n<script>\n \n// javascript program for the above approach\n \n// Function to count the number of\n// triplets having difference\n// between adjacent elements equal to D\nfunction countTriplets(D, arr)\n{\n // Stores the frequency\n // of array elements\n var freq = new Map();\n \n // Stores the count of\n // resultant triplets\n var ans = 0;\n var i;\n \n // Traverse the array\n for (i = 0; i < arr.length; i++) {\n \n // Check if arr[i] - D and\n // arr[i] - 2 * D exists\n // in the Hashmap or not\n if (freq.has(arr[i] - D) && freq.has(arr[i] - 2 * D)) {\n \n // Update the value of ans\n ans += freq.get(arr[i] - D) * freq.get(arr[i] - 2 * D);\n }\n \n // Increase the frequency\n // of the current element\n freq.set(arr[i],freq.get(arr[i])+1);\n }\n \n // Return the resultant count\n return ans;\n}\n \n// Driver Code\n var arr = [1, 2, 4, 5, 7, 8, 10];\n var D = 1;\n document.write(countTriplets(D, arr));\n \n</script>\n\n\n\n\n\n",
"e": 32928,
"s": 31900,
"text": null
},
{
"code": null,
"e": 32930,
"s": 32928,
"text": "0"
},
{
"code": null,
"e": 32976,
"s": 32932,
"text": "Time Complexity: O(N) Auxiliary Space: O(N)"
},
{
"code": null,
"e": 32991,
"s": 32976,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 32997,
"s": 32991,
"text": "ukasp"
},
{
"code": null,
"e": 33009,
"s": 32997,
"text": "29AjayKumar"
},
{
"code": null,
"e": 33026,
"s": 33009,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 33047,
"s": 33026,
"text": "\nfrequency-counting\n"
},
{
"code": null,
"e": 33059,
"s": 33047,
"text": "\nHashTable\n"
},
{
"code": null,
"e": 33068,
"s": 33059,
"text": "\nArrays\n"
},
{
"code": null,
"e": 33075,
"s": 33068,
"text": "\nHash\n"
},
{
"code": null,
"e": 33090,
"s": 33075,
"text": "\nMathematical\n"
},
{
"code": null,
"e": 33102,
"s": 33090,
"text": "\nSearching\n"
},
{
"code": null,
"e": 33307,
"s": 33102,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 33332,
"s": 33307,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 33352,
"s": 33332,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 33390,
"s": 33352,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 33475,
"s": 33390,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
},
{
"code": null,
"e": 33524,
"s": 33475,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 33560,
"s": 33524,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 33591,
"s": 33560,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 33625,
"s": 33591,
"text": "Hashing | Set 3 (Open Addressing)"
},
{
"code": null,
"e": 33652,
"s": 33625,
"text": "Count pairs with given sum"
}
] |
How to limit the number of characters allowed in form input text field?
|
The HTML <input> tag is used to get user input in HTML. To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively.
To limit the number of characters, use the maxlength attribute. The max and min attributes are used with number, range, date, datetime, datetime-local, month, time and week input types.
You can try to run the following code to limit the number of characters allowed in form input text field:
<!DOCTYPE html>
<html>
<head>
<title>HTML maxlength attribute</title>
</head>
<body>
<form action = "/cgi-bin/hello_get.cgi" method = "get">
Student Name:
<br>
<input type = "text" name = "first_name" value = "" maxlength = "40" />
<br>
Student Subject: <br>
<input type = "text" name = "last_name" value = "" maxlength = "30" />
<br>
<input type = "submit" value ="Submit" />
</form>
</body>
</html>
|
[
{
"code": null,
"e": 1267,
"s": 1062,
"text": "The HTML <input> tag is used to get user input in HTML. To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively."
},
{
"code": null,
"e": 1453,
"s": 1267,
"text": "To limit the number of characters, use the maxlength attribute. The max and min attributes are used with number, range, date, datetime, datetime-local, month, time and week input types."
},
{
"code": null,
"e": 1559,
"s": 1453,
"text": "You can try to run the following code to limit the number of characters allowed in form input text field:"
},
{
"code": null,
"e": 2062,
"s": 1559,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML maxlength attribute</title>\n </head>\n <body>\n <form action = \"/cgi-bin/hello_get.cgi\" method = \"get\">\n Student Name:\n <br>\n <input type = \"text\" name = \"first_name\" value = \"\" maxlength = \"40\" />\n <br>\n Student Subject: <br>\n <input type = \"text\" name = \"last_name\" value = \"\" maxlength = \"30\" />\n <br>\n <input type = \"submit\" value =\"Submit\" />\n </form>\n </body>\n</html>"
}
] |
Overloaded method and ambiguity in C#
|
With method overloading, you can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list.
Let us see an example. In this the call would go to the method with a single parameter −
using System;
class Student {
static void DisplayMarks(int marks1 = 90) {
Console.WriteLine("Method with one parameter!");
}
static void DisplayMarks(int marks1, int marks2 = 95) {
Console.WriteLine("Method with two parameters!");
}
static void Main() {
DisplayMarks(97);
}
}
Now let us see what creates an ambiguous call. Here the confusion is that the second method would need two arguments as defaults, whereas the first methid needs one argument to be defaulted. This creates ambiguity.
using System;
class Student {
static void DisplayMarks(int marks1 = 90, int marks2 = 80) {
Console.WriteLine("Method with two parameters!");
}
static void DisplayMarks(int marks1, int marks2 = 80, marks3 = 98) {
Console.WriteLine("Method with three parameters!");
}
static void Main() {
DisplayMarks(80);
}
}
|
[
{
"code": null,
"e": 1292,
"s": 1062,
"text": "With method overloading, you can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list."
},
{
"code": null,
"e": 1381,
"s": 1292,
"text": "Let us see an example. In this the call would go to the method with a single parameter −"
},
{
"code": null,
"e": 1696,
"s": 1381,
"text": "using System;\n\nclass Student {\n static void DisplayMarks(int marks1 = 90) {\n Console.WriteLine(\"Method with one parameter!\");\n }\n\n static void DisplayMarks(int marks1, int marks2 = 95) {\n Console.WriteLine(\"Method with two parameters!\");\n }\n\n static void Main() {\n DisplayMarks(97);\n }\n}"
},
{
"code": null,
"e": 1911,
"s": 1696,
"text": "Now let us see what creates an ambiguous call. Here the confusion is that the second method would need two arguments as defaults, whereas the first methid needs one argument to be defaulted. This creates ambiguity."
},
{
"code": null,
"e": 2259,
"s": 1911,
"text": "using System;\n\nclass Student {\n static void DisplayMarks(int marks1 = 90, int marks2 = 80) {\n Console.WriteLine(\"Method with two parameters!\");\n }\n\n static void DisplayMarks(int marks1, int marks2 = 80, marks3 = 98) {\n Console.WriteLine(\"Method with three parameters!\");\n }\n\n static void Main() {\n DisplayMarks(80);\n }\n}"
}
] |
AngularJS - Dependency Injection
|
Dependency Injection is a software design in which components are given their dependencies instead of hard coding them within the component. It relieves a component from locating the dependency and makes dependencies configurable. It also helps in making components reusable, maintainable and testable.
AngularJS provides a supreme Dependency Injection mechanism. It provides following core components which can be injected into each other as dependencies.
Value
Factory
Service
Provider
Constant
Value is a simple JavaScript object, which is required to pass values to the controller during config phase (config phase is when AngularJS bootstraps itself).
//define a module
var mainApp = angular.module("mainApp", []);
//create a value object as "defaultInput" and pass it a data.
mainApp.value("defaultInput", 5);
...
//inject the value in the controller using its name "defaultInput"
mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {
$scope.number = defaultInput;
$scope.result = CalcService.square($scope.number);
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
}
});
Factory is a function which is used to return value. It creates a value on demand whenever a service or a controller requires it. It generally uses a factory function to calculate and return the value.
//define a module
var mainApp = angular.module("mainApp", []);
//create a factory "MathService" which provides a method multiply to return multiplication of two numbers
mainApp.factory('MathService', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b
}
return factory;
});
//inject the factory "MathService" in a service to utilize the multiply method of factory.
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
}
});
...
Service is a singleton JavaScript object containing a set of functions to perform certain tasks. Service is defined using service() function and it is then injected into the controllers.
//define a module
var mainApp = angular.module("mainApp", []);
...
//create a service which defines a method square to return square of a number.
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
}
});
//inject the service "CalcService" into the controller
mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {
$scope.number = defaultInput;
$scope.result = CalcService.square($scope.number);
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
}
});
Provider is used by AngularJS internally to create services, factory, etc. during the config phase. The following script can be used to create MathService that we created earlier. Provider is a special factory method with get() method which is used to return the value/service/factory.
//define a module
var mainApp = angular.module("mainApp", []);
...
//create a service using provider which defines a method square to return square of a number.
mainApp.config(function($provide) {
$provide.provider('MathService', function() {
this.$get = function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
}
return factory;
};
});
});
Constants are used to pass values at the config phase considering the fact that value cannot be used during the config phase.
mainApp.constant("configParam", "constant value");
The following example shows the use of all the above-mentioned directives −
<html>
<head>
<title>AngularJS Dependency Injection</title>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "mainApp" ng-controller = "CalcController">
<p>Enter a number: <input type = "number" ng-model = "number" /></p>
<button ng-click = "square()">X<sup>2</sup></button>
<p>Result: {{result}}</p>
</div>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.config(function($provide) {
$provide.provider('MathService', function() {
this.$get = function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
}
return factory;
};
});
});
mainApp.value("defaultInput", 5);
mainApp.factory('MathService', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
}
return factory;
});
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
}
});
mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {
$scope.number = defaultInput;
$scope.result = CalcService.square($scope.number);
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
}
});
</script>
</body>
</html>
Open testAngularJS.htm in a web browser and see the result.
Enter a number:
X2
Result: {{result}}
16 Lectures
1.5 hours
Anadi Sharma
40 Lectures
2.5 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3002,
"s": 2699,
"text": "Dependency Injection is a software design in which components are given their dependencies instead of hard coding them within the component. It relieves a component from locating the dependency and makes dependencies configurable. It also helps in making components reusable, maintainable and testable."
},
{
"code": null,
"e": 3156,
"s": 3002,
"text": "AngularJS provides a supreme Dependency Injection mechanism. It provides following core components which can be injected into each other as dependencies."
},
{
"code": null,
"e": 3162,
"s": 3156,
"text": "Value"
},
{
"code": null,
"e": 3170,
"s": 3162,
"text": "Factory"
},
{
"code": null,
"e": 3178,
"s": 3170,
"text": "Service"
},
{
"code": null,
"e": 3187,
"s": 3178,
"text": "Provider"
},
{
"code": null,
"e": 3196,
"s": 3187,
"text": "Constant"
},
{
"code": null,
"e": 3356,
"s": 3196,
"text": "Value is a simple JavaScript object, which is required to pass values to the controller during config phase (config phase is when AngularJS bootstraps itself)."
},
{
"code": null,
"e": 3860,
"s": 3356,
"text": "//define a module\nvar mainApp = angular.module(\"mainApp\", []);\n\n//create a value object as \"defaultInput\" and pass it a data.\nmainApp.value(\"defaultInput\", 5);\n...\n\n//inject the value in the controller using its name \"defaultInput\"\nmainApp.controller('CalcController', function($scope, CalcService, defaultInput) {\n $scope.number = defaultInput;\n $scope.result = CalcService.square($scope.number);\n \n $scope.square = function() {\n $scope.result = CalcService.square($scope.number);\n }\n});"
},
{
"code": null,
"e": 4062,
"s": 3860,
"text": "Factory is a function which is used to return value. It creates a value on demand whenever a service or a controller requires it. It generally uses a factory function to calculate and return the value."
},
{
"code": null,
"e": 4619,
"s": 4062,
"text": "//define a module\nvar mainApp = angular.module(\"mainApp\", []);\n\n//create a factory \"MathService\" which provides a method multiply to return multiplication of two numbers\nmainApp.factory('MathService', function() {\n var factory = {};\n \n factory.multiply = function(a, b) {\n return a * b\n }\n return factory;\n}); \n\n//inject the factory \"MathService\" in a service to utilize the multiply method of factory.\nmainApp.service('CalcService', function(MathService) {\n this.square = function(a) {\n return MathService.multiply(a,a);\n }\n});\n..."
},
{
"code": null,
"e": 4806,
"s": 4619,
"text": "Service is a singleton JavaScript object containing a set of functions to perform certain tasks. Service is defined using service() function and it is then injected into the controllers."
},
{
"code": null,
"e": 5417,
"s": 4806,
"text": "//define a module\nvar mainApp = angular.module(\"mainApp\", []);\n...\n\n//create a service which defines a method square to return square of a number.\nmainApp.service('CalcService', function(MathService) {\n this.square = function(a) {\n return MathService.multiply(a,a); \n }\n});\n\n//inject the service \"CalcService\" into the controller\nmainApp.controller('CalcController', function($scope, CalcService, defaultInput) {\n $scope.number = defaultInput;\n $scope.result = CalcService.square($scope.number);\n \n $scope.square = function() {\n $scope.result = CalcService.square($scope.number);\n }\n});"
},
{
"code": null,
"e": 5703,
"s": 5417,
"text": "Provider is used by AngularJS internally to create services, factory, etc. during the config phase. The following script can be used to create MathService that we created earlier. Provider is a special factory method with get() method which is used to return the value/service/factory."
},
{
"code": null,
"e": 6148,
"s": 5703,
"text": "//define a module\nvar mainApp = angular.module(\"mainApp\", []);\n...\n\n//create a service using provider which defines a method square to return square of a number.\nmainApp.config(function($provide) {\n $provide.provider('MathService', function() {\n this.$get = function() {\n var factory = {}; \n \n factory.multiply = function(a, b) {\n return a * b; \n }\n return factory;\n };\n });\n});"
},
{
"code": null,
"e": 6274,
"s": 6148,
"text": "Constants are used to pass values at the config phase considering the fact that value cannot be used during the config phase."
},
{
"code": null,
"e": 6326,
"s": 6274,
"text": "mainApp.constant(\"configParam\", \"constant value\");\n"
},
{
"code": null,
"e": 6402,
"s": 6326,
"text": "The following example shows the use of all the above-mentioned directives −"
},
{
"code": null,
"e": 8228,
"s": 6402,
"text": "<html>\n <head>\n <title>AngularJS Dependency Injection</title>\n </head>\n \n <body>\n <h2>AngularJS Sample Application</h2>\n \n <div ng-app = \"mainApp\" ng-controller = \"CalcController\">\n <p>Enter a number: <input type = \"number\" ng-model = \"number\" /></p>\n <button ng-click = \"square()\">X<sup>2</sup></button>\n <p>Result: {{result}}</p>\n </div>\n \n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js\">\n </script>\n \n <script>\n var mainApp = angular.module(\"mainApp\", []);\n \n mainApp.config(function($provide) {\n $provide.provider('MathService', function() {\n this.$get = function() {\n var factory = {};\n \n factory.multiply = function(a, b) {\n return a * b;\n }\n return factory;\n };\n });\n });\n\t\t\t\n mainApp.value(\"defaultInput\", 5);\n \n mainApp.factory('MathService', function() {\n var factory = {};\n \n factory.multiply = function(a, b) {\n return a * b;\n }\n return factory;\n });\n mainApp.service('CalcService', function(MathService) {\n this.square = function(a) {\n return MathService.multiply(a,a);\n }\n });\n mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {\n $scope.number = defaultInput;\n $scope.result = CalcService.square($scope.number);\n\n $scope.square = function() {\n $scope.result = CalcService.square($scope.number);\n }\n });\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 8288,
"s": 8228,
"text": "Open testAngularJS.htm in a web browser and see the result."
},
{
"code": null,
"e": 8309,
"s": 8288,
"text": "Enter a number: \nX2\n"
},
{
"code": null,
"e": 8328,
"s": 8309,
"text": "Result: {{result}}"
},
{
"code": null,
"e": 8363,
"s": 8328,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8377,
"s": 8363,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 8412,
"s": 8377,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8432,
"s": 8412,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 8439,
"s": 8432,
"text": " Print"
},
{
"code": null,
"e": 8450,
"s": 8439,
"text": " Add Notes"
}
] |
How to concatenate byte array in java?
|
You ByteArrayOutputStream to write byte arrays and get the result using its toByteArray() method.
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class Tester {
public static void main(String[] args) throws IOException {
byte[] a = { 1,2,3};
byte[] b = { 4,5,6};
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(a);
baos.write(b);
byte[] c = baos.toByteArray();
for(int i=0; i< c.length ; i++){
System.out.print(c[i] +" ");
}
}
}
1 2 3 4 5 6
|
[
{
"code": null,
"e": 1160,
"s": 1062,
"text": "You ByteArrayOutputStream to write byte arrays and get the result using its toByteArray() method."
},
{
"code": null,
"e": 1600,
"s": 1160,
"text": "import java.io.ByteArrayOutputStream;\nimport java.io.IOException;\npublic class Tester {\n public static void main(String[] args) throws IOException {\n byte[] a = { 1,2,3};\n byte[] b = { 4,5,6};\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n baos.write(a);\n baos.write(b);\n byte[] c = baos.toByteArray();\n for(int i=0; i< c.length ; i++){\n System.out.print(c[i] +\" \");\n }\n }\n}"
},
{
"code": null,
"e": 1613,
"s": 1600,
"text": "1 2 3 4 5 6\n"
}
] |
Binning method for data smoothing in Python
|
Many times we use a method called data smoothing to make the data proper and qualitative for statistical analysis. During the smoking process we define a range also called bin and any data value within the range is made to fit into the bin. This is called the binning method. Below is an example of binning. Then we will see how we can achieve the binning method using a Python program.
Let’s take a series of numbers. Find the maximum and minimum values. Decide on the number of bins we need depending on how many data points the analysis needs. Create these groups and assign each of these numbers to this groups.The upper value is excluded and belongs to next group.
Given numbers: 12, 32, 10, 17, 19, 28, 22, 26, 29,16
Number of groups : 4
Here
Max Value: 32
Min Value: 10
So the groups are –
(10-15), (15-21), (21-27), (27-32)
On putting the numbers into bins, we get the following result −
12 -> (10-15)
32 -> (27-32)
10 -> (10-15)
17 -> (15-21)
19 -> (15-21)
28 -> (27-32)
22 -> (21-27)
26 -> (21-27)
29 -> (27-32)
16 -> (15-21)
For this program we define two functions. One for creating the bins by defining the upper and lower bounds. The other function is to assign the input values to each of the bin. Each of the bin also gets an index. We see how each of the input value is assigned to the bin and keep track of how many values go to a specific bin.
Live Demo
from collections import Counter
def Binning_method(lower_bound, width, quantity):
binning = []
for low in range(lower_bound, lower_bound + quantity * width + 1, width):
binning.append((low, low + width))
return binning
def bin_assign(v, b):
for i in range(0, len(b)):
if b[i][0] <= v < b[i][1]:
return i
the_bins = Binning_method(lower_bound=50,
width=4,
quantity=10)
print("The Bins: \n",the_bins)
weights_of_objects = [89.2, 57.2, 63.4, 84.6, 90.2, 60.3,88.7, 65.2, 79.8, 80.2, 93.5, 79.3,72.5, 59.2, 77.2, 67.0, 88.2, 73.5]
print("\nBinned Values:\n")
binned_weight = []
for val in weights_of_objects:
index = bin_assign(val, the_bins)
#print(val, index, binning[index])
print(val,"-with index-", index,":", the_bins[index])
binned_weight.append(index)
freq = Counter(binned_weight)
print("\nCount of values in each index: ")
print(freq)
Running the above code gives us the following result −
The Bins:
[(50, 54), (54, 58), (58, 62), (62, 66), (66, 70), (70, 74), (74, 78), (78, 82), (82, 86), (86, 90), (90, 94)]
Binned Values:
89.2 -with index- 9 : (86, 90)
57.2 -with index- 1 : (54, 58)
63.4 -with index- 3 : (62, 66)
84.6 -with index- 8 : (82, 86)
90.2 -with index- 10 : (90, 94)
60.3 -with index- 2 : (58, 62)
88.7 -with index- 9 : (86, 90)
65.2 -with index- 3 : (62, 66)
79.8 -with index- 7 : (78, 82)
80.2 -with index- 7 : (78, 82)
93.5 -with index- 10 : (90, 94)
79.3 -with index- 7 : (78, 82)
72.5 -with index- 5 : (70, 74)
59.2 -with index- 2 : (58, 62)
77.2 -with index- 6 : (74, 78)
67.0 -with index- 4 : (66, 70)
88.2 -with index- 9 : (86, 90)
73.5 -with index- 5 : (70, 74)
Count of values in each index:
Counter({9: 3, 7: 3, 3: 2, 10: 2, 2: 2, 5: 2, 1: 1, 8: 1, 6: 1, 4: 1})
|
[
{
"code": null,
"e": 1449,
"s": 1062,
"text": "Many times we use a method called data smoothing to make the data proper and qualitative for statistical analysis. During the smoking process we define a range also called bin and any data value within the range is made to fit into the bin. This is called the binning method. Below is an example of binning. Then we will see how we can achieve the binning method using a Python program."
},
{
"code": null,
"e": 1732,
"s": 1449,
"text": "Let’s take a series of numbers. Find the maximum and minimum values. Decide on the number of bins we need depending on how many data points the analysis needs. Create these groups and assign each of these numbers to this groups.The upper value is excluded and belongs to next group."
},
{
"code": null,
"e": 1894,
"s": 1732,
"text": "Given numbers: 12, 32, 10, 17, 19, 28, 22, 26, 29,16\nNumber of groups : 4\nHere\nMax Value: 32\nMin Value: 10\nSo the groups are –\n(10-15), (15-21), (21-27), (27-32)"
},
{
"code": null,
"e": 1958,
"s": 1894,
"text": "On putting the numbers into bins, we get the following result −"
},
{
"code": null,
"e": 2098,
"s": 1958,
"text": "12 -> (10-15)\n32 -> (27-32)\n10 -> (10-15)\n17 -> (15-21)\n19 -> (15-21)\n28 -> (27-32)\n22 -> (21-27)\n26 -> (21-27)\n29 -> (27-32)\n16 -> (15-21)"
},
{
"code": null,
"e": 2425,
"s": 2098,
"text": "For this program we define two functions. One for creating the bins by defining the upper and lower bounds. The other function is to assign the input values to each of the bin. Each of the bin also gets an index. We see how each of the input value is assigned to the bin and keep track of how many values go to a specific bin."
},
{
"code": null,
"e": 2436,
"s": 2425,
"text": " Live Demo"
},
{
"code": null,
"e": 3328,
"s": 2436,
"text": "from collections import Counter\ndef Binning_method(lower_bound, width, quantity):\n binning = []\n for low in range(lower_bound, lower_bound + quantity * width + 1, width):\n binning.append((low, low + width))\n return binning\ndef bin_assign(v, b):\n for i in range(0, len(b)):\n if b[i][0] <= v < b[i][1]:\n return i\nthe_bins = Binning_method(lower_bound=50,\n width=4,\n quantity=10)\nprint(\"The Bins: \\n\",the_bins)\nweights_of_objects = [89.2, 57.2, 63.4, 84.6, 90.2, 60.3,88.7, 65.2, 79.8, 80.2, 93.5, 79.3,72.5, 59.2, 77.2, 67.0, 88.2, 73.5]\nprint(\"\\nBinned Values:\\n\")\nbinned_weight = []\nfor val in weights_of_objects:\n index = bin_assign(val, the_bins)\n #print(val, index, binning[index])\n print(val,\"-with index-\", index,\":\", the_bins[index])\n binned_weight.append(index)\nfreq = Counter(binned_weight)\nprint(\"\\nCount of values in each index: \")\nprint(freq)"
},
{
"code": null,
"e": 3383,
"s": 3328,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 4184,
"s": 3383,
"text": "The Bins:\n [(50, 54), (54, 58), (58, 62), (62, 66), (66, 70), (70, 74), (74, 78), (78, 82), (82, 86), (86, 90), (90, 94)]\nBinned Values:\n89.2 -with index- 9 : (86, 90)\n57.2 -with index- 1 : (54, 58)\n63.4 -with index- 3 : (62, 66)\n84.6 -with index- 8 : (82, 86)\n90.2 -with index- 10 : (90, 94)\n60.3 -with index- 2 : (58, 62)\n88.7 -with index- 9 : (86, 90)\n65.2 -with index- 3 : (62, 66)\n79.8 -with index- 7 : (78, 82)\n80.2 -with index- 7 : (78, 82)\n93.5 -with index- 10 : (90, 94)\n79.3 -with index- 7 : (78, 82)\n72.5 -with index- 5 : (70, 74)\n59.2 -with index- 2 : (58, 62)\n77.2 -with index- 6 : (74, 78)\n67.0 -with index- 4 : (66, 70)\n88.2 -with index- 9 : (86, 90)\n73.5 -with index- 5 : (70, 74)\nCount of values in each index:\nCounter({9: 3, 7: 3, 3: 2, 10: 2, 2: 2, 5: 2, 1: 1, 8: 1, 6: 1, 4: 1})"
}
] |
Adding new property to each document in a large MongoDB collection?
|
You can use update command along with forEach() for large collection. Let us first create a collection with documents
>db.addingNewPropertyDemo.insertOne({"StudentName":"John","StudentAge":23,"CountryName":"US"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca1e61866324ffac2a7dc56")
}
>db.addingNewPropertyDemo.insertOne({"StudentName":"David","StudentAge":21,"CountryName":"AUS"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca1e62366324ffac2a7dc57")
}
>db.addingNewPropertyDemo.insertOne({"StudentName":"Bob","StudentAge":21,"CountryName":"UK"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca1e62d66324ffac2a7dc58")
}
Following is the query to display all documents from a collection with the help of find() method
> db.addingNewPropertyDemo.find().pretty();
This will produce the following output
{
"_id" : ObjectId("5ca1e61866324ffac2a7dc56"),
"StudentName" : "John",
"StudentAge" : 23,
"CountryName" : "US"
}
{
"_id" : ObjectId("5ca1e62366324ffac2a7dc57"),
"StudentName" : "David",
"StudentAge" : 21,
"CountryName" : "AUS"
}
{
"_id" : ObjectId("5ca1e62d66324ffac2a7dc58"),
"StudentName" : "Bob",
"StudentAge" : 21,
"CountryName" : "UK"
}
Following is the query to add new property to each document in a large collection
> db.addingNewPropertyDemo.find().forEach(function(data){ db.addingNewPropertyDemo.update({_id: data._id}, {$set: { StudentNameInUpperCase: data.StudentName.toUpperCase() }}) });
Let us check a new property is added or not
> db.addingNewPropertyDemo.find().pretty();
Following is the output displaying the new property as well
{
"_id" : ObjectId("5ca1e61866324ffac2a7dc56"),
"StudentName" : "John",
"StudentAge" : 23,
"CountryName" : "US",
"StudentNameInUpperCase" : "JOHN"
}
{
"_id" : ObjectId("5ca1e62366324ffac2a7dc57"),
"StudentName" : "David",
"StudentAge" : 21,
"CountryName" : "AUS",
"StudentNameInUpperCase" : "DAVID"
}
{
"_id" : ObjectId("5ca1e62d66324ffac2a7dc58"),
"StudentName" : "Bob",
"StudentAge" : 21,
"CountryName" : "UK",
"StudentNameInUpperCase" : "BOB"
}
Look at the above sample output, StudentNameInUpperCase property is added.
|
[
{
"code": null,
"e": 1180,
"s": 1062,
"text": "You can use update command along with forEach() for large collection. Let us first create a collection with documents"
},
{
"code": null,
"e": 1724,
"s": 1180,
"text": ">db.addingNewPropertyDemo.insertOne({\"StudentName\":\"John\",\"StudentAge\":23,\"CountryName\":\"US\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ca1e61866324ffac2a7dc56\")\n}\n>db.addingNewPropertyDemo.insertOne({\"StudentName\":\"David\",\"StudentAge\":21,\"CountryName\":\"AUS\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ca1e62366324ffac2a7dc57\")\n}\n>db.addingNewPropertyDemo.insertOne({\"StudentName\":\"Bob\",\"StudentAge\":21,\"CountryName\":\"UK\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ca1e62d66324ffac2a7dc58\")\n}"
},
{
"code": null,
"e": 1821,
"s": 1724,
"text": "Following is the query to display all documents from a collection with the help of find() method"
},
{
"code": null,
"e": 1865,
"s": 1821,
"text": "> db.addingNewPropertyDemo.find().pretty();"
},
{
"code": null,
"e": 1904,
"s": 1865,
"text": "This will produce the following output"
},
{
"code": null,
"e": 2283,
"s": 1904,
"text": "{\n \"_id\" : ObjectId(\"5ca1e61866324ffac2a7dc56\"),\n \"StudentName\" : \"John\",\n \"StudentAge\" : 23,\n \"CountryName\" : \"US\"\n}\n{\n \"_id\" : ObjectId(\"5ca1e62366324ffac2a7dc57\"),\n \"StudentName\" : \"David\",\n \"StudentAge\" : 21,\n \"CountryName\" : \"AUS\"\n}\n{\n \"_id\" : ObjectId(\"5ca1e62d66324ffac2a7dc58\"),\n \"StudentName\" : \"Bob\",\n \"StudentAge\" : 21,\n \"CountryName\" : \"UK\"\n}"
},
{
"code": null,
"e": 2365,
"s": 2283,
"text": "Following is the query to add new property to each document in a large collection"
},
{
"code": null,
"e": 2544,
"s": 2365,
"text": "> db.addingNewPropertyDemo.find().forEach(function(data){ db.addingNewPropertyDemo.update({_id: data._id}, {$set: { StudentNameInUpperCase: data.StudentName.toUpperCase() }}) });"
},
{
"code": null,
"e": 2588,
"s": 2544,
"text": "Let us check a new property is added or not"
},
{
"code": null,
"e": 2632,
"s": 2588,
"text": "> db.addingNewPropertyDemo.find().pretty();"
},
{
"code": null,
"e": 2692,
"s": 2632,
"text": "Following is the output displaying the new property as well"
},
{
"code": null,
"e": 3185,
"s": 2692,
"text": "{\n \"_id\" : ObjectId(\"5ca1e61866324ffac2a7dc56\"),\n \"StudentName\" : \"John\",\n \"StudentAge\" : 23,\n \"CountryName\" : \"US\",\n \"StudentNameInUpperCase\" : \"JOHN\"\n}\n{\n \"_id\" : ObjectId(\"5ca1e62366324ffac2a7dc57\"),\n \"StudentName\" : \"David\",\n \"StudentAge\" : 21,\n \"CountryName\" : \"AUS\",\n \"StudentNameInUpperCase\" : \"DAVID\"\n}\n{\n \"_id\" : ObjectId(\"5ca1e62d66324ffac2a7dc58\"),\n \"StudentName\" : \"Bob\",\n \"StudentAge\" : 21,\n \"CountryName\" : \"UK\",\n \"StudentNameInUpperCase\" : \"BOB\"\n}"
},
{
"code": null,
"e": 3260,
"s": 3185,
"text": "Look at the above sample output, StudentNameInUpperCase property is added."
}
] |
PHP include Statement
|
PHP code in one file can be made available for use in another PHP script with the help of include statement. This feature enables modular program development by writing functions and classes once and calling wherever needed.
The include statement checks for the file in current folder by default and further in directories mentioned in include_path setting of php.ini. If file asked for is not available in current folder as well as include_path folders, PHP parser emits E_WARNING and execution of calling module continues.
The included file can access variables defined in calling module prior to inclusion. Such variables will have global scope.
In following example main php script includes test.php
Live Demo
<?php
echo "inside main script\n";
$var1=100;
echo "now calling test.php script\n";
include "test.php";
echo "returns from test.php";
?>
//test.php
<?php
$var2=200;
//accessing $var1 from main script
echo $var1+$var2 . "\n";
?>
This will produce following result when main script is run from command line −
inside main script<br />now calling test.php script<br /><br />300<br />returns from test.php
In following example,attempt to include nonexisting file results in warning
Live Demo
<?php
echo "inside main script\n";
$var1=100;
echo "now calling nosuchfile.php script\n";
include "nosuchfile.php";
echo "returns from nosuchfile.php";
?>
This will produce following result. Note that program doesn't teerminate on warning −
inside main script
now calling nosuchfile.php script
PHP Warning: include(nosuchfile.php): failed to open stream: No such file or directory in line 5
PHP Warning: include(): Failed opening 'nosuchfile.php' for inclusion (include_path='C:\xampp\php\PEAR') in line 5
returns from nosuchfile.php
In next example, test.php is included inside a function. Code inside included file will be treated as part of function. Hence variables in the include file will not accessible outside the function
Live Demo
//main script
<?php
function myfunction(){
$var1=100;
include "test.php";
echo $var1+$var2."\n";
}
myfunction();
echo "variable from included file outside function: $var2";
?>
//test.php included
<?php
echo "test.php called from inside function\n";
$var2=200;
return;
?>
This will produce following result when main script is run from command line−
100
test.php called from inside function
PHP Notice: Undefined variable: var2 in C:\xampp\php\testscript.php on line 9
Notice: Undefined variable: var2 in C:\xampp\php\testscript.php on line 9
variable from included file outside function
The include statement returns TRUE on success and FALSE on failure. If the include file explicitly returns an expression, it can be used by calling module for further processing.
//main script
<?php
$result=include "test.php"; // returns value
echo "retun value : $result\n";
$y=include "test1.php"; //with return only
echo "return value : $y\n";
$x=include "test2.php"; //no return statement
echo "return value : $x\n";
?>
//test.php
<?php
$var=100;
return $var;
?>
//test1.php
<?php
$var=100;
return;
?>
//test2.php
<?php
$var=100;
?>
This will produce following result −
retun value : 100
return value :
return value : 1
|
[
{
"code": null,
"e": 1287,
"s": 1062,
"text": "PHP code in one file can be made available for use in another PHP script with the help of include statement. This feature enables modular program development by writing functions and classes once and calling wherever needed."
},
{
"code": null,
"e": 1587,
"s": 1287,
"text": "The include statement checks for the file in current folder by default and further in directories mentioned in include_path setting of php.ini. If file asked for is not available in current folder as well as include_path folders, PHP parser emits E_WARNING and execution of calling module continues."
},
{
"code": null,
"e": 1711,
"s": 1587,
"text": "The included file can access variables defined in calling module prior to inclusion. Such variables will have global scope."
},
{
"code": null,
"e": 1766,
"s": 1711,
"text": "In following example main php script includes test.php"
},
{
"code": null,
"e": 1777,
"s": 1766,
"text": " Live Demo"
},
{
"code": null,
"e": 2005,
"s": 1777,
"text": "<?php\necho \"inside main script\\n\";\n$var1=100;\necho \"now calling test.php script\\n\";\ninclude \"test.php\";\necho \"returns from test.php\";\n?>\n//test.php\n<?php\n$var2=200;\n//accessing $var1 from main script\necho $var1+$var2 . \"\\n\";\n?>"
},
{
"code": null,
"e": 2084,
"s": 2005,
"text": "This will produce following result when main script is run from command line −"
},
{
"code": null,
"e": 2178,
"s": 2084,
"text": "inside main script<br />now calling test.php script<br /><br />300<br />returns from test.php"
},
{
"code": null,
"e": 2254,
"s": 2178,
"text": "In following example,attempt to include nonexisting file results in warning"
},
{
"code": null,
"e": 2265,
"s": 2254,
"text": " Live Demo"
},
{
"code": null,
"e": 2420,
"s": 2265,
"text": "<?php\necho \"inside main script\\n\";\n$var1=100;\necho \"now calling nosuchfile.php script\\n\";\ninclude \"nosuchfile.php\";\necho \"returns from nosuchfile.php\";\n?>"
},
{
"code": null,
"e": 2506,
"s": 2420,
"text": "This will produce following result. Note that program doesn't teerminate on warning −"
},
{
"code": null,
"e": 2799,
"s": 2506,
"text": "inside main script\nnow calling nosuchfile.php script\nPHP Warning: include(nosuchfile.php): failed to open stream: No such file or directory in line 5\nPHP Warning: include(): Failed opening 'nosuchfile.php' for inclusion (include_path='C:\\xampp\\php\\PEAR') in line 5\nreturns from nosuchfile.php"
},
{
"code": null,
"e": 2996,
"s": 2799,
"text": "In next example, test.php is included inside a function. Code inside included file will be treated as part of function. Hence variables in the include file will not accessible outside the function"
},
{
"code": null,
"e": 3007,
"s": 2996,
"text": " Live Demo"
},
{
"code": null,
"e": 3287,
"s": 3007,
"text": "//main script\n<?php\nfunction myfunction(){\n $var1=100;\n include \"test.php\";\n echo $var1+$var2.\"\\n\";\n}\nmyfunction();\necho \"variable from included file outside function: $var2\";\n?>\n//test.php included\n<?php\necho \"test.php called from inside function\\n\";\n$var2=200;\nreturn;\n?>"
},
{
"code": null,
"e": 3365,
"s": 3287,
"text": "This will produce following result when main script is run from command line−"
},
{
"code": null,
"e": 3603,
"s": 3365,
"text": "100\ntest.php called from inside function\nPHP Notice: Undefined variable: var2 in C:\\xampp\\php\\testscript.php on line 9\nNotice: Undefined variable: var2 in C:\\xampp\\php\\testscript.php on line 9\nvariable from included file outside function"
},
{
"code": null,
"e": 3782,
"s": 3603,
"text": "The include statement returns TRUE on success and FALSE on failure. If the include file explicitly returns an expression, it can be used by calling module for further processing."
},
{
"code": null,
"e": 4140,
"s": 3782,
"text": "//main script\n<?php\n$result=include \"test.php\"; // returns value\necho \"retun value : $result\\n\";\n$y=include \"test1.php\"; //with return only\necho \"return value : $y\\n\";\n$x=include \"test2.php\"; //no return statement\necho \"return value : $x\\n\";\n?>\n//test.php\n<?php\n$var=100;\nreturn $var;\n?>\n//test1.php\n<?php\n$var=100;\nreturn;\n?>\n//test2.php\n<?php\n$var=100;\n?>"
},
{
"code": null,
"e": 4177,
"s": 4140,
"text": "This will produce following result −"
},
{
"code": null,
"e": 4227,
"s": 4177,
"text": "retun value : 100\nreturn value :\nreturn value : 1"
}
] |
CSS - border-style
|
The border-style property allows you to select one of the following styles of border −
none − No border. (Equivalent of border-width:0;)
none − No border. (Equivalent of border-width:0;)
solid − Border is a single solid line.
solid − Border is a single solid line.
dotted − Border is a series of dots.
dotted − Border is a series of dots.
dashed − Border is a series of short lines.
dashed − Border is a series of short lines.
double − Border is two solid lines.
double − Border is two solid lines.
groove − Border looks as though it is carved into the page.
groove − Border looks as though it is carved into the page.
ridge − Border looks the opposite of groove.
ridge − Border looks the opposite of groove.
inset − Border makes the box look like it is embedded in the page.
inset − Border makes the box look like it is embedded in the page.
outset − Border makes the box look like it is coming out of the canvas.
outset − Border makes the box look like it is coming out of the canvas.
hidden − Same as none, except in terms of border-conflict resolution for table elements.
hidden − Same as none, except in terms of border-conflict resolution for table elements.
You can individually change the style of the bottom, left, top, and right borders of an element using following properties −
border-bottom-style − changes the style of bottom border.
border-bottom-style − changes the style of bottom border.
border-top-style − changes the style of top border.
border-top-style − changes the style of top border.
border-left-style − changes the style of left border.
border-left-style − changes the style of left border.
border-right-style − changes the style of right border.
border-right-style − changes the style of right border.
Any of the values defined above.
All the HTML elements.
object.style.borderStyle = "Any of the values defined above";
Following is the example to show all these border styles −
<html>
<head>
</head>
<body>
<p style = "border-width:4px; border-style:none;">
This is a border with none width.
</p>
<p style = "border-width:4px; border-style:solid;">
This is a solid border.
</p>
<p style = "border-width:4px; border-style:dashed;">
This is a dashed border.
</p>
<p style = "border-width:4px; border-style:double;">
This is a double border.
</p>
<p style = "border-width:4px; border-style:groove;">
This is a groove border.
</p>
<p style = "border-width:4px; border-style:ridge">
This is a ridge border.
</p>
<p style = "border-width:4px; border-style:inset;">
This is a inset border.
</p>
<p style = "border-width:4px; border-style:outset;">
This is a outset border.
</p>
<p style = "border-width:4px; border-style:hidden;">
This is a hidden border.
</p>
<p style = "border-width:4px;
border-top-style:solid;
border-bottom-style:dashed;
border-left-style:groove;
border-right-style:double;">
This is a a border with four different styles.
</p>
</body>
</html>
This will produce following result −
This is a border with none width.
This is a solid border.
This is a dahsed border.
This is a double border.
This is a groove border.
This is aridge border.
This is a inset border.
This is a outset border.
This is a hidden border.
This is a a border with four different styles.
33 Lectures
2.5 hours
Anadi Sharma
26 Lectures
2.5 hours
Frahaan Hussain
44 Lectures
4.5 hours
DigiFisk (Programming Is Fun)
21 Lectures
2.5 hours
DigiFisk (Programming Is Fun)
51 Lectures
7.5 hours
DigiFisk (Programming Is Fun)
52 Lectures
4 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2713,
"s": 2626,
"text": "The border-style property allows you to select one of the following styles of border −"
},
{
"code": null,
"e": 2763,
"s": 2713,
"text": "none − No border. (Equivalent of border-width:0;)"
},
{
"code": null,
"e": 2813,
"s": 2763,
"text": "none − No border. (Equivalent of border-width:0;)"
},
{
"code": null,
"e": 2852,
"s": 2813,
"text": "solid − Border is a single solid line."
},
{
"code": null,
"e": 2891,
"s": 2852,
"text": "solid − Border is a single solid line."
},
{
"code": null,
"e": 2928,
"s": 2891,
"text": "dotted − Border is a series of dots."
},
{
"code": null,
"e": 2965,
"s": 2928,
"text": "dotted − Border is a series of dots."
},
{
"code": null,
"e": 3009,
"s": 2965,
"text": "dashed − Border is a series of short lines."
},
{
"code": null,
"e": 3053,
"s": 3009,
"text": "dashed − Border is a series of short lines."
},
{
"code": null,
"e": 3089,
"s": 3053,
"text": "double − Border is two solid lines."
},
{
"code": null,
"e": 3125,
"s": 3089,
"text": "double − Border is two solid lines."
},
{
"code": null,
"e": 3185,
"s": 3125,
"text": "groove − Border looks as though it is carved into the page."
},
{
"code": null,
"e": 3245,
"s": 3185,
"text": "groove − Border looks as though it is carved into the page."
},
{
"code": null,
"e": 3290,
"s": 3245,
"text": "ridge − Border looks the opposite of groove."
},
{
"code": null,
"e": 3335,
"s": 3290,
"text": "ridge − Border looks the opposite of groove."
},
{
"code": null,
"e": 3402,
"s": 3335,
"text": "inset − Border makes the box look like it is embedded in the page."
},
{
"code": null,
"e": 3469,
"s": 3402,
"text": "inset − Border makes the box look like it is embedded in the page."
},
{
"code": null,
"e": 3541,
"s": 3469,
"text": "outset − Border makes the box look like it is coming out of the canvas."
},
{
"code": null,
"e": 3613,
"s": 3541,
"text": "outset − Border makes the box look like it is coming out of the canvas."
},
{
"code": null,
"e": 3702,
"s": 3613,
"text": "hidden − Same as none, except in terms of border-conflict resolution for table elements."
},
{
"code": null,
"e": 3791,
"s": 3702,
"text": "hidden − Same as none, except in terms of border-conflict resolution for table elements."
},
{
"code": null,
"e": 3916,
"s": 3791,
"text": "You can individually change the style of the bottom, left, top, and right borders of an element using following properties −"
},
{
"code": null,
"e": 3974,
"s": 3916,
"text": "border-bottom-style − changes the style of bottom border."
},
{
"code": null,
"e": 4032,
"s": 3974,
"text": "border-bottom-style − changes the style of bottom border."
},
{
"code": null,
"e": 4084,
"s": 4032,
"text": "border-top-style − changes the style of top border."
},
{
"code": null,
"e": 4136,
"s": 4084,
"text": "border-top-style − changes the style of top border."
},
{
"code": null,
"e": 4190,
"s": 4136,
"text": "border-left-style − changes the style of left border."
},
{
"code": null,
"e": 4244,
"s": 4190,
"text": "border-left-style − changes the style of left border."
},
{
"code": null,
"e": 4300,
"s": 4244,
"text": "border-right-style − changes the style of right border."
},
{
"code": null,
"e": 4356,
"s": 4300,
"text": "border-right-style − changes the style of right border."
},
{
"code": null,
"e": 4389,
"s": 4356,
"text": "Any of the values defined above."
},
{
"code": null,
"e": 4412,
"s": 4389,
"text": "All the HTML elements."
},
{
"code": null,
"e": 4475,
"s": 4412,
"text": "object.style.borderStyle = \"Any of the values defined above\";\n"
},
{
"code": null,
"e": 4534,
"s": 4475,
"text": "Following is the example to show all these border styles −"
},
{
"code": null,
"e": 5846,
"s": 4534,
"text": "<html>\n <head>\n </head>\n \n <body>\n <p style = \"border-width:4px; border-style:none;\">\n This is a border with none width.\n </p>\n \n <p style = \"border-width:4px; border-style:solid;\">\n This is a solid border.\n </p>\n \n <p style = \"border-width:4px; border-style:dashed;\">\n This is a dashed border.\n </p>\n \n <p style = \"border-width:4px; border-style:double;\">\n This is a double border.\n </p>\n \n <p style = \"border-width:4px; border-style:groove;\">\n This is a groove border.\n </p>\n \n <p style = \"border-width:4px; border-style:ridge\">\n This is a ridge border.\n </p>\n \n <p style = \"border-width:4px; border-style:inset;\">\n This is a inset border.\n </p>\n \n <p style = \"border-width:4px; border-style:outset;\">\n This is a outset border.\n </p>\n \n <p style = \"border-width:4px; border-style:hidden;\">\n This is a hidden border.\n </p>\n \n <p style = \"border-width:4px; \n border-top-style:solid;\n border-bottom-style:dashed;\n border-left-style:groove;\n border-right-style:double;\">\n This is a a border with four different styles.\n </p>\n \n </body>\n</html>"
},
{
"code": null,
"e": 5883,
"s": 5846,
"text": "This will produce following result −"
},
{
"code": null,
"e": 5922,
"s": 5883,
"text": "\n This is a border with none width.\n"
},
{
"code": null,
"e": 5951,
"s": 5922,
"text": "\n This is a solid border.\n"
},
{
"code": null,
"e": 5981,
"s": 5951,
"text": "\n This is a dahsed border.\n"
},
{
"code": null,
"e": 6011,
"s": 5981,
"text": "\n This is a double border.\n"
},
{
"code": null,
"e": 6041,
"s": 6011,
"text": "\n This is a groove border.\n"
},
{
"code": null,
"e": 6070,
"s": 6041,
"text": "\n This is aridge border.\n"
},
{
"code": null,
"e": 6099,
"s": 6070,
"text": "\n This is a inset border.\n"
},
{
"code": null,
"e": 6129,
"s": 6099,
"text": "\n This is a outset border.\n"
},
{
"code": null,
"e": 6159,
"s": 6129,
"text": "\n This is a hidden border.\n"
},
{
"code": null,
"e": 6211,
"s": 6159,
"text": "\n This is a a border with four different styles.\n"
},
{
"code": null,
"e": 6246,
"s": 6211,
"text": "\n 33 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6260,
"s": 6246,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6295,
"s": 6260,
"text": "\n 26 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6312,
"s": 6295,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6347,
"s": 6312,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6378,
"s": 6347,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 6413,
"s": 6378,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6444,
"s": 6413,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 6479,
"s": 6444,
"text": "\n 51 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 6510,
"s": 6479,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 6543,
"s": 6510,
"text": "\n 52 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6574,
"s": 6543,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 6581,
"s": 6574,
"text": " Print"
},
{
"code": null,
"e": 6592,
"s": 6581,
"text": " Add Notes"
}
] |
RxJS - Observables
|
An observable is a function that creates an observer and attaches it to the source where values are expected from, for example, clicks, mouse events from a dom element or an Http request, etc.
Observer is an object with callback functions, that will get called when there is interaction to the Observable, i.e., the source has interacted for an example button click, Http request, etc.
We are going to discuss following topics in this chapter −
Create Observable
Subscribe Observable
Execute Observable
The observable can be created using observable constructor and also using observable create method and by passing subscribe function as an argument to it as shown below −
import { Observable } from 'rxjs';
var observable = new Observable(
function subscribe(subscriber) {
subscriber.next("My First Observable")
}
);
We have created an observable and added a message “My First Observable” using subscriber.next method available inside Observable.
We can also create Observable using, Observable.create() method as shown below −
import { Observable } from 'rxjs';
var observer = Observable.create(
function subscribe(subscriber) {
subscriber.next("My First Observable")
}
);
You can subscribe to an observable as follows −
import { Observable } from 'rxjs';
var observer = new Observable(
function subscribe(subscriber) {
subscriber.next("My First Observable")
}
);
observer.subscribe(x => console.log(x));
When the observer is subscribed, it will start the execution of the Observable.
This is what we see in the browser console −
An observable gets executed when it is subscribed. An observer is an object with three methods that are notified,
next() − This method will send values like a number, string, object etc.
complete() − This method will not send any value and indicates the observable as completed.
error() − This method will send the error if any.
Let us create the observable with all three notifications and execute the same.
import { Observable } from 'rxjs';
var observer = new Observable(
function subscribe(subscriber) {
try {
subscriber.next("My First Observable");
subscriber.next("Testing Observable");
subscriber.complete();
} catch(e){
subscriber.error(e);
}
}
);
observer.subscribe(x => console.log(x), (e)=>console.log(e),
()=>console.log("Observable is complete"));
In the above code, we have added, next, complete and error method.
try{
subscriber.next("My First Observable");
subscriber.next("Testing Observable");
subscriber.complete();
} catch(e){
subscriber.error(e);
}
To execute next, complete and error, we have to call the subscribe method as shown below −
observer.subscribe(x => console.log(x), (e)=>console.log(e),
()=>console.log("Observable is complete"));
The error method will be invoked only if there is an error.
This is the output seen in the browser −
51 Lectures
4 hours
Daniel Stern
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2017,
"s": 1824,
"text": "An observable is a function that creates an observer and attaches it to the source where values are expected from, for example, clicks, mouse events from a dom element or an Http request, etc."
},
{
"code": null,
"e": 2210,
"s": 2017,
"text": "Observer is an object with callback functions, that will get called when there is interaction to the Observable, i.e., the source has interacted for an example button click, Http request, etc."
},
{
"code": null,
"e": 2269,
"s": 2210,
"text": "We are going to discuss following topics in this chapter −"
},
{
"code": null,
"e": 2287,
"s": 2269,
"text": "Create Observable"
},
{
"code": null,
"e": 2308,
"s": 2287,
"text": "Subscribe Observable"
},
{
"code": null,
"e": 2327,
"s": 2308,
"text": "Execute Observable"
},
{
"code": null,
"e": 2498,
"s": 2327,
"text": "The observable can be created using observable constructor and also using observable create method and by passing subscribe function as an argument to it as shown below −"
},
{
"code": null,
"e": 2656,
"s": 2498,
"text": "import { Observable } from 'rxjs';\n\nvar observable = new Observable(\n function subscribe(subscriber) {\n subscriber.next(\"My First Observable\")\n }\n);"
},
{
"code": null,
"e": 2786,
"s": 2656,
"text": "We have created an observable and added a message “My First Observable” using subscriber.next method available inside Observable."
},
{
"code": null,
"e": 2867,
"s": 2786,
"text": "We can also create Observable using, Observable.create() method as shown below −"
},
{
"code": null,
"e": 3025,
"s": 2867,
"text": "import { Observable } from 'rxjs';\nvar observer = Observable.create(\n function subscribe(subscriber) {\n subscriber.next(\"My First Observable\")\n }\n);"
},
{
"code": null,
"e": 3073,
"s": 3025,
"text": "You can subscribe to an observable as follows −"
},
{
"code": null,
"e": 3270,
"s": 3073,
"text": "import { Observable } from 'rxjs';\n\nvar observer = new Observable(\n function subscribe(subscriber) {\n subscriber.next(\"My First Observable\")\n }\n);\nobserver.subscribe(x => console.log(x));"
},
{
"code": null,
"e": 3350,
"s": 3270,
"text": "When the observer is subscribed, it will start the execution of the Observable."
},
{
"code": null,
"e": 3395,
"s": 3350,
"text": "This is what we see in the browser console −"
},
{
"code": null,
"e": 3509,
"s": 3395,
"text": "An observable gets executed when it is subscribed. An observer is an object with three methods that are notified,"
},
{
"code": null,
"e": 3582,
"s": 3509,
"text": "next() − This method will send values like a number, string, object etc."
},
{
"code": null,
"e": 3674,
"s": 3582,
"text": "complete() − This method will not send any value and indicates the observable as completed."
},
{
"code": null,
"e": 3724,
"s": 3674,
"text": "error() − This method will send the error if any."
},
{
"code": null,
"e": 3804,
"s": 3724,
"text": "Let us create the observable with all three notifications and execute the same."
},
{
"code": null,
"e": 4220,
"s": 3804,
"text": "import { Observable } from 'rxjs';\nvar observer = new Observable(\n function subscribe(subscriber) {\n try {\n subscriber.next(\"My First Observable\");\n subscriber.next(\"Testing Observable\");\n subscriber.complete();\n } catch(e){\n subscriber.error(e);\n }\n }\n);\nobserver.subscribe(x => console.log(x), (e)=>console.log(e), \n ()=>console.log(\"Observable is complete\"));"
},
{
"code": null,
"e": 4287,
"s": 4220,
"text": "In the above code, we have added, next, complete and error method."
},
{
"code": null,
"e": 4441,
"s": 4287,
"text": "try{\n subscriber.next(\"My First Observable\");\n subscriber.next(\"Testing Observable\");\n subscriber.complete();\n} catch(e){\n subscriber.error(e);\n}"
},
{
"code": null,
"e": 4532,
"s": 4441,
"text": "To execute next, complete and error, we have to call the subscribe method as shown below −"
},
{
"code": null,
"e": 4642,
"s": 4532,
"text": "observer.subscribe(x => console.log(x), (e)=>console.log(e), \n ()=>console.log(\"Observable is complete\"));\n"
},
{
"code": null,
"e": 4702,
"s": 4642,
"text": "The error method will be invoked only if there is an error."
},
{
"code": null,
"e": 4743,
"s": 4702,
"text": "This is the output seen in the browser −"
},
{
"code": null,
"e": 4776,
"s": 4743,
"text": "\n 51 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4790,
"s": 4776,
"text": " Daniel Stern"
},
{
"code": null,
"e": 4797,
"s": 4790,
"text": " Print"
},
{
"code": null,
"e": 4808,
"s": 4797,
"text": " Add Notes"
}
] |
How to count rows – count (*) and Java
|
The SQL Count() function returns the number of rows in a table. Using this you can get the number of rows in a table.
select count(*) from TABLE_NAME;
Let us create a table with name cricketers_data in MySQL database using CREATE statement as shown below −
CREATE TABLE cricketers_data(
First_Name VARCHAR(255),
Last_Name VARCHAR(255),
Date_Of_Birth date,
Place_Of_Birth VARCHAR(255),
Country VARCHAR(255),
);
Now, we will insert 5 records in cricketers_data table using INSERT statements −
insert into cricketers_data values('Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');
insert into cricketers_data values('Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');
insert into cricketers_data values('Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');
insert into cricketers_data values('Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');
insert into cricketers_data values('Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');
Following JDBC program establishes connection with MySQL and displays the number of rows in the table named cricketers_data.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Count_Example {
public static void main(String args[]) throws Exception {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Creating the Statement object
Statement stmt = con.createStatement();
//Query to get the number of rows in a table
String query = "select count(*) from Cricketers_Data";
//Executing the query
ResultSet rs = stmt.executeQuery(query);
//Retrieving the result
rs.next();
int count = rs.getInt(1);
System.out.println("Number of records in the cricketers_data table: "+count);
}
}
Connection established......
Number of records in the cricketers_data table: 5
|
[
{
"code": null,
"e": 1180,
"s": 1062,
"text": "The SQL Count() function returns the number of rows in a table. Using this you can get the number of rows in a table."
},
{
"code": null,
"e": 1213,
"s": 1180,
"text": "select count(*) from TABLE_NAME;"
},
{
"code": null,
"e": 1319,
"s": 1213,
"text": "Let us create a table with name cricketers_data in MySQL database using CREATE statement as shown below −"
},
{
"code": null,
"e": 1487,
"s": 1319,
"text": "CREATE TABLE cricketers_data(\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Date_Of_Birth date,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255),\n);"
},
{
"code": null,
"e": 1568,
"s": 1487,
"text": "Now, we will insert 5 records in cricketers_data table using INSERT statements −"
},
{
"code": null,
"e": 2055,
"s": 1568,
"text": "insert into cricketers_data values('Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');\ninsert into cricketers_data values('Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');\ninsert into cricketers_data values('Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');\ninsert into cricketers_data values('Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');\ninsert into cricketers_data values('Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');"
},
{
"code": null,
"e": 2180,
"s": 2055,
"text": "Following JDBC program establishes connection with MySQL and displays the number of rows in the table named cricketers_data."
},
{
"code": null,
"e": 3182,
"s": 2180,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\npublic class Count_Example {\n public static void main(String args[]) throws Exception {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating the Statement object\n Statement stmt = con.createStatement();\n //Query to get the number of rows in a table\n String query = \"select count(*) from Cricketers_Data\";\n //Executing the query\n ResultSet rs = stmt.executeQuery(query);\n //Retrieving the result\n rs.next();\n int count = rs.getInt(1);\n System.out.println(\"Number of records in the cricketers_data table: \"+count);\n }\n}"
},
{
"code": null,
"e": 3261,
"s": 3182,
"text": "Connection established......\nNumber of records in the cricketers_data table: 5"
}
] |
Simple Data Profiling with SQL. Before jumping in , understand the true... | by Robert de Graaf | Towards Data Science
|
Many organizations store their data in SQL compliant databases. It is far from unheard of for those databases to have grown organically for at least part of their lifecycle, so tables may or may not contain what their label would make you think they contain, and the quality may or may not match your expectations and be useful for your application.
In any case, the original purpose of creating the database was seldom to create a convenient well structured environment for a data scientist to use a basis for analysis. Therefore, although you are itching to migrate that data into R or Python to analyze and hopefully build a model with it, you need to figure out which data is what you need, and which of it meets basic standards of data quality to make it worth modeling with.
It’s true that major database packages have tools specifically for data profiling. However, it is also noticeable that these tools are complex to learn and sometimes seem to be a sledgehammer to crack a walnut. What’s really needed is some simple queries that can get the job done quickly.
In earlier articles in this series, we looked at quantiles in SQL, and exploratory stats on missing values in SQL. This time we will look at identifying unique values and exploring how frequently they occur.
Unique values by themselves are not difficult to identify — SQL has a built in keyword DISTINCT which limits the rows returned to those having unique values. Hence, it is trivial to discover the number of values for any row by creating a query SELECT DISTINCT col_name from Table and seeing how many rows are returned.
Simply knowing the number of unique values in a specific colum is a little useful, but possibly not as useful as knowing the number of times each value occurs in the event the variable is categorical (and multiple occurrences of most values might be a strong sign that this is a categorical value if you don’t know in advance).
This is also relatively simple, as you can put keywords such as DISTINCT into the brackets of an aggregate such as COUNT. Hence
select count(DISTINCT x) from tablegroup by x
More useful is to know the proportion of variables which are unique. This can be helpful if fields are poorly labelled, and you need to double check which columns could be unique ids — and also to avoid mistaking a field meant as a simple identifier with a field that contains information. Don’t forget that as COUNT returns an integer, you need to convert the result to get a fraction:
select cast(count(DISTINCT x) as decimal)/count(X) from table
For categorical variables, understanding the number of unique values is an important step towards understanding the overall usefulness of your overall data set.
Robert de Graaf’s book, Managing Your Data Science Projects, is out now through Apress.
Follow Robert on Twitter
|
[
{
"code": null,
"e": 522,
"s": 172,
"text": "Many organizations store their data in SQL compliant databases. It is far from unheard of for those databases to have grown organically for at least part of their lifecycle, so tables may or may not contain what their label would make you think they contain, and the quality may or may not match your expectations and be useful for your application."
},
{
"code": null,
"e": 953,
"s": 522,
"text": "In any case, the original purpose of creating the database was seldom to create a convenient well structured environment for a data scientist to use a basis for analysis. Therefore, although you are itching to migrate that data into R or Python to analyze and hopefully build a model with it, you need to figure out which data is what you need, and which of it meets basic standards of data quality to make it worth modeling with."
},
{
"code": null,
"e": 1243,
"s": 953,
"text": "It’s true that major database packages have tools specifically for data profiling. However, it is also noticeable that these tools are complex to learn and sometimes seem to be a sledgehammer to crack a walnut. What’s really needed is some simple queries that can get the job done quickly."
},
{
"code": null,
"e": 1451,
"s": 1243,
"text": "In earlier articles in this series, we looked at quantiles in SQL, and exploratory stats on missing values in SQL. This time we will look at identifying unique values and exploring how frequently they occur."
},
{
"code": null,
"e": 1770,
"s": 1451,
"text": "Unique values by themselves are not difficult to identify — SQL has a built in keyword DISTINCT which limits the rows returned to those having unique values. Hence, it is trivial to discover the number of values for any row by creating a query SELECT DISTINCT col_name from Table and seeing how many rows are returned."
},
{
"code": null,
"e": 2098,
"s": 1770,
"text": "Simply knowing the number of unique values in a specific colum is a little useful, but possibly not as useful as knowing the number of times each value occurs in the event the variable is categorical (and multiple occurrences of most values might be a strong sign that this is a categorical value if you don’t know in advance)."
},
{
"code": null,
"e": 2226,
"s": 2098,
"text": "This is also relatively simple, as you can put keywords such as DISTINCT into the brackets of an aggregate such as COUNT. Hence"
},
{
"code": null,
"e": 2272,
"s": 2226,
"text": "select count(DISTINCT x) from tablegroup by x"
},
{
"code": null,
"e": 2659,
"s": 2272,
"text": "More useful is to know the proportion of variables which are unique. This can be helpful if fields are poorly labelled, and you need to double check which columns could be unique ids — and also to avoid mistaking a field meant as a simple identifier with a field that contains information. Don’t forget that as COUNT returns an integer, you need to convert the result to get a fraction:"
},
{
"code": null,
"e": 2721,
"s": 2659,
"text": "select cast(count(DISTINCT x) as decimal)/count(X) from table"
},
{
"code": null,
"e": 2882,
"s": 2721,
"text": "For categorical variables, understanding the number of unique values is an important step towards understanding the overall usefulness of your overall data set."
},
{
"code": null,
"e": 2970,
"s": 2882,
"text": "Robert de Graaf’s book, Managing Your Data Science Projects, is out now through Apress."
}
] |
Social Media Sentiment Analysis using Machine Learning : Part — I | by Deepak Das | Towards Data Science
|
Social media has opened a whole new world for people around the globe. People are just a click away from getting huge chunk of information. With information comes people’s opinion and with this comes the positive and negative outlook of people regarding a topic. Sometimes this also results into bullying and passing on hate comments about someone or something.
So in this article we will use a data set containing a collection of tweets to detect the sentiment associated with a particular tweet and detect it as negative or positive accordingly using Machine Learning.
Note : Use of Jupyter Notebook or Google Colab is highly recommended.
Do give a read to this blog post if you want to know more about Jupyter Notebook and it’s functionalities.
towardsdatascience.com
So let’s start, shall we ?
Formally, given a training sample of tweets and labels, where label ‘1’ denotes the tweet is racist/sexist and label ‘0’ denotes the tweet is not racist/sexist,our objective is to predict the labels on the given test dataset.
id : The id associated with the tweets in the given dataset.
tweets : The tweets collected from various sources and having either positive or negative sentiments associated with it.
label : A tweet with label ‘0’ is of positive sentiment while a tweet with label ‘1’ is of negative sentiment.
Importing the necessary packages
Reading the train.csv Pandas file
In the first line we read the train.csv file using Pandas.
In the second line as a safe backup we keep a copy of our original train.csv file. We make a copy of train data so that even if we have to make any changes in this dataset we would not lose the original dataset.
Overview of the training dataset
As you can see we have 3 attributes present in our dataset and a total of 31962 labeled tweets , ‘1’ standing for tweets with negative sentiment and ‘0’ for tweets with positive sentiments.
Reading the test.csv Pandas file
In the first line we read the test.csv file using Pandas.
In the second line as a safe backup we keep a copy of our original test.csv file. We make a copy of test data so that even if we have to make any changes in this dataset we would not lose the original dataset.
Overview of the test dataset
As we can see we have 2 attributes present here that is ‘id’ and ‘tweets’. This is the dataset on which we are going to test our Machine Learning models so it is unlabeled.
Let’s begin with the pre-processing of our dataset.
Combine the train.csv and test.csv files.
Pandas dataframe.append() function is used to append rows of other dataframe to the end of the given dataframe, returning a new dataframe object.
Overview of the combined train and test dataset.
Type combine.head() in the cell and you get the following result.
Again type combine.tail() in the cell and you get the following result.
Columns not in the original dataframes are added as new columns and the new cells are populated with NaN value.
To know more about the append() function in Pandas refer to the below link.
pandas.pydata.org
Removing Twitter Handles(@User)
In our analysis we can clearly see that the Twitter handles do not contribute anything significant to solve our problem. So it’s better if we remove them in our dataset.
Given below is a user-defined function to remove unwanted text patterns from the tweets. It takes two arguments, one is the original string of text and the other is the pattern of text that we want to remove from the string. The function returns the same input string but without the given pattern. We will use this function to remove the pattern ‘@user’ from all the tweets in our data.
Here NumPy Vectorization ‘np.vectorize()’ is used because it is much more faster than the conventional for loops when working on datasets of medium to large sizes.
For more detailed discussion you can refer to the below medium blog post.
towardsdatascience.com
Removing Punctuation, Numbers, and Special Characters
Punctuation, numbers and special characters do not help much. It is better to remove them from the text just as we removed the twitter handles. Here we will replace everything except characters and hashtags with spaces.
Removing Short Words
We have to be a little careful here in selecting the length of the words which we want to remove. So, I have decided to remove all the words having length 3 or less. These words are also known as Stop Words.
For example, terms like “hmm”, “and”, “oh” are of very little use. It is better to get rid of them.
Tokenization
Now we will tokenize all the cleaned tweets in our dataset. Tokens are individual terms or words, and tokenization is the process of splitting a string of text into tokens.
Here we tokenize our sentences because we will apply Stemming from the “NLTK” package in the next step.
Stemming
Stemming is a rule-based process of stripping the suffixes (“ing”, “ly”, “es”, “s” etc) from a word.
For example — “play”, “player”, “played”, “plays” and “playing” are the different variations of the word — “play”
Now let’s stitch these tokens back together
So finally these are the basic steps to follow when we have to Pre-Process a dataset containing textual data.
Note : To get an in depth knowledge about the concepts used in the different stages of Pre-Processing like Stemming,Tokenization,Regex,NLTK refer to the following blog post.
towardsdatascience.com
OK, so now we are done with our Data Pre-Processing stages.
Let’s move on to our next step that is Data Visualisation.
So Data Visualisation is one of the most important steps in Machine Learning projects because it gives us an approximate idea about the dataset and what it is all about before proceeding to apply different machine learning models.
So, let’s dive in.
One of the popular visualisation techniques is WordCloud.
A WordCloud is a visualisation wherein the most frequent words appear in large size and the less frequent words appear in smaller sizes.
So, in Python we have a package for generating WordCloud.
Let’s dive into the code to see how can we generate a WordCloud.
Importing packages necessary for generating a WordCloud
Store all the words from the dataset which are non-racist/sexist.
The code to generate the required WordCloud.
Each line has been properly commented for a better understanding.
We can see most of the words are positive or neutral. With happy, smile, and love being the most frequent ones. Hence, most of the frequent words are compatible with tweets in positive sentiment.
Store all the words from the dataset which are non-racist/sexist.
The code to generate the required WordCloud.
Each line has been properly commented for a better understanding.
We can clearly see, most of the words have negative connotations. So, it seems we have a pretty good text data to work on.
Hash-tagging on Twitter can have a major impact when it comes to your follower count by using general and non-specific hashtags. If you hashtag general words, like #creative, or events, like #TIFF, that are going on, it is more likely that your tweet will reach beyond your follower list.
So we will look how we can extract the hashtags and see which hashtags fall into which category.
Function to extract hashtags from tweets
A nested list of all the hashtags from the positive reviews from the dataset.
OUTPUT :
Here we unnest the list
OUTPUT :
A nested list of all the hashtags from the negative reviews from the dataset
OUTPUT :
Here we unnest the list
OUTPUT :
Counting the frequency of the words having Positive Sentiment
OUTPUT:
FreqDist({'love': 1654, 'posit': 917, 'smile': 676, 'healthi': 573, 'thank': 534, 'fun': 463, 'life': 425, 'affirm': 423, 'summer': 390, 'model': 375, ...})
Creating a dataframe for the most frequently used words in hashtags
Plotting the barplot for the 20 most frequent words used for hashtags
Counting the frequency of the words having Negative Sentiment
OUTPUT :
FreqDist({'trump': 136, 'polit': 95, 'allahsoil': 92, 'liber': 81, 'libtard': 77, 'sjw': 75, 'retweet': 63, 'black': 46, 'miami': 46, 'hate': 37, ...})
Creating a dataframe for the most frequently used words in hashtags
Plotting the barplot for the 20 most frequent words used for hashtags
And that’s a wrap for Part — I.
So, Let’s see what we have learnt so far.
What is it exactly that we are going to do in this Project.
Here we get an overview about the dataset we are going to use and how the train and test are divided with one being labeled and another being unlabeled respectively with the number of tweets present in each of the dataset.
Removing Twitter Handles( @user )
Removing punctuation,numbers,special characters
Removing short words i.e. words with length
Tokenization
Stemming
WordCloud
Bar plots
So that’s all for now, folks. Will be coming back soon with part — II of this post where we will learn about two of the most popular word embedding techniques Bag-of-Words and TF-IDF.
We will also get to know how we can apply different Machine Learning models to this problem statement.
Stay Tuned.
Edit : If you want to read Part — II of this article head on to the following post.
towardsdatascience.com
You can reach me at
LinkedIn : https://www.linkedin.com/in/deepak-das-profile/
GitHub : https://github.com/dD2405
|
[
{
"code": null,
"e": 533,
"s": 171,
"text": "Social media has opened a whole new world for people around the globe. People are just a click away from getting huge chunk of information. With information comes people’s opinion and with this comes the positive and negative outlook of people regarding a topic. Sometimes this also results into bullying and passing on hate comments about someone or something."
},
{
"code": null,
"e": 742,
"s": 533,
"text": "So in this article we will use a data set containing a collection of tweets to detect the sentiment associated with a particular tweet and detect it as negative or positive accordingly using Machine Learning."
},
{
"code": null,
"e": 812,
"s": 742,
"text": "Note : Use of Jupyter Notebook or Google Colab is highly recommended."
},
{
"code": null,
"e": 919,
"s": 812,
"text": "Do give a read to this blog post if you want to know more about Jupyter Notebook and it’s functionalities."
},
{
"code": null,
"e": 942,
"s": 919,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 969,
"s": 942,
"text": "So let’s start, shall we ?"
},
{
"code": null,
"e": 1195,
"s": 969,
"text": "Formally, given a training sample of tweets and labels, where label ‘1’ denotes the tweet is racist/sexist and label ‘0’ denotes the tweet is not racist/sexist,our objective is to predict the labels on the given test dataset."
},
{
"code": null,
"e": 1256,
"s": 1195,
"text": "id : The id associated with the tweets in the given dataset."
},
{
"code": null,
"e": 1377,
"s": 1256,
"text": "tweets : The tweets collected from various sources and having either positive or negative sentiments associated with it."
},
{
"code": null,
"e": 1488,
"s": 1377,
"text": "label : A tweet with label ‘0’ is of positive sentiment while a tweet with label ‘1’ is of negative sentiment."
},
{
"code": null,
"e": 1521,
"s": 1488,
"text": "Importing the necessary packages"
},
{
"code": null,
"e": 1555,
"s": 1521,
"text": "Reading the train.csv Pandas file"
},
{
"code": null,
"e": 1614,
"s": 1555,
"text": "In the first line we read the train.csv file using Pandas."
},
{
"code": null,
"e": 1826,
"s": 1614,
"text": "In the second line as a safe backup we keep a copy of our original train.csv file. We make a copy of train data so that even if we have to make any changes in this dataset we would not lose the original dataset."
},
{
"code": null,
"e": 1859,
"s": 1826,
"text": "Overview of the training dataset"
},
{
"code": null,
"e": 2049,
"s": 1859,
"text": "As you can see we have 3 attributes present in our dataset and a total of 31962 labeled tweets , ‘1’ standing for tweets with negative sentiment and ‘0’ for tweets with positive sentiments."
},
{
"code": null,
"e": 2082,
"s": 2049,
"text": "Reading the test.csv Pandas file"
},
{
"code": null,
"e": 2140,
"s": 2082,
"text": "In the first line we read the test.csv file using Pandas."
},
{
"code": null,
"e": 2350,
"s": 2140,
"text": "In the second line as a safe backup we keep a copy of our original test.csv file. We make a copy of test data so that even if we have to make any changes in this dataset we would not lose the original dataset."
},
{
"code": null,
"e": 2379,
"s": 2350,
"text": "Overview of the test dataset"
},
{
"code": null,
"e": 2552,
"s": 2379,
"text": "As we can see we have 2 attributes present here that is ‘id’ and ‘tweets’. This is the dataset on which we are going to test our Machine Learning models so it is unlabeled."
},
{
"code": null,
"e": 2604,
"s": 2552,
"text": "Let’s begin with the pre-processing of our dataset."
},
{
"code": null,
"e": 2646,
"s": 2604,
"text": "Combine the train.csv and test.csv files."
},
{
"code": null,
"e": 2792,
"s": 2646,
"text": "Pandas dataframe.append() function is used to append rows of other dataframe to the end of the given dataframe, returning a new dataframe object."
},
{
"code": null,
"e": 2841,
"s": 2792,
"text": "Overview of the combined train and test dataset."
},
{
"code": null,
"e": 2907,
"s": 2841,
"text": "Type combine.head() in the cell and you get the following result."
},
{
"code": null,
"e": 2979,
"s": 2907,
"text": "Again type combine.tail() in the cell and you get the following result."
},
{
"code": null,
"e": 3091,
"s": 2979,
"text": "Columns not in the original dataframes are added as new columns and the new cells are populated with NaN value."
},
{
"code": null,
"e": 3167,
"s": 3091,
"text": "To know more about the append() function in Pandas refer to the below link."
},
{
"code": null,
"e": 3185,
"s": 3167,
"text": "pandas.pydata.org"
},
{
"code": null,
"e": 3217,
"s": 3185,
"text": "Removing Twitter Handles(@User)"
},
{
"code": null,
"e": 3387,
"s": 3217,
"text": "In our analysis we can clearly see that the Twitter handles do not contribute anything significant to solve our problem. So it’s better if we remove them in our dataset."
},
{
"code": null,
"e": 3775,
"s": 3387,
"text": "Given below is a user-defined function to remove unwanted text patterns from the tweets. It takes two arguments, one is the original string of text and the other is the pattern of text that we want to remove from the string. The function returns the same input string but without the given pattern. We will use this function to remove the pattern ‘@user’ from all the tweets in our data."
},
{
"code": null,
"e": 3939,
"s": 3775,
"text": "Here NumPy Vectorization ‘np.vectorize()’ is used because it is much more faster than the conventional for loops when working on datasets of medium to large sizes."
},
{
"code": null,
"e": 4013,
"s": 3939,
"text": "For more detailed discussion you can refer to the below medium blog post."
},
{
"code": null,
"e": 4036,
"s": 4013,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4090,
"s": 4036,
"text": "Removing Punctuation, Numbers, and Special Characters"
},
{
"code": null,
"e": 4310,
"s": 4090,
"text": "Punctuation, numbers and special characters do not help much. It is better to remove them from the text just as we removed the twitter handles. Here we will replace everything except characters and hashtags with spaces."
},
{
"code": null,
"e": 4331,
"s": 4310,
"text": "Removing Short Words"
},
{
"code": null,
"e": 4539,
"s": 4331,
"text": "We have to be a little careful here in selecting the length of the words which we want to remove. So, I have decided to remove all the words having length 3 or less. These words are also known as Stop Words."
},
{
"code": null,
"e": 4639,
"s": 4539,
"text": "For example, terms like “hmm”, “and”, “oh” are of very little use. It is better to get rid of them."
},
{
"code": null,
"e": 4652,
"s": 4639,
"text": "Tokenization"
},
{
"code": null,
"e": 4825,
"s": 4652,
"text": "Now we will tokenize all the cleaned tweets in our dataset. Tokens are individual terms or words, and tokenization is the process of splitting a string of text into tokens."
},
{
"code": null,
"e": 4929,
"s": 4825,
"text": "Here we tokenize our sentences because we will apply Stemming from the “NLTK” package in the next step."
},
{
"code": null,
"e": 4938,
"s": 4929,
"text": "Stemming"
},
{
"code": null,
"e": 5039,
"s": 4938,
"text": "Stemming is a rule-based process of stripping the suffixes (“ing”, “ly”, “es”, “s” etc) from a word."
},
{
"code": null,
"e": 5153,
"s": 5039,
"text": "For example — “play”, “player”, “played”, “plays” and “playing” are the different variations of the word — “play”"
},
{
"code": null,
"e": 5197,
"s": 5153,
"text": "Now let’s stitch these tokens back together"
},
{
"code": null,
"e": 5307,
"s": 5197,
"text": "So finally these are the basic steps to follow when we have to Pre-Process a dataset containing textual data."
},
{
"code": null,
"e": 5481,
"s": 5307,
"text": "Note : To get an in depth knowledge about the concepts used in the different stages of Pre-Processing like Stemming,Tokenization,Regex,NLTK refer to the following blog post."
},
{
"code": null,
"e": 5504,
"s": 5481,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5564,
"s": 5504,
"text": "OK, so now we are done with our Data Pre-Processing stages."
},
{
"code": null,
"e": 5623,
"s": 5564,
"text": "Let’s move on to our next step that is Data Visualisation."
},
{
"code": null,
"e": 5854,
"s": 5623,
"text": "So Data Visualisation is one of the most important steps in Machine Learning projects because it gives us an approximate idea about the dataset and what it is all about before proceeding to apply different machine learning models."
},
{
"code": null,
"e": 5873,
"s": 5854,
"text": "So, let’s dive in."
},
{
"code": null,
"e": 5931,
"s": 5873,
"text": "One of the popular visualisation techniques is WordCloud."
},
{
"code": null,
"e": 6068,
"s": 5931,
"text": "A WordCloud is a visualisation wherein the most frequent words appear in large size and the less frequent words appear in smaller sizes."
},
{
"code": null,
"e": 6126,
"s": 6068,
"text": "So, in Python we have a package for generating WordCloud."
},
{
"code": null,
"e": 6191,
"s": 6126,
"text": "Let’s dive into the code to see how can we generate a WordCloud."
},
{
"code": null,
"e": 6247,
"s": 6191,
"text": "Importing packages necessary for generating a WordCloud"
},
{
"code": null,
"e": 6313,
"s": 6247,
"text": "Store all the words from the dataset which are non-racist/sexist."
},
{
"code": null,
"e": 6358,
"s": 6313,
"text": "The code to generate the required WordCloud."
},
{
"code": null,
"e": 6424,
"s": 6358,
"text": "Each line has been properly commented for a better understanding."
},
{
"code": null,
"e": 6620,
"s": 6424,
"text": "We can see most of the words are positive or neutral. With happy, smile, and love being the most frequent ones. Hence, most of the frequent words are compatible with tweets in positive sentiment."
},
{
"code": null,
"e": 6686,
"s": 6620,
"text": "Store all the words from the dataset which are non-racist/sexist."
},
{
"code": null,
"e": 6731,
"s": 6686,
"text": "The code to generate the required WordCloud."
},
{
"code": null,
"e": 6797,
"s": 6731,
"text": "Each line has been properly commented for a better understanding."
},
{
"code": null,
"e": 6920,
"s": 6797,
"text": "We can clearly see, most of the words have negative connotations. So, it seems we have a pretty good text data to work on."
},
{
"code": null,
"e": 7209,
"s": 6920,
"text": "Hash-tagging on Twitter can have a major impact when it comes to your follower count by using general and non-specific hashtags. If you hashtag general words, like #creative, or events, like #TIFF, that are going on, it is more likely that your tweet will reach beyond your follower list."
},
{
"code": null,
"e": 7306,
"s": 7209,
"text": "So we will look how we can extract the hashtags and see which hashtags fall into which category."
},
{
"code": null,
"e": 7347,
"s": 7306,
"text": "Function to extract hashtags from tweets"
},
{
"code": null,
"e": 7425,
"s": 7347,
"text": "A nested list of all the hashtags from the positive reviews from the dataset."
},
{
"code": null,
"e": 7434,
"s": 7425,
"text": "OUTPUT :"
},
{
"code": null,
"e": 7458,
"s": 7434,
"text": "Here we unnest the list"
},
{
"code": null,
"e": 7467,
"s": 7458,
"text": "OUTPUT :"
},
{
"code": null,
"e": 7544,
"s": 7467,
"text": "A nested list of all the hashtags from the negative reviews from the dataset"
},
{
"code": null,
"e": 7553,
"s": 7544,
"text": "OUTPUT :"
},
{
"code": null,
"e": 7577,
"s": 7553,
"text": "Here we unnest the list"
},
{
"code": null,
"e": 7586,
"s": 7577,
"text": "OUTPUT :"
},
{
"code": null,
"e": 7648,
"s": 7586,
"text": "Counting the frequency of the words having Positive Sentiment"
},
{
"code": null,
"e": 7656,
"s": 7648,
"text": "OUTPUT:"
},
{
"code": null,
"e": 7813,
"s": 7656,
"text": "FreqDist({'love': 1654, 'posit': 917, 'smile': 676, 'healthi': 573, 'thank': 534, 'fun': 463, 'life': 425, 'affirm': 423, 'summer': 390, 'model': 375, ...})"
},
{
"code": null,
"e": 7881,
"s": 7813,
"text": "Creating a dataframe for the most frequently used words in hashtags"
},
{
"code": null,
"e": 7951,
"s": 7881,
"text": "Plotting the barplot for the 20 most frequent words used for hashtags"
},
{
"code": null,
"e": 8013,
"s": 7951,
"text": "Counting the frequency of the words having Negative Sentiment"
},
{
"code": null,
"e": 8022,
"s": 8013,
"text": "OUTPUT :"
},
{
"code": null,
"e": 8174,
"s": 8022,
"text": "FreqDist({'trump': 136, 'polit': 95, 'allahsoil': 92, 'liber': 81, 'libtard': 77, 'sjw': 75, 'retweet': 63, 'black': 46, 'miami': 46, 'hate': 37, ...})"
},
{
"code": null,
"e": 8242,
"s": 8174,
"text": "Creating a dataframe for the most frequently used words in hashtags"
},
{
"code": null,
"e": 8312,
"s": 8242,
"text": "Plotting the barplot for the 20 most frequent words used for hashtags"
},
{
"code": null,
"e": 8344,
"s": 8312,
"text": "And that’s a wrap for Part — I."
},
{
"code": null,
"e": 8386,
"s": 8344,
"text": "So, Let’s see what we have learnt so far."
},
{
"code": null,
"e": 8446,
"s": 8386,
"text": "What is it exactly that we are going to do in this Project."
},
{
"code": null,
"e": 8669,
"s": 8446,
"text": "Here we get an overview about the dataset we are going to use and how the train and test are divided with one being labeled and another being unlabeled respectively with the number of tweets present in each of the dataset."
},
{
"code": null,
"e": 8703,
"s": 8669,
"text": "Removing Twitter Handles( @user )"
},
{
"code": null,
"e": 8751,
"s": 8703,
"text": "Removing punctuation,numbers,special characters"
},
{
"code": null,
"e": 8795,
"s": 8751,
"text": "Removing short words i.e. words with length"
},
{
"code": null,
"e": 8808,
"s": 8795,
"text": "Tokenization"
},
{
"code": null,
"e": 8817,
"s": 8808,
"text": "Stemming"
},
{
"code": null,
"e": 8827,
"s": 8817,
"text": "WordCloud"
},
{
"code": null,
"e": 8837,
"s": 8827,
"text": "Bar plots"
},
{
"code": null,
"e": 9021,
"s": 8837,
"text": "So that’s all for now, folks. Will be coming back soon with part — II of this post where we will learn about two of the most popular word embedding techniques Bag-of-Words and TF-IDF."
},
{
"code": null,
"e": 9124,
"s": 9021,
"text": "We will also get to know how we can apply different Machine Learning models to this problem statement."
},
{
"code": null,
"e": 9136,
"s": 9124,
"text": "Stay Tuned."
},
{
"code": null,
"e": 9220,
"s": 9136,
"text": "Edit : If you want to read Part — II of this article head on to the following post."
},
{
"code": null,
"e": 9243,
"s": 9220,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9263,
"s": 9243,
"text": "You can reach me at"
},
{
"code": null,
"e": 9322,
"s": 9263,
"text": "LinkedIn : https://www.linkedin.com/in/deepak-das-profile/"
}
] |
Tryit Editor v3.7
|
CSS How To
Tryit: Cascading order
|
[
{
"code": null,
"e": 20,
"s": 9,
"text": "CSS How To"
}
] |
How to create an image to zoom with CSS and JavaScript?
|
Following is the code to create an image zoom:
Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
* {box-sizing: border-box;}
.img{
display: inline-block;
}
.img-zoom-container {
position: relative;
}
.img-zoom-zoomLens {
position: absolute;
border: 1px solid #d4d4d4;
width: 50px;
height: 50px;
}
.myresult{
display: inline-block;
}
.img-zoom-result {
border: 1px solid #d4d4d4;
}
</style>
</head>
<body>
<h1>Image Zoom Example</h1>
<div class="img-zoom-container">
<img class="myimage" src="https://i.picsum.photos/id/1015/536/354.jpg?hmac=x7KEhPoOftwPXIgnQoTQzNtVUqaPYwndK8n1x_9rWuM" style="width: 400px; height: 400px;">
<div class="myresult" class="img-zoom-result" style="width: 400px;height: 400px;"></div>
</div>
<h1>Hover over the image on the left to see it zoomed on right</h1>
<script>
let imageEle = document.querySelector('.myimage');
let resultEle = document.querySelector('.myresult');
enlargeImage(imageEle, resultEle);
function enlargeImage(imgEle, resultEle) {
var zoomLens, xPos, yPos;
zoomLens = document.createElement("DIV");
zoomLens.setAttribute("class", "img-zoom-zoomLens");
imgEle.parentElement.insertBefore(zoomLens, imgEle);
xPos = resultEle.offsetWidth / zoomLens.offsetWidth;
yPos = resultEle.offsetHeight / zoomLens.offsetHeight;
resultEle.style.backgroundImage = `url(${imgEle.src})`;
resultEle.style.backgroundSize = (imgEle.width * xPos) + "px " + (imgEle.height * yPos) + "px";
zoomLens.addEventListener("mousemove", lensMoveCalculate);
imgEle.addEventListener("mousemove", lensMoveCalculate);
zoomLens.addEventListener("touchmove", lensMoveCalculate);
imgEle.addEventListener("touchmove", lensMoveCalculate);
function lensMoveCalculate(e) {
var pos, x, y;
pos = currentCursonPos(e);
x = pos.x - (zoomLens.offsetWidth / 2);
y = pos.y - (zoomLens.offsetHeight / 2);
if (x > imgEle.width - zoomLens.offsetWidth) {x = imgEle.width - zoomLens.offsetWidth;}
if (x < 0) {x = 0;}
if (y > imgEle.height - zoomLens.offsetHeight) {y = imgEle.height - zoomLens.offsetHeight;}
if (y < 0) {y = 0;}
zoomLens.style.left = x + "px";
zoomLens.style.top = y + "px";
resultEle.style.backgroundPosition = "-" + (x * xPos) + "px -" + (y * yPos) + "px";
}
function currentCursonPos(e) {
var a, x = 0, y = 0;
e = e || window.event;
a = imgEle.getBoundingClientRect();
x = e.pageX - a.left;
y = e.pageY - a.top;
x = x - window.pageXOffset;
y = y - window.pageYOffset;
return {x : x, y : y};
}
}
</script>
</body>
</html>
The above code will produce the following output:
|
[
{
"code": null,
"e": 1109,
"s": 1062,
"text": "Following is the code to create an image zoom:"
},
{
"code": null,
"e": 1120,
"s": 1109,
"text": " Live Demo"
},
{
"code": null,
"e": 3927,
"s": 1120,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<style>\n * {box-sizing: border-box;}\n .img{\n display: inline-block;\n }\n .img-zoom-container {\n position: relative;\n }\n .img-zoom-zoomLens {\n position: absolute;\n border: 1px solid #d4d4d4;\n width: 50px;\n height: 50px;\n }\n .myresult{\n display: inline-block;\n }\n .img-zoom-result {\n border: 1px solid #d4d4d4;\n }\n</style>\n</head>\n<body>\n<h1>Image Zoom Example</h1>\n<div class=\"img-zoom-container\">\n<img class=\"myimage\" src=\"https://i.picsum.photos/id/1015/536/354.jpg?hmac=x7KEhPoOftwPXIgnQoTQzNtVUqaPYwndK8n1x_9rWuM\" style=\"width: 400px; height: 400px;\">\n<div class=\"myresult\" class=\"img-zoom-result\" style=\"width: 400px;height: 400px;\"></div>\n</div>\n<h1>Hover over the image on the left to see it zoomed on right</h1>\n<script>\n let imageEle = document.querySelector('.myimage');\n let resultEle = document.querySelector('.myresult');\n enlargeImage(imageEle, resultEle);\n function enlargeImage(imgEle, resultEle) {\n var zoomLens, xPos, yPos;\n zoomLens = document.createElement(\"DIV\");\n zoomLens.setAttribute(\"class\", \"img-zoom-zoomLens\");\n imgEle.parentElement.insertBefore(zoomLens, imgEle);\n xPos = resultEle.offsetWidth / zoomLens.offsetWidth;\n yPos = resultEle.offsetHeight / zoomLens.offsetHeight;\n resultEle.style.backgroundImage = `url(${imgEle.src})`;\n resultEle.style.backgroundSize = (imgEle.width * xPos) + \"px \" + (imgEle.height * yPos) + \"px\";\n zoomLens.addEventListener(\"mousemove\", lensMoveCalculate);\n imgEle.addEventListener(\"mousemove\", lensMoveCalculate);\n zoomLens.addEventListener(\"touchmove\", lensMoveCalculate);\n imgEle.addEventListener(\"touchmove\", lensMoveCalculate);\n function lensMoveCalculate(e) {\n var pos, x, y;\n pos = currentCursonPos(e);\n x = pos.x - (zoomLens.offsetWidth / 2);\n y = pos.y - (zoomLens.offsetHeight / 2);\n if (x > imgEle.width - zoomLens.offsetWidth) {x = imgEle.width - zoomLens.offsetWidth;}\n if (x < 0) {x = 0;}\n if (y > imgEle.height - zoomLens.offsetHeight) {y = imgEle.height - zoomLens.offsetHeight;}\n if (y < 0) {y = 0;}\n zoomLens.style.left = x + \"px\";\n zoomLens.style.top = y + \"px\";\n resultEle.style.backgroundPosition = \"-\" + (x * xPos) + \"px -\" + (y * yPos) + \"px\";\n }\n function currentCursonPos(e) {\n var a, x = 0, y = 0;\n e = e || window.event;\n a = imgEle.getBoundingClientRect();\n x = e.pageX - a.left;\n y = e.pageY - a.top;\n x = x - window.pageXOffset;\n y = y - window.pageYOffset;\n return {x : x, y : y};\n }\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 3977,
"s": 3927,
"text": "The above code will produce the following output:"
}
] |
Best First Search (Informed Search)
|
Best first search is a traversal technique that decides which node is to be visited next by checking which node is the most promising one and then check it. For this it uses an evaluation function to decide the traversal.
This best first search technique of tree traversal comes under the category of heuristic search or informed search technique.
The cost of nodes is stored in a priority queue. This makes implementation of best-first search is same as that of breadth First search. We will use the priorityqueue just like we use a queue for BFS.
Step 1 : Create a priorityQueue pqueue.
Step 2 : insert ‘start’ in pqueue : pqueue.insert(start)
Step 3 : delete all elements of pqueue one by one.
Step 3.1 : if, the element is goal . Exit.
Step 3.2 : else, traverse neighbours and mark the node examined.
Step 4 : End.
This algorithm will traverse the shortest path first in the queue. In worst case scenario the algorithm takes O(n*logn) time.
|
[
{
"code": null,
"e": 1284,
"s": 1062,
"text": "Best first search is a traversal technique that decides which node is to be visited next by checking which node is the most promising one and then check it. For this it uses an evaluation function to decide the traversal."
},
{
"code": null,
"e": 1410,
"s": 1284,
"text": "This best first search technique of tree traversal comes under the category of heuristic search or informed search technique."
},
{
"code": null,
"e": 1611,
"s": 1410,
"text": "The cost of nodes is stored in a priority queue. This makes implementation of best-first search is same as that of breadth First search. We will use the priorityqueue just like we use a queue for BFS."
},
{
"code": null,
"e": 1887,
"s": 1611,
"text": "Step 1 : Create a priorityQueue pqueue.\nStep 2 : insert ‘start’ in pqueue : pqueue.insert(start)\nStep 3 : delete all elements of pqueue one by one.\n Step 3.1 : if, the element is goal . Exit.\n Step 3.2 : else, traverse neighbours and mark the node examined.\nStep 4 : End."
},
{
"code": null,
"e": 2013,
"s": 1887,
"text": "This algorithm will traverse the shortest path first in the queue. In worst case scenario the algorithm takes O(n*logn) time."
}
] |
From Python to Go. Learn Go Programming by Translating... | by Kasper Müller | Towards Data Science
|
My hope is that this article can be used both as a dictionary for Pythonistas who want to learn Go but also as an introduction to Go for those out there who know Python and just want to get started quickly with Golang.
Before we begin, I want to briefly explain why it might be a great choice to learn Go when you already know Python.
First of all, I am not saying that Go is a better language than Python. Python is a great language and often a better choice than Go. It depends of course on the problem you are trying to solve or the application that you want to build, but Go does have a lot of things going for it that Python doesn’t.
Go is fast — really fast! With almost C-like speeds, Go blows Python out of the water on this parameter. That is partly because Go is a statically typed language with an optimized, extremely fast compiler which makes Go both fast to develop in and fast at execution.Developer-friendly. Despite the swiftness of Go, it is surprisingly fast to write in. I think there are a couple of reasons for this. First of all, in Go you only have what you really need, so you are rarely in doubt about what to use where. The syntax is clear and readable. Even syntactically it is cleansed from ugly parentheses and other unnecessary syntaxes. Secondly, the Go interpreter is pretty smart and Go’s type system is a nice balance between the lack of unnecessary declarations and a save system guarding for unused imports and unstated datatypes in function arguments for example.Built-in concurrency and parallelism. Go is a young and modern language and if you have ever tried running bigger projects with some parallel computing in Python, you know that it is a pain. But in Go, it is not. You have green threads called goroutines and you have channels which is a data structure that makes parallel workers communicate rather safely with each other. You also have a way of locking containers like arrays to avoid race conditions (if the default blocking nature of channels isn’t enough) and of course a way to prioritize which goroutine to run as well as a synchronization feature known as a waitgroup.Low level. Even though Go is a developer-friendly, multi-purpose programming language it is very low level. That is, you have a lot of control over your machine. Some examples of what you can build in this performant and low-level language are Docker and Kubernetes. Think about the syscalls you have to make just to create a Docker container!
Go is fast — really fast! With almost C-like speeds, Go blows Python out of the water on this parameter. That is partly because Go is a statically typed language with an optimized, extremely fast compiler which makes Go both fast to develop in and fast at execution.
Developer-friendly. Despite the swiftness of Go, it is surprisingly fast to write in. I think there are a couple of reasons for this. First of all, in Go you only have what you really need, so you are rarely in doubt about what to use where. The syntax is clear and readable. Even syntactically it is cleansed from ugly parentheses and other unnecessary syntaxes. Secondly, the Go interpreter is pretty smart and Go’s type system is a nice balance between the lack of unnecessary declarations and a save system guarding for unused imports and unstated datatypes in function arguments for example.
Built-in concurrency and parallelism. Go is a young and modern language and if you have ever tried running bigger projects with some parallel computing in Python, you know that it is a pain. But in Go, it is not. You have green threads called goroutines and you have channels which is a data structure that makes parallel workers communicate rather safely with each other. You also have a way of locking containers like arrays to avoid race conditions (if the default blocking nature of channels isn’t enough) and of course a way to prioritize which goroutine to run as well as a synchronization feature known as a waitgroup.
Low level. Even though Go is a developer-friendly, multi-purpose programming language it is very low level. That is, you have a lot of control over your machine. Some examples of what you can build in this performant and low-level language are Docker and Kubernetes. Think about the syscalls you have to make just to create a Docker container!
In this article, we shall embark on a syntactic journey from one language to another. That being said, I will also discuss style and structure, for as you all know, a direct translation line by line, is a bad one no matter the languages.
Note that this is a short article and certain features of Go have been skipped. That being said, I have tried to include the most important parts so that this is as self-contained as possible and so that you will get a full picture of the language and actually learn some Go.
Without further ado, let’s jump right into it, by talking briefly about imports, data types, and the declaration of variables.
The first thing that stands out in Go when you come from Python is that in every go file you need to specify what is called a package. I won’t go into detail about the packages and the structure of Go projects because this article is about syntax, but it suffices to say that if two files are in the same package, then they have access to the content of one another.
So you start by declaring a package and if you want to have your starting point of execution in your file, then you should name that package main. The main keyword is a special word in Go meaning “this is where the program starts".
The second thing alien for Python programmers is that you don’t need to actively state which function to run because, in Go, you always run the function called main. That also means that you have to create such a function in Go if you want to run anything.
Before you create functions though, you have an option to import stuff. This is finally something that you should recognize from Python.
Let’s look at some “Hello World" programs in each language to see what a possible start looks like.
The Python file needs no comments really. The only thing interesting in comparison to Go is that you need to specify which function you want to run and you don’t need to import anything.
The Go file however is a lot different already. You specify a package (you will get an error if you don’t) and you need to import a format-lib to do IO action. You also need to create a function called main, that will run no matter what and functions in Go are created using the func statement where of course we use def in Python.
To run the Go file called “main.go”, you simply open up a terminal or shell environment, make sure you are in the folder where the file is, and type:
go run main.go
The Go functions need to be told which data types to expect as input as well as output.
func calc(number int) float64 {...return result}
This is in many ways a good thing because it avoids many errors. It is simply safer.
Now that we are at the shell, terminal, cmd, powershell or whatever you prefer to use, there are some Go commands that you should know.
go run will compile and run your file.
go build will compile your file and build an executable that you can then share with your friends and delete their harddrive :-) (or maybe just make a game if you wanna keep your friends).
Go get is yet another nice command that lets you download Go packages directly from an online source like Github.
There are of course many more nice Go commands but I won’t spoil all the fun.
Both languages have the usual number types like int, float, etc., so I won’t go through them all. There are some data types, however, that we need to look at.
Strings in Go are much like Python’s but many of the operations needed for strings will be found in a library you need to import. Namely, the strings library.
In Go, there are two main containers that resemble Python’s lists. Arrays and slices. Arrays have a prespecified number of elements and can be used when you know how many elements you need to store in the variable. Moreover, there can only be one datatype through the array.
Slices are more flexible and are more like Python’s lists. They are mutable and can store any number of elements. But they differ from Python lists in that they also can only store one kind of datatype. There is however a way out of the one-datatype problem that I will address later.
Let’s visit the syntax.
Note that we use the shorthand declaration and instantiation using the symbol :=. This is fine in many cases but only inside a function.
You can declare variables in outer scope but that syntax is different. You would need to do something like
var b uint = 5
When you declare a variable like this, you have more control over your data type. Here I have declared an unsigned int (meaning a non-negative integer). I could not do that using the shorthand above because Go would have thought that b was of type int.
You can try to run the above snippet. You will see that we print out the type of the array and the value of the slice respectively.
Once you have declared say, a slice, there is of course a lot of syntax associated with them. A lot like in Python’s syntax actually.
Sometimes we say that s is a “slice of string” to be explicit about the data type.
Now of course Python has more container types. For example, what's the equivalent of Python’s dict?
Like many other languages, Go chose to call their hashmap map.
They are much like Python’s dicts.
There are a few ways to create a map in Go, but once created, it will be very familiar to Pythonistas.
In Python, we have of course the for loop and the while loop. Go aimed to be a little more restrictive and so they only have one syntax (more or less) and only one loop type. The for loop.
But Go’s for loop is different from Python’s in that it needs to be stopped or else it simply won’t and then you have a while loop.
Let’s compare some code in the two languages.
I will add a little more to the Go file, to explain some syntax.
I believe several comments are in order here. Note that Go uses curly brackets instead of indentation and also that there are no parentheses like in C-like languages. You also see here how to write an if-else clause in Go, note also here that there are no parentheses and the else keyword should be between two curly brackets.
When we iterate over an iterator like numbers above, Go has a keyword called range that makes this possible and returns an index by default. Go supports multiple outputs and you need to learn the basics of when and where Go outputs what.
The rule of thumb is that indexes are outputted to the left of the value and bools and errors are outputted to the right. You can just keep this in mind as we move on with the examples.
If you are not using the index of the elements then you just use an underscore in its place.
for _, number := range numbers {...
In the above snippet with the loops, we used an empty for-loop as a “while True” in Python. In Go, you can also use a boolean type (called bool in Go), so it becomes a true while loop.
for someBool {...
Go also have an else-if statement equivalent to Python’s elif of course and the syntax is
} else if ... {
The switch statement in Go is very useful when you have multiple possibilities for a value and you need to do effective control flow in your program. In Python, you have to do a lot of if-elif-else statements but in Go you can do the following.
This syntax is almost self-explanatory. The default block will run if no other choices happen and is similar to “else”. It is not mandatory and you can skip it as you see in the top switch block. Note that Go has borrowed the colon and indentation from Python here to make it more readable.
In Go, error handling is very different from many other languages. I personally like it, but not all do.
An error in Go is usually returned from a function. So the following is a common pattern to see
You can of course print the error message or of course make go shut down in a so-called panic. The line
panic(message)
will print out the message and shut down the program.
Go is a low-level programming language. This means that you have great control over your computer. In particular, you can access the memory addresses with pointers. This has many advantages. It is especially useful when you need to do a permanent update to a datatype inside say, some function or method (more about that later).
The syntax of pointers is easy and very much like in C.
In the following example, we create an int a and get the memory address of it and store it in a variable b.
This code will print out something like
0xc0000140b85
Note that we use the dereferencing operator (asterisk) * to get back the value that the memory address holds.
Python is, of course, an object-oriented programming language i.e. it has support for classes and instantiations of these called objects. In fact, in Python, almost everything is an object. From functions to strings and generators — they are all objects. If you don’t believe me, you can try calling the built-in function dir on some piece of data, print out the output and you will see the attributes and methods you can call on the given object.
In Go, things are quite different.
Go is not an object-oriented language and therefore it has no classes, class-methods, or objects. It does however have equivalents as you will see now.
Go has Structs. Like in C, these resemble Objects in JavaScript and in a sense classes with only fields in Python.
The basic syntax is as follows:
You create a struct in Go using the type keyword and the idea is like in the case of classes in Python that you can make your own data types.
Like classes, Go offers methods as well and they are very much like Python’s methods except that they are not defined inside the struct but outside the struct.
Let’s see them in action. Add the following to the above.
You can see that the way we define methods in Go is much like functions except that we define which struct it belongs to in parenthesis (in the definition) before the arguments.
Note also that it accepts a pointer type and not an instance of the struct itself. If I had removed the asterisk and simply created a method of the form
func (p person) setSkill(skill string) {p.skills = skill}
then this wouldn’t work. The reason is simple. I want to change the instance of the struct permanently! I don’t want to just get the changed value and leave it unchanged. I could of course do this but it would not change the struct for good. Instead, if I change the value at the memory address (the place that the pointer points) then the instance of the struct gets the value changed until we change it again.
Then you may ask, why (on line 12) don’t we need to pass a pointer to the method? We have p and not &p.
Well, actually you could have done this explicitly like
(&p).setSkill("Coding Go")
but the Go compiler is clever enough to understand that what you want is actually a pointer and not the instance of the struct itself, so this is just syntactic sugar for the above parenthesis-ugliness.
This concept of pointers in methods tends to confuse a lot of new learners but you should just keep in mind that if you want to change something permanently then use pointer methods. If you just want to use some value, then use the struct itself.
One of the really nice and useful features of Go is the concept of interfaces. You should think of an interface as a common denominator that glues together structs that have the same kind of methods.
More precisely, an interface is a collection of methods, so that if a struct has exactly those methods then it satisfies the interface and we can use the interface and the struct with its methods interchangeably.
Say that I have a circle struct and a square struct. They both have a perimeter method and an area method with the same arguments and outputs.
Then we could declare a shape interface containing these types of methods.
Let us look at a classical example of this situation and note the parentheses around the packages that we import — this is the syntax for multiple imports.
The point is that even though the function measure takes in a type of shape, it can accept types of rect and circle as well. This concept is known as polymorphism and Go supports that through interfaces.
Have you thought about how the Println function is able to print different types or how the len function is able to calculate the length of different types?
That is because of interfaces.
In Python, of course, this is possible as well since it is an object-oriented language. You could simply access the dunder-method __len__() and return it.
An example of a very useful interface is the empty interface.
interface{}
Every struct satisfies the empty interface and therefore this interface represents any type.
Remember that I told you that there was a solution to the one-type-only in arrays and slices? The answer is interfaces.
We can make a slice of a certain interface that accepts many types. The following would work.
d := []interface{}{1, "Kasper", 3.2, 'A'}fmt.Println(d)
Note that the last entry of the slice is a char denoted by surrounding single quotes.
The empty interface is a nice trick to have but not exactly best practice. One should always try to be as restrictive as possible in order to avoid errors. That being said, there might be no other solution.
Parallelizing code in Python is a challenge in many cases.
Now, Go is a modern language with built-in support for concurrency and parallelism. They even have a keyword for it.
It is of course important to be aware of the fact that concurrency and parallel computing are not the same. This could be a whole article in itself. The high-level understanding is enough for now.
Namely that parallel computing is when the CPU does several computations at the same time (using several kernels or threads). Concurrency means that the program switches context between parallel workers (or threads) so that when one worker can’t move on (is blocked by some reason or simply have to wait e.g. for a server response) then the context switches to a ready worker that then picks up where it left off. This doesn’t mean that the workers do anything at the same time.
One can do both things quite easily in Go and in many cases you do both at the same time without the Go compiler even lets you know.
Before we get started down this fascinating road, let us start with something that you have already come across, namely the main goroutine.
The main function that runs no matter what, is actually what is known as a goroutine (also called a green thread in other languages). It just always runs.
You should imagine a Go program like a river where the main thread is the main river, and small branches of the river could spawn or branch out if you will.
The branching rivers are called goroutines and are called with the keyword go
Note how the background strings are printed out in parallel in no apparent order. That is how easy it is to parallelize code in Go.
Of course, this poses a potential danger because of rase conditions, non-secure data transfer, and synchronization issues but Go is intelligently build, so there are of course solutions to all these points.
Channels in Go is a data type that can transfer data from one goroutine to another in a relatively safe manner.
An example:
In the above snippet, the following happens:
First, we create a channel called messages, then we branch out of the main routine with an anonymous function (like Pythons lambdas) that shoots the message “ping” into the channel. At this point, the channel is blocked. If another goroutine were to try to send a message, the message would end up in a queue waiting for the channel to be empty/read so it can receive another message. You can make channels with so-called buffers that can accept x number of messages before blocking but we won’t go into detail about that.
Then we read the message on line 11 and store it in a variable called msg. Then, of course, we print it out to the console.
There is an important thing to note about the lifetime of a Go program. When the main function finishes, all other goroutines exit as well, even if the functions did not finish and did not get to return anything. To display this, let us take a look at the following.
If you try to run this, you will see that we don’t get a single ping! This is because the main function (goroutine) finishes before the anonymous goroutine gets to print out anything. However, if you wait for it, it will get to print something. The following will print out all the pings.
This is working, but it is not best practice.
In Go we have what is known as a waitgroup. Its purpose is to synchronize all your goroutines, so that when the main function returns, then all your goroutines have returned as well.
This code is much better but it needs some explanation.
We have changed the function from an anonymous function to a normal function that doesn’t run until called. We call the function counting.
Back in the main function we declare a variable called wg of type WaitGroup. This is basically a counter. When wg.Add(x) is called we add x to the counter, and when wg.Done() is called we subtract 1.
The function counting has an argument of type pointer to waitgroup. The pointer type is needed because remember we want to subract 1 from the waitgroup permanently.
The defer statement inside the counting function means “do the following as the last action before returning”. This is very useful since it can be hard sometimes to know which order things will happen in. In our case, we tell the waitgroup that we are done and the waitgroup counter decreases by 1.
After running the function counting as a goroutine in the background, we call wg.Wait() which will wait for the waitgroup counter to become 0 before moving to the next line.
The rule of waitgroups is, every time you run a goroutine you need to add 1 to the waitgroup. Every time a goroutine returns you should subtract 1. Then wait for all to finish with wg.Wait().
There is however another way of doing this without waitgroups.
It turns out that you can loop over a channel, and this will only stop if the channel is closed. So this blocking nature is often used to sync your goroutines. Check out the following code, which will give the same output as above.
Very neat! We give the function counting a channel as an argument and use that channel to communicate back to the main goroutine where we will loop over the channel and print out all the messages sent. Back in counting, we close the channel just before exiting the function, in the main function we now know that the channel has been closed and we can move on.
Sometimes you have multiple channels to read from and it can be hard to know apriori which channel is ready to be read. You don’t want to waste any time of course so how do we solve this?
The answer is yet another brilliant invention called the select statement. Take a look at the following example.
The select statement is very much like the switch statement, except that it selects between channels. The above is a good example of when this is useful. There is no reason to wait for the c2 channel when c1 is ready to be read. The result of this is that it only takes about 2 seconds to run this and not 3.
The select statement also has a default case and that can be very useful as well.
You might have noticed that I tend to keep variable names quite short as opposed to names in Python for example. This is actually on purpose.
You see, a part of the Go language is simplicity, effectivity, and short names. It is no joke! Of course, as always names should be descriptive but you don’t need to overdo it. Dummy variables in loops for example should be one letter names, function names should be one word, etc. Use shorthand when it makes sense for a reviewer, reader, or coworker.
Also, the variables should be camel case instead of underscores.
There is one important thing though that you need to be aware of. The capitalization of the first letter of a variable matters!
In Go, if you want to export functions and variables in order to access them in other files, they should begin with a capital letter. That’s it. Then you can access them from the outside. If they begin with a small letter, then they are private variables, only accessible in your file or scope.
I would recommend a tour of Go along with a couple of other links.
You can find a tour of go here: A Tour of Go
Also, Go’s official website is great: Go
The official documentation: Docs
Go by example is also great: Examples
I hope that you learned some Go and enjoyed the ride. I am confident that this language will become one of the most popular and sought of languages in the world and already it is quite popular, of course.
It can be a little hard to understand the language sometimes because a lot of the standard library is using interfaces to do all kinds of tricks behind the scene like write bytes to an array in the background for example, but if you keep Going, then you will learn it in a short time.
|
[
{
"code": null,
"e": 390,
"s": 171,
"text": "My hope is that this article can be used both as a dictionary for Pythonistas who want to learn Go but also as an introduction to Go for those out there who know Python and just want to get started quickly with Golang."
},
{
"code": null,
"e": 506,
"s": 390,
"text": "Before we begin, I want to briefly explain why it might be a great choice to learn Go when you already know Python."
},
{
"code": null,
"e": 810,
"s": 506,
"text": "First of all, I am not saying that Go is a better language than Python. Python is a great language and often a better choice than Go. It depends of course on the problem you are trying to solve or the application that you want to build, but Go does have a lot of things going for it that Python doesn’t."
},
{
"code": null,
"e": 2641,
"s": 810,
"text": "Go is fast — really fast! With almost C-like speeds, Go blows Python out of the water on this parameter. That is partly because Go is a statically typed language with an optimized, extremely fast compiler which makes Go both fast to develop in and fast at execution.Developer-friendly. Despite the swiftness of Go, it is surprisingly fast to write in. I think there are a couple of reasons for this. First of all, in Go you only have what you really need, so you are rarely in doubt about what to use where. The syntax is clear and readable. Even syntactically it is cleansed from ugly parentheses and other unnecessary syntaxes. Secondly, the Go interpreter is pretty smart and Go’s type system is a nice balance between the lack of unnecessary declarations and a save system guarding for unused imports and unstated datatypes in function arguments for example.Built-in concurrency and parallelism. Go is a young and modern language and if you have ever tried running bigger projects with some parallel computing in Python, you know that it is a pain. But in Go, it is not. You have green threads called goroutines and you have channels which is a data structure that makes parallel workers communicate rather safely with each other. You also have a way of locking containers like arrays to avoid race conditions (if the default blocking nature of channels isn’t enough) and of course a way to prioritize which goroutine to run as well as a synchronization feature known as a waitgroup.Low level. Even though Go is a developer-friendly, multi-purpose programming language it is very low level. That is, you have a lot of control over your machine. Some examples of what you can build in this performant and low-level language are Docker and Kubernetes. Think about the syscalls you have to make just to create a Docker container!"
},
{
"code": null,
"e": 2908,
"s": 2641,
"text": "Go is fast — really fast! With almost C-like speeds, Go blows Python out of the water on this parameter. That is partly because Go is a statically typed language with an optimized, extremely fast compiler which makes Go both fast to develop in and fast at execution."
},
{
"code": null,
"e": 3505,
"s": 2908,
"text": "Developer-friendly. Despite the swiftness of Go, it is surprisingly fast to write in. I think there are a couple of reasons for this. First of all, in Go you only have what you really need, so you are rarely in doubt about what to use where. The syntax is clear and readable. Even syntactically it is cleansed from ugly parentheses and other unnecessary syntaxes. Secondly, the Go interpreter is pretty smart and Go’s type system is a nice balance between the lack of unnecessary declarations and a save system guarding for unused imports and unstated datatypes in function arguments for example."
},
{
"code": null,
"e": 4131,
"s": 3505,
"text": "Built-in concurrency and parallelism. Go is a young and modern language and if you have ever tried running bigger projects with some parallel computing in Python, you know that it is a pain. But in Go, it is not. You have green threads called goroutines and you have channels which is a data structure that makes parallel workers communicate rather safely with each other. You also have a way of locking containers like arrays to avoid race conditions (if the default blocking nature of channels isn’t enough) and of course a way to prioritize which goroutine to run as well as a synchronization feature known as a waitgroup."
},
{
"code": null,
"e": 4475,
"s": 4131,
"text": "Low level. Even though Go is a developer-friendly, multi-purpose programming language it is very low level. That is, you have a lot of control over your machine. Some examples of what you can build in this performant and low-level language are Docker and Kubernetes. Think about the syscalls you have to make just to create a Docker container!"
},
{
"code": null,
"e": 4713,
"s": 4475,
"text": "In this article, we shall embark on a syntactic journey from one language to another. That being said, I will also discuss style and structure, for as you all know, a direct translation line by line, is a bad one no matter the languages."
},
{
"code": null,
"e": 4989,
"s": 4713,
"text": "Note that this is a short article and certain features of Go have been skipped. That being said, I have tried to include the most important parts so that this is as self-contained as possible and so that you will get a full picture of the language and actually learn some Go."
},
{
"code": null,
"e": 5116,
"s": 4989,
"text": "Without further ado, let’s jump right into it, by talking briefly about imports, data types, and the declaration of variables."
},
{
"code": null,
"e": 5483,
"s": 5116,
"text": "The first thing that stands out in Go when you come from Python is that in every go file you need to specify what is called a package. I won’t go into detail about the packages and the structure of Go projects because this article is about syntax, but it suffices to say that if two files are in the same package, then they have access to the content of one another."
},
{
"code": null,
"e": 5715,
"s": 5483,
"text": "So you start by declaring a package and if you want to have your starting point of execution in your file, then you should name that package main. The main keyword is a special word in Go meaning “this is where the program starts\"."
},
{
"code": null,
"e": 5972,
"s": 5715,
"text": "The second thing alien for Python programmers is that you don’t need to actively state which function to run because, in Go, you always run the function called main. That also means that you have to create such a function in Go if you want to run anything."
},
{
"code": null,
"e": 6109,
"s": 5972,
"text": "Before you create functions though, you have an option to import stuff. This is finally something that you should recognize from Python."
},
{
"code": null,
"e": 6209,
"s": 6109,
"text": "Let’s look at some “Hello World\" programs in each language to see what a possible start looks like."
},
{
"code": null,
"e": 6396,
"s": 6209,
"text": "The Python file needs no comments really. The only thing interesting in comparison to Go is that you need to specify which function you want to run and you don’t need to import anything."
},
{
"code": null,
"e": 6728,
"s": 6396,
"text": "The Go file however is a lot different already. You specify a package (you will get an error if you don’t) and you need to import a format-lib to do IO action. You also need to create a function called main, that will run no matter what and functions in Go are created using the func statement where of course we use def in Python."
},
{
"code": null,
"e": 6878,
"s": 6728,
"text": "To run the Go file called “main.go”, you simply open up a terminal or shell environment, make sure you are in the folder where the file is, and type:"
},
{
"code": null,
"e": 6893,
"s": 6878,
"text": "go run main.go"
},
{
"code": null,
"e": 6981,
"s": 6893,
"text": "The Go functions need to be told which data types to expect as input as well as output."
},
{
"code": null,
"e": 7030,
"s": 6981,
"text": "func calc(number int) float64 {...return result}"
},
{
"code": null,
"e": 7115,
"s": 7030,
"text": "This is in many ways a good thing because it avoids many errors. It is simply safer."
},
{
"code": null,
"e": 7251,
"s": 7115,
"text": "Now that we are at the shell, terminal, cmd, powershell or whatever you prefer to use, there are some Go commands that you should know."
},
{
"code": null,
"e": 7290,
"s": 7251,
"text": "go run will compile and run your file."
},
{
"code": null,
"e": 7479,
"s": 7290,
"text": "go build will compile your file and build an executable that you can then share with your friends and delete their harddrive :-) (or maybe just make a game if you wanna keep your friends)."
},
{
"code": null,
"e": 7593,
"s": 7479,
"text": "Go get is yet another nice command that lets you download Go packages directly from an online source like Github."
},
{
"code": null,
"e": 7671,
"s": 7593,
"text": "There are of course many more nice Go commands but I won’t spoil all the fun."
},
{
"code": null,
"e": 7830,
"s": 7671,
"text": "Both languages have the usual number types like int, float, etc., so I won’t go through them all. There are some data types, however, that we need to look at."
},
{
"code": null,
"e": 7989,
"s": 7830,
"text": "Strings in Go are much like Python’s but many of the operations needed for strings will be found in a library you need to import. Namely, the strings library."
},
{
"code": null,
"e": 8264,
"s": 7989,
"text": "In Go, there are two main containers that resemble Python’s lists. Arrays and slices. Arrays have a prespecified number of elements and can be used when you know how many elements you need to store in the variable. Moreover, there can only be one datatype through the array."
},
{
"code": null,
"e": 8549,
"s": 8264,
"text": "Slices are more flexible and are more like Python’s lists. They are mutable and can store any number of elements. But they differ from Python lists in that they also can only store one kind of datatype. There is however a way out of the one-datatype problem that I will address later."
},
{
"code": null,
"e": 8573,
"s": 8549,
"text": "Let’s visit the syntax."
},
{
"code": null,
"e": 8710,
"s": 8573,
"text": "Note that we use the shorthand declaration and instantiation using the symbol :=. This is fine in many cases but only inside a function."
},
{
"code": null,
"e": 8817,
"s": 8710,
"text": "You can declare variables in outer scope but that syntax is different. You would need to do something like"
},
{
"code": null,
"e": 8832,
"s": 8817,
"text": "var b uint = 5"
},
{
"code": null,
"e": 9085,
"s": 8832,
"text": "When you declare a variable like this, you have more control over your data type. Here I have declared an unsigned int (meaning a non-negative integer). I could not do that using the shorthand above because Go would have thought that b was of type int."
},
{
"code": null,
"e": 9217,
"s": 9085,
"text": "You can try to run the above snippet. You will see that we print out the type of the array and the value of the slice respectively."
},
{
"code": null,
"e": 9351,
"s": 9217,
"text": "Once you have declared say, a slice, there is of course a lot of syntax associated with them. A lot like in Python’s syntax actually."
},
{
"code": null,
"e": 9434,
"s": 9351,
"text": "Sometimes we say that s is a “slice of string” to be explicit about the data type."
},
{
"code": null,
"e": 9534,
"s": 9434,
"text": "Now of course Python has more container types. For example, what's the equivalent of Python’s dict?"
},
{
"code": null,
"e": 9597,
"s": 9534,
"text": "Like many other languages, Go chose to call their hashmap map."
},
{
"code": null,
"e": 9632,
"s": 9597,
"text": "They are much like Python’s dicts."
},
{
"code": null,
"e": 9735,
"s": 9632,
"text": "There are a few ways to create a map in Go, but once created, it will be very familiar to Pythonistas."
},
{
"code": null,
"e": 9924,
"s": 9735,
"text": "In Python, we have of course the for loop and the while loop. Go aimed to be a little more restrictive and so they only have one syntax (more or less) and only one loop type. The for loop."
},
{
"code": null,
"e": 10056,
"s": 9924,
"text": "But Go’s for loop is different from Python’s in that it needs to be stopped or else it simply won’t and then you have a while loop."
},
{
"code": null,
"e": 10102,
"s": 10056,
"text": "Let’s compare some code in the two languages."
},
{
"code": null,
"e": 10167,
"s": 10102,
"text": "I will add a little more to the Go file, to explain some syntax."
},
{
"code": null,
"e": 10494,
"s": 10167,
"text": "I believe several comments are in order here. Note that Go uses curly brackets instead of indentation and also that there are no parentheses like in C-like languages. You also see here how to write an if-else clause in Go, note also here that there are no parentheses and the else keyword should be between two curly brackets."
},
{
"code": null,
"e": 10732,
"s": 10494,
"text": "When we iterate over an iterator like numbers above, Go has a keyword called range that makes this possible and returns an index by default. Go supports multiple outputs and you need to learn the basics of when and where Go outputs what."
},
{
"code": null,
"e": 10918,
"s": 10732,
"text": "The rule of thumb is that indexes are outputted to the left of the value and bools and errors are outputted to the right. You can just keep this in mind as we move on with the examples."
},
{
"code": null,
"e": 11011,
"s": 10918,
"text": "If you are not using the index of the elements then you just use an underscore in its place."
},
{
"code": null,
"e": 11047,
"s": 11011,
"text": "for _, number := range numbers {..."
},
{
"code": null,
"e": 11232,
"s": 11047,
"text": "In the above snippet with the loops, we used an empty for-loop as a “while True” in Python. In Go, you can also use a boolean type (called bool in Go), so it becomes a true while loop."
},
{
"code": null,
"e": 11250,
"s": 11232,
"text": "for someBool {..."
},
{
"code": null,
"e": 11340,
"s": 11250,
"text": "Go also have an else-if statement equivalent to Python’s elif of course and the syntax is"
},
{
"code": null,
"e": 11356,
"s": 11340,
"text": "} else if ... {"
},
{
"code": null,
"e": 11601,
"s": 11356,
"text": "The switch statement in Go is very useful when you have multiple possibilities for a value and you need to do effective control flow in your program. In Python, you have to do a lot of if-elif-else statements but in Go you can do the following."
},
{
"code": null,
"e": 11892,
"s": 11601,
"text": "This syntax is almost self-explanatory. The default block will run if no other choices happen and is similar to “else”. It is not mandatory and you can skip it as you see in the top switch block. Note that Go has borrowed the colon and indentation from Python here to make it more readable."
},
{
"code": null,
"e": 11997,
"s": 11892,
"text": "In Go, error handling is very different from many other languages. I personally like it, but not all do."
},
{
"code": null,
"e": 12093,
"s": 11997,
"text": "An error in Go is usually returned from a function. So the following is a common pattern to see"
},
{
"code": null,
"e": 12197,
"s": 12093,
"text": "You can of course print the error message or of course make go shut down in a so-called panic. The line"
},
{
"code": null,
"e": 12212,
"s": 12197,
"text": "panic(message)"
},
{
"code": null,
"e": 12266,
"s": 12212,
"text": "will print out the message and shut down the program."
},
{
"code": null,
"e": 12595,
"s": 12266,
"text": "Go is a low-level programming language. This means that you have great control over your computer. In particular, you can access the memory addresses with pointers. This has many advantages. It is especially useful when you need to do a permanent update to a datatype inside say, some function or method (more about that later)."
},
{
"code": null,
"e": 12651,
"s": 12595,
"text": "The syntax of pointers is easy and very much like in C."
},
{
"code": null,
"e": 12759,
"s": 12651,
"text": "In the following example, we create an int a and get the memory address of it and store it in a variable b."
},
{
"code": null,
"e": 12799,
"s": 12759,
"text": "This code will print out something like"
},
{
"code": null,
"e": 12813,
"s": 12799,
"text": "0xc0000140b85"
},
{
"code": null,
"e": 12923,
"s": 12813,
"text": "Note that we use the dereferencing operator (asterisk) * to get back the value that the memory address holds."
},
{
"code": null,
"e": 13371,
"s": 12923,
"text": "Python is, of course, an object-oriented programming language i.e. it has support for classes and instantiations of these called objects. In fact, in Python, almost everything is an object. From functions to strings and generators — they are all objects. If you don’t believe me, you can try calling the built-in function dir on some piece of data, print out the output and you will see the attributes and methods you can call on the given object."
},
{
"code": null,
"e": 13406,
"s": 13371,
"text": "In Go, things are quite different."
},
{
"code": null,
"e": 13558,
"s": 13406,
"text": "Go is not an object-oriented language and therefore it has no classes, class-methods, or objects. It does however have equivalents as you will see now."
},
{
"code": null,
"e": 13673,
"s": 13558,
"text": "Go has Structs. Like in C, these resemble Objects in JavaScript and in a sense classes with only fields in Python."
},
{
"code": null,
"e": 13705,
"s": 13673,
"text": "The basic syntax is as follows:"
},
{
"code": null,
"e": 13847,
"s": 13705,
"text": "You create a struct in Go using the type keyword and the idea is like in the case of classes in Python that you can make your own data types."
},
{
"code": null,
"e": 14007,
"s": 13847,
"text": "Like classes, Go offers methods as well and they are very much like Python’s methods except that they are not defined inside the struct but outside the struct."
},
{
"code": null,
"e": 14065,
"s": 14007,
"text": "Let’s see them in action. Add the following to the above."
},
{
"code": null,
"e": 14243,
"s": 14065,
"text": "You can see that the way we define methods in Go is much like functions except that we define which struct it belongs to in parenthesis (in the definition) before the arguments."
},
{
"code": null,
"e": 14396,
"s": 14243,
"text": "Note also that it accepts a pointer type and not an instance of the struct itself. If I had removed the asterisk and simply created a method of the form"
},
{
"code": null,
"e": 14454,
"s": 14396,
"text": "func (p person) setSkill(skill string) {p.skills = skill}"
},
{
"code": null,
"e": 14866,
"s": 14454,
"text": "then this wouldn’t work. The reason is simple. I want to change the instance of the struct permanently! I don’t want to just get the changed value and leave it unchanged. I could of course do this but it would not change the struct for good. Instead, if I change the value at the memory address (the place that the pointer points) then the instance of the struct gets the value changed until we change it again."
},
{
"code": null,
"e": 14970,
"s": 14866,
"text": "Then you may ask, why (on line 12) don’t we need to pass a pointer to the method? We have p and not &p."
},
{
"code": null,
"e": 15026,
"s": 14970,
"text": "Well, actually you could have done this explicitly like"
},
{
"code": null,
"e": 15053,
"s": 15026,
"text": "(&p).setSkill(\"Coding Go\")"
},
{
"code": null,
"e": 15256,
"s": 15053,
"text": "but the Go compiler is clever enough to understand that what you want is actually a pointer and not the instance of the struct itself, so this is just syntactic sugar for the above parenthesis-ugliness."
},
{
"code": null,
"e": 15503,
"s": 15256,
"text": "This concept of pointers in methods tends to confuse a lot of new learners but you should just keep in mind that if you want to change something permanently then use pointer methods. If you just want to use some value, then use the struct itself."
},
{
"code": null,
"e": 15703,
"s": 15503,
"text": "One of the really nice and useful features of Go is the concept of interfaces. You should think of an interface as a common denominator that glues together structs that have the same kind of methods."
},
{
"code": null,
"e": 15916,
"s": 15703,
"text": "More precisely, an interface is a collection of methods, so that if a struct has exactly those methods then it satisfies the interface and we can use the interface and the struct with its methods interchangeably."
},
{
"code": null,
"e": 16059,
"s": 15916,
"text": "Say that I have a circle struct and a square struct. They both have a perimeter method and an area method with the same arguments and outputs."
},
{
"code": null,
"e": 16134,
"s": 16059,
"text": "Then we could declare a shape interface containing these types of methods."
},
{
"code": null,
"e": 16290,
"s": 16134,
"text": "Let us look at a classical example of this situation and note the parentheses around the packages that we import — this is the syntax for multiple imports."
},
{
"code": null,
"e": 16494,
"s": 16290,
"text": "The point is that even though the function measure takes in a type of shape, it can accept types of rect and circle as well. This concept is known as polymorphism and Go supports that through interfaces."
},
{
"code": null,
"e": 16651,
"s": 16494,
"text": "Have you thought about how the Println function is able to print different types or how the len function is able to calculate the length of different types?"
},
{
"code": null,
"e": 16682,
"s": 16651,
"text": "That is because of interfaces."
},
{
"code": null,
"e": 16837,
"s": 16682,
"text": "In Python, of course, this is possible as well since it is an object-oriented language. You could simply access the dunder-method __len__() and return it."
},
{
"code": null,
"e": 16899,
"s": 16837,
"text": "An example of a very useful interface is the empty interface."
},
{
"code": null,
"e": 16911,
"s": 16899,
"text": "interface{}"
},
{
"code": null,
"e": 17004,
"s": 16911,
"text": "Every struct satisfies the empty interface and therefore this interface represents any type."
},
{
"code": null,
"e": 17124,
"s": 17004,
"text": "Remember that I told you that there was a solution to the one-type-only in arrays and slices? The answer is interfaces."
},
{
"code": null,
"e": 17218,
"s": 17124,
"text": "We can make a slice of a certain interface that accepts many types. The following would work."
},
{
"code": null,
"e": 17274,
"s": 17218,
"text": "d := []interface{}{1, \"Kasper\", 3.2, 'A'}fmt.Println(d)"
},
{
"code": null,
"e": 17360,
"s": 17274,
"text": "Note that the last entry of the slice is a char denoted by surrounding single quotes."
},
{
"code": null,
"e": 17567,
"s": 17360,
"text": "The empty interface is a nice trick to have but not exactly best practice. One should always try to be as restrictive as possible in order to avoid errors. That being said, there might be no other solution."
},
{
"code": null,
"e": 17626,
"s": 17567,
"text": "Parallelizing code in Python is a challenge in many cases."
},
{
"code": null,
"e": 17743,
"s": 17626,
"text": "Now, Go is a modern language with built-in support for concurrency and parallelism. They even have a keyword for it."
},
{
"code": null,
"e": 17940,
"s": 17743,
"text": "It is of course important to be aware of the fact that concurrency and parallel computing are not the same. This could be a whole article in itself. The high-level understanding is enough for now."
},
{
"code": null,
"e": 18419,
"s": 17940,
"text": "Namely that parallel computing is when the CPU does several computations at the same time (using several kernels or threads). Concurrency means that the program switches context between parallel workers (or threads) so that when one worker can’t move on (is blocked by some reason or simply have to wait e.g. for a server response) then the context switches to a ready worker that then picks up where it left off. This doesn’t mean that the workers do anything at the same time."
},
{
"code": null,
"e": 18552,
"s": 18419,
"text": "One can do both things quite easily in Go and in many cases you do both at the same time without the Go compiler even lets you know."
},
{
"code": null,
"e": 18692,
"s": 18552,
"text": "Before we get started down this fascinating road, let us start with something that you have already come across, namely the main goroutine."
},
{
"code": null,
"e": 18847,
"s": 18692,
"text": "The main function that runs no matter what, is actually what is known as a goroutine (also called a green thread in other languages). It just always runs."
},
{
"code": null,
"e": 19004,
"s": 18847,
"text": "You should imagine a Go program like a river where the main thread is the main river, and small branches of the river could spawn or branch out if you will."
},
{
"code": null,
"e": 19082,
"s": 19004,
"text": "The branching rivers are called goroutines and are called with the keyword go"
},
{
"code": null,
"e": 19214,
"s": 19082,
"text": "Note how the background strings are printed out in parallel in no apparent order. That is how easy it is to parallelize code in Go."
},
{
"code": null,
"e": 19421,
"s": 19214,
"text": "Of course, this poses a potential danger because of rase conditions, non-secure data transfer, and synchronization issues but Go is intelligently build, so there are of course solutions to all these points."
},
{
"code": null,
"e": 19533,
"s": 19421,
"text": "Channels in Go is a data type that can transfer data from one goroutine to another in a relatively safe manner."
},
{
"code": null,
"e": 19545,
"s": 19533,
"text": "An example:"
},
{
"code": null,
"e": 19590,
"s": 19545,
"text": "In the above snippet, the following happens:"
},
{
"code": null,
"e": 20113,
"s": 19590,
"text": "First, we create a channel called messages, then we branch out of the main routine with an anonymous function (like Pythons lambdas) that shoots the message “ping” into the channel. At this point, the channel is blocked. If another goroutine were to try to send a message, the message would end up in a queue waiting for the channel to be empty/read so it can receive another message. You can make channels with so-called buffers that can accept x number of messages before blocking but we won’t go into detail about that."
},
{
"code": null,
"e": 20237,
"s": 20113,
"text": "Then we read the message on line 11 and store it in a variable called msg. Then, of course, we print it out to the console."
},
{
"code": null,
"e": 20504,
"s": 20237,
"text": "There is an important thing to note about the lifetime of a Go program. When the main function finishes, all other goroutines exit as well, even if the functions did not finish and did not get to return anything. To display this, let us take a look at the following."
},
{
"code": null,
"e": 20793,
"s": 20504,
"text": "If you try to run this, you will see that we don’t get a single ping! This is because the main function (goroutine) finishes before the anonymous goroutine gets to print out anything. However, if you wait for it, it will get to print something. The following will print out all the pings."
},
{
"code": null,
"e": 20839,
"s": 20793,
"text": "This is working, but it is not best practice."
},
{
"code": null,
"e": 21022,
"s": 20839,
"text": "In Go we have what is known as a waitgroup. Its purpose is to synchronize all your goroutines, so that when the main function returns, then all your goroutines have returned as well."
},
{
"code": null,
"e": 21078,
"s": 21022,
"text": "This code is much better but it needs some explanation."
},
{
"code": null,
"e": 21217,
"s": 21078,
"text": "We have changed the function from an anonymous function to a normal function that doesn’t run until called. We call the function counting."
},
{
"code": null,
"e": 21417,
"s": 21217,
"text": "Back in the main function we declare a variable called wg of type WaitGroup. This is basically a counter. When wg.Add(x) is called we add x to the counter, and when wg.Done() is called we subtract 1."
},
{
"code": null,
"e": 21582,
"s": 21417,
"text": "The function counting has an argument of type pointer to waitgroup. The pointer type is needed because remember we want to subract 1 from the waitgroup permanently."
},
{
"code": null,
"e": 21881,
"s": 21582,
"text": "The defer statement inside the counting function means “do the following as the last action before returning”. This is very useful since it can be hard sometimes to know which order things will happen in. In our case, we tell the waitgroup that we are done and the waitgroup counter decreases by 1."
},
{
"code": null,
"e": 22055,
"s": 21881,
"text": "After running the function counting as a goroutine in the background, we call wg.Wait() which will wait for the waitgroup counter to become 0 before moving to the next line."
},
{
"code": null,
"e": 22247,
"s": 22055,
"text": "The rule of waitgroups is, every time you run a goroutine you need to add 1 to the waitgroup. Every time a goroutine returns you should subtract 1. Then wait for all to finish with wg.Wait()."
},
{
"code": null,
"e": 22310,
"s": 22247,
"text": "There is however another way of doing this without waitgroups."
},
{
"code": null,
"e": 22542,
"s": 22310,
"text": "It turns out that you can loop over a channel, and this will only stop if the channel is closed. So this blocking nature is often used to sync your goroutines. Check out the following code, which will give the same output as above."
},
{
"code": null,
"e": 22903,
"s": 22542,
"text": "Very neat! We give the function counting a channel as an argument and use that channel to communicate back to the main goroutine where we will loop over the channel and print out all the messages sent. Back in counting, we close the channel just before exiting the function, in the main function we now know that the channel has been closed and we can move on."
},
{
"code": null,
"e": 23091,
"s": 22903,
"text": "Sometimes you have multiple channels to read from and it can be hard to know apriori which channel is ready to be read. You don’t want to waste any time of course so how do we solve this?"
},
{
"code": null,
"e": 23204,
"s": 23091,
"text": "The answer is yet another brilliant invention called the select statement. Take a look at the following example."
},
{
"code": null,
"e": 23513,
"s": 23204,
"text": "The select statement is very much like the switch statement, except that it selects between channels. The above is a good example of when this is useful. There is no reason to wait for the c2 channel when c1 is ready to be read. The result of this is that it only takes about 2 seconds to run this and not 3."
},
{
"code": null,
"e": 23595,
"s": 23513,
"text": "The select statement also has a default case and that can be very useful as well."
},
{
"code": null,
"e": 23737,
"s": 23595,
"text": "You might have noticed that I tend to keep variable names quite short as opposed to names in Python for example. This is actually on purpose."
},
{
"code": null,
"e": 24090,
"s": 23737,
"text": "You see, a part of the Go language is simplicity, effectivity, and short names. It is no joke! Of course, as always names should be descriptive but you don’t need to overdo it. Dummy variables in loops for example should be one letter names, function names should be one word, etc. Use shorthand when it makes sense for a reviewer, reader, or coworker."
},
{
"code": null,
"e": 24155,
"s": 24090,
"text": "Also, the variables should be camel case instead of underscores."
},
{
"code": null,
"e": 24283,
"s": 24155,
"text": "There is one important thing though that you need to be aware of. The capitalization of the first letter of a variable matters!"
},
{
"code": null,
"e": 24578,
"s": 24283,
"text": "In Go, if you want to export functions and variables in order to access them in other files, they should begin with a capital letter. That’s it. Then you can access them from the outside. If they begin with a small letter, then they are private variables, only accessible in your file or scope."
},
{
"code": null,
"e": 24645,
"s": 24578,
"text": "I would recommend a tour of Go along with a couple of other links."
},
{
"code": null,
"e": 24690,
"s": 24645,
"text": "You can find a tour of go here: A Tour of Go"
},
{
"code": null,
"e": 24731,
"s": 24690,
"text": "Also, Go’s official website is great: Go"
},
{
"code": null,
"e": 24764,
"s": 24731,
"text": "The official documentation: Docs"
},
{
"code": null,
"e": 24802,
"s": 24764,
"text": "Go by example is also great: Examples"
},
{
"code": null,
"e": 25007,
"s": 24802,
"text": "I hope that you learned some Go and enjoyed the ride. I am confident that this language will become one of the most popular and sought of languages in the world and already it is quite popular, of course."
}
] |
Facebook Login using Python
|
We can use the python package called selenium to automate the interaction with webdrivers. In this article we will see the interaction between python’s selenium package and logging in to Facebook.
Selenium package is used to automate and controls web browsers activity. Out python code will need the selenium package to be installed and also a driver software known as geckodriver to be available for the program. Below are the steps to achieve this.
Install selenium in you python environment
pip install selenium
Download the geckodriver from this link. Place it in the same directory where we are going to have this python script.
Next we create the program which will import the relevant modules form the selenium package and able to open the webpage for login.
To get the id details of the input boxes for login, we can view the source code of the webpage facebook.com and find the id of the fields as follows.
The code below contains the comments that explain the purpose of the code segments.
from selenium import webdriver
#Open Firefox
browser = webdriver.Firefox()
# Go to the Facebook URL
browser.get("http://www.facebook.com")
# Enter the username and Password
uname = browser.find_element_by_id("email")
psword = browser.find_element_by_id("pass")
submit = browser.find_element_by_id("loginbutton")
# Send the details to respective fields
uname.send_keys("hello@gmail.com")
psword.send_keys("thepassword")
# Automate Click Login
submit.click()
Running the above code gives us the following result −
With the correct credentials the facebook login will happen automatically and you can see the logged in page. Selenium’s features enable this functionality.
|
[
{
"code": null,
"e": 1259,
"s": 1062,
"text": "We can use the python package called selenium to automate the interaction with webdrivers. In this article we will see the interaction between python’s selenium package and logging in to Facebook."
},
{
"code": null,
"e": 1513,
"s": 1259,
"text": "Selenium package is used to automate and controls web browsers activity. Out python code will need the selenium package to be installed and also a driver software known as geckodriver to be available for the program. Below are the steps to achieve this."
},
{
"code": null,
"e": 1556,
"s": 1513,
"text": "Install selenium in you python environment"
},
{
"code": null,
"e": 1577,
"s": 1556,
"text": "pip install selenium"
},
{
"code": null,
"e": 1696,
"s": 1577,
"text": "Download the geckodriver from this link. Place it in the same directory where we are going to have this python script."
},
{
"code": null,
"e": 1828,
"s": 1696,
"text": "Next we create the program which will import the relevant modules form the selenium package and able to open the webpage for login."
},
{
"code": null,
"e": 1978,
"s": 1828,
"text": "To get the id details of the input boxes for login, we can view the source code of the webpage facebook.com and find the id of the fields as follows."
},
{
"code": null,
"e": 2062,
"s": 1978,
"text": "The code below contains the comments that explain the purpose of the code segments."
},
{
"code": null,
"e": 2519,
"s": 2062,
"text": "from selenium import webdriver\n#Open Firefox\nbrowser = webdriver.Firefox()\n# Go to the Facebook URL\nbrowser.get(\"http://www.facebook.com\")\n# Enter the username and Password\nuname = browser.find_element_by_id(\"email\")\npsword = browser.find_element_by_id(\"pass\")\nsubmit = browser.find_element_by_id(\"loginbutton\")\n# Send the details to respective fields\nuname.send_keys(\"hello@gmail.com\")\npsword.send_keys(\"thepassword\")\n# Automate Click Login\nsubmit.click()"
},
{
"code": null,
"e": 2574,
"s": 2519,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2731,
"s": 2574,
"text": "With the correct credentials the facebook login will happen automatically and you can see the logged in page. Selenium’s features enable this functionality."
}
] |
Bitwise OR of Bitwise AND of all subarrays of an array - GeeksforGeeks
|
20 Oct, 2021
Given an array arr[] consisting of N positive integers, the task is to find the Bitwise OR of Bitwise AND of all subarrays of the given arrays.
Examples:
Input: arr[] = {1, 2, 3}Output: 3Explanation:The following are Bitwise AND of all possible subarrays are:
{1}, Bitwise AND is 1.
{1, 2}, Bitwise AND is 0.
{1, 2, 3}, Bitwise AND is 0.
{2}, Bitwise AND is 2.
{2, 3}, Bitwise AND is 2.
{3}, Bitwise AND is 3.
{1}, Bitwise AND is 1.
{1, 2}, Bitwise AND is 0.
{1, 2, 3}, Bitwise AND is 0.
{2}, Bitwise AND is 2.
{2, 3}, Bitwise AND is 2.
{3}, Bitwise AND is 3.
The Bitwise OR of all the above values is 3.
Input: arr[] = {1, 4, 2, 10}Output: 15
Naive Approach: The simplest approach to solve the given problem is to generate all possible subarray of the given array and then find the Bitwise OR of all Bitwise AND of all the generated subarray as the result.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the Bitwise OR
// of Bitwise AND of all subarrays
void findbitwiseOR(int* a, int n)
{
// Stores the required result
int res = 0;
// Generate all the subarrays
for (int i = 0; i < n; i++) {
// Store the current element
int curr_sub_array = a[i];
// Find the Bitwise OR
res = res | curr_sub_array;
for (int j = i; j < n; j++) {
// Update the result
curr_sub_array = curr_sub_array
& a[j];
res = res | curr_sub_array;
}
}
// Print the result
cout << res;
}
// Driver Code
int main()
{
int A[] = { 1, 2, 3 };
int N = sizeof(A) / sizeof(A[0]);
findbitwiseOR(A, N);
return 0;
}
// Java program for the above approach
public class GFG {
// Function to find the Bitwise OR
// of Bitwise AND of all subarrays
static void findbitwiseOR(int[] a, int n)
{
// Stores the required result
int res = 0;
// Generate all the subarrays
for (int i = 0; i < n; i++) {
// Store the current element
int curr_sub_array = a[i];
// Find the Bitwise OR
res = res | curr_sub_array;
for (int j = i; j < n; j++) {
// Update the result
curr_sub_array = curr_sub_array & a[j];
res = res | curr_sub_array;
}
}
// Print the result
System.out.println(res);
}
// Driver code
public static void main(String[] args)
{
int A[] = { 1, 2, 3 };
int N = A.length;
findbitwiseOR(A, N);
}
}
// This code is contributed by abhinavjain194
# Python3 program for the above approach
# Function to find the Bitwise OR
# of Bitwise AND of all subarrays
def findbitwiseOR(a, n):
# Stores the required result
res = 0
# Generate all the subarrays
for i in range(n):
# Store the current element
curr_sub_array = a[i]
# Find the Bitwise OR
res = res | curr_sub_array
for j in range(i, n):
# Update the result
curr_sub_array = curr_sub_array & a[j]
res = res | curr_sub_array
# Print the result
print (res)
# Driver Code
if __name__ == '__main__':
A = [ 1, 2, 3 ]
N = len(A)
findbitwiseOR(A, N)
# This code is contributed by mohit kumar 29
// C# program for the above approach
using System;
class GFG{
// Function to find the Bitwise OR
// of Bitwise AND of all subarrays
static void findbitwiseOR(int[] a, int n)
{
// Stores the required result
int res = 0;
// Generate all the subarrays
for (int i = 0; i < n; i++) {
// Store the current element
int curr_sub_array = a[i];
// Find the Bitwise OR
res = res | curr_sub_array;
for (int j = i; j < n; j++) {
// Update the result
curr_sub_array = curr_sub_array & a[j];
res = res | curr_sub_array;
}
}
// Print the result
Console.Write(res);
}
// Driver code
static void Main()
{
int[] A = { 1, 2, 3 };
int N = A.Length;
findbitwiseOR(A, N);
}
}
// This code is contributed by sanjoy_62.
<script>
// JavaScript program for the above approach
// Function to find the Bitwise OR
// of Bitwise AND of all subarrays
function findbitwiseOR(a, n)
{
// Stores the required result
let res = 0;
// Generate all the subarrays
for (let i = 0; i < n; i++) {
// Store the current element
let curr_sub_array = a[i];
// Find the Bitwise OR
res = res | curr_sub_array;
for (let j = i; j < n; j++) {
// Update the result
curr_sub_array = curr_sub_array & a[j];
res = res | curr_sub_array;
}
}
// Print the result
document.write(res);
}
// Driver Code
let A = [ 1, 2, 3 ];
let N = A.length;
findbitwiseOR(A, N);
</script>
3
Time Complexity: O(N2)Auxiliary Space: O(1)
Efficient Approach: The above approach can also be optimized based on the observation that the Bitwise AND of any subarray is always less than or equal to the first element in the subarray. Therefore, the maximum possible value is the Bitwise AND of the subarrays are the elements themselves. Therefore, the task is reduced to finding the Bitwise OR of all the array elements as the result.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the Bitwise OR of
// Bitwise AND of all consecutive
// subsets of the array
void findbitwiseOR(int* a, int n)
{
// Stores the required result
int res = 0;
// Traverse the given array
for (int i = 0; i < n; i++)
res = res | a[i];
// Print the result
cout << res;
}
// Driver Code
int main()
{
int A[] = { 1, 2, 3 };
int N = sizeof(A) / sizeof(A[0]);
findbitwiseOR(A, N);
return 0;
}
// Java program for the above approach
import java.io.*;
class GFG{
// Function to find the Bitwise OR of
// Bitwise AND of all consecutive
// subsets of the array
static void findbitwiseOR(int[] a, int n)
{
// Stores the required result
int res = 0;
// Traverse the given array
for(int i = 0; i < n; i++)
res = res | a[i];
// Print the result
System.out.println(res);
}
// Driver Code
public static void main(String[] args)
{
int[] A = { 1, 2, 3 };
int N = A.length;
findbitwiseOR(A, N);
}
}
// This code is contributed by Dharanendra L V.
# Python3 program for the above approach
# Function to find the Bitwise OR of
# Bitwise AND of all consecutive
# subsets of the array
def findbitwiseOR(a, n):
# Stores the required result
res = 0
# Traverse the given array
for i in range(n):
res = res | a[i]
# Print the result
print(res)
# Driver Code
if __name__ == '__main__':
A = [ 1, 2, 3 ]
N = len(A)
findbitwiseOR(A, N)
# This code is contributed by ipg2016107
// C# program for the above approach
using System;
class GFG{
// Function to find the Bitwise OR of
// Bitwise AND of all consecutive
// subsets of the array
static void findbitwiseOR(int[] a, int n)
{
// Stores the required result
int res = 0;
// Traverse the given array
for(int i = 0; i < n; i++)
res = res | a[i];
// Print the result
Console.Write(res);
}
// Driver Code
public static void Main()
{
int[] A = { 1, 2, 3 };
int N = A.Length;
findbitwiseOR(A, N);
}
}
// This code is contributed by ukasp
<script>
// JavaScript program for the above approach
// Function to find the Bitwise OR of
// Bitwise AND of all consecutive
// subsets of the array
function findbitwiseOR(a, n)
{
// Stores the required result
var res = 0;
var i;
// Traverse the given array
for (i = 0; i < n; i++)
res = res | a[i];
// Print the result
document.write(res);
}
// Driver Code
var A = [1, 2, 3];
var N = A.length;
findbitwiseOR(A, N);
</script>
3
Time Complexity: O(N)Auxiliary Space: O(1)
abhinavjain194
sanjoy_62
mohit kumar 29
ukasp
susmitakundugoaldanga
SURENDRA_GANGWAR
dharanendralv23
ipg2016107
Kirti_Mangal
Bitwise-AND
Bitwise-OR
subarray
Arrays
Bit Magic
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Next Greater Element
Window Sliding Technique
Count pairs with given sum
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Count set bits in an integer
Cyclic Redundancy Check and Modulo-2 Division
|
[
{
"code": null,
"e": 24507,
"s": 24476,
"text": " \n20 Oct, 2021\n"
},
{
"code": null,
"e": 24651,
"s": 24507,
"text": "Given an array arr[] consisting of N positive integers, the task is to find the Bitwise OR of Bitwise AND of all subarrays of the given arrays."
},
{
"code": null,
"e": 24661,
"s": 24651,
"text": "Examples:"
},
{
"code": null,
"e": 24767,
"s": 24661,
"text": "Input: arr[] = {1, 2, 3}Output: 3Explanation:The following are Bitwise AND of all possible subarrays are:"
},
{
"code": null,
"e": 24919,
"s": 24767,
"text": "\n{1}, Bitwise AND is 1.\n{1, 2}, Bitwise AND is 0.\n{1, 2, 3}, Bitwise AND is 0.\n{2}, Bitwise AND is 2.\n{2, 3}, Bitwise AND is 2.\n{3}, Bitwise AND is 3.\n"
},
{
"code": null,
"e": 24942,
"s": 24919,
"text": "{1}, Bitwise AND is 1."
},
{
"code": null,
"e": 24968,
"s": 24942,
"text": "{1, 2}, Bitwise AND is 0."
},
{
"code": null,
"e": 24997,
"s": 24968,
"text": "{1, 2, 3}, Bitwise AND is 0."
},
{
"code": null,
"e": 25020,
"s": 24997,
"text": "{2}, Bitwise AND is 2."
},
{
"code": null,
"e": 25046,
"s": 25020,
"text": "{2, 3}, Bitwise AND is 2."
},
{
"code": null,
"e": 25069,
"s": 25046,
"text": "{3}, Bitwise AND is 3."
},
{
"code": null,
"e": 25114,
"s": 25069,
"text": "The Bitwise OR of all the above values is 3."
},
{
"code": null,
"e": 25153,
"s": 25114,
"text": "Input: arr[] = {1, 4, 2, 10}Output: 15"
},
{
"code": null,
"e": 25367,
"s": 25153,
"text": "Naive Approach: The simplest approach to solve the given problem is to generate all possible subarray of the given array and then find the Bitwise OR of all Bitwise AND of all the generated subarray as the result."
},
{
"code": null,
"e": 25418,
"s": 25367,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25422,
"s": 25418,
"text": "C++"
},
{
"code": null,
"e": 25427,
"s": 25422,
"text": "Java"
},
{
"code": null,
"e": 25435,
"s": 25427,
"text": "Python3"
},
{
"code": null,
"e": 25438,
"s": 25435,
"text": "C#"
},
{
"code": null,
"e": 25449,
"s": 25438,
"text": "Javascript"
},
{
"code": "\n\n\n\n\n\n\n// C++ program for the above approach\n \n#include <bits/stdc++.h>\nusing namespace std;\n \n// Function to find the Bitwise OR\n// of Bitwise AND of all subarrays\nvoid findbitwiseOR(int* a, int n)\n{\n // Stores the required result\n int res = 0;\n \n // Generate all the subarrays\n for (int i = 0; i < n; i++) {\n \n // Store the current element\n int curr_sub_array = a[i];\n \n // Find the Bitwise OR\n res = res | curr_sub_array;\n \n for (int j = i; j < n; j++) {\n \n // Update the result\n curr_sub_array = curr_sub_array\n & a[j];\n res = res | curr_sub_array;\n }\n }\n \n // Print the result\n cout << res;\n}\n \n// Driver Code\nint main()\n{\n int A[] = { 1, 2, 3 };\n int N = sizeof(A) / sizeof(A[0]);\n findbitwiseOR(A, N);\n \n return 0;\n}\n\n\n\n\n\n",
"e": 26325,
"s": 25459,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// Java program for the above approach\npublic class GFG {\n \n // Function to find the Bitwise OR\n // of Bitwise AND of all subarrays\n static void findbitwiseOR(int[] a, int n)\n {\n // Stores the required result\n int res = 0;\n \n // Generate all the subarrays\n for (int i = 0; i < n; i++) {\n \n // Store the current element\n int curr_sub_array = a[i];\n \n // Find the Bitwise OR\n res = res | curr_sub_array;\n \n for (int j = i; j < n; j++) {\n \n // Update the result\n curr_sub_array = curr_sub_array & a[j];\n res = res | curr_sub_array;\n }\n }\n \n // Print the result\n System.out.println(res);\n }\n // Driver code\n public static void main(String[] args)\n {\n int A[] = { 1, 2, 3 };\n int N = A.length;\n findbitwiseOR(A, N);\n }\n}\n// This code is contributed by abhinavjain194\n\n\n\n\n\n",
"e": 27318,
"s": 26335,
"text": null
},
{
"code": "\n\n\n\n\n\n\n# Python3 program for the above approach\n \n# Function to find the Bitwise OR\n# of Bitwise AND of all subarrays\ndef findbitwiseOR(a, n):\n \n # Stores the required result\n res = 0\n \n # Generate all the subarrays\n for i in range(n):\n \n # Store the current element\n curr_sub_array = a[i]\n \n # Find the Bitwise OR\n res = res | curr_sub_array\n \n for j in range(i, n):\n \n # Update the result\n curr_sub_array = curr_sub_array & a[j]\n res = res | curr_sub_array\n \n # Print the result\n print (res)\n \n# Driver Code\nif __name__ == '__main__':\n \n A = [ 1, 2, 3 ]\n N = len(A)\n \n findbitwiseOR(A, N)\n \n# This code is contributed by mohit kumar 29\n\n\n\n\n\n",
"e": 28099,
"s": 27328,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// C# program for the above approach\nusing System;\n \nclass GFG{\n \n // Function to find the Bitwise OR\n // of Bitwise AND of all subarrays\n static void findbitwiseOR(int[] a, int n)\n {\n // Stores the required result\n int res = 0;\n \n // Generate all the subarrays\n for (int i = 0; i < n; i++) {\n \n // Store the current element\n int curr_sub_array = a[i];\n \n // Find the Bitwise OR\n res = res | curr_sub_array;\n \n for (int j = i; j < n; j++) {\n \n // Update the result\n curr_sub_array = curr_sub_array & a[j];\n res = res | curr_sub_array;\n }\n }\n \n // Print the result\n Console.Write(res);\n }\n \n// Driver code\nstatic void Main()\n{\n int[] A = { 1, 2, 3 };\n int N = A.Length;\n findbitwiseOR(A, N);\n \n}\n}\n \n// This code is contributed by sanjoy_62.\n\n\n\n\n\n",
"e": 29065,
"s": 28109,
"text": null
},
{
"code": "\n\n\n\n\n\n\n<script>\n \n// JavaScript program for the above approach\n \n // Function to find the Bitwise OR\n // of Bitwise AND of all subarrays\n function findbitwiseOR(a, n)\n {\n // Stores the required result\n let res = 0;\n \n // Generate all the subarrays\n for (let i = 0; i < n; i++) {\n \n // Store the current element\n let curr_sub_array = a[i];\n \n // Find the Bitwise OR\n res = res | curr_sub_array;\n \n for (let j = i; j < n; j++) {\n \n // Update the result\n curr_sub_array = curr_sub_array & a[j];\n res = res | curr_sub_array;\n }\n }\n \n // Print the result\n document.write(res);\n }\n \n// Driver Code\n \n let A = [ 1, 2, 3 ];\n let N = A.length;\n findbitwiseOR(A, N);\n \n</script> \n\n\n\n\n\n",
"e": 29949,
"s": 29075,
"text": null
},
{
"code": null,
"e": 29951,
"s": 29949,
"text": "3"
},
{
"code": null,
"e": 29997,
"s": 29953,
"text": "Time Complexity: O(N2)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 30388,
"s": 29997,
"text": "Efficient Approach: The above approach can also be optimized based on the observation that the Bitwise AND of any subarray is always less than or equal to the first element in the subarray. Therefore, the maximum possible value is the Bitwise AND of the subarrays are the elements themselves. Therefore, the task is reduced to finding the Bitwise OR of all the array elements as the result."
},
{
"code": null,
"e": 30439,
"s": 30388,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 30443,
"s": 30439,
"text": "C++"
},
{
"code": null,
"e": 30448,
"s": 30443,
"text": "Java"
},
{
"code": null,
"e": 30456,
"s": 30448,
"text": "Python3"
},
{
"code": null,
"e": 30459,
"s": 30456,
"text": "C#"
},
{
"code": null,
"e": 30470,
"s": 30459,
"text": "Javascript"
},
{
"code": "\n\n\n\n\n\n\n// C++ program for the above approach\n \n#include <bits/stdc++.h>\nusing namespace std;\n \n// Function to find the Bitwise OR of\n// Bitwise AND of all consecutive\n// subsets of the array\nvoid findbitwiseOR(int* a, int n)\n{\n // Stores the required result\n int res = 0;\n \n // Traverse the given array\n for (int i = 0; i < n; i++)\n res = res | a[i];\n \n // Print the result\n cout << res;\n}\n \n// Driver Code\nint main()\n{\n int A[] = { 1, 2, 3 };\n int N = sizeof(A) / sizeof(A[0]);\n findbitwiseOR(A, N);\n \n return 0;\n}\n\n\n\n\n\n",
"e": 31039,
"s": 30480,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// Java program for the above approach\nimport java.io.*;\n \nclass GFG{\n \n// Function to find the Bitwise OR of\n// Bitwise AND of all consecutive\n// subsets of the array\nstatic void findbitwiseOR(int[] a, int n)\n{\n \n // Stores the required result\n int res = 0;\n \n // Traverse the given array\n for(int i = 0; i < n; i++)\n res = res | a[i];\n \n // Print the result\n System.out.println(res);\n}\n \n// Driver Code\npublic static void main(String[] args)\n{\n int[] A = { 1, 2, 3 };\n int N = A.length;\n \n findbitwiseOR(A, N);\n}\n}\n \n// This code is contributed by Dharanendra L V.\n\n\n\n\n\n",
"e": 31673,
"s": 31049,
"text": null
},
{
"code": "\n\n\n\n\n\n\n# Python3 program for the above approach\n \n# Function to find the Bitwise OR of\n# Bitwise AND of all consecutive\n# subsets of the array\ndef findbitwiseOR(a, n):\n \n # Stores the required result\n res = 0\n \n # Traverse the given array\n for i in range(n):\n res = res | a[i]\n \n # Print the result\n print(res)\n \n# Driver Code\nif __name__ == '__main__':\n \n A = [ 1, 2, 3 ]\n N = len(A)\n \n findbitwiseOR(A, N)\n \n# This code is contributed by ipg2016107\n\n\n\n\n\n",
"e": 32186,
"s": 31683,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// C# program for the above approach\nusing System;\n \nclass GFG{\n \n// Function to find the Bitwise OR of\n// Bitwise AND of all consecutive\n// subsets of the array\nstatic void findbitwiseOR(int[] a, int n)\n{\n \n // Stores the required result\n int res = 0;\n \n // Traverse the given array\n for(int i = 0; i < n; i++)\n res = res | a[i];\n \n // Print the result\n Console.Write(res);\n}\n \n// Driver Code\npublic static void Main()\n{\n int[] A = { 1, 2, 3 };\n int N = A.Length;\n \n findbitwiseOR(A, N);\n}\n}\n \n// This code is contributed by ukasp\n\n\n\n\n\n",
"e": 32783,
"s": 32196,
"text": null
},
{
"code": "\n\n\n\n\n\n\n<script>\n \n// JavaScript program for the above approach\n \n// Function to find the Bitwise OR of\n// Bitwise AND of all consecutive\n// subsets of the array\nfunction findbitwiseOR(a, n)\n{\n // Stores the required result\n var res = 0;\n \n var i;\n // Traverse the given array\n for (i = 0; i < n; i++)\n res = res | a[i];\n \n // Print the result\n document.write(res);\n}\n \n// Driver Code\n var A = [1, 2, 3];\n var N = A.length;\n findbitwiseOR(A, N);\n \n</script>\n\n\n\n\n\n",
"e": 33301,
"s": 32793,
"text": null
},
{
"code": null,
"e": 33303,
"s": 33301,
"text": "3"
},
{
"code": null,
"e": 33348,
"s": 33305,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 33363,
"s": 33348,
"text": "abhinavjain194"
},
{
"code": null,
"e": 33373,
"s": 33363,
"text": "sanjoy_62"
},
{
"code": null,
"e": 33388,
"s": 33373,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 33394,
"s": 33388,
"text": "ukasp"
},
{
"code": null,
"e": 33416,
"s": 33394,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 33433,
"s": 33416,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 33449,
"s": 33433,
"text": "dharanendralv23"
},
{
"code": null,
"e": 33460,
"s": 33449,
"text": "ipg2016107"
},
{
"code": null,
"e": 33473,
"s": 33460,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 33487,
"s": 33473,
"text": "\nBitwise-AND\n"
},
{
"code": null,
"e": 33500,
"s": 33487,
"text": "\nBitwise-OR\n"
},
{
"code": null,
"e": 33511,
"s": 33500,
"text": "\nsubarray\n"
},
{
"code": null,
"e": 33520,
"s": 33511,
"text": "\nArrays\n"
},
{
"code": null,
"e": 33532,
"s": 33520,
"text": "\nBit Magic\n"
},
{
"code": null,
"e": 33547,
"s": 33532,
"text": "\nMathematical\n"
},
{
"code": null,
"e": 33752,
"s": 33547,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 33773,
"s": 33752,
"text": "Next Greater Element"
},
{
"code": null,
"e": 33798,
"s": 33773,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 33825,
"s": 33798,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 33874,
"s": 33825,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 33912,
"s": 33874,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 33939,
"s": 33912,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 33985,
"s": 33939,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 34053,
"s": 33985,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 34082,
"s": 34053,
"text": "Count set bits in an integer"
}
] |
AVL Tree Insertion | Practice | GeeksforGeeks
|
Given a AVL tree and N values to be inserted in the tree. Write a function to insert a given value into the tree.
Example 1:
​N = 3
Values to be inserted = {5,1,4}
Input:
Value to be inserted = 5
Output:
5
Input :
Value to be inserted = 1
Output:
5
/
1
​Input :
Value to be inserted = 4
Output:
4
/ \
1 5
Your Task:
You dont need to read input or print anything. Complete the function insertToAVL() which takes the root of the tree and the value of the node to be inserted as input parameters and returns the root of the modified tree.
Note:
The tree will be checked after each insertion.
If it violates the properties of balanced BST, an error message will be printed followed by the inorder traversal of the tree at that moment.
If instead all insertions are successful, inorder traversal of tree will be printed.
Expected Time Complexity: O(log N)
Expected Auxiliary Space: O(height of tree)
Constraints:
1 ≤ N ≤ 500
0
gyaanutsukin 29 minutes
class Solution {
static int height(Node root) {
if (root == null) {
return 0;
}
return root.height;
}
static int calculateBalanceFactor(Node root) {
if (root == null) {
return 0;
}
return height(root.left) - height(root.right);
}
Node rotateRight(Node x) {
if (x == null) {
return x;
}
Node y = x.left;
Node yR = y.right;
// Perform rotation
x.left = yR;
y.right = x;
// Update heights --> order of height updation is important
x.height = 1 + Math.max(height(x.left), height(x.right));
y.height = 1 + Math.max(height(y.left), height(y.right));
return y;
}
Node rotateLeft(Node x) {
if (x == null) {
return x;
}
Node y = x.right;
Node yL = y.left;
// Perform Rotation
x.right = yL;
y.left = x;
// Update heights
x.height = 1 + Math.max(height(x.left), height(x.right));
y.height = 1 + Math.max(height(y.left), height(y.right));
return y;
}
public Node insertToAVL(Node root, int data) {
/* I. Apply Normal BST Insertion */
// Base Case
if (root == null) {
return new Node(data);
}
if (data < root.data) {
root.left = insertToAVL(root.left, data);
} else if (data > root.data) {
root.right = insertToAVL(root.right, data);
} else { // data == root.data => duplicates are nt allowed
return root;
}
/* II. Update current node's height */
root.height = 1 + Math.max(height(root.left), height(root.right));
/* III. Calculate the Balance Factor of the current node */
int balance = calculateBalanceFactor(root);
/* IV. Check for cases of rotation */
// Left Imbalance
if (balance > 1) {
// Right GrandChild is Greater --> Left Right Imbalance
if (data > root.left.data) {
root.left = rotateLeft(root.left);
}
// Common step for both LL and LR
return rotateRight(root);
}
// Right Imbalance
if (balance < -1) {
// Left Grandhild is Lesser --> Right Left Imbalance
if (data < root.right.data) {
root.right = rotateRight(root.right);
}
// Common step for both RR and RL
return rotateLeft(root);
}
return root;
}
}
0
patildhiren442 months ago
// Java - 0.8
int height(Node node){
if(node == null){
return 0;
}
return node.height;
}
int getbalance(Node node){
if(node==null){
return 0;
}
return height(node.left) - height(node.right);
}
Node rightRo(Node node){
Node x = node.left;
Node y = x.right;
x.right = node;
node.left = y;
node.height = 1 + Math.max(height(node.left), height(node.right));
x.height = 1 + Math.max(height(x.left), height(x.right));
return x;
}
Node leftRo(Node node){
Node x = node.right;
Node y = x.left;
x.left = node;
node.right = y;
node.height = 1 + Math.max(height(node.left), height(node.right));
x.height = 1 + Math.max(height(x.left), height(x.right));
return x;
}
public Node insertToAVL(Node node,int data)
{
//code here
if(node==null){
return new Node(data);
}
if(data < node.data){
node.left = insertToAVL(node.left, data);
}else if(data > node.data){
node.right = insertToAVL(node.right, data);
}else{
return node;
}
node.height = 1 + Math.max(height(node.left), height(node.right));
int bal = getbalance(node);
if(bal > 1 && data < node.left.data){
return rightRo(node);
}
if(bal < -1 && data > node.right.data){
return leftRo(node);
}
if(bal > 1 && data > node.left.data){
node.left = leftRo(node.left);
return rightRo(node);
}
if(bal < -1 && data < node.right.data){
node.right = rightRo(node.right);
return leftRo(node);
}
return node;
}
0
lindan1232 months ago
int height(Node *N)
{
if (N == NULL)
return 0;
return N->height;
}
Node *rightRotate(Node *y)
{
Node *x = y->left;
Node *T2 = x->right;
x->right = y;
y->left = T2;
y->height = max(height(y->left),
height(y->right)) + 1;
x->height = max(height(x->left),
height(x->right)) + 1;
return x;
}
Node *leftRotate(Node *x)
{
Node *y = x->right;
Node *T2 = y->left;
y->left = x;
x->right = T2;
x->height = max(height(x->left),
height(x->right)) + 1;
y->height = max(height(y->left),
height(y->right)) + 1;
return y;
}
int getBalance(Node *N)
{
if (N == NULL)
return 0;
return height(N->left) - height(N->right);
}
Node* insertToAVL(Node* node, int key)
{
if (node == NULL)
return(new Node(key));
if (key < node->data)
node->left = insertToAVL(node->left, key);
else if (key > node->data)
node->right = insertToAVL(node->right, key);
else
return node;
node->height = 1 + max(height(node->left),
height(node->right));
int balance = getBalance(node);
if (balance > 1 && key < node->left->data)
return rightRotate(node);
if (balance < -1 && key > node->right->data)
return leftRotate(node);
if (balance > 1 && key > node->left->data)
{
node->left = leftRotate(node->left);
return rightRotate(node);
}
if (balance < -1 && key < node->right->data)
{
node->right = rightRotate(node->right);
return leftRotate(node);
}
return node;
}
Time Taken : 0.1sec
Cpp
+1
ghoshghoshbishal2 months ago
If you are thinking your code is right but getting the wrong answer, that you don't know why, then there may be a possibility that you are making a mistake in calculating the height inside the rotateLeft() or rotateRight() function. You first need to calculate the height of the bottom node, then calculate the height of the upper node. Let say in rotateRight(), after performing the rotation, you want to return node y, and x is the right node of y, then calculate height of node x first then calculate height of node y.
0
ajeetkumarece222 months ago
int height(Node *root){
if(root==NULL) return 0;
else
return root->height;
}
int getBalance_factor(Node *root){
if(root==NULL) return 0;
else
return height(root->left)-height(root->right);
}
Node *rightRotate(Node *y){
Node *x=y->left;
Node *T2=x->right;
x->right=y;
y->left=T2;
y->height=max(height(y->left),height(y->right))+1;
x->height=max(height(x->left),height(x->right))+1;
return x;
}
Node *leftRotate(Node *x){
Node *y=x->right;
Node *T2=y->left;
y->left=x;
x->right=T2;
x->height=max(height(x->left),height(x->right))+1;
y->height=max(height(y->left),height(y->right))+1;
return y;
}
Node* insertToAVL(Node* root, int key)
{
//Your code here
if(root==NULL) return new Node(key);
else if(key < root->data){
root->left=insertToAVL(root->left,key);
}
else if(key > root->data){
root->right=insertToAVL(root->right,key);
}
else return root;
//update the height of this Node
root->height=max(height(root->left),height(root->right))+1;
//get balance factor of this Node
int balance=getBalance_factor(root);
//now check Node is balanced or not then do rotation
//for right right case
if(balance < -1 && key > root->right->data){
return leftRotate(root);
}
//for left left case
if(balance > 1 && key < root->left->data){
return rightRotate(root);
}
//right left case
if(balance < -1 && key < root->right->data){
root->right=rightRotate(root->right);
return leftRotate(root);
}
//left right case
if(balance > 1 && key > root->left->data){
root->left=leftRotate(root->left);
return rightRotate(root);
}
return root;
}
-1
tf1536 months ago
class Solution{
int height(Node *node){
if(!node)
return 0;
return max(height(node->left),height(node->right))+1;
}
int BF(Node *node){
if(!node)
return -1;
else
return height(node->left)-height(node->right);
}
Node *lr(Node *node){
Node *parent=node->left;
Node *temp=parent->right;
parent->right=node;
node->left=temp;
return parent;
}
Node *rr(Node *node){
Node *parent=node->right;
Node *temp=parent->left;
parent->left=node;
node->right=temp;
return parent;
}
public:
Node* insertToAVL(Node* node, int data)
{
if(!node)
return new Node(data);
if(node->data<data)
node->right= insertToAVL(node->right,data);
else if(node->data>data)
node->left=insertToAVL(node->left,data);
else
return node;
int bf=BF(node);
if(bf>1 and data<node->left->data){
return lr(node);
}
if(bf<-1 and data>node->right->data){
return rr(node);
}
if(bf>1 and data>node->left->data){
node->left=rr(node->left);
return lr(node);
}
if(bf<-1 and data<node->right->data){
node->right=lr(node->right);
return rr(node);
}
return node;
}
};
+1
thejiteshkumar7 months ago
Steps:
find heightget balanced factor(bf)implement right and left rotateUse normal BST insertion with extra conditions use bf value and given data/key value forleft leftright rightleft rightright leftreturn root
find height
get balanced factor(bf)
implement right and left rotate
Use normal BST insertion with extra conditions
use bf value and given data/key value for
left left
right right
left right
right left
return root
Link to solution (only the above steps and code for class solution is given:
https://ide.geeksforgeeks.org/GeqlbCMrSx
0
thejiteshkumar
This comment was deleted.
+1
Apoorv Singh8 months ago
Apoorv Singh
I don't know why but the code is working correct on my local environment but here it is inserting only first three nodes in the tree. How to resolve this?
0
Y0U Cha*ngE9 months ago
Y0U Cha*ngE
What's wrong in this code// LL means Left imbalance's rotation// LR means Left-right imbalance's rotation// RR means Right imbalance's rotation// RL means Right-left imbalance's rotation
int findheight(Node *root) { if(root==NULL) return 0; return (1+ max(findheight(root->left),findheight(root->right))); } void updateheight(Node *root) { if(root==NULL) return; root->height= findheight(root); } int balancefactor(Node *root) { if(root==NULL) return 0; else return (((root->left)->height) - ((root->right)->height)); } /*You are required to complete this method */ Node* LL(Node* root) { Node *l=root->left; Node*lr=l->right; l->right=root; root->left=lr; return l; } Node* RR(Node* root) { Node *r=root->right; Node* rl=r->left; r->left=root; root->right=rl; return r;
} Node* LR(Node *root) { Node *l=root->left, *lr=l->right; Node *lrl=lr->left, *lrr=lr->right; lr->right=root; root->left=lrr; lr->left=l; l->right=lrl; return lr; } Node* RL(Node *root) { Node *r=root->right, *rl=r->left; Node *rll=rl->left, *rlr=rl->right; rl->left=root; root->right=rll; rl->right=r; r->left=rlr; return rl; } Node* insertToAVL(Node* node, int data) { if(node==NULL) { Node *root=new Node(data); root->height=1; return root; } if(data > node->data) node->right=insertToAVL(node->right,data); else if(data< node->data) node->left= insertToAVL(node->left,data); else return node;
updateheight(node); int bl=balancefactor(node);
if( abs(bl) <=1) return node; else { if((bl==2) && data<node->left->data) return LL(node); else if((bl==2) && data> node->left->data) return LR(node); else if((bl==-2) && data>node->right->data) return RR(node); else if(bl==-2 && data <node->right->data) return RL(node); }
}};
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": 352,
"s": 238,
"text": "Given a AVL tree and N values to be inserted in the tree. Write a function to insert a given value into the tree."
},
{
"code": null,
"e": 363,
"s": 352,
"text": "Example 1:"
},
{
"code": null,
"e": 594,
"s": 363,
"text": "​N = 3\nValues to be inserted = {5,1,4}\n\nInput: \nValue to be inserted = 5\nOutput:\n 5\n\nInput : \nValue to be inserted = 1\nOutput:\n 5\n /\n 1\n\n​Input : \nValue to be inserted = 4\nOutput:\n 4\n / \\\n 1 5"
},
{
"code": null,
"e": 828,
"s": 594,
"text": "\nYour Task: \nYou dont need to read input or print anything. Complete the function insertToAVL() which takes the root of the tree and the value of the node to be inserted as input parameters and returns the root of the modified tree."
},
{
"code": null,
"e": 1109,
"s": 828,
"text": "Note:\nThe tree will be checked after each insertion. \nIf it violates the properties of balanced BST, an error message will be printed followed by the inorder traversal of the tree at that moment.\nIf instead all insertions are successful, inorder traversal of tree will be printed."
},
{
"code": null,
"e": 1189,
"s": 1109,
"text": "\nExpected Time Complexity: O(log N)\nExpected Auxiliary Space: O(height of tree)"
},
{
"code": null,
"e": 1215,
"s": 1189,
"text": "\nConstraints:\n1 ≤ N ≤ 500"
},
{
"code": null,
"e": 1217,
"s": 1215,
"text": "0"
},
{
"code": null,
"e": 1241,
"s": 1217,
"text": "gyaanutsukin 29 minutes"
},
{
"code": null,
"e": 3996,
"s": 1241,
"text": "class Solution {\n static int height(Node root) {\n if (root == null) {\n return 0;\n }\n return root.height;\n }\n \n static int calculateBalanceFactor(Node root) {\n if (root == null) {\n return 0;\n }\n \n return height(root.left) - height(root.right);\n }\n \n Node rotateRight(Node x) {\n if (x == null) {\n return x;\n }\n \n Node y = x.left;\n Node yR = y.right;\n \n // Perform rotation\n x.left = yR;\n y.right = x;\n \n // Update heights --> order of height updation is important\n x.height = 1 + Math.max(height(x.left), height(x.right));\n y.height = 1 + Math.max(height(y.left), height(y.right));\n \n return y;\n }\n \n Node rotateLeft(Node x) {\n if (x == null) {\n return x;\n }\n \n Node y = x.right;\n Node yL = y.left;\n \n // Perform Rotation\n x.right = yL;\n y.left = x;\n \n // Update heights\n x.height = 1 + Math.max(height(x.left), height(x.right));\n y.height = 1 + Math.max(height(y.left), height(y.right));\n \n return y;\n }\n \n \n public Node insertToAVL(Node root, int data) {\n /* I. Apply Normal BST Insertion */\n \n // Base Case\n if (root == null) {\n return new Node(data);\n }\n \n if (data < root.data) {\n root.left = insertToAVL(root.left, data);\n } else if (data > root.data) {\n root.right = insertToAVL(root.right, data);\n } else { // data == root.data => duplicates are nt allowed\n return root;\n }\n \n /* II. Update current node's height */\n root.height = 1 + Math.max(height(root.left), height(root.right));\n \n /* III. Calculate the Balance Factor of the current node */\n int balance = calculateBalanceFactor(root);\n \n /* IV. Check for cases of rotation */\n \n // Left Imbalance\n if (balance > 1) {\n // Right GrandChild is Greater --> Left Right Imbalance\n if (data > root.left.data) {\n root.left = rotateLeft(root.left);\n }\n // Common step for both LL and LR\n return rotateRight(root);\n }\n \n // Right Imbalance\n if (balance < -1) {\n // Left Grandhild is Lesser --> Right Left Imbalance\n if (data < root.right.data) {\n root.right = rotateRight(root.right);\n }\n // Common step for both RR and RL\n return rotateLeft(root);\n }\n \n return root;\n }\n}"
},
{
"code": null,
"e": 3998,
"s": 3996,
"text": "0"
},
{
"code": null,
"e": 4024,
"s": 3998,
"text": "patildhiren442 months ago"
},
{
"code": null,
"e": 4038,
"s": 4024,
"text": "// Java - 0.8"
},
{
"code": null,
"e": 6014,
"s": 4038,
"text": "int height(Node node){\n if(node == null){\n return 0;\n }\n \n return node.height;\n }\n \n int getbalance(Node node){\n if(node==null){\n return 0;\n }\n \n return height(node.left) - height(node.right);\n }\n \n Node rightRo(Node node){\n Node x = node.left;\n Node y = x.right;\n \n x.right = node;\n node.left = y;\n \n node.height = 1 + Math.max(height(node.left), height(node.right));\n x.height = 1 + Math.max(height(x.left), height(x.right));\n \n return x;\n }\n \n Node leftRo(Node node){\n Node x = node.right;\n Node y = x.left;\n \n x.left = node;\n node.right = y;\n \n node.height = 1 + Math.max(height(node.left), height(node.right));\n x.height = 1 + Math.max(height(x.left), height(x.right));\n \n return x;\n }\n \n public Node insertToAVL(Node node,int data)\n {\n //code here\n if(node==null){\n return new Node(data);\n }\n \n if(data < node.data){\n node.left = insertToAVL(node.left, data);\n }else if(data > node.data){\n node.right = insertToAVL(node.right, data);\n }else{\n return node;\n }\n \n node.height = 1 + Math.max(height(node.left), height(node.right));\n \n int bal = getbalance(node);\n \n if(bal > 1 && data < node.left.data){\n return rightRo(node);\n }\n \n if(bal < -1 && data > node.right.data){\n return leftRo(node);\n }\n \n if(bal > 1 && data > node.left.data){\n node.left = leftRo(node.left); \n return rightRo(node);\n }\n \n if(bal < -1 && data < node.right.data){\n node.right = rightRo(node.right); \n return leftRo(node);\n }\n \n return node;\n }"
},
{
"code": null,
"e": 6016,
"s": 6014,
"text": "0"
},
{
"code": null,
"e": 6038,
"s": 6016,
"text": "lindan1232 months ago"
},
{
"code": null,
"e": 7766,
"s": 6038,
"text": "int height(Node *N)\n {\n if (N == NULL)\n return 0;\n return N->height;\n }\n\nNode *rightRotate(Node *y)\n{\n Node *x = y->left;\n Node *T2 = x->right;\n \n x->right = y;\n y->left = T2;\n \n y->height = max(height(y->left),\n height(y->right)) + 1;\n x->height = max(height(x->left),\n height(x->right)) + 1;\n \n return x;\n}\n\nNode *leftRotate(Node *x)\n{\n Node *y = x->right;\n Node *T2 = y->left;\n \n y->left = x;\n x->right = T2;\n \n x->height = max(height(x->left), \n height(x->right)) + 1;\n y->height = max(height(y->left),\n height(y->right)) + 1;\n \n return y;\n}\n\nint getBalance(Node *N)\n{\n if (N == NULL)\n return 0;\n return height(N->left) - height(N->right);\n}\n\n Node* insertToAVL(Node* node, int key)\n {\n if (node == NULL)\n return(new Node(key));\n \n if (key < node->data)\n node->left = insertToAVL(node->left, key);\n else if (key > node->data)\n node->right = insertToAVL(node->right, key);\n else \n return node;\n \n \n node->height = 1 + max(height(node->left),\n height(node->right));\n \n \n int balance = getBalance(node);\n \n if (balance > 1 && key < node->left->data)\n return rightRotate(node);\n \n if (balance < -1 && key > node->right->data)\n return leftRotate(node);\n \n if (balance > 1 && key > node->left->data)\n {\n node->left = leftRotate(node->left);\n return rightRotate(node);\n }\n \n if (balance < -1 && key < node->right->data)\n {\n node->right = rightRotate(node->right);\n return leftRotate(node);\n }\n \n return node;\n }"
},
{
"code": null,
"e": 7786,
"s": 7766,
"text": "Time Taken : 0.1sec"
},
{
"code": null,
"e": 7790,
"s": 7786,
"text": "Cpp"
},
{
"code": null,
"e": 7793,
"s": 7790,
"text": "+1"
},
{
"code": null,
"e": 7822,
"s": 7793,
"text": "ghoshghoshbishal2 months ago"
},
{
"code": null,
"e": 8345,
"s": 7822,
"text": "If you are thinking your code is right but getting the wrong answer, that you don't know why, then there may be a possibility that you are making a mistake in calculating the height inside the rotateLeft() or rotateRight() function. You first need to calculate the height of the bottom node, then calculate the height of the upper node. Let say in rotateRight(), after performing the rotation, you want to return node y, and x is the right node of y, then calculate height of node x first then calculate height of node y. "
},
{
"code": null,
"e": 8347,
"s": 8345,
"text": "0"
},
{
"code": null,
"e": 8375,
"s": 8347,
"text": "ajeetkumarece222 months ago"
},
{
"code": null,
"e": 8400,
"s": 8375,
"text": " int height(Node *root){"
},
{
"code": null,
"e": 8429,
"s": 8400,
"text": " if(root==NULL) return 0;"
},
{
"code": null,
"e": 8438,
"s": 8429,
"text": " else"
},
{
"code": null,
"e": 8463,
"s": 8438,
"text": " return root->height;"
},
{
"code": null,
"e": 8465,
"s": 8463,
"text": "}"
},
{
"code": null,
"e": 8500,
"s": 8465,
"text": "int getBalance_factor(Node *root){"
},
{
"code": null,
"e": 8529,
"s": 8500,
"text": " if(root==NULL) return 0;"
},
{
"code": null,
"e": 8538,
"s": 8529,
"text": " else"
},
{
"code": null,
"e": 8591,
"s": 8538,
"text": " return height(root->left)-height(root->right);"
},
{
"code": null,
"e": 8593,
"s": 8591,
"text": "}"
},
{
"code": null,
"e": 8621,
"s": 8593,
"text": "Node *rightRotate(Node *y){"
},
{
"code": null,
"e": 8642,
"s": 8621,
"text": " Node *x=y->left;"
},
{
"code": null,
"e": 8665,
"s": 8642,
"text": " Node *T2=x->right;"
},
{
"code": null,
"e": 8681,
"s": 8665,
"text": " x->right=y;"
},
{
"code": null,
"e": 8697,
"s": 8681,
"text": " y->left=T2;"
},
{
"code": null,
"e": 8752,
"s": 8697,
"text": " y->height=max(height(y->left),height(y->right))+1;"
},
{
"code": null,
"e": 8807,
"s": 8752,
"text": " x->height=max(height(x->left),height(x->right))+1;"
},
{
"code": null,
"e": 8821,
"s": 8807,
"text": " return x;"
},
{
"code": null,
"e": 8823,
"s": 8821,
"text": "}"
},
{
"code": null,
"e": 8850,
"s": 8823,
"text": "Node *leftRotate(Node *x){"
},
{
"code": null,
"e": 8872,
"s": 8850,
"text": " Node *y=x->right;"
},
{
"code": null,
"e": 8894,
"s": 8872,
"text": " Node *T2=y->left;"
},
{
"code": null,
"e": 8909,
"s": 8894,
"text": " y->left=x;"
},
{
"code": null,
"e": 8926,
"s": 8909,
"text": " x->right=T2;"
},
{
"code": null,
"e": 8981,
"s": 8926,
"text": " x->height=max(height(x->left),height(x->right))+1;"
},
{
"code": null,
"e": 9036,
"s": 8981,
"text": " y->height=max(height(y->left),height(y->right))+1;"
},
{
"code": null,
"e": 9050,
"s": 9036,
"text": " return y;"
},
{
"code": null,
"e": 9052,
"s": 9050,
"text": "}"
},
{
"code": null,
"e": 9095,
"s": 9052,
"text": " Node* insertToAVL(Node* root, int key)"
},
{
"code": null,
"e": 9101,
"s": 9095,
"text": " {"
},
{
"code": null,
"e": 9126,
"s": 9101,
"text": " //Your code here"
},
{
"code": null,
"e": 9169,
"s": 9126,
"text": " if(root==NULL) return new Node(key);"
},
{
"code": null,
"e": 9200,
"s": 9169,
"text": " else if(key < root->data){"
},
{
"code": null,
"e": 9248,
"s": 9200,
"text": " root->left=insertToAVL(root->left,key);"
},
{
"code": null,
"e": 9254,
"s": 9248,
"text": " }"
},
{
"code": null,
"e": 9285,
"s": 9254,
"text": " else if(key > root->data){"
},
{
"code": null,
"e": 9335,
"s": 9285,
"text": " root->right=insertToAVL(root->right,key);"
},
{
"code": null,
"e": 9341,
"s": 9335,
"text": " }"
},
{
"code": null,
"e": 9363,
"s": 9341,
"text": " else return root;"
},
{
"code": null,
"e": 9400,
"s": 9363,
"text": " //update the height of this Node"
},
{
"code": null,
"e": 9464,
"s": 9400,
"text": " root->height=max(height(root->left),height(root->right))+1;"
},
{
"code": null,
"e": 9502,
"s": 9464,
"text": " //get balance factor of this Node"
},
{
"code": null,
"e": 9543,
"s": 9502,
"text": " int balance=getBalance_factor(root);"
},
{
"code": null,
"e": 9600,
"s": 9543,
"text": " //now check Node is balanced or not then do rotation"
},
{
"code": null,
"e": 9627,
"s": 9600,
"text": " //for right right case"
},
{
"code": null,
"e": 9676,
"s": 9627,
"text": " if(balance < -1 && key > root->right->data){"
},
{
"code": null,
"e": 9709,
"s": 9676,
"text": " return leftRotate(root);"
},
{
"code": null,
"e": 9715,
"s": 9709,
"text": " }"
},
{
"code": null,
"e": 9740,
"s": 9715,
"text": " //for left left case"
},
{
"code": null,
"e": 9787,
"s": 9740,
"text": " if(balance > 1 && key < root->left->data){"
},
{
"code": null,
"e": 9821,
"s": 9787,
"text": " return rightRotate(root);"
},
{
"code": null,
"e": 9827,
"s": 9821,
"text": " }"
},
{
"code": null,
"e": 9849,
"s": 9827,
"text": " //right left case"
},
{
"code": null,
"e": 9898,
"s": 9849,
"text": " if(balance < -1 && key < root->right->data){"
},
{
"code": null,
"e": 9944,
"s": 9898,
"text": " root->right=rightRotate(root->right);"
},
{
"code": null,
"e": 9977,
"s": 9944,
"text": " return leftRotate(root);"
},
{
"code": null,
"e": 9983,
"s": 9977,
"text": " }"
},
{
"code": null,
"e": 10005,
"s": 9983,
"text": " //left right case"
},
{
"code": null,
"e": 10052,
"s": 10005,
"text": " if(balance > 1 && key > root->left->data){"
},
{
"code": null,
"e": 10095,
"s": 10052,
"text": " root->left=leftRotate(root->left);"
},
{
"code": null,
"e": 10129,
"s": 10095,
"text": " return rightRotate(root);"
},
{
"code": null,
"e": 10135,
"s": 10129,
"text": " }"
},
{
"code": null,
"e": 10152,
"s": 10135,
"text": " return root;"
},
{
"code": null,
"e": 10158,
"s": 10152,
"text": " }"
},
{
"code": null,
"e": 10161,
"s": 10158,
"text": "-1"
},
{
"code": null,
"e": 10179,
"s": 10161,
"text": "tf1536 months ago"
},
{
"code": null,
"e": 11638,
"s": 10179,
"text": "class Solution{\n int height(Node *node){\n if(!node)\n return 0;\n return max(height(node->left),height(node->right))+1;\n }\n int BF(Node *node){\n if(!node)\n return -1;\n else\n return height(node->left)-height(node->right);\n }\n Node *lr(Node *node){\n Node *parent=node->left;\n Node *temp=parent->right;\n parent->right=node;\n node->left=temp;\n return parent;\n }\n Node *rr(Node *node){\n Node *parent=node->right;\n Node *temp=parent->left;\n parent->left=node;\n node->right=temp;\n return parent;\n }\n public:\n Node* insertToAVL(Node* node, int data)\n {\n if(!node)\n return new Node(data);\n \n if(node->data<data)\n node->right= insertToAVL(node->right,data);\n else if(node->data>data)\n node->left=insertToAVL(node->left,data);\n else\n return node;\n \n int bf=BF(node);\n if(bf>1 and data<node->left->data){\n return lr(node);\n }\n if(bf<-1 and data>node->right->data){\n return rr(node);\n }\n if(bf>1 and data>node->left->data){\n node->left=rr(node->left);\n return lr(node);\n }\n if(bf<-1 and data<node->right->data){\n node->right=lr(node->right);\n return rr(node);\n }\n return node;\n }\n};"
},
{
"code": null,
"e": 11641,
"s": 11638,
"text": "+1"
},
{
"code": null,
"e": 11668,
"s": 11641,
"text": "thejiteshkumar7 months ago"
},
{
"code": null,
"e": 11676,
"s": 11668,
"text": "Steps: "
},
{
"code": null,
"e": 11881,
"s": 11676,
"text": "find heightget balanced factor(bf)implement right and left rotateUse normal BST insertion with extra conditions use bf value and given data/key value forleft leftright rightleft rightright leftreturn root"
},
{
"code": null,
"e": 11893,
"s": 11881,
"text": "find height"
},
{
"code": null,
"e": 11917,
"s": 11893,
"text": "get balanced factor(bf)"
},
{
"code": null,
"e": 11949,
"s": 11917,
"text": "implement right and left rotate"
},
{
"code": null,
"e": 11997,
"s": 11949,
"text": "Use normal BST insertion with extra conditions "
},
{
"code": null,
"e": 12039,
"s": 11997,
"text": "use bf value and given data/key value for"
},
{
"code": null,
"e": 12049,
"s": 12039,
"text": "left left"
},
{
"code": null,
"e": 12061,
"s": 12049,
"text": "right right"
},
{
"code": null,
"e": 12072,
"s": 12061,
"text": "left right"
},
{
"code": null,
"e": 12083,
"s": 12072,
"text": "right left"
},
{
"code": null,
"e": 12095,
"s": 12083,
"text": "return root"
},
{
"code": null,
"e": 12172,
"s": 12095,
"text": "Link to solution (only the above steps and code for class solution is given:"
},
{
"code": null,
"e": 12213,
"s": 12172,
"text": "https://ide.geeksforgeeks.org/GeqlbCMrSx"
},
{
"code": null,
"e": 12215,
"s": 12213,
"text": "0"
},
{
"code": null,
"e": 12230,
"s": 12215,
"text": "thejiteshkumar"
},
{
"code": null,
"e": 12256,
"s": 12230,
"text": "This comment was deleted."
},
{
"code": null,
"e": 12259,
"s": 12256,
"text": "+1"
},
{
"code": null,
"e": 12284,
"s": 12259,
"text": "Apoorv Singh8 months ago"
},
{
"code": null,
"e": 12297,
"s": 12284,
"text": "Apoorv Singh"
},
{
"code": null,
"e": 12452,
"s": 12297,
"text": "I don't know why but the code is working correct on my local environment but here it is inserting only first three nodes in the tree. How to resolve this?"
},
{
"code": null,
"e": 12454,
"s": 12452,
"text": "0"
},
{
"code": null,
"e": 12478,
"s": 12454,
"text": "Y0U Cha*ngE9 months ago"
},
{
"code": null,
"e": 12490,
"s": 12478,
"text": "Y0U Cha*ngE"
},
{
"code": null,
"e": 12677,
"s": 12490,
"text": "What's wrong in this code// LL means Left imbalance's rotation// LR means Left-right imbalance's rotation// RR means Right imbalance's rotation// RL means Right-left imbalance's rotation"
},
{
"code": null,
"e": 13447,
"s": 12677,
"text": " int findheight(Node *root) { if(root==NULL) return 0; return (1+ max(findheight(root->left),findheight(root->right))); } void updateheight(Node *root) { if(root==NULL) return; root->height= findheight(root); } int balancefactor(Node *root) { if(root==NULL) return 0; else return (((root->left)->height) - ((root->right)->height)); } /*You are required to complete this method */ Node* LL(Node* root) { Node *l=root->left; Node*lr=l->right; l->right=root; root->left=lr; return l; } Node* RR(Node* root) { Node *r=root->right; Node* rl=r->left; r->left=root; root->right=rl; return r;"
},
{
"code": null,
"e": 14248,
"s": 13447,
"text": " } Node* LR(Node *root) { Node *l=root->left, *lr=l->right; Node *lrl=lr->left, *lrr=lr->right; lr->right=root; root->left=lrr; lr->left=l; l->right=lrl; return lr; } Node* RL(Node *root) { Node *r=root->right, *rl=r->left; Node *rll=rl->left, *rlr=rl->right; rl->left=root; root->right=rll; rl->right=r; r->left=rlr; return rl; } Node* insertToAVL(Node* node, int data) { if(node==NULL) { Node *root=new Node(data); root->height=1; return root; } if(data > node->data) node->right=insertToAVL(node->right,data); else if(data< node->data) node->left= insertToAVL(node->left,data); else return node;"
},
{
"code": null,
"e": 14311,
"s": 14248,
"text": " updateheight(node); int bl=balancefactor(node);"
},
{
"code": null,
"e": 14709,
"s": 14311,
"text": " if( abs(bl) <=1) return node; else { if((bl==2) && data<node->left->data) return LL(node); else if((bl==2) && data> node->left->data) return LR(node); else if((bl==-2) && data>node->right->data) return RR(node); else if(bl==-2 && data <node->right->data) return RL(node); }"
},
{
"code": null,
"e": 14717,
"s": 14709,
"text": " }};"
},
{
"code": null,
"e": 14863,
"s": 14717,
"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": 14899,
"s": 14863,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 14909,
"s": 14899,
"text": "\nProblem\n"
},
{
"code": null,
"e": 14919,
"s": 14909,
"text": "\nContest\n"
},
{
"code": null,
"e": 14982,
"s": 14919,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 15130,
"s": 14982,
"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": 15338,
"s": 15130,
"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": 15444,
"s": 15338,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Finding product of an array using recursion in JavaScript
|
We are required to write a JavaScript function that takes in an array of Integers. Our function should do the following two things −
Make use of a recursive approach.
Make use of a recursive approach.
Calculate the product of all the elements in the array.
Calculate the product of all the elements in the array.
And finally, it should return the product.
For example −
If the input array is −
const arr = [1, 3, 6, .2, 2, 5];
Then the output should be −
const output = 36;
The code for this will be −
const arr = [1, 3, 6, .2, 2, 5];
const arrayProduct = ([front, ...end]) => {
if (front === undefined) {
return 1;
};
return front * arrayProduct(end);
};
console.log(arrayProduct(arr));
And the output in the console will be −
36
|
[
{
"code": null,
"e": 1195,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in an array of Integers. Our function should do the following two things −"
},
{
"code": null,
"e": 1229,
"s": 1195,
"text": "Make use of a recursive approach."
},
{
"code": null,
"e": 1263,
"s": 1229,
"text": "Make use of a recursive approach."
},
{
"code": null,
"e": 1319,
"s": 1263,
"text": "Calculate the product of all the elements in the array."
},
{
"code": null,
"e": 1375,
"s": 1319,
"text": "Calculate the product of all the elements in the array."
},
{
"code": null,
"e": 1418,
"s": 1375,
"text": "And finally, it should return the product."
},
{
"code": null,
"e": 1432,
"s": 1418,
"text": "For example −"
},
{
"code": null,
"e": 1456,
"s": 1432,
"text": "If the input array is −"
},
{
"code": null,
"e": 1489,
"s": 1456,
"text": "const arr = [1, 3, 6, .2, 2, 5];"
},
{
"code": null,
"e": 1517,
"s": 1489,
"text": "Then the output should be −"
},
{
"code": null,
"e": 1536,
"s": 1517,
"text": "const output = 36;"
},
{
"code": null,
"e": 1564,
"s": 1536,
"text": "The code for this will be −"
},
{
"code": null,
"e": 1765,
"s": 1564,
"text": "const arr = [1, 3, 6, .2, 2, 5];\nconst arrayProduct = ([front, ...end]) => {\n if (front === undefined) {\n return 1;\n };\n return front * arrayProduct(end);\n};\nconsole.log(arrayProduct(arr));"
},
{
"code": null,
"e": 1805,
"s": 1765,
"text": "And the output in the console will be −"
},
{
"code": null,
"e": 1808,
"s": 1805,
"text": "36"
}
] |
Get the asymmetric difference of two sets in Java
|
Use removeAll() method to get the asymmetric difference of two sets.
First set −
HashSet <String> set1 = new HashSet <String>();
set1.add("Mat");
set1.add("Sat");
set1.add("Cat");
Second set −
HashSet <String> set2 = new HashSet <String>();
set2.add("Mat");
To get the asymmetric difference −
set1.removeAll(set2);
The following is an example that displays how to get the asymmetric difference between two sets −
Live Demo
import java.util.*;
public class Demo {
public static void main(String args[]) {
HashSet <String> set1 = new HashSet <String>();
HashSet <String> set2 = new HashSet <String>();
set1.add("Mat");
set1.add("Sat");
set1.add("Cat");
System.out.println("Set1 = "+ set1);
set2.add("Mat");
System.out.println("Set2 = "+ set2);
set1.removeAll(set2);
System.out.println("Asymmetric difference = "+ set1);
}
}
Set1 = [Mat, Sat, Cat]
Set2 = [Mat]
Asymmetric difference = [Sat, Cat]
|
[
{
"code": null,
"e": 1131,
"s": 1062,
"text": "Use removeAll() method to get the asymmetric difference of two sets."
},
{
"code": null,
"e": 1143,
"s": 1131,
"text": "First set −"
},
{
"code": null,
"e": 1242,
"s": 1143,
"text": "HashSet <String> set1 = new HashSet <String>();\nset1.add(\"Mat\");\nset1.add(\"Sat\");\nset1.add(\"Cat\");"
},
{
"code": null,
"e": 1255,
"s": 1242,
"text": "Second set −"
},
{
"code": null,
"e": 1320,
"s": 1255,
"text": "HashSet <String> set2 = new HashSet <String>();\nset2.add(\"Mat\");"
},
{
"code": null,
"e": 1355,
"s": 1320,
"text": "To get the asymmetric difference −"
},
{
"code": null,
"e": 1377,
"s": 1355,
"text": "set1.removeAll(set2);"
},
{
"code": null,
"e": 1475,
"s": 1377,
"text": "The following is an example that displays how to get the asymmetric difference between two sets −"
},
{
"code": null,
"e": 1486,
"s": 1475,
"text": " Live Demo"
},
{
"code": null,
"e": 1951,
"s": 1486,
"text": "import java.util.*;\npublic class Demo {\n public static void main(String args[]) {\n HashSet <String> set1 = new HashSet <String>();\n HashSet <String> set2 = new HashSet <String>();\n set1.add(\"Mat\");\n set1.add(\"Sat\");\n set1.add(\"Cat\");\n System.out.println(\"Set1 = \"+ set1);\n set2.add(\"Mat\");\n System.out.println(\"Set2 = \"+ set2);\n set1.removeAll(set2);\n System.out.println(\"Asymmetric difference = \"+ set1);\n }\n}"
},
{
"code": null,
"e": 2022,
"s": 1951,
"text": "Set1 = [Mat, Sat, Cat]\nSet2 = [Mat]\nAsymmetric difference = [Sat, Cat]"
}
] |
How to append a vector in a vector in C++?
|
To append a vector in a vector can simply be done by vector insert() method.
Begin
Declare a function show().
Pass a constructor of a vector as a parameter within show()
function.
for (auto const& i: input)
Print the value of variable i.
Declare vect1 of vector type.
Initialize values in the vect1.
Declare vect2 of vector type.
Initialize values in the vect2.
Call vect2.insert(vect2.begin(), vect1.begin(), vect1.end()) to
append the vect1 into vect2.
Print “Resultant vector is:”
Call show() function to display the value of vect2.
End.
Live Demo
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void show(vector<int> const &input) {
for (auto const& i: input) {
std::cout << i << " ";
}
}
int main() {
vector<int> v1 = { 1, 2, 3 };
vector<int> v2 = { 4, 5 };
v2.insert(v2.begin(), v1.begin(), v1.end());
cout<<"Resultant vector is:"<<endl;
show(v2);
return 0;
}
Resultant vector is:
1 2 3 4 5
|
[
{
"code": null,
"e": 1139,
"s": 1062,
"text": "To append a vector in a vector can simply be done by vector insert() method."
},
{
"code": null,
"e": 1663,
"s": 1139,
"text": "Begin\n Declare a function show().\n Pass a constructor of a vector as a parameter within show()\n function.\n for (auto const& i: input)\n Print the value of variable i.\n Declare vect1 of vector type.\n Initialize values in the vect1.\n Declare vect2 of vector type.\n Initialize values in the vect2.\n Call vect2.insert(vect2.begin(), vect1.begin(), vect1.end()) to\n append the vect1 into vect2.\n Print “Resultant vector is:”\n Call show() function to display the value of vect2.\nEnd."
},
{
"code": null,
"e": 1674,
"s": 1663,
"text": " Live Demo"
},
{
"code": null,
"e": 2051,
"s": 1674,
"text": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\nvoid show(vector<int> const &input) {\n for (auto const& i: input) {\n std::cout << i << \" \";\n }\n}\nint main() {\n vector<int> v1 = { 1, 2, 3 };\n vector<int> v2 = { 4, 5 };\n v2.insert(v2.begin(), v1.begin(), v1.end());\n cout<<\"Resultant vector is:\"<<endl;\n show(v2);\n return 0;\n}"
},
{
"code": null,
"e": 2082,
"s": 2051,
"text": "Resultant vector is:\n1 2 3 4 5"
}
] |
How to filter ng-repeat values according to ng-model using AngularJS ? - GeeksforGeeks
|
31 Oct, 2019
The ng-repeat values can be filtered according to the ng-model in AngularJS by using the value of the input field as an expression in a filter. We can set the ng-model directive on an input field to filter ng-repeat values.
Below examples illustrates the approach:Example 1: Filtering input text ng-repeat values according to ng-model. This filter will show the names of only the matching city
<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body> <center> <h1 style="color:green;">GeeksforGeeks</h1> <h3>Filter ng-reapet values according to ng-model</h3> </center> <div ng-app="app1" ng-controller="controller1"> <p>Type a city name in the input field:</p> <p> <input type="text" ng-model="testfilter"> </p> <p>Filter show the names of only the matching city.</p> <ul> <li ng-repeat="x in citynames | filter:testfilter"> {{ x }} </li> </ul> </div> <script> angular.module('app1', []).controller('controller1', function($scope) { $scope.citynames = [ 'Ahmedabad', 'Ajmer', 'Bhopal', 'Jaipur', 'Surat', 'Nagpur', 'Mumbai', 'Pune', 'Indore', 'Udaipur', 'Jodhpur', 'Jabalpur', 'Gwalior', 'Delhi', 'Lucknow', 'Banglore' ]; }); </script> </body> </html>
Output:
Example 2: Filtering input text ng-repeat values according to ng-model. This filter will shows the names of only the matching programming language after capitalizing each language by applying filter.
<!DOCTYPE html><html><head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body> <center> <h1 style="color:green;">GeeksforGeeks</h1> <h3>Filtering input text ng-repeat values according to ng-model</h3> </center> <div ng-app="app1" ng-controller="controller1"> <p>Type a programming language name in the input field:</p> <p> <input type="text" ng-model="testfilter"> </p> <p> Filter shows the names of only the matching programming language after capitalizing each language by applying filter. </p> <ul> <li ng-repeat="x in programminglanguagenames| filter:testfilter"> {{ x |myfilter}} </li> </ul> </div> <script> var app = angular.module('app1', []); app.filter('myfilter', function() { return function(x) { var i, c, txt = ""; for (i = 0; i < x.length; i++) { c = x[i]; c = c.toUpperCase(); txt += c; } return txt; }; }); app.controller('controller1', function($scope) { $scope.programminglanguagenames = [ 'cobol', 'pascal', 'ruby', 'php', 'perl', 'python', 'c', 'c++', 'java', 'html', 'css', 'javascript', 'basic', 'lisp', 'smalltalk', 'bootstrap' ]; }); </script> </body> </html>
Output:
AngularJS-Directives
Picked
AngularJS
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Auth Guards in Angular 9/10/11
How to bundle an Angular app for production?
What is AOT and JIT Compiler in Angular ?
Angular PrimeNG Dropdown Component
How to set focus on input field automatically on page load in AngularJS ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 23916,
"s": 23888,
"text": "\n31 Oct, 2019"
},
{
"code": null,
"e": 24140,
"s": 23916,
"text": "The ng-repeat values can be filtered according to the ng-model in AngularJS by using the value of the input field as an expression in a filter. We can set the ng-model directive on an input field to filter ng-repeat values."
},
{
"code": null,
"e": 24310,
"s": 24140,
"text": "Below examples illustrates the approach:Example 1: Filtering input text ng-repeat values according to ng-model. This filter will show the names of only the matching city"
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body> <center> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h3>Filter ng-reapet values according to ng-model</h3> </center> <div ng-app=\"app1\" ng-controller=\"controller1\"> <p>Type a city name in the input field:</p> <p> <input type=\"text\" ng-model=\"testfilter\"> </p> <p>Filter show the names of only the matching city.</p> <ul> <li ng-repeat=\"x in citynames | filter:testfilter\"> {{ x }} </li> </ul> </div> <script> angular.module('app1', []).controller('controller1', function($scope) { $scope.citynames = [ 'Ahmedabad', 'Ajmer', 'Bhopal', 'Jaipur', 'Surat', 'Nagpur', 'Mumbai', 'Pune', 'Indore', 'Udaipur', 'Jodhpur', 'Jabalpur', 'Gwalior', 'Delhi', 'Lucknow', 'Banglore' ]; }); </script> </body> </html>",
"e": 25566,
"s": 24310,
"text": null
},
{
"code": null,
"e": 25574,
"s": 25566,
"text": "Output:"
},
{
"code": null,
"e": 25774,
"s": 25574,
"text": "Example 2: Filtering input text ng-repeat values according to ng-model. This filter will shows the names of only the matching programming language after capitalizing each language by applying filter."
},
{
"code": "<!DOCTYPE html><html><head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body> <center> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h3>Filtering input text ng-repeat values according to ng-model</h3> </center> <div ng-app=\"app1\" ng-controller=\"controller1\"> <p>Type a programming language name in the input field:</p> <p> <input type=\"text\" ng-model=\"testfilter\"> </p> <p> Filter shows the names of only the matching programming language after capitalizing each language by applying filter. </p> <ul> <li ng-repeat=\"x in programminglanguagenames| filter:testfilter\"> {{ x |myfilter}} </li> </ul> </div> <script> var app = angular.module('app1', []); app.filter('myfilter', function() { return function(x) { var i, c, txt = \"\"; for (i = 0; i < x.length; i++) { c = x[i]; c = c.toUpperCase(); txt += c; } return txt; }; }); app.controller('controller1', function($scope) { $scope.programminglanguagenames = [ 'cobol', 'pascal', 'ruby', 'php', 'perl', 'python', 'c', 'c++', 'java', 'html', 'css', 'javascript', 'basic', 'lisp', 'smalltalk', 'bootstrap' ]; }); </script> </body> </html>",
"e": 27521,
"s": 25774,
"text": null
},
{
"code": null,
"e": 27529,
"s": 27521,
"text": "Output:"
},
{
"code": null,
"e": 27550,
"s": 27529,
"text": "AngularJS-Directives"
},
{
"code": null,
"e": 27557,
"s": 27550,
"text": "Picked"
},
{
"code": null,
"e": 27567,
"s": 27557,
"text": "AngularJS"
},
{
"code": null,
"e": 27584,
"s": 27567,
"text": "Web Technologies"
},
{
"code": null,
"e": 27611,
"s": 27584,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 27709,
"s": 27611,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27718,
"s": 27709,
"text": "Comments"
},
{
"code": null,
"e": 27731,
"s": 27718,
"text": "Old Comments"
},
{
"code": null,
"e": 27762,
"s": 27731,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 27807,
"s": 27762,
"text": "How to bundle an Angular app for production?"
},
{
"code": null,
"e": 27849,
"s": 27807,
"text": "What is AOT and JIT Compiler in Angular ?"
},
{
"code": null,
"e": 27884,
"s": 27849,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 27958,
"s": 27884,
"text": "How to set focus on input field automatically on page load in AngularJS ?"
},
{
"code": null,
"e": 28014,
"s": 27958,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 28047,
"s": 28014,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28109,
"s": 28047,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28152,
"s": 28109,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to Serialize ArrayList in Java? - GeeksforGeeks
|
15 Dec, 2020
ArrayList is a class under the collections framework of java. It is present in java.util package. An ArrayList is a re-sizable array in java i.e., unlike an array, the size of an ArrayList can be modified dynamically according to our requirement. Also, the ArrayList class provides many useful methods to perform insertion, deletion, and many other operations on large amounts of data.
What is serialization?
To serialize an object means to convert its state to a byte stream so that the byte stream can be reverted back into a copy of the object. A Java object is serializable if its class or any of its superclasses implement either the java.io.Serializable interface or its sub interface, java.io.Externalizable. When an object is serialized, information that identifies its class is recorded in the serialized stream.
Serializing ArrayList:
In Java, the ArrayList class implements a Serializable interface by default i.e., ArrayList is by default serialized. We can just use the ObjectOutputStream directly to serialize it.
Java
// Java program to demonstrate serialization of ArrayList import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectOutputStream;import java.util.ArrayList; public class ArrayListEx { // method to serialize an ArrayList object static void serializeArrayList() { // an ArrayList // object "namesList" // is created ArrayList<String> namesList = new ArrayList<String>(); // adding the data into the ArrayList namesList.add("Geeks"); namesList.add("for"); namesList.add("Geeks"); try { // an OutputStream file // "namesListData" is // created FileOutputStream fos = new FileOutputStream("namesListData"); // an ObjectOutputStream object is // created on the FileOutputStream // object ObjectOutputStream oos = new ObjectOutputStream(fos); // calling the writeObject() // method of the // ObjectOutputStream on the // OutputStream file "namesList" oos.writeObject(namesList); // close the ObjectOutputStream oos.close(); // close the OutputStream file fos.close(); System.out.println("namesList serialized"); } catch (IOException ioe) { ioe.printStackTrace(); } } // Driver method public static void main(String[] args) throws Exception { // calling the // serializeArrayList() method serializeArrayList(); }}
Output:
Note:All the elements stored in the ArrayList should also be serializable in order to serialize the ArrayList, else NotSerializableException will be thrown.
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
|
[
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n15 Dec, 2020"
},
{
"code": null,
"e": 24334,
"s": 23948,
"text": "ArrayList is a class under the collections framework of java. It is present in java.util package. An ArrayList is a re-sizable array in java i.e., unlike an array, the size of an ArrayList can be modified dynamically according to our requirement. Also, the ArrayList class provides many useful methods to perform insertion, deletion, and many other operations on large amounts of data."
},
{
"code": null,
"e": 24357,
"s": 24334,
"text": "What is serialization?"
},
{
"code": null,
"e": 24770,
"s": 24357,
"text": "To serialize an object means to convert its state to a byte stream so that the byte stream can be reverted back into a copy of the object. A Java object is serializable if its class or any of its superclasses implement either the java.io.Serializable interface or its sub interface, java.io.Externalizable. When an object is serialized, information that identifies its class is recorded in the serialized stream."
},
{
"code": null,
"e": 24793,
"s": 24770,
"text": "Serializing ArrayList:"
},
{
"code": null,
"e": 24976,
"s": 24793,
"text": "In Java, the ArrayList class implements a Serializable interface by default i.e., ArrayList is by default serialized. We can just use the ObjectOutputStream directly to serialize it."
},
{
"code": null,
"e": 24981,
"s": 24976,
"text": "Java"
},
{
"code": "// Java program to demonstrate serialization of ArrayList import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectOutputStream;import java.util.ArrayList; public class ArrayListEx { // method to serialize an ArrayList object static void serializeArrayList() { // an ArrayList // object \"namesList\" // is created ArrayList<String> namesList = new ArrayList<String>(); // adding the data into the ArrayList namesList.add(\"Geeks\"); namesList.add(\"for\"); namesList.add(\"Geeks\"); try { // an OutputStream file // \"namesListData\" is // created FileOutputStream fos = new FileOutputStream(\"namesListData\"); // an ObjectOutputStream object is // created on the FileOutputStream // object ObjectOutputStream oos = new ObjectOutputStream(fos); // calling the writeObject() // method of the // ObjectOutputStream on the // OutputStream file \"namesList\" oos.writeObject(namesList); // close the ObjectOutputStream oos.close(); // close the OutputStream file fos.close(); System.out.println(\"namesList serialized\"); } catch (IOException ioe) { ioe.printStackTrace(); } } // Driver method public static void main(String[] args) throws Exception { // calling the // serializeArrayList() method serializeArrayList(); }}",
"e": 26610,
"s": 24981,
"text": null
},
{
"code": null,
"e": 26619,
"s": 26610,
"text": "Output: "
},
{
"code": null,
"e": 26776,
"s": 26619,
"text": "Note:All the elements stored in the ArrayList should also be serializable in order to serialize the ArrayList, else NotSerializableException will be thrown."
},
{
"code": null,
"e": 26783,
"s": 26776,
"text": "Picked"
},
{
"code": null,
"e": 26807,
"s": 26783,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 26812,
"s": 26807,
"text": "Java"
},
{
"code": null,
"e": 26826,
"s": 26812,
"text": "Java Programs"
},
{
"code": null,
"e": 26845,
"s": 26826,
"text": "Technical Scripter"
},
{
"code": null,
"e": 26850,
"s": 26845,
"text": "Java"
},
{
"code": null,
"e": 26948,
"s": 26850,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26963,
"s": 26948,
"text": "Stream In Java"
},
{
"code": null,
"e": 27009,
"s": 26963,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27030,
"s": 27009,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27049,
"s": 27030,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27079,
"s": 27049,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27123,
"s": 27079,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 27149,
"s": 27123,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 27183,
"s": 27149,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 27230,
"s": 27183,
"text": "Implementing a Linked List in Java using Class"
}
] |
Create a Circular Progress Bar using HTML and CSS - GeeksforGeeks
|
24 Jun, 2021
A progress bar is used to display the progress of a process on a computer. A progress bar displays how much of the process is completed and how much is left. So, today we will design a circular progress bar using HTML and CSS. By using HTML, we will design the different components for that progress bar and then by using the properties of CSS, we can style the progress bar.
A sample Picture is provided to understand today’s task with more clarity.
Step by Step Implementation:
Step 1: First, we will design a basic progress bar structure using HTML. First, we will create a container div that holds both progress bars. After that, we will create another div inside the container div that creates the circular div element. Here we have added some comments that will help readers to understand easily.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<!-- Set title of web page -->
<title>GFG Circular progress Bar</title>
</head>
<body>
<!-- Added heading of the page -->
<h1>GeeksForGeeks Circular Progress Bars</h1>
<!-- Creating a container class that
hold other useful classes -->
<div class="container">
<!-- Creating a ui-widgets classes that
store other useful classes like
ui-values and ui-labels -->
<div class="ui-widgets">
<div class="ui-values">85%</div>
<div class="ui-labels">Java</div>
</div>
<div class="ui-widgets">
<div class="ui-values">50%</div>
<div class="ui-labels">HTML</div>
</div>
</div>
</body>
</html>
Step 2: Next, we will use some CSS properties to design the progress bar. The container class sets the position of the div element. Other CSS classes are used to create the circular progress bar and added CSS styles.
CSS
/* Apply css properties to h1 element */
h1{
text-align: center;
}
/* Create a container using css properties */
.container {
top: 30%;
left:50%;
position: absolute;
text-align: center;
transform: translate(-50%, -50%);
}
/* Apply css properties to ui-widgets class */
.ui-widgets {
position: relative;
display: inline-block;
width: 10rem;
height: 10rem;
border-radius: 9rem;
margin:1.5rem;
border: 1.2rem solid palegreen;
box-shadow: inset 0 0 7px grey;
border-left-color: palegreen;
border-top-color:chartreuse ;
border-right-color: darkgreen;
border-bottom-color: white ;
text-align: center;
box-sizing: border-box;
}
/* Apply css properties to the second
child of ui-widgets class */
.ui-widgets:nth-child(2) {
border-top-color:chartreuse ;
border-right-color: white;
border-left-color: palegreen;
border-bottom-color: white;
}
/* Apply css properties to ui-widgets
class and ui-values class */
.ui-widgets .ui-values {
top: 40px;
position: absolute;
left: 10px;
right: 0;
font-weight: 700;
font-size: 2.0rem;
}
/* Apply css properties to ui-widgets
class and ui-labels class */
.ui-widgets .ui-labels {
left: 0;
bottom: -16px;
text-shadow: 0 0 4px grey;
color:black;
position: absolute;
width: 100%;
font-size: 16px;
}
Complete Code: In this section, we will combine the above two sections to create a circular progress bar using HTML and CSS.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<!-- Set title of web page -->
<title>GFG Circular progress Bar</title>
<style>
/* Apply css properties to h1 element */
h1 {
text-align: center;
}
/* Create a container using CSS properties */
.container {
top: 30%;
left: 50%;
position: absolute;
text-align: center;
transform: translate(-50%, -50%);
}
/* Apply CSS properties to ui-widgets class */
.ui-widgets {
position: relative;
display: inline-block;
width: 10rem;
height: 10rem;
border-radius: 9rem;
margin: 1.5rem;
border: 1.2rem solid palegreen;
box-shadow: inset 0 0 7px grey;
border-left-color: palegreen;
border-top-color: chartreuse;
border-right-color: darkgreen;
border-bottom-color: white;
text-align: center;
box-sizing: border-box;
}
/* Apply css properties to the second
child of ui-widgets class */
.ui-widgets:nth-child(2) {
border-top-color: chartreuse;
border-right-color: white;
border-left-color: palegreen;
border-bottom-color: white;
}
/* Apply css properties to ui-widgets class
and ui-values class*/
.ui-widgets .ui-values {
top: 40px;
position: absolute;
left: 10px;
right: 0;
font-weight: 700;
font-size: 2.0rem;
}
/* Apply css properties to ui-widgets
class and ui-labels class*/
.ui-widgets .ui-labels {
left: 0;
bottom: -16px;
text-shadow: 0 0 4px grey;
color: black;
position: absolute;
width: 100%;
font-size: 16px;
}
</style>
</head>
<body>
<!-- Add heading of the page -->
<h1>GeeksforGeeks Circular Progress Bar</h1>
<!-- Creating of a container class that
store other useful classes -->
<div class="container">
<!-- Creating a ui-widgets classes that
store other useful classes like
ui-values and ui-labels -->
<div class="ui-widgets">
<div class="ui-values">85%</div>
<div class="ui-labels">Java</div>
</div>
<div class="ui-widgets">
<div class="ui-values">50%</div>
<div class="ui-labels">HTML</div>
</div>
</div>
</body>
</html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Properties
CSS-Questions
CSS-Selectors
HTML-Questions
CSS
HTML
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
Making a div vertically scrollable using CSS
Build a Survey Form using HTML and CSS
CSS | Text Formatting
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Types of CSS (Cascading Style Sheet)
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
|
[
{
"code": null,
"e": 24079,
"s": 24048,
"text": " \n24 Jun, 2021\n"
},
{
"code": null,
"e": 24455,
"s": 24079,
"text": "A progress bar is used to display the progress of a process on a computer. A progress bar displays how much of the process is completed and how much is left. So, today we will design a circular progress bar using HTML and CSS. By using HTML, we will design the different components for that progress bar and then by using the properties of CSS, we can style the progress bar."
},
{
"code": null,
"e": 24530,
"s": 24455,
"text": "A sample Picture is provided to understand today’s task with more clarity."
},
{
"code": null,
"e": 24559,
"s": 24530,
"text": "Step by Step Implementation:"
},
{
"code": null,
"e": 24882,
"s": 24559,
"text": "Step 1: First, we will design a basic progress bar structure using HTML. First, we will create a container div that holds both progress bars. After that, we will create another div inside the container div that creates the circular div element. Here we have added some comments that will help readers to understand easily."
},
{
"code": null,
"e": 24887,
"s": 24882,
"text": "HTML"
},
{
"code": "\n\n\n\n\n\n\n<!DOCTYPE html> \n<html lang=\"en\"> \n \n<head> \n <meta charset=\"UTF-8\"> \n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> \n <meta name=\"viewport\" content= \n \"width=device-width, initial-scale=1.0\"> \n \n <!-- Set title of web page -->\n <title>GFG Circular progress Bar</title> \n</head> \n \n<body> \n \n <!-- Added heading of the page -->\n <h1>GeeksForGeeks Circular Progress Bars</h1> \n \n <!-- Creating a container class that \n hold other useful classes -->\n <div class=\"container\"> \n \n <!-- Creating a ui-widgets classes that \n store other useful classes like \n ui-values and ui-labels -->\n <div class=\"ui-widgets\"> \n <div class=\"ui-values\">85%</div> \n <div class=\"ui-labels\">Java</div> \n </div> \n \n <div class=\"ui-widgets\"> \n <div class=\"ui-values\">50%</div> \n <div class=\"ui-labels\">HTML</div> \n </div> \n </div> \n</body> \n \n</html>\n\n\n\n\n\n",
"e": 25899,
"s": 24897,
"text": null
},
{
"code": null,
"e": 26117,
"s": 25899,
"text": "Step 2: Next, we will use some CSS properties to design the progress bar. The container class sets the position of the div element. Other CSS classes are used to create the circular progress bar and added CSS styles. "
},
{
"code": null,
"e": 26121,
"s": 26117,
"text": "CSS"
},
{
"code": "\n\n\n\n\n\n\n/* Apply css properties to h1 element */\nh1{ \n text-align: center; \n} \n \n/* Create a container using css properties */\n.container { \n top: 30%; \n left:50%; \n position: absolute; \n text-align: center; \n transform: translate(-50%, -50%); \n} \n \n/* Apply css properties to ui-widgets class */\n.ui-widgets { \n position: relative; \n display: inline-block; \n width: 10rem; \n height: 10rem; \n border-radius: 9rem; \n margin:1.5rem; \n border: 1.2rem solid palegreen; \n box-shadow: inset 0 0 7px grey; \n border-left-color: palegreen; \n border-top-color:chartreuse ; \n border-right-color: darkgreen; \n border-bottom-color: white ; \n text-align: center; \n box-sizing: border-box; \n} \n \n/* Apply css properties to the second \n child of ui-widgets class */\n.ui-widgets:nth-child(2) { \n border-top-color:chartreuse ; \n border-right-color: white; \n border-left-color: palegreen; \n border-bottom-color: white; \n} \n \n/* Apply css properties to ui-widgets \n class and ui-values class */\n.ui-widgets .ui-values { \n top: 40px; \n position: absolute; \n left: 10px; \n right: 0; \n font-weight: 700; \n font-size: 2.0rem; \n} \n \n/* Apply css properties to ui-widgets \nclass and ui-labels class */\n.ui-widgets .ui-labels { \n left: 0; \n bottom: -16px; \n text-shadow: 0 0 4px grey; \n color:black; \n position: absolute; \n width: 100%; \n font-size: 16px; \n}\n\n\n\n\n\n",
"e": 27591,
"s": 26131,
"text": null
},
{
"code": null,
"e": 27716,
"s": 27591,
"text": "Complete Code: In this section, we will combine the above two sections to create a circular progress bar using HTML and CSS."
},
{
"code": null,
"e": 27721,
"s": 27716,
"text": "HTML"
},
{
"code": "\n\n\n\n\n\n\n<!DOCTYPE html> \n<html lang=\"en\"> \n \n<head> \n <meta charset=\"UTF-8\"> \n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> \n <meta name=\"viewport\" content= \n \"width=device-width, initial-scale=1.0\"> \n \n <!-- Set title of web page -->\n <title>GFG Circular progress Bar</title> \n \n <style> \n \n /* Apply css properties to h1 element */ \n h1 { \n text-align: center; \n } \n \n /* Create a container using CSS properties */ \n .container { \n top: 30%; \n left: 50%; \n position: absolute; \n text-align: center; \n transform: translate(-50%, -50%); \n } \n \n /* Apply CSS properties to ui-widgets class */ \n .ui-widgets { \n position: relative; \n display: inline-block; \n width: 10rem; \n height: 10rem; \n border-radius: 9rem; \n margin: 1.5rem; \n border: 1.2rem solid palegreen; \n box-shadow: inset 0 0 7px grey; \n border-left-color: palegreen; \n border-top-color: chartreuse; \n border-right-color: darkgreen; \n border-bottom-color: white; \n text-align: center; \n box-sizing: border-box; \n } \n \n /* Apply css properties to the second \n child of ui-widgets class */ \n .ui-widgets:nth-child(2) { \n border-top-color: chartreuse; \n border-right-color: white; \n border-left-color: palegreen; \n border-bottom-color: white; \n } \n \n /* Apply css properties to ui-widgets class \n and ui-values class*/ \n .ui-widgets .ui-values { \n top: 40px; \n position: absolute; \n left: 10px; \n right: 0; \n font-weight: 700; \n font-size: 2.0rem; \n \n } \n \n /* Apply css properties to ui-widgets \n class and ui-labels class*/ \n .ui-widgets .ui-labels { \n \n left: 0; \n bottom: -16px; \n text-shadow: 0 0 4px grey; \n color: black; \n position: absolute; \n width: 100%; \n font-size: 16px; \n } \n </style> \n</head> \n \n<body> \n \n <!-- Add heading of the page -->\n <h1>GeeksforGeeks Circular Progress Bar</h1> \n \n <!-- Creating of a container class that \n store other useful classes -->\n <div class=\"container\"> \n \n <!-- Creating a ui-widgets classes that \n store other useful classes like \n ui-values and ui-labels -->\n <div class=\"ui-widgets\"> \n <div class=\"ui-values\">85%</div> \n <div class=\"ui-labels\">Java</div> \n </div> \n \n <div class=\"ui-widgets\"> \n <div class=\"ui-values\">50%</div> \n <div class=\"ui-labels\">HTML</div> \n </div> \n </div> \n</body> \n \n</html>\n\n\n\n\n\n",
"e": 30701,
"s": 27731,
"text": null
},
{
"code": null,
"e": 30709,
"s": 30701,
"text": "Output:"
},
{
"code": null,
"e": 30846,
"s": 30709,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 30863,
"s": 30846,
"text": "\nCSS-Properties\n"
},
{
"code": null,
"e": 30879,
"s": 30863,
"text": "\nCSS-Questions\n"
},
{
"code": null,
"e": 30895,
"s": 30879,
"text": "\nCSS-Selectors\n"
},
{
"code": null,
"e": 30912,
"s": 30895,
"text": "\nHTML-Questions\n"
},
{
"code": null,
"e": 30918,
"s": 30912,
"text": "\nCSS\n"
},
{
"code": null,
"e": 30925,
"s": 30918,
"text": "\nHTML\n"
},
{
"code": null,
"e": 30944,
"s": 30925,
"text": "\nWeb Technologies\n"
},
{
"code": null,
"e": 31149,
"s": 30944,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 31207,
"s": 31149,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 31244,
"s": 31207,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 31289,
"s": 31244,
"text": "Making a div vertically scrollable using CSS"
},
{
"code": null,
"e": 31328,
"s": 31289,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 31350,
"s": 31328,
"text": "CSS | Text Formatting"
},
{
"code": null,
"e": 31410,
"s": 31350,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 31471,
"s": 31410,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 31508,
"s": 31471,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 31561,
"s": 31508,
"text": "Hide or show elements in HTML using display property"
}
] |
Covid-19 Analysis and Visualization using Plotly Express - GeeksforGeeks
|
14 Sep, 2021
In this article, we will discuss Analyse Covid-19 data and will visualize it using Plotly Express in Python. This article deals with creating dozens of bar charts, line graphs, bubble charts, scatter plots. The graph that will be made in this project will be of excellent quality. Envisioning COVID-19 will primarily be using Plotly Express for this project. The analysis and visualization enable people to understand complex scenarios and make predictions about the future from the current situation.
This analysis summarizes the modeling, simulation, and analytics work around the COVID-19 outbreak around the world from the perspective of data science and visual analytics. It examines the impact of best practices and preventive measures in various sectors and enables outbreaks to be managed with available health resources.
Tools and Technologies Used in the Project: Google Colab(Runtime type – GPU).
Requirements to Build the Project:
Basic knowledge of Python
Basic understanding of graphs and charts
Data visualization
Pandas
Numpy
Matplotlib
Plotly Express
Choropleth
Wordcloud
The task is simple, once the installation of all the required libraries is successful, they need to be imported to the working space, since they will provide the additional support for analysis and visualization.
Example: importing libraries
Python3
# Data analysis and Manipulationimport plotly.graph_objs as goimport plotly.io as pioimport plotly.express as pximport pandas as pd # Data Visualizationimport matplotlib.pyplot as plt # Importing Plotlyimport plotly.offline as pypy.init_notebook_mode(connected=True) # Initializing Plotlypio.renderers.default = 'colab'
Importing three datasets into this project
covid– This dataset contains Country/Region, Continent, Population, TotalCases, NewCases, TotalDeaths, NewDeaths, TotalRecovered, NewRecovered, ActiveCases, Serious, Critical, Tot Cases/1M pop, Deaths/1M pop, TotalTests, Tests/1M pop, WHO Region, iso_alpha.
covid_grouped– This dataset contains Date(from 20-01-22 to 20-07-27), Country/Region, Confirmed, Deaths, Recovered, Active, New cases, New deaths, New recovered, WHO Region, iso_alpha.
coviddeath– This dataset contains real-world examples of a number of Covid-19 deaths and the reasons behind the deaths.
To import datasets to the working space pandas read_csv() method can be used.
Syntax:
read_csv(path)
Python3
# Importing Dataset1dataset1 = pd.read_csv("covid.csv")dataset1.head() # returns first 5 rows
Output:
Further, information regarding the dataset we are using will help us sample it better for analysis.
Python3
# Returns tuple of shape (Rows, columns)print(dataset1.shape) # Returns size of dataframeprint(dataset1.size)
Output:
(209, 17)
3553
Python3
# Information about Dataset1# return concise summary of dataframedataset1.info()
Output:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 209 entries, 0 to 208
Data columns (total 17 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Country/Region 209 non-null object
1 Continent 208 non-null object
2 Population 208 non-null float64
3 TotalCases 209 non-null int64
4 NewCases 4 non-null float64
5 TotalDeaths 188 non-null float64
6 NewDeaths 3 non-null float64
7 TotalRecovered 205 non-null float64
8 NewRecovered 3 non-null float64
9 ActiveCases 205 non-null float64
10 Serious,Critical 122 non-null float64
11 Tot Cases/1M pop 208 non-null float64
12 Deaths/1M pop 187 non-null float64
13 TotalTests 191 non-null float64
14 Tests/1M pop 191 non-null float64
15 WHO Region 184 non-null object
16 iso_alpha 209 non-null object
dtypes: float64(12), int64(1), object(4)
memory usage: 27.9+ KB
Similarly other datasets can be imported and explored.
Python3
# Importing Dataset2dataset2 = pd.read_csv("covid_grouped.csv")dataset2.head() # return first 5 rows of dataset2
Output:
Python3
# Returns tuple of shape (Rows, columns)print(dataset2.shape) # Returns size of dataframeprint(dataset2.size)
Output:
(35156, 11)
386716
Python3
# Information about Dataset2dataset2.info() # return concise summary of dataframe
Output:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 35156 entries, 0 to 35155
Data columns (total 11 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Date 35156 non-null object
1 Country/Region 35156 non-null object
2 Confirmed 35156 non-null int64
3 Deaths 35156 non-null int64
4 Recovered 35156 non-null int64
5 Active 35156 non-null int64
6 New cases 35156 non-null int64
7 New deaths 35156 non-null int64
8 New recovered 35156 non-null int64
9 WHO Region 35156 non-null object
10 iso_alpha 35156 non-null object
dtypes: int64(7), object(4)
memory usage: 3.0+ MB
Data cleaning is the process of altering, modifying a recordset, correcting erroneous records from the database and identifying incomplete, incorrect, or irrelevant parts of the data, and then removing dirty data.
Python3
# Columns labels of a Dataset1dataset1.columns
Output:
Index([‘Country/Region’, ‘Continent’, ‘Population’, ‘TotalCases’, ‘NewCases’, ‘TotalDeaths’, ‘NewDeaths’, ‘TotalRecovered’, ‘NewRecovered’, ‘ActiveCases’, ‘Serious,Critical’, ‘Tot Cases/1M pop’, ‘Deaths/1M pop’, ‘TotalTests’, ‘Tests/1M pop’, ‘WHO Region’, ‘iso_alpha’], dtype=’object’)
We don’t need ‘NewCases’, ‘NewDeaths’, ‘NewRecovered’ columns as they contains NaN values. So drop these columns by drop() function of pandas.
Syntax:
drop(name of columns)
Python3
# Drop NewCases, NewDeaths, NewRecovered rows from dataset1 dataset1.drop(['NewCases', 'NewDeaths', 'NewRecovered'], axis=1, inplace=True) # Select random set of values from dataset1dataset1.sample(5)
Output:
Let’s create a table through the table function already available in plotly express.
Python3
# Import create_table Figure Factory from plotly.figure_factory import create_table colorscale = [[0, '#4d004c'], [.5, '#f2e5ff'], [1, '#ffffff']]table = create_table(dataset1.head(15), colorscale=colorscale)py.iplot(table)
Output:
Using one line of code, we will create amazing graphs using Plotly Express. Visualization can be done easily by moving the cursor in any plot, we can get label presence point directly by using the cursor. We can visualize and analyze the dataset with each aspect using the relation between the columns.
Primarily look at the country with respect to a total number of cases by top 15 countries only and color total cases and hover data as ‘Country/Region’, ‘Continent’.
Python3
px.bar(dataset1.head(15), x = 'Country/Region', y = 'TotalCases',color = 'TotalCases', height = 500,hover_data = ['Country/Region', 'Continent'])
Output:
As the plot clearly shows the data for the top 15 countries, now again take the country with respect to the total number of cases from the top 15 countries, color the total deaths hover data as ‘Country/Region’, ‘Continent’ and analyze the visualization.
Python3
px.bar(dataset1.head(15), x = 'Country/Region', y = 'TotalCases', color = 'TotalDeaths', height = 500, hover_data = ['Country/Region', 'Continent'])
Output:
Let’s analyze by coloring the total number of recovered cases
Python3
px.bar(dataset1.head(15), x = 'Country/Region', y = 'TotalCases', color = 'TotalDeaths', height = 500, hover_data = ['Country/Region', 'Continent'])
Output:
Visualize the same again by coloring the total number of tests.
Python3
px.bar(dataset1.head(15), x = 'Country/Region', y = 'TotalCases', color = 'TotalTests', height = 500, hover_data = ['Country/Region', 'Continent'])
Output:
The visualization could be as we have done with the top 15 countries with total cases, deaths, recoveries, and tests. We can analyze the plot by looking at them.
Let’s create a horizontal orientation plot with X-axis as ‘TotalTests’ and Y-axis as ‘Country/Region’ with passing parameter orientation=”h” and color the plot by ‘TotalTests’.
Python3
px.bar(dataset1.head(15), x = 'TotalTests', y = 'Country/Region', color = 'TotalTests',orientation ='h', height = 500, hover_data = ['Country/Region', 'Continent'])
Output:
Let’s look at ‘TotalTests’ followed by ‘Continent’ and color the plot with ‘Continent’.
Python3
px.bar(dataset1.head(15), x = 'TotalTests', y = 'Continent', color = 'TotalTests',orientation ='h', height = 500, hover_data = ['Country/Region', 'Continent'])
Output:
Total Tests & Continents(Horizontal Orientation)
Let’s create a scatter plot and take a look at the continent’s statistics, firstly look at the total number of cases by continent and take hover data as ‘Country/Region’, ‘Continent’.
Python3
px.scatter(dataset1, x='Continent',y='TotalCases', hover_data=['Country/Region', 'Continent'], color='TotalCases', size='TotalCases', size_max=80)
Output:
log_y= True, the histogram axis (not the returned parameter) is in log scale. The return parameter (n, bins), i.e. the values of bins and sides of bins are the same for log=True and log=False. This means both n==n2 and bins==bins2 are true
Python3
px.scatter(dataset1.head(57), x='Continent',y='TotalCases', hover_data=['Country/Region', 'Continent'], color='TotalCases', size='TotalCases', size_max=80, log_y=True)
Output:
Python3
px.scatter(dataset1.head(54), x='Continent',y='TotalTests', hover_data=['Country/Region', 'Continent'], color='TotalTests', size='TotalTests', size_max=80)
Output:
Python3
px.scatter(dataset1.head(50), x='Continent',y='TotalTests', hover_data=['Country/Region', 'Continent'], color='TotalTests', size='TotalTests', size_max=80, log_y=True)
Output:
Let’s take a look at the country-wise data visualization, first look at the continent with respect to the total number of deaths by the top 50 countries only and color the total number of deaths and take the hover data as ‘Country/Region’, ‘Continent’.
Python3
px.scatter(dataset1.head(100), x='Country/Region', y='TotalCases', hover_data=['Country/Region', 'Continent'], color='TotalCases', size='TotalCases', size_max=80)
Output:
Now, the Country/Region with respect to the total number of cases for top 30 countries only and color the total number of cases and take the hover data as ‘Country/Region’, ‘Continent’.
Python3
px.scatter(dataset1.head(30), x='Country/Region', y='TotalCases', hover_data=['Country/Region', 'Continent'], color='Country/Region', size='TotalCases', size_max=80, log_y=True)
Output:
Now format the image of the country/region in relation to the total number of deaths. And do the same for the other aspects of COVID-19 from dataset1.
Python3
px.scatter(dataset1.head(10), x='Country/Region', y= 'TotalDeaths', hover_data=['Country/Region', 'Continent'], color='Country/Region', size= 'TotalDeaths', size_max=80)
Output:
Python3
px.scatter(dataset1.head(30), x='Country/Region', y= 'Tests/1M pop', hover_data=['Country/Region', 'Continent'], color='Country/Region', size= 'Tests/1M pop', size_max=80)
Output:
Python3
px.scatter(dataset1.head(30), x='Country/Region', y= 'Tests/1M pop', hover_data=['Country/Region', 'Continent'], color='Tests/1M pop', size= 'Tests/1M pop', size_max=80)
Output:
Python3
px.scatter(dataset1.head(30), x='TotalCases', y= 'TotalDeaths', hover_data=['Country/Region', 'Continent'], color='TotalDeaths', size= 'TotalDeaths', size_max=80)
Output:
It is clear from the result that they have a linear relationship between the total number of cases and the total number of deaths. That means more cases, more deaths.
Python3
px.scatter(dataset1.head(30), x='TotalCases', y= 'TotalDeaths', hover_data=['Country/Region', 'Continent'], color='TotalDeaths', size= 'TotalDeaths', size_max=80, log_x=True, log_y=True)
Output:
TotalCases VS TotalDeaths (with log_y=True)
Python3
px.scatter(dataset1.head(30), x='TotalTests', y= 'TotalCases', hover_data=['Country/Region', 'Continent'], color='TotalTests', size= 'TotalTests', size_max=80, log_x=True, log_y=True)
Output:
TotalTestes VS TotalCases
In this task, we will explore covid-19 data using bar graphs and charts and use dataset2 as it has date column.
Python3
px.bar(dataset2, x="Date", y="Confirmed", color="Confirmed", hover_data=["Confirmed", "Date", "Country/Region"], height=400)
Output:
The above graph we get as output which includes all countries with respect to recovered cases. we can imagine the exponential growth of corona cases by date. We can use log function for this to be more clear.
Python3
px.bar(dataset2, x="Date", y="Confirmed", color="Confirmed", hover_data=["Confirmed", "Date", "Country/Region"],log_y=True, height=400)
Output:
Let’s imagine death instead of confirmation with the same and color it by date.
Python3
px.bar(dataset2, x="Date", y="Deaths", color="Deaths", hover_data=["Confirmed", "Date", "Country/Region"], log_y=False, height=400)
Output:
In this specific task, we will analyze data of the USA country.
Python3
df_US= dataset2.loc[dataset2["Country/Region"]=="US"]
Now let us plot and study the covid situation in the USA.
Python3
px.bar(df_US, x="Date", y="Confirmed", color="Confirmed", height=400)
Output:
Here we can clearly see how the confirmed cases increased in the United States with respect to time (January 2020 to July 2020). Similarly, we can check the same for recovered cases, tests and deaths.
Python3
px.bar(df_US,x="Date", y="Recovered", color="Recovered", height=400)
Output:
Similarly, we can analyze the data in all the ways to generate the line graph for the same.
Python3
px.line(df_US,x="Date", y="Recovered", height=400)
Output:
Python3
px.line(df_US,x="Date", y="Deaths", height=400)
Output:
Python3
px.line(df_US,x="Date", y="Confirmed", height=400)
Output:
Python3
px.line(df_US,x="Date", y="New cases", height=400)
Output:
Now let us create bar charts and study the USA situation using that.
Python3
px.bar(df_US,x="Date", y="New cases", height=400)
Output:
Similarly, let us also plot a line plot.
Python3
px.scatter(df_US, x="Confirmed", y="Deaths", height=400)
Output:
We can use choropleth to visualize the data in terms of maps, with maps usually being the predominant way of visualizing the data. Since COVID-19 is a global phenomenon and so we look through and fix them in terms of wall maps. Ortho-graphics, rectangular and natural earth projection to visualize the data With dataset2 for the purpose as it has Dates column. It will look at the growth of Covid-19 (from Jan to July 2020) as in how the virus reached across the world.
Choropleth is an amazing representation of data on a map. Choropleth maps provide an easy way to visualize how a measurement varies across a geographic areal-Life
Project Application in Real choropleth map displays divided geographical areas or regions that are colored, shaded or patterned in relation to a data variable.
Equi-rectangular Projection:
Syntax: chloropleth()
parameters:
dataset
locations= ISOALPHA
color
hover_name
color_continuous_scale= [RdYlGn, Blues, Viridis...]
animation_frame= Date
Python3
px.choropleth(dataset2, locations="iso_alpha", color="Confirmed", hover_name="Country/Region", color_continuous_scale="Blues", animation_frame="Date")
Output:
This creates an animation containing visualizations from January to July 2020. Playing this animation will make it more clear how the virus spread around the world. The darker the color, the higher the confirmed cases are.
Python3
px.choropleth(dataset2, locations='iso_alpha', color="Deaths", hover_name="Country/Region", color_continuous_scale="Viridis", animation_frame="Date" )
Output:
This code creates an animation of death cases by date. By playing this animation it will be shown how deaths increase around the world.
Natural Earth projection is a compromise pseudo-cylindrical map projection for world maps.
Python3
px.choropleth(dataset2, locations='iso_alpha', color="Recovered", hover_name="Country/Region", color_continuous_scale="RdYlGn", projection="natural earth", animation_frame="Date" )
Output:
By running the output, things start to become more clear about how the recovery rate changes with respect to the date. Lets also look at how an animation can be added to a bar graph. We can convert the bar graph into animation using Dates column that is in dataset2.
Python3
px.bar(dataset2, x="WHO Region", y="Confirmed", color="WHO Region", animation_frame="Date", hover_name="Country/Region")
Output:
When running the output, the animation will run from January to July 2020. It will show 6 different bar graphs, each continent has its own color representing the confirmed cases.
Visualize the causes of death due to covid-19, as covid-19 affects people in different ways, hence creating a word cloud to visualize the leading cause of covid-19 deaths. To visualize the text the steps need to be followed are-
Used to convert data elements of an array into list.
Convert the string to one single string.
Convert the string into word cloud
Dataset3: This dataset contains real world examples of number of Covid-19 deaths and the reasons behind the deaths.
Python3
dataset3= pd.read_csv("covid+death.csv")dataset3.head()
Output:
Python3
dataset3.tail()
Output:
Python3
dataset3.groupby(["Condition"]).count()
Output:
Conditions
Python3
# import word cloudfrom wordcloud import WordCloud sentences = dataset3["Condition"].tolist()sentences_as_a_string = ' '.join(sentences) # Convert the string into WordCloudplt.figure(figsize=(20, 20))plt.imshow(WordCloud().generate(sentences_as_a_string))
Output:
From the output, it can be clearly seen that the leading cause of death is Influenza Pneumonia. We have converted the condition group to the list and stored the list in the variable “column_to_list”. Here we have converted the list into a single string and stored in a variable named “column2_to_string” by using .join().
Python3
column2_tolist= dataset3["Condition Group"].tolist() # Convert the list to one single stringcolumn_to_string= " ".join(column2_tolist) # Convert the string into WordCloudplt.figure(figsize=(20,20))plt.imshow(WordCloud().generate(column_to_string))
Output:
Here, respiratory diseases are the major cause of death followed by circulatory diseases which are cardiovascular diseases.
Blogathon-2021
Data Visualization
Python-Plotly
Blogathon
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Import JSON Data into SQL Server?
How to Create a Table With Multiple Foreign Keys in SQL?
How to Install Tkinter in Windows?
SQL Query to Convert Datetime to Date
SQL Query to Create Table With a Primary Key
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 24836,
"s": 24808,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 25338,
"s": 24836,
"text": "In this article, we will discuss Analyse Covid-19 data and will visualize it using Plotly Express in Python. This article deals with creating dozens of bar charts, line graphs, bubble charts, scatter plots. The graph that will be made in this project will be of excellent quality. Envisioning COVID-19 will primarily be using Plotly Express for this project. The analysis and visualization enable people to understand complex scenarios and make predictions about the future from the current situation."
},
{
"code": null,
"e": 25666,
"s": 25338,
"text": "This analysis summarizes the modeling, simulation, and analytics work around the COVID-19 outbreak around the world from the perspective of data science and visual analytics. It examines the impact of best practices and preventive measures in various sectors and enables outbreaks to be managed with available health resources."
},
{
"code": null,
"e": 25744,
"s": 25666,
"text": "Tools and Technologies Used in the Project: Google Colab(Runtime type – GPU)."
},
{
"code": null,
"e": 25780,
"s": 25744,
"text": "Requirements to Build the Project: "
},
{
"code": null,
"e": 25806,
"s": 25780,
"text": "Basic knowledge of Python"
},
{
"code": null,
"e": 25847,
"s": 25806,
"text": "Basic understanding of graphs and charts"
},
{
"code": null,
"e": 25866,
"s": 25847,
"text": "Data visualization"
},
{
"code": null,
"e": 25873,
"s": 25866,
"text": "Pandas"
},
{
"code": null,
"e": 25879,
"s": 25873,
"text": "Numpy"
},
{
"code": null,
"e": 25890,
"s": 25879,
"text": "Matplotlib"
},
{
"code": null,
"e": 25905,
"s": 25890,
"text": "Plotly Express"
},
{
"code": null,
"e": 25916,
"s": 25905,
"text": "Choropleth"
},
{
"code": null,
"e": 25926,
"s": 25916,
"text": "Wordcloud"
},
{
"code": null,
"e": 26139,
"s": 25926,
"text": "The task is simple, once the installation of all the required libraries is successful, they need to be imported to the working space, since they will provide the additional support for analysis and visualization."
},
{
"code": null,
"e": 26168,
"s": 26139,
"text": "Example: importing libraries"
},
{
"code": null,
"e": 26176,
"s": 26168,
"text": "Python3"
},
{
"code": "# Data analysis and Manipulationimport plotly.graph_objs as goimport plotly.io as pioimport plotly.express as pximport pandas as pd # Data Visualizationimport matplotlib.pyplot as plt # Importing Plotlyimport plotly.offline as pypy.init_notebook_mode(connected=True) # Initializing Plotlypio.renderers.default = 'colab'",
"e": 26499,
"s": 26176,
"text": null
},
{
"code": null,
"e": 26542,
"s": 26499,
"text": "Importing three datasets into this project"
},
{
"code": null,
"e": 26802,
"s": 26542,
"text": "covid– This dataset contains Country/Region, Continent, Population, TotalCases, NewCases, TotalDeaths, NewDeaths, TotalRecovered, NewRecovered, ActiveCases, Serious, Critical, Tot Cases/1M pop, Deaths/1M pop, TotalTests, Tests/1M pop, WHO Region, iso_alpha."
},
{
"code": null,
"e": 26987,
"s": 26802,
"text": "covid_grouped– This dataset contains Date(from 20-01-22 to 20-07-27), Country/Region, Confirmed, Deaths, Recovered, Active, New cases, New deaths, New recovered, WHO Region, iso_alpha."
},
{
"code": null,
"e": 27107,
"s": 26987,
"text": "coviddeath– This dataset contains real-world examples of a number of Covid-19 deaths and the reasons behind the deaths."
},
{
"code": null,
"e": 27185,
"s": 27107,
"text": "To import datasets to the working space pandas read_csv() method can be used."
},
{
"code": null,
"e": 27193,
"s": 27185,
"text": "Syntax:"
},
{
"code": null,
"e": 27208,
"s": 27193,
"text": "read_csv(path)"
},
{
"code": null,
"e": 27216,
"s": 27208,
"text": "Python3"
},
{
"code": "# Importing Dataset1dataset1 = pd.read_csv(\"covid.csv\")dataset1.head() # returns first 5 rows",
"e": 27311,
"s": 27216,
"text": null
},
{
"code": null,
"e": 27319,
"s": 27311,
"text": "Output:"
},
{
"code": null,
"e": 27419,
"s": 27319,
"text": "Further, information regarding the dataset we are using will help us sample it better for analysis."
},
{
"code": null,
"e": 27427,
"s": 27419,
"text": "Python3"
},
{
"code": "# Returns tuple of shape (Rows, columns)print(dataset1.shape) # Returns size of dataframeprint(dataset1.size)",
"e": 27538,
"s": 27427,
"text": null
},
{
"code": null,
"e": 27546,
"s": 27538,
"text": "Output:"
},
{
"code": null,
"e": 27561,
"s": 27546,
"text": "(209, 17)\n3553"
},
{
"code": null,
"e": 27569,
"s": 27561,
"text": "Python3"
},
{
"code": "# Information about Dataset1# return concise summary of dataframedataset1.info() ",
"e": 27652,
"s": 27569,
"text": null
},
{
"code": null,
"e": 27660,
"s": 27652,
"text": "Output:"
},
{
"code": null,
"e": 28722,
"s": 27660,
"text": "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 209 entries, 0 to 208\nData columns (total 17 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Country/Region 209 non-null object \n 1 Continent 208 non-null object \n 2 Population 208 non-null float64\n 3 TotalCases 209 non-null int64 \n 4 NewCases 4 non-null float64\n 5 TotalDeaths 188 non-null float64\n 6 NewDeaths 3 non-null float64\n 7 TotalRecovered 205 non-null float64\n 8 NewRecovered 3 non-null float64\n 9 ActiveCases 205 non-null float64\n 10 Serious,Critical 122 non-null float64\n 11 Tot Cases/1M pop 208 non-null float64\n 12 Deaths/1M pop 187 non-null float64\n 13 TotalTests 191 non-null float64\n 14 Tests/1M pop 191 non-null float64\n 15 WHO Region 184 non-null object \n 16 iso_alpha 209 non-null object \ndtypes: float64(12), int64(1), object(4)\nmemory usage: 27.9+ KB"
},
{
"code": null,
"e": 28777,
"s": 28722,
"text": "Similarly other datasets can be imported and explored."
},
{
"code": null,
"e": 28785,
"s": 28777,
"text": "Python3"
},
{
"code": "# Importing Dataset2dataset2 = pd.read_csv(\"covid_grouped.csv\")dataset2.head() # return first 5 rows of dataset2",
"e": 28899,
"s": 28785,
"text": null
},
{
"code": null,
"e": 28907,
"s": 28899,
"text": "Output:"
},
{
"code": null,
"e": 28915,
"s": 28907,
"text": "Python3"
},
{
"code": "# Returns tuple of shape (Rows, columns)print(dataset2.shape) # Returns size of dataframeprint(dataset2.size)",
"e": 29026,
"s": 28915,
"text": null
},
{
"code": null,
"e": 29034,
"s": 29026,
"text": "Output:"
},
{
"code": null,
"e": 29053,
"s": 29034,
"text": "(35156, 11)\n386716"
},
{
"code": null,
"e": 29061,
"s": 29053,
"text": "Python3"
},
{
"code": "# Information about Dataset2dataset2.info() # return concise summary of dataframe",
"e": 29144,
"s": 29061,
"text": null
},
{
"code": null,
"e": 29152,
"s": 29144,
"text": "Output:"
},
{
"code": null,
"e": 29883,
"s": 29152,
"text": "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 35156 entries, 0 to 35155\nData columns (total 11 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Date 35156 non-null object\n 1 Country/Region 35156 non-null object\n 2 Confirmed 35156 non-null int64 \n 3 Deaths 35156 non-null int64 \n 4 Recovered 35156 non-null int64 \n 5 Active 35156 non-null int64 \n 6 New cases 35156 non-null int64 \n 7 New deaths 35156 non-null int64 \n 8 New recovered 35156 non-null int64 \n 9 WHO Region 35156 non-null object\n 10 iso_alpha 35156 non-null object\ndtypes: int64(7), object(4)\nmemory usage: 3.0+ MB"
},
{
"code": null,
"e": 30097,
"s": 29883,
"text": "Data cleaning is the process of altering, modifying a recordset, correcting erroneous records from the database and identifying incomplete, incorrect, or irrelevant parts of the data, and then removing dirty data."
},
{
"code": null,
"e": 30105,
"s": 30097,
"text": "Python3"
},
{
"code": "# Columns labels of a Dataset1dataset1.columns",
"e": 30152,
"s": 30105,
"text": null
},
{
"code": null,
"e": 30160,
"s": 30152,
"text": "Output:"
},
{
"code": null,
"e": 30447,
"s": 30160,
"text": "Index([‘Country/Region’, ‘Continent’, ‘Population’, ‘TotalCases’, ‘NewCases’, ‘TotalDeaths’, ‘NewDeaths’, ‘TotalRecovered’, ‘NewRecovered’, ‘ActiveCases’, ‘Serious,Critical’, ‘Tot Cases/1M pop’, ‘Deaths/1M pop’, ‘TotalTests’, ‘Tests/1M pop’, ‘WHO Region’, ‘iso_alpha’], dtype=’object’)"
},
{
"code": null,
"e": 30590,
"s": 30447,
"text": "We don’t need ‘NewCases’, ‘NewDeaths’, ‘NewRecovered’ columns as they contains NaN values. So drop these columns by drop() function of pandas."
},
{
"code": null,
"e": 30598,
"s": 30590,
"text": "Syntax:"
},
{
"code": null,
"e": 30620,
"s": 30598,
"text": "drop(name of columns)"
},
{
"code": null,
"e": 30628,
"s": 30620,
"text": "Python3"
},
{
"code": "# Drop NewCases, NewDeaths, NewRecovered rows from dataset1 dataset1.drop(['NewCases', 'NewDeaths', 'NewRecovered'], axis=1, inplace=True) # Select random set of values from dataset1dataset1.sample(5)",
"e": 30845,
"s": 30628,
"text": null
},
{
"code": null,
"e": 30853,
"s": 30845,
"text": "Output:"
},
{
"code": null,
"e": 30938,
"s": 30853,
"text": "Let’s create a table through the table function already available in plotly express."
},
{
"code": null,
"e": 30946,
"s": 30938,
"text": "Python3"
},
{
"code": "# Import create_table Figure Factory from plotly.figure_factory import create_table colorscale = [[0, '#4d004c'], [.5, '#f2e5ff'], [1, '#ffffff']]table = create_table(dataset1.head(15), colorscale=colorscale)py.iplot(table)",
"e": 31172,
"s": 30946,
"text": null
},
{
"code": null,
"e": 31180,
"s": 31172,
"text": "Output:"
},
{
"code": null,
"e": 31483,
"s": 31180,
"text": "Using one line of code, we will create amazing graphs using Plotly Express. Visualization can be done easily by moving the cursor in any plot, we can get label presence point directly by using the cursor. We can visualize and analyze the dataset with each aspect using the relation between the columns."
},
{
"code": null,
"e": 31649,
"s": 31483,
"text": "Primarily look at the country with respect to a total number of cases by top 15 countries only and color total cases and hover data as ‘Country/Region’, ‘Continent’."
},
{
"code": null,
"e": 31657,
"s": 31649,
"text": "Python3"
},
{
"code": "px.bar(dataset1.head(15), x = 'Country/Region', y = 'TotalCases',color = 'TotalCases', height = 500,hover_data = ['Country/Region', 'Continent'])",
"e": 31817,
"s": 31657,
"text": null
},
{
"code": null,
"e": 31825,
"s": 31817,
"text": "Output:"
},
{
"code": null,
"e": 32080,
"s": 31825,
"text": "As the plot clearly shows the data for the top 15 countries, now again take the country with respect to the total number of cases from the top 15 countries, color the total deaths hover data as ‘Country/Region’, ‘Continent’ and analyze the visualization."
},
{
"code": null,
"e": 32088,
"s": 32080,
"text": "Python3"
},
{
"code": "px.bar(dataset1.head(15), x = 'Country/Region', y = 'TotalCases', color = 'TotalDeaths', height = 500, hover_data = ['Country/Region', 'Continent'])",
"e": 32249,
"s": 32088,
"text": null
},
{
"code": null,
"e": 32257,
"s": 32249,
"text": "Output:"
},
{
"code": null,
"e": 32320,
"s": 32257,
"text": "Let’s analyze by coloring the total number of recovered cases "
},
{
"code": null,
"e": 32328,
"s": 32320,
"text": "Python3"
},
{
"code": "px.bar(dataset1.head(15), x = 'Country/Region', y = 'TotalCases', color = 'TotalDeaths', height = 500, hover_data = ['Country/Region', 'Continent'])",
"e": 32489,
"s": 32328,
"text": null
},
{
"code": null,
"e": 32497,
"s": 32489,
"text": "Output:"
},
{
"code": null,
"e": 32561,
"s": 32497,
"text": "Visualize the same again by coloring the total number of tests."
},
{
"code": null,
"e": 32569,
"s": 32561,
"text": "Python3"
},
{
"code": "px.bar(dataset1.head(15), x = 'Country/Region', y = 'TotalCases', color = 'TotalTests', height = 500, hover_data = ['Country/Region', 'Continent'])",
"e": 32723,
"s": 32569,
"text": null
},
{
"code": null,
"e": 32731,
"s": 32723,
"text": "Output:"
},
{
"code": null,
"e": 32893,
"s": 32731,
"text": "The visualization could be as we have done with the top 15 countries with total cases, deaths, recoveries, and tests. We can analyze the plot by looking at them."
},
{
"code": null,
"e": 33070,
"s": 32893,
"text": "Let’s create a horizontal orientation plot with X-axis as ‘TotalTests’ and Y-axis as ‘Country/Region’ with passing parameter orientation=”h” and color the plot by ‘TotalTests’."
},
{
"code": null,
"e": 33078,
"s": 33070,
"text": "Python3"
},
{
"code": "px.bar(dataset1.head(15), x = 'TotalTests', y = 'Country/Region', color = 'TotalTests',orientation ='h', height = 500, hover_data = ['Country/Region', 'Continent'])",
"e": 33256,
"s": 33078,
"text": null
},
{
"code": null,
"e": 33264,
"s": 33256,
"text": "Output:"
},
{
"code": null,
"e": 33352,
"s": 33264,
"text": "Let’s look at ‘TotalTests’ followed by ‘Continent’ and color the plot with ‘Continent’."
},
{
"code": null,
"e": 33360,
"s": 33352,
"text": "Python3"
},
{
"code": "px.bar(dataset1.head(15), x = 'TotalTests', y = 'Continent', color = 'TotalTests',orientation ='h', height = 500, hover_data = ['Country/Region', 'Continent'])",
"e": 33533,
"s": 33360,
"text": null
},
{
"code": null,
"e": 33541,
"s": 33533,
"text": "Output:"
},
{
"code": null,
"e": 33590,
"s": 33541,
"text": "Total Tests & Continents(Horizontal Orientation)"
},
{
"code": null,
"e": 33774,
"s": 33590,
"text": "Let’s create a scatter plot and take a look at the continent’s statistics, firstly look at the total number of cases by continent and take hover data as ‘Country/Region’, ‘Continent’."
},
{
"code": null,
"e": 33782,
"s": 33774,
"text": "Python3"
},
{
"code": "px.scatter(dataset1, x='Continent',y='TotalCases', hover_data=['Country/Region', 'Continent'], color='TotalCases', size='TotalCases', size_max=80)",
"e": 33951,
"s": 33782,
"text": null
},
{
"code": null,
"e": 33959,
"s": 33951,
"text": "Output:"
},
{
"code": null,
"e": 34199,
"s": 33959,
"text": "log_y= True, the histogram axis (not the returned parameter) is in log scale. The return parameter (n, bins), i.e. the values of bins and sides of bins are the same for log=True and log=False. This means both n==n2 and bins==bins2 are true"
},
{
"code": null,
"e": 34207,
"s": 34199,
"text": "Python3"
},
{
"code": "px.scatter(dataset1.head(57), x='Continent',y='TotalCases', hover_data=['Country/Region', 'Continent'], color='TotalCases', size='TotalCases', size_max=80, log_y=True)",
"e": 34397,
"s": 34207,
"text": null
},
{
"code": null,
"e": 34405,
"s": 34397,
"text": "Output:"
},
{
"code": null,
"e": 34413,
"s": 34405,
"text": "Python3"
},
{
"code": "px.scatter(dataset1.head(54), x='Continent',y='TotalTests', hover_data=['Country/Region', 'Continent'], color='TotalTests', size='TotalTests', size_max=80)",
"e": 34591,
"s": 34413,
"text": null
},
{
"code": null,
"e": 34599,
"s": 34591,
"text": "Output:"
},
{
"code": null,
"e": 34607,
"s": 34599,
"text": "Python3"
},
{
"code": "px.scatter(dataset1.head(50), x='Continent',y='TotalTests', hover_data=['Country/Region', 'Continent'], color='TotalTests', size='TotalTests', size_max=80, log_y=True)",
"e": 34797,
"s": 34607,
"text": null
},
{
"code": null,
"e": 34805,
"s": 34797,
"text": "Output:"
},
{
"code": null,
"e": 35058,
"s": 34805,
"text": "Let’s take a look at the country-wise data visualization, first look at the continent with respect to the total number of deaths by the top 50 countries only and color the total number of deaths and take the hover data as ‘Country/Region’, ‘Continent’."
},
{
"code": null,
"e": 35066,
"s": 35058,
"text": "Python3"
},
{
"code": "px.scatter(dataset1.head(100), x='Country/Region', y='TotalCases', hover_data=['Country/Region', 'Continent'], color='TotalCases', size='TotalCases', size_max=80)",
"e": 35250,
"s": 35066,
"text": null
},
{
"code": null,
"e": 35258,
"s": 35250,
"text": "Output:"
},
{
"code": null,
"e": 35444,
"s": 35258,
"text": "Now, the Country/Region with respect to the total number of cases for top 30 countries only and color the total number of cases and take the hover data as ‘Country/Region’, ‘Continent’."
},
{
"code": null,
"e": 35452,
"s": 35444,
"text": "Python3"
},
{
"code": "px.scatter(dataset1.head(30), x='Country/Region', y='TotalCases', hover_data=['Country/Region', 'Continent'], color='Country/Region', size='TotalCases', size_max=80, log_y=True)",
"e": 35651,
"s": 35452,
"text": null
},
{
"code": null,
"e": 35659,
"s": 35651,
"text": "Output:"
},
{
"code": null,
"e": 35810,
"s": 35659,
"text": "Now format the image of the country/region in relation to the total number of deaths. And do the same for the other aspects of COVID-19 from dataset1."
},
{
"code": null,
"e": 35818,
"s": 35810,
"text": "Python3"
},
{
"code": "px.scatter(dataset1.head(10), x='Country/Region', y= 'TotalDeaths', hover_data=['Country/Region', 'Continent'], color='Country/Region', size= 'TotalDeaths', size_max=80)",
"e": 36009,
"s": 35818,
"text": null
},
{
"code": null,
"e": 36017,
"s": 36009,
"text": "Output:"
},
{
"code": null,
"e": 36025,
"s": 36017,
"text": "Python3"
},
{
"code": "px.scatter(dataset1.head(30), x='Country/Region', y= 'Tests/1M pop', hover_data=['Country/Region', 'Continent'], color='Country/Region', size= 'Tests/1M pop', size_max=80)",
"e": 36218,
"s": 36025,
"text": null
},
{
"code": null,
"e": 36226,
"s": 36218,
"text": "Output:"
},
{
"code": null,
"e": 36234,
"s": 36226,
"text": "Python3"
},
{
"code": "px.scatter(dataset1.head(30), x='Country/Region', y= 'Tests/1M pop', hover_data=['Country/Region', 'Continent'], color='Tests/1M pop', size= 'Tests/1M pop', size_max=80)",
"e": 36425,
"s": 36234,
"text": null
},
{
"code": null,
"e": 36434,
"s": 36425,
"text": "Output: "
},
{
"code": null,
"e": 36442,
"s": 36434,
"text": "Python3"
},
{
"code": "px.scatter(dataset1.head(30), x='TotalCases', y= 'TotalDeaths', hover_data=['Country/Region', 'Continent'], color='TotalDeaths', size= 'TotalDeaths', size_max=80)",
"e": 36626,
"s": 36442,
"text": null
},
{
"code": null,
"e": 36634,
"s": 36626,
"text": "Output:"
},
{
"code": null,
"e": 36801,
"s": 36634,
"text": "It is clear from the result that they have a linear relationship between the total number of cases and the total number of deaths. That means more cases, more deaths."
},
{
"code": null,
"e": 36809,
"s": 36801,
"text": "Python3"
},
{
"code": "px.scatter(dataset1.head(30), x='TotalCases', y= 'TotalDeaths', hover_data=['Country/Region', 'Continent'], color='TotalDeaths', size= 'TotalDeaths', size_max=80, log_x=True, log_y=True)",
"e": 37028,
"s": 36809,
"text": null
},
{
"code": null,
"e": 37036,
"s": 37028,
"text": "Output:"
},
{
"code": null,
"e": 37080,
"s": 37036,
"text": "TotalCases VS TotalDeaths (with log_y=True)"
},
{
"code": null,
"e": 37088,
"s": 37080,
"text": "Python3"
},
{
"code": "px.scatter(dataset1.head(30), x='TotalTests', y= 'TotalCases', hover_data=['Country/Region', 'Continent'], color='TotalTests', size= 'TotalTests', size_max=80, log_x=True, log_y=True)",
"e": 37304,
"s": 37088,
"text": null
},
{
"code": null,
"e": 37312,
"s": 37304,
"text": "Output:"
},
{
"code": null,
"e": 37338,
"s": 37312,
"text": "TotalTestes VS TotalCases"
},
{
"code": null,
"e": 37450,
"s": 37338,
"text": "In this task, we will explore covid-19 data using bar graphs and charts and use dataset2 as it has date column."
},
{
"code": null,
"e": 37458,
"s": 37450,
"text": "Python3"
},
{
"code": "px.bar(dataset2, x=\"Date\", y=\"Confirmed\", color=\"Confirmed\", hover_data=[\"Confirmed\", \"Date\", \"Country/Region\"], height=400)",
"e": 37590,
"s": 37458,
"text": null
},
{
"code": null,
"e": 37598,
"s": 37590,
"text": "Output:"
},
{
"code": null,
"e": 37808,
"s": 37598,
"text": "The above graph we get as output which includes all countries with respect to recovered cases. we can imagine the exponential growth of corona cases by date. We can use log function for this to be more clear. "
},
{
"code": null,
"e": 37816,
"s": 37808,
"text": "Python3"
},
{
"code": "px.bar(dataset2, x=\"Date\", y=\"Confirmed\", color=\"Confirmed\", hover_data=[\"Confirmed\", \"Date\", \"Country/Region\"],log_y=True, height=400)",
"e": 37959,
"s": 37816,
"text": null
},
{
"code": null,
"e": 37967,
"s": 37959,
"text": "Output:"
},
{
"code": null,
"e": 38047,
"s": 37967,
"text": "Let’s imagine death instead of confirmation with the same and color it by date."
},
{
"code": null,
"e": 38055,
"s": 38047,
"text": "Python3"
},
{
"code": "px.bar(dataset2, x=\"Date\", y=\"Deaths\", color=\"Deaths\", hover_data=[\"Confirmed\", \"Date\", \"Country/Region\"], log_y=False, height=400)",
"e": 38200,
"s": 38055,
"text": null
},
{
"code": null,
"e": 38208,
"s": 38200,
"text": "Output:"
},
{
"code": null,
"e": 38272,
"s": 38208,
"text": "In this specific task, we will analyze data of the USA country."
},
{
"code": null,
"e": 38280,
"s": 38272,
"text": "Python3"
},
{
"code": "df_US= dataset2.loc[dataset2[\"Country/Region\"]==\"US\"]",
"e": 38334,
"s": 38280,
"text": null
},
{
"code": null,
"e": 38392,
"s": 38334,
"text": "Now let us plot and study the covid situation in the USA."
},
{
"code": null,
"e": 38400,
"s": 38392,
"text": "Python3"
},
{
"code": "px.bar(df_US, x=\"Date\", y=\"Confirmed\", color=\"Confirmed\", height=400)",
"e": 38470,
"s": 38400,
"text": null
},
{
"code": null,
"e": 38478,
"s": 38470,
"text": "Output:"
},
{
"code": null,
"e": 38679,
"s": 38478,
"text": "Here we can clearly see how the confirmed cases increased in the United States with respect to time (January 2020 to July 2020). Similarly, we can check the same for recovered cases, tests and deaths."
},
{
"code": null,
"e": 38687,
"s": 38679,
"text": "Python3"
},
{
"code": "px.bar(df_US,x=\"Date\", y=\"Recovered\", color=\"Recovered\", height=400)",
"e": 38756,
"s": 38687,
"text": null
},
{
"code": null,
"e": 38764,
"s": 38756,
"text": "Output:"
},
{
"code": null,
"e": 38856,
"s": 38764,
"text": "Similarly, we can analyze the data in all the ways to generate the line graph for the same."
},
{
"code": null,
"e": 38864,
"s": 38856,
"text": "Python3"
},
{
"code": "px.line(df_US,x=\"Date\", y=\"Recovered\", height=400)",
"e": 38915,
"s": 38864,
"text": null
},
{
"code": null,
"e": 38923,
"s": 38915,
"text": "Output:"
},
{
"code": null,
"e": 38931,
"s": 38923,
"text": "Python3"
},
{
"code": "px.line(df_US,x=\"Date\", y=\"Deaths\", height=400)",
"e": 38979,
"s": 38931,
"text": null
},
{
"code": null,
"e": 38987,
"s": 38979,
"text": "Output:"
},
{
"code": null,
"e": 38995,
"s": 38987,
"text": "Python3"
},
{
"code": "px.line(df_US,x=\"Date\", y=\"Confirmed\", height=400)",
"e": 39046,
"s": 38995,
"text": null
},
{
"code": null,
"e": 39054,
"s": 39046,
"text": "Output:"
},
{
"code": null,
"e": 39062,
"s": 39054,
"text": "Python3"
},
{
"code": "px.line(df_US,x=\"Date\", y=\"New cases\", height=400)",
"e": 39113,
"s": 39062,
"text": null
},
{
"code": null,
"e": 39121,
"s": 39113,
"text": "Output:"
},
{
"code": null,
"e": 39190,
"s": 39121,
"text": "Now let us create bar charts and study the USA situation using that."
},
{
"code": null,
"e": 39198,
"s": 39190,
"text": "Python3"
},
{
"code": "px.bar(df_US,x=\"Date\", y=\"New cases\", height=400)",
"e": 39248,
"s": 39198,
"text": null
},
{
"code": null,
"e": 39256,
"s": 39248,
"text": "Output:"
},
{
"code": null,
"e": 39297,
"s": 39256,
"text": "Similarly, let us also plot a line plot."
},
{
"code": null,
"e": 39305,
"s": 39297,
"text": "Python3"
},
{
"code": "px.scatter(df_US, x=\"Confirmed\", y=\"Deaths\", height=400)",
"e": 39362,
"s": 39305,
"text": null
},
{
"code": null,
"e": 39370,
"s": 39362,
"text": "Output:"
},
{
"code": null,
"e": 39840,
"s": 39370,
"text": "We can use choropleth to visualize the data in terms of maps, with maps usually being the predominant way of visualizing the data. Since COVID-19 is a global phenomenon and so we look through and fix them in terms of wall maps. Ortho-graphics, rectangular and natural earth projection to visualize the data With dataset2 for the purpose as it has Dates column. It will look at the growth of Covid-19 (from Jan to July 2020) as in how the virus reached across the world."
},
{
"code": null,
"e": 40003,
"s": 39840,
"text": "Choropleth is an amazing representation of data on a map. Choropleth maps provide an easy way to visualize how a measurement varies across a geographic areal-Life"
},
{
"code": null,
"e": 40163,
"s": 40003,
"text": "Project Application in Real choropleth map displays divided geographical areas or regions that are colored, shaded or patterned in relation to a data variable."
},
{
"code": null,
"e": 40192,
"s": 40163,
"text": "Equi-rectangular Projection:"
},
{
"code": null,
"e": 40214,
"s": 40192,
"text": "Syntax: chloropleth()"
},
{
"code": null,
"e": 40226,
"s": 40214,
"text": "parameters:"
},
{
"code": null,
"e": 40234,
"s": 40226,
"text": "dataset"
},
{
"code": null,
"e": 40254,
"s": 40234,
"text": "locations= ISOALPHA"
},
{
"code": null,
"e": 40260,
"s": 40254,
"text": "color"
},
{
"code": null,
"e": 40271,
"s": 40260,
"text": "hover_name"
},
{
"code": null,
"e": 40323,
"s": 40271,
"text": "color_continuous_scale= [RdYlGn, Blues, Viridis...]"
},
{
"code": null,
"e": 40345,
"s": 40323,
"text": "animation_frame= Date"
},
{
"code": null,
"e": 40353,
"s": 40345,
"text": "Python3"
},
{
"code": "px.choropleth(dataset2, locations=\"iso_alpha\", color=\"Confirmed\", hover_name=\"Country/Region\", color_continuous_scale=\"Blues\", animation_frame=\"Date\")",
"e": 40570,
"s": 40353,
"text": null
},
{
"code": null,
"e": 40578,
"s": 40570,
"text": "Output:"
},
{
"code": null,
"e": 40801,
"s": 40578,
"text": "This creates an animation containing visualizations from January to July 2020. Playing this animation will make it more clear how the virus spread around the world. The darker the color, the higher the confirmed cases are."
},
{
"code": null,
"e": 40809,
"s": 40801,
"text": "Python3"
},
{
"code": "px.choropleth(dataset2, locations='iso_alpha', color=\"Deaths\", hover_name=\"Country/Region\", color_continuous_scale=\"Viridis\", animation_frame=\"Date\" )",
"e": 41025,
"s": 40809,
"text": null
},
{
"code": null,
"e": 41033,
"s": 41025,
"text": "Output:"
},
{
"code": null,
"e": 41169,
"s": 41033,
"text": "This code creates an animation of death cases by date. By playing this animation it will be shown how deaths increase around the world."
},
{
"code": null,
"e": 41260,
"s": 41169,
"text": "Natural Earth projection is a compromise pseudo-cylindrical map projection for world maps."
},
{
"code": null,
"e": 41268,
"s": 41260,
"text": "Python3"
},
{
"code": "px.choropleth(dataset2, locations='iso_alpha', color=\"Recovered\", hover_name=\"Country/Region\", color_continuous_scale=\"RdYlGn\", projection=\"natural earth\", animation_frame=\"Date\" )",
"e": 41527,
"s": 41268,
"text": null
},
{
"code": null,
"e": 41535,
"s": 41527,
"text": "Output:"
},
{
"code": null,
"e": 41802,
"s": 41535,
"text": "By running the output, things start to become more clear about how the recovery rate changes with respect to the date. Lets also look at how an animation can be added to a bar graph. We can convert the bar graph into animation using Dates column that is in dataset2."
},
{
"code": null,
"e": 41810,
"s": 41802,
"text": "Python3"
},
{
"code": "px.bar(dataset2, x=\"WHO Region\", y=\"Confirmed\", color=\"WHO Region\", animation_frame=\"Date\", hover_name=\"Country/Region\")",
"e": 41938,
"s": 41810,
"text": null
},
{
"code": null,
"e": 41946,
"s": 41938,
"text": "Output:"
},
{
"code": null,
"e": 42125,
"s": 41946,
"text": "When running the output, the animation will run from January to July 2020. It will show 6 different bar graphs, each continent has its own color representing the confirmed cases."
},
{
"code": null,
"e": 42354,
"s": 42125,
"text": "Visualize the causes of death due to covid-19, as covid-19 affects people in different ways, hence creating a word cloud to visualize the leading cause of covid-19 deaths. To visualize the text the steps need to be followed are-"
},
{
"code": null,
"e": 42407,
"s": 42354,
"text": "Used to convert data elements of an array into list."
},
{
"code": null,
"e": 42448,
"s": 42407,
"text": "Convert the string to one single string."
},
{
"code": null,
"e": 42483,
"s": 42448,
"text": "Convert the string into word cloud"
},
{
"code": null,
"e": 42599,
"s": 42483,
"text": "Dataset3: This dataset contains real world examples of number of Covid-19 deaths and the reasons behind the deaths."
},
{
"code": null,
"e": 42607,
"s": 42599,
"text": "Python3"
},
{
"code": "dataset3= pd.read_csv(\"covid+death.csv\")dataset3.head()",
"e": 42663,
"s": 42607,
"text": null
},
{
"code": null,
"e": 42671,
"s": 42663,
"text": "Output:"
},
{
"code": null,
"e": 42679,
"s": 42671,
"text": "Python3"
},
{
"code": "dataset3.tail()",
"e": 42695,
"s": 42679,
"text": null
},
{
"code": null,
"e": 42703,
"s": 42695,
"text": "Output:"
},
{
"code": null,
"e": 42711,
"s": 42703,
"text": "Python3"
},
{
"code": "dataset3.groupby([\"Condition\"]).count()",
"e": 42751,
"s": 42711,
"text": null
},
{
"code": null,
"e": 42759,
"s": 42751,
"text": "Output:"
},
{
"code": null,
"e": 42772,
"s": 42759,
"text": "Conditions "
},
{
"code": null,
"e": 42780,
"s": 42772,
"text": "Python3"
},
{
"code": "# import word cloudfrom wordcloud import WordCloud sentences = dataset3[\"Condition\"].tolist()sentences_as_a_string = ' '.join(sentences) # Convert the string into WordCloudplt.figure(figsize=(20, 20))plt.imshow(WordCloud().generate(sentences_as_a_string))",
"e": 43040,
"s": 42780,
"text": null
},
{
"code": null,
"e": 43048,
"s": 43040,
"text": "Output:"
},
{
"code": null,
"e": 43372,
"s": 43048,
"text": "From the output, it can be clearly seen that the leading cause of death is Influenza Pneumonia. We have converted the condition group to the list and stored the list in the variable “column_to_list”. Here we have converted the list into a single string and stored in a variable named “column2_to_string” by using .join()."
},
{
"code": null,
"e": 43380,
"s": 43372,
"text": "Python3"
},
{
"code": "column2_tolist= dataset3[\"Condition Group\"].tolist() # Convert the list to one single stringcolumn_to_string= \" \".join(column2_tolist) # Convert the string into WordCloudplt.figure(figsize=(20,20))plt.imshow(WordCloud().generate(column_to_string))",
"e": 43630,
"s": 43380,
"text": null
},
{
"code": null,
"e": 43638,
"s": 43630,
"text": "Output:"
},
{
"code": null,
"e": 43762,
"s": 43638,
"text": "Here, respiratory diseases are the major cause of death followed by circulatory diseases which are cardiovascular diseases."
},
{
"code": null,
"e": 43777,
"s": 43762,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 43796,
"s": 43777,
"text": "Data Visualization"
},
{
"code": null,
"e": 43810,
"s": 43796,
"text": "Python-Plotly"
},
{
"code": null,
"e": 43820,
"s": 43810,
"text": "Blogathon"
},
{
"code": null,
"e": 43827,
"s": 43820,
"text": "Python"
},
{
"code": null,
"e": 43925,
"s": 43827,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43966,
"s": 43925,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 44023,
"s": 43966,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 44058,
"s": 44023,
"text": "How to Install Tkinter in Windows?"
},
{
"code": null,
"e": 44096,
"s": 44058,
"text": "SQL Query to Convert Datetime to Date"
},
{
"code": null,
"e": 44141,
"s": 44096,
"text": "SQL Query to Create Table With a Primary Key"
},
{
"code": null,
"e": 44169,
"s": 44141,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 44219,
"s": 44169,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 44241,
"s": 44219,
"text": "Python map() function"
}
] |
How to create a bar plot with ggplot2 using stat_summary in R?
|
There are multiple ways to create a bar plot in R and one such way is using stat_summary of ggplot2 package. In this function, we need to supply a function for the y-axis and to create the bars we must use geom="bar". The main thing is to decide which function should be used for y-axis values.
Consider the below data frame:
Live Demo
> x<-sample(c("Male","Female"),20,replace=TRUE)
> y<-rpois(20,5)
> df<-data.frame(x,y)
> df
x y
1 Female 3
2 Male 3
3 Female 7
4 Male 3
5 Female 8
6 Female 5
7 Male 11
8 Male 6
9 Male 5
10 Female 3
11 Female 2
12 Female 7
13 Male 6
14 Female 5
15 Male 3
16 Male 6
17 Female 9
18 Female 6
19 Female 8
20 Female 3
Loading ggplot2 package and creating bar plot using stat_summary:
> library(ggplot2)
> ggplot(df,aes(x,y))+stat_summary(fun="mean",geom="bar")
|
[
{
"code": null,
"e": 1357,
"s": 1062,
"text": "There are multiple ways to create a bar plot in R and one such way is using stat_summary of ggplot2 package. In this function, we need to supply a function for the y-axis and to create the bars we must use geom=\"bar\". The main thing is to decide which function should be used for y-axis values."
},
{
"code": null,
"e": 1388,
"s": 1357,
"text": "Consider the below data frame:"
},
{
"code": null,
"e": 1398,
"s": 1388,
"text": "Live Demo"
},
{
"code": null,
"e": 1490,
"s": 1398,
"text": "> x<-sample(c(\"Male\",\"Female\"),20,replace=TRUE)\n> y<-rpois(20,5)\n> df<-data.frame(x,y)\n> df"
},
{
"code": null,
"e": 1717,
"s": 1490,
"text": " x y\n1 Female 3\n2 Male 3\n3 Female 7\n4 Male 3\n5 Female 8\n6 Female 5\n7 Male 11\n8 Male 6\n9 Male 5\n10 Female 3\n11 Female 2\n12 Female 7\n13 Male 6\n14 Female 5\n15 Male 3\n16 Male 6\n17 Female 9\n18 Female 6\n19 Female 8\n20 Female 3"
},
{
"code": null,
"e": 1783,
"s": 1717,
"text": "Loading ggplot2 package and creating bar plot using stat_summary:"
},
{
"code": null,
"e": 1860,
"s": 1783,
"text": "> library(ggplot2)\n> ggplot(df,aes(x,y))+stat_summary(fun=\"mean\",geom=\"bar\")"
}
] |
Nested Routing in React.js
|
import React, { Component } from 'react';
import { Link, Route, Switch } from 'react-router-dom';
import Category from './Category';
class App extends Component {
render() {
return (
<div>
<nav className="navbar navbar-light">
<ul className="nav navbar-nav">
<li><Link to="/">Main Page</Link></li>
<li><Link to="/users">Users</Link></li>
</ul>
</nav>
<Switch>
<Route exact path="/" component={MainPage}/>
<Route path="/users" component={Users}/>
</Switch>
</div>
);
}
}
export default App;
We have two components here MainPage and Users. MainPage is our main component which is mapped using exact keyword and path as ‘/’
The User component is where we will have the nested routing. The actual nesting will be implemented inside the Users component. Here in app.jsx file we will have only the parent link to the Users component.
import React from 'react';
import { Link, Route } from 'react-router-dom';
const Users = ({ match }) => {
return(
<div>
<ul>
<li><Link to={`${match.url}/David`}>David</Link></li>
<li><Link to={`${match.url}/Steve`}>Steve</Link></li>
<li><Link to={`${match.url}/John`}>John</Link></li>
</ul>
<Route path={`${match.path}/:name`} render= {({match}) =>( <div><h3> {match.params.name} </h3></div>)}/>
</div>
)
}
export default Users;
The match object contains the path /users and :name attribute contains the nesting for particular user. We have also created the Link components in Users for navigating to specific users.
Note the use of render attribute on Route path in Users component. Render is executing the function to display user.
|
[
{
"code": null,
"e": 1732,
"s": 1062,
"text": "import React, { Component } from 'react';\nimport { Link, Route, Switch } from 'react-router-dom';\nimport Category from './Category';\nclass App extends Component {\n render() {\n return (\n <div>\n <nav className=\"navbar navbar-light\">\n <ul className=\"nav navbar-nav\">\n <li><Link to=\"/\">Main Page</Link></li>\n <li><Link to=\"/users\">Users</Link></li>\n </ul>\n </nav>\n <Switch>\n <Route exact path=\"/\" component={MainPage}/>\n <Route path=\"/users\" component={Users}/>\n </Switch>\n </div>\n );\n }\n}\nexport default App;"
},
{
"code": null,
"e": 1863,
"s": 1732,
"text": "We have two components here MainPage and Users. MainPage is our main component which is mapped using exact keyword and path as ‘/’"
},
{
"code": null,
"e": 2070,
"s": 1863,
"text": "The User component is where we will have the nested routing. The actual nesting will be implemented inside the Users component. Here in app.jsx file we will have only the parent link to the Users component."
},
{
"code": null,
"e": 2580,
"s": 2070,
"text": "import React from 'react';\nimport { Link, Route } from 'react-router-dom';\nconst Users = ({ match }) => {\n return(\n <div>\n <ul>\n <li><Link to={`${match.url}/David`}>David</Link></li>\n <li><Link to={`${match.url}/Steve`}>Steve</Link></li>\n <li><Link to={`${match.url}/John`}>John</Link></li>\n </ul>\n <Route path={`${match.path}/:name`} render= {({match}) =>( <div><h3> {match.params.name} </h3></div>)}/>\n </div>\n )\n}\nexport default Users;"
},
{
"code": null,
"e": 2768,
"s": 2580,
"text": "The match object contains the path /users and :name attribute contains the nesting for particular user. We have also created the Link components in Users for navigating to specific users."
},
{
"code": null,
"e": 2885,
"s": 2768,
"text": "Note the use of render attribute on Route path in Users component. Render is executing the function to display user."
}
] |
Reverse Only Letters in Python
|
Suppose we have a string S, we have to find the reversed string where all characters that are not a letter will not change their positions and all letters reverse their positions. So if the given string is "a-bC-dEf-ghIj", then output will be "j-Ih-gfE-dCba"
To solve this, we will follow these steps −
We will use the regular expression library to solve this
if S is empty, then return S
str := an empty string, index1 := 0 and index2 := length of S – 1
while index1 < length of Sif index2 >= 0 and S[index1] is alphabet and S[index2] is alphabetstr := str + S[index2]decrease index2 by 1, and increase index1 by 1else if S[index1] is alphabet then decrease index2 by 1else if S[index1] is not alphabet, then str := str + S[index1], increase index1 by 1else decrease index2 by 1, and increase index1 by 1
if index2 >= 0 and S[index1] is alphabet and S[index2] is alphabetstr := str + S[index2]decrease index2 by 1, and increase index1 by 1
str := str + S[index2]
decrease index2 by 1, and increase index1 by 1
else if S[index1] is alphabet then decrease index2 by 1
else if S[index1] is not alphabet, then str := str + S[index1], increase index1 by 1
else decrease index2 by 1, and increase index1 by 1
return str
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
def reverseOnlyLetters(self, S):
if not S:
return S
str_= ""
index1 = 0
index2 = len(S)-1
while index1<len(S):
#print(index1,index2)
if index2>=0 and S[index1].isalpha() and S[index2].isalpha():
str_+=S[index2]
index2 -= 1
index1 += 1
elif S[index1].isalpha():
index2-=1
elif not S[index1].isalpha():
str_+=S[index1]
index1+=1
else:
index2 -= 1
index1 += 1
return str_
ob1 = Solution()
print(ob1.reverseOnlyLetters("a-bC-dEf-ghIj"))
"a-bC-dEf-ghIj"
"j-Ih-gfE-dCba"
|
[
{
"code": null,
"e": 1321,
"s": 1062,
"text": "Suppose we have a string S, we have to find the reversed string where all characters that are not a letter will not change their positions and all letters reverse their positions. So if the given string is \"a-bC-dEf-ghIj\", then output will be \"j-Ih-gfE-dCba\""
},
{
"code": null,
"e": 1365,
"s": 1321,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1422,
"s": 1365,
"text": "We will use the regular expression library to solve this"
},
{
"code": null,
"e": 1451,
"s": 1422,
"text": "if S is empty, then return S"
},
{
"code": null,
"e": 1517,
"s": 1451,
"text": "str := an empty string, index1 := 0 and index2 := length of S – 1"
},
{
"code": null,
"e": 1868,
"s": 1517,
"text": "while index1 < length of Sif index2 >= 0 and S[index1] is alphabet and S[index2] is alphabetstr := str + S[index2]decrease index2 by 1, and increase index1 by 1else if S[index1] is alphabet then decrease index2 by 1else if S[index1] is not alphabet, then str := str + S[index1], increase index1 by 1else decrease index2 by 1, and increase index1 by 1"
},
{
"code": null,
"e": 2003,
"s": 1868,
"text": "if index2 >= 0 and S[index1] is alphabet and S[index2] is alphabetstr := str + S[index2]decrease index2 by 1, and increase index1 by 1"
},
{
"code": null,
"e": 2026,
"s": 2003,
"text": "str := str + S[index2]"
},
{
"code": null,
"e": 2073,
"s": 2026,
"text": "decrease index2 by 1, and increase index1 by 1"
},
{
"code": null,
"e": 2129,
"s": 2073,
"text": "else if S[index1] is alphabet then decrease index2 by 1"
},
{
"code": null,
"e": 2214,
"s": 2129,
"text": "else if S[index1] is not alphabet, then str := str + S[index1], increase index1 by 1"
},
{
"code": null,
"e": 2266,
"s": 2214,
"text": "else decrease index2 by 1, and increase index1 by 1"
},
{
"code": null,
"e": 2277,
"s": 2266,
"text": "return str"
},
{
"code": null,
"e": 2347,
"s": 2277,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2358,
"s": 2347,
"text": " Live Demo"
},
{
"code": null,
"e": 2996,
"s": 2358,
"text": "class Solution:\n def reverseOnlyLetters(self, S):\n if not S:\n return S\n str_= \"\"\n index1 = 0\n index2 = len(S)-1\n while index1<len(S):\n #print(index1,index2)\n if index2>=0 and S[index1].isalpha() and S[index2].isalpha():\n str_+=S[index2]\n index2 -= 1\n index1 += 1\n elif S[index1].isalpha():\n index2-=1\n elif not S[index1].isalpha():\n str_+=S[index1]\n index1+=1\n else:\n index2 -= 1\n index1 += 1\n return str_\nob1 = Solution()\nprint(ob1.reverseOnlyLetters(\"a-bC-dEf-ghIj\"))"
},
{
"code": null,
"e": 3012,
"s": 2996,
"text": "\"a-bC-dEf-ghIj\""
},
{
"code": null,
"e": 3028,
"s": 3012,
"text": "\"j-Ih-gfE-dCba\""
}
] |
Performing inverse binary thresholding on an image using OpenCV
|
In this program, we will perform inverse binary thresholding on an image using openCV. Thresholding is a process in which the value of each pixel is changed in relation to a threshold value.
The pixel is given a certain value if it is less than the threshold and some other value if it is greater than the threshold. In inverse binary thresholding, if the value of the pixel is less than the threshold, it will be given a maximum value i.e. white. If it is greater than the threshold, it will be assigned 0, i.e., black.
Step 1: Import cv2.
Step 2: Define threshold and max_val.
Step 3: Pass these parameters in the cv2.threshold value and specify the type of thresholding you want to do.
Step 4: Display the output.
import cv2
image = cv2.imread('testimage.jpg')
threshold_value = 120
max_val = 255
ret, image = cv2.threshold(image, threshold_value, max_val, cv2.THRESH_BINARY_INV)
cv2.imshow('InverseBinaryThresholding', image)
The ret variable in the program simply returns the threshold value. For any pixels having value smaller than the threshold value, they are replaced by max_val, i.e., 255.
|
[
{
"code": null,
"e": 1253,
"s": 1062,
"text": "In this program, we will perform inverse binary thresholding on an image using openCV. Thresholding is a process in which the value of each pixel is changed in relation to a threshold value."
},
{
"code": null,
"e": 1583,
"s": 1253,
"text": "The pixel is given a certain value if it is less than the threshold and some other value if it is greater than the threshold. In inverse binary thresholding, if the value of the pixel is less than the threshold, it will be given a maximum value i.e. white. If it is greater than the threshold, it will be assigned 0, i.e., black."
},
{
"code": null,
"e": 1779,
"s": 1583,
"text": "Step 1: Import cv2.\nStep 2: Define threshold and max_val.\nStep 3: Pass these parameters in the cv2.threshold value and specify the type of thresholding you want to do.\nStep 4: Display the output."
},
{
"code": null,
"e": 1994,
"s": 1779,
"text": "import cv2\n\nimage = cv2.imread('testimage.jpg')\nthreshold_value = 120\nmax_val = 255\n\nret, image = cv2.threshold(image, threshold_value, max_val, cv2.THRESH_BINARY_INV)\ncv2.imshow('InverseBinaryThresholding', image)"
},
{
"code": null,
"e": 2165,
"s": 1994,
"text": "The ret variable in the program simply returns the threshold value. For any pixels having value smaller than the threshold value, they are replaced by max_val, i.e., 255."
}
] |
C++ Program to Implement Quick Sort with Given Complexity Constraint
|
Quick sort is based on divide-and-conquer. The average time complexity of this algorithm is O(n*log(n)) but the worst case complexity is O(n^2). To reduce the chances of the worst case here Quicksort is implemented using randomization.
Begin
pivot = h
Index = l
start = l and end = h
while start < end do
while a[start] <= pivot AND start < end do
start = start +1
done
while a[end] > pivot do
end = end – 1
done
if start < end then
swap a[start] with a[end]
done
a[low] = a[end]
a[end] = pivot
return end
End
Begin
n = rand()
pivot = l + n%(h-l+1);
Swap a[h] with a[pivot]
return Partition(a, l, h)
End
Begin
int pindex;
If (l<h)
pindex = RandomPivotPartition(a, l, h)
QuickSort(a, l, pindex-1)
QuickSort(a, pindex+1, h)
return 0
End
#include<iostream>
#include<cstdlib>
using namespace std;
void swap(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int Partition(int a[], int l, int h) {
int pivot, index, i;
index = l;
pivot = h;
for(i = l; i < h; i++) {
if(a[i] < a[pivot]) {
swap(&a[i], &a[index]);
index++;
}
}
swap(&a[pivot], &a[index]);
return index;
}
int RandomPivotPartition(int a[], int l, int h) {
int pvt, n, temp;
n = rand();
pvt = l + n%(h-l+1);
swap(&a[h], &a[pvt]);
return Partition(a, l, h);
}
int QuickSort(int a[], int l, int h) {
int pindex;
if(l < h) {
pindex = RandomPivotPartition(a, l, h);
QuickSort(a, l, pindex-1);
QuickSort(a, pindex+1, h);
}
return 0;
}
int main() {
int n, i;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;
int arr[n];
for(i = 0; i < n; i++) {
cout<<"Enter element "<<i+1<<": ";
cin>>arr[i];
}
QuickSort(arr, 0, n-1);
cout<<"\nSorted Data ";
for (i = 0; i < n; i++)
cout<<"->"<<arr[i];
return 0;
}
Enter the number of data element to be sorted: 4 Enter element 1: 3
Enter element 2: 4
Enter element 3: 7
Enter element 4: 6
Sorted Data ->3->4->6->7
|
[
{
"code": null,
"e": 1298,
"s": 1062,
"text": "Quick sort is based on divide-and-conquer. The average time complexity of this algorithm is O(n*log(n)) but the worst case complexity is O(n^2). To reduce the chances of the worst case here Quicksort is implemented using randomization."
},
{
"code": null,
"e": 1662,
"s": 1298,
"text": "Begin\n pivot = h\n Index = l\n start = l and end = h\n while start < end do\n while a[start] <= pivot AND start < end do\n start = start +1\n done\n while a[end] > pivot do\n end = end – 1\n done\n if start < end then\n swap a[start] with a[end]\n done\n a[low] = a[end]\n a[end] = pivot\n return end\nEnd"
},
{
"code": null,
"e": 1768,
"s": 1662,
"text": "Begin\n n = rand()\n pivot = l + n%(h-l+1);\n Swap a[h] with a[pivot]\n return Partition(a, l, h)\nEnd"
},
{
"code": null,
"e": 1926,
"s": 1768,
"text": "Begin\n int pindex;\n If (l<h)\n pindex = RandomPivotPartition(a, l, h)\n QuickSort(a, l, pindex-1)\n QuickSort(a, pindex+1, h)\n return 0\nEnd"
},
{
"code": null,
"e": 3028,
"s": 1926,
"text": "#include<iostream>\n#include<cstdlib>\n\nusing namespace std;\n\nvoid swap(int *a, int *b) {\n int temp;\n temp = *a;\n *a = *b;\n *b = temp;\n}\n\nint Partition(int a[], int l, int h) {\n int pivot, index, i;\n index = l;\n pivot = h;\n for(i = l; i < h; i++) {\n if(a[i] < a[pivot]) {\n swap(&a[i], &a[index]);\n index++;\n }\n }\n swap(&a[pivot], &a[index]);\n return index;\n}\nint RandomPivotPartition(int a[], int l, int h) {\n int pvt, n, temp;\n n = rand();\n pvt = l + n%(h-l+1);\n swap(&a[h], &a[pvt]);\n return Partition(a, l, h);\n}\nint QuickSort(int a[], int l, int h) {\n int pindex;\n if(l < h) {\n pindex = RandomPivotPartition(a, l, h);\n QuickSort(a, l, pindex-1);\n QuickSort(a, pindex+1, h);\n }\n return 0;\n}\nint main() {\n int n, i;\n cout<<\"\\nEnter the number of data element to be sorted: \";\n cin>>n;\n int arr[n];\n for(i = 0; i < n; i++) {\n cout<<\"Enter element \"<<i+1<<\": \";\n cin>>arr[i];\n }\n QuickSort(arr, 0, n-1);\n cout<<\"\\nSorted Data \";\n for (i = 0; i < n; i++)\n cout<<\"->\"<<arr[i];\n return 0;\n}"
},
{
"code": null,
"e": 3178,
"s": 3028,
"text": "Enter the number of data element to be sorted: 4 Enter element 1: 3\nEnter element 2: 4\nEnter element 3: 7\nEnter element 4: 6\nSorted Data ->3->4->6->7"
}
] |
What are finalizers in C#?
|
Finalizers in C# are used to destruct instances of classes. With that, you can also use it to release resources.
Here are some of the key points about Finalizers −
Only one finalizer is allowed for a class
You cannot inherit or overload Finalizers
A finalizer cannot have parameters
Finalizers invoke automatically
Finalizers in C# are declared like destructors. Let’s say the class name is Demo, therefore, the following would be our finalizer −
~Demo() {
//
}
The finalizer declaration is prefixed with a tilde before the class name.
|
[
{
"code": null,
"e": 1175,
"s": 1062,
"text": "Finalizers in C# are used to destruct instances of classes. With that, you can also use it to release resources."
},
{
"code": null,
"e": 1226,
"s": 1175,
"text": "Here are some of the key points about Finalizers −"
},
{
"code": null,
"e": 1268,
"s": 1226,
"text": "Only one finalizer is allowed for a class"
},
{
"code": null,
"e": 1310,
"s": 1268,
"text": "You cannot inherit or overload Finalizers"
},
{
"code": null,
"e": 1345,
"s": 1310,
"text": "A finalizer cannot have parameters"
},
{
"code": null,
"e": 1377,
"s": 1345,
"text": "Finalizers invoke automatically"
},
{
"code": null,
"e": 1509,
"s": 1377,
"text": "Finalizers in C# are declared like destructors. Let’s say the class name is Demo, therefore, the following would be our finalizer −"
},
{
"code": null,
"e": 1527,
"s": 1509,
"text": "~Demo() {\n //\n}"
},
{
"code": null,
"e": 1601,
"s": 1527,
"text": "The finalizer declaration is prefixed with a tilde before the class name."
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.