title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Basic Line Chart With Customizable axis and tick labels
Following is an example of a basic line chart with customized axis and tick labels. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example. We've added textStyle and titleTextStyle configurations to change default text styles. // Set chart options var options = { textStyle: { color: '#01579b', fontSize: 20, fontName: 'Arial', bold: true, italic: true }, titleTextStyle: { color: '#01579b', fontSize: 16, fontName: 'Arial', bold: false, italic: true } }; googlecharts_line_axis.htm <html> <head> <title>Google Charts Tutorial</title> <script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js"> </script> <script type = "text/javascript"> google.charts.load('current', {packages: ['corechart','line']}); </script> </head> <body> <div id = "container" style = "width: 550px; height: 400px; margin: 0 auto"> </div> <script language = "JavaScript"> function drawChart() { // Define the chart to be drawn. var data = new google.visualization.DataTable(); data.addColumn('string', 'Month'); data.addColumn('number', 'Tokyo'); data.addColumn('number', 'New York'); data.addColumn('number', 'Berlin'); data.addColumn('number', 'London'); data.addRows([ ['Jan', 7.0, -0.2, -0.9, 3.9], ['Feb', 6.9, 0.8, 0.6, 4.2], ['Mar', 9.5, 5.7, 3.5, 5.7], ['Apr', 14.5, 11.3, 8.4, 8.5], ['May', 18.2, 17.0, 13.5, 11.9], ['Jun', 21.5, 22.0, 17.0, 15.2], ['Jul', 25.2, 24.8, 18.6, 17.0], ['Aug', 26.5, 24.1, 17.9, 16.6], ['Sep', 23.3, 20.1, 14.3, 14.2], ['Oct', 18.3, 14.1, 9.0, 10.3], ['Nov', 13.9, 8.6, 3.9, 6.6], ['Dec', 9.6, 2.5, 1.0, 4.8] ]); // Set chart options var options = {'title' : 'Average Temperatures of Cities', hAxis: { title: 'Month', textStyle: { color: '#01579b', fontSize: 20, fontName: 'Arial', bold: true, italic: true }, titleTextStyle: { color: '#01579b', fontSize: 16, fontName: 'Arial', bold: false, italic: true } }, vAxis: { title: 'Temperature', textStyle: { color: '#1a237e', fontSize: 24, bold: true }, titleTextStyle: { color: '#1a237e', fontSize: 24, bold: true } }, 'width':550, 'height':400, colors: ['#a52714', '#0000ff', '#ff0000', '#00ff00'] }; // Instantiate and draw the chart. var chart = new google.visualization.LineChart(document.getElementById('container')); chart.draw(data, options); } google.charts.setOnLoadCallback(drawChart); </script> </body> </html> Verify the result. Print Add Notes Bookmark this page
[ { "code": null, "e": 2489, "s": 2261, "text": "Following is an example of a basic line chart with customized axis and tick labels. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example." }, { "code": null, "e": 2576, "s": 2489, "text": "We've added textStyle and titleTextStyle configurations to change default text styles." }, { "code": null, "e": 2877, "s": 2576, "text": "// Set chart options\nvar options = {\n textStyle: {\n color: '#01579b',\n fontSize: 20,\n fontName: 'Arial',\n bold: true,\n italic: true\n },\n titleTextStyle: {\n color: '#01579b',\n fontSize: 16,\n fontName: 'Arial',\n bold: false,\n italic: true\n }\n};" }, { "code": null, "e": 2904, "s": 2877, "text": "googlecharts_line_axis.htm" }, { "code": null, "e": 5915, "s": 2904, "text": "<html>\n <head>\n <title>Google Charts Tutorial</title>\n <script type = \"text/javascript\" src = \"https://www.gstatic.com/charts/loader.js\">\n </script>\n <script type = \"text/javascript\">\n google.charts.load('current', {packages: ['corechart','line']}); \n </script>\n </head>\n\n <body>\n <div id = \"container\" style = \"width: 550px; height: 400px; margin: 0 auto\">\n </div>\n <script language = \"JavaScript\">\n function drawChart() {\n // Define the chart to be drawn.\n var data = new google.visualization.DataTable();\n data.addColumn('string', 'Month');\n data.addColumn('number', 'Tokyo');\n data.addColumn('number', 'New York');\n data.addColumn('number', 'Berlin');\n data.addColumn('number', 'London');\n data.addRows([\n ['Jan', 7.0, -0.2, -0.9, 3.9],\n ['Feb', 6.9, 0.8, 0.6, 4.2],\n ['Mar', 9.5, 5.7, 3.5, 5.7],\n ['Apr', 14.5, 11.3, 8.4, 8.5],\n ['May', 18.2, 17.0, 13.5, 11.9],\n ['Jun', 21.5, 22.0, 17.0, 15.2],\n \n ['Jul', 25.2, 24.8, 18.6, 17.0],\n ['Aug', 26.5, 24.1, 17.9, 16.6],\n ['Sep', 23.3, 20.1, 14.3, 14.2],\n ['Oct', 18.3, 14.1, 9.0, 10.3],\n ['Nov', 13.9, 8.6, 3.9, 6.6],\n ['Dec', 9.6, 2.5, 1.0, 4.8]\n ]);\n \n // Set chart options\n var options = {'title' : 'Average Temperatures of Cities',\n hAxis: {\n title: 'Month',\n textStyle: {\n color: '#01579b',\n fontSize: 20,\n fontName: 'Arial',\n bold: true,\n italic: true\n },\n \n titleTextStyle: {\n color: '#01579b',\n fontSize: 16,\n fontName: 'Arial',\n bold: false,\n italic: true\n }\n },\n \n vAxis: {\n title: 'Temperature',\n textStyle: {\n color: '#1a237e',\n fontSize: 24,\n bold: true\n },\n titleTextStyle: {\n color: '#1a237e',\n fontSize: 24,\n bold: true\n }\n }, \n \n 'width':550,\n 'height':400,\t \n colors: ['#a52714', '#0000ff', '#ff0000', '#00ff00']\n };\n\n // Instantiate and draw the chart.\n var chart = new google.visualization.LineChart(document.getElementById('container'));\n chart.draw(data, options);\n }\n google.charts.setOnLoadCallback(drawChart);\n </script>\n </body>\n</html>" }, { "code": null, "e": 5934, "s": 5915, "text": "Verify the result." }, { "code": null, "e": 5941, "s": 5934, "text": " Print" }, { "code": null, "e": 5952, "s": 5941, "text": " Add Notes" } ]
Use LIKE % to fetch multiple values in a single MySQL query
To fetch multiple values wit LIKE, use the LIKE operator along with OR operator. Let us first create a table − mysql> create table DemoTable1027 ( Id int, Name varchar(100) ); Query OK, 0 rows affected (1.64 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1027 values(100,'John'); Query OK, 1 row affected (0.72 sec) mysql> insert into DemoTable1027 values(20,'Chris'); Query OK, 1 row affected (0.56 sec) mysql> insert into DemoTable1027 values(200,'Robert'); Query OK, 1 row affected (0.84 sec) mysql> insert into DemoTable1027 values(400,'Mike'); Query OK, 1 row affected (0.47 sec) Display all records from the table using select statement − mysql> select *from DemoTable1027; This will produce the following output − +------+--------+ | Id | Name | +------+--------+ | 100 | John | | 20 | Chris | | 200 | Robert | | 400 | Mike | +------+--------+ 4 rows in set (0.00 sec) Following is the query to use LIKE and fetch multiple records − mysql> select *from DemoTable1027 where Id LIKE '%100%' or Id LIKE '%200%'; This will produce the following output − +------+--------+ | Id | Name | +------+--------+ | 100 | John | | 200 | Robert | +------+--------+ 2 rows in set (0.74 sec)
[ { "code": null, "e": 1173, "s": 1062, "text": "To fetch multiple values wit LIKE, use the LIKE operator along with OR operator. Let us first create a table −" }, { "code": null, "e": 1281, "s": 1173, "text": "mysql> create table DemoTable1027\n(\n Id int,\n Name varchar(100)\n);\nQuery OK, 0 rows affected (1.64 sec)" }, { "code": null, "e": 1337, "s": 1281, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1695, "s": 1337, "text": "mysql> insert into DemoTable1027 values(100,'John');\nQuery OK, 1 row affected (0.72 sec)\nmysql> insert into DemoTable1027 values(20,'Chris');\nQuery OK, 1 row affected (0.56 sec)\nmysql> insert into DemoTable1027 values(200,'Robert');\nQuery OK, 1 row affected (0.84 sec)\nmysql> insert into DemoTable1027 values(400,'Mike');\nQuery OK, 1 row affected (0.47 sec)" }, { "code": null, "e": 1755, "s": 1695, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1790, "s": 1755, "text": "mysql> select *from DemoTable1027;" }, { "code": null, "e": 1831, "s": 1790, "text": "This will produce the following output −" }, { "code": null, "e": 2002, "s": 1831, "text": "+------+--------+\n| Id | Name | \n+------+--------+\n| 100 | John |\n| 20 | Chris |\n| 200 | Robert |\n| 400 | Mike |\n+------+--------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2066, "s": 2002, "text": "Following is the query to use LIKE and fetch multiple records −" }, { "code": null, "e": 2142, "s": 2066, "text": "mysql> select *from DemoTable1027 where Id LIKE '%100%' or Id LIKE '%200%';" }, { "code": null, "e": 2183, "s": 2142, "text": "This will produce the following output −" }, { "code": null, "e": 2316, "s": 2183, "text": "+------+--------+\n| Id | Name |\n+------+--------+\n| 100 | John |\n| 200 | Robert |\n+------+--------+\n2 rows in set (0.74 sec)" } ]
How to work with Invoke-Command Scriptblock output?
When we simply write the Invoke-Command, it shows the output on the console. Invoke-Command -ComputerName Test1-Win2k12 -ScriptBlock {Get-Service} It shows the output along with the computer name. Now let's say you want to sort the output or you want to work with the output you need to store it. It is similar like we store the output in the variable but we can’t store the output inside the scriptblock and display it outside. $ser = @() Invoke-Command -ComputerName Test1-Win2k12 -ScriptBlock {$ser = Get-Service} Write-Output "Services output" $ser You won’t get any output of the above command because Invoke-Command is known to work on the remote computer. Instead, we can use the RETURN command to return the output to the main console. $ser = @() Invoke-Command -ComputerName Test1-Win2k12 -ScriptBlock {$ser = Get-Service return $ser } Write-Output "Services output" $ser You will get the output shown in the first image. You can also store the entire output in the variable if you further want to work with the output. $sb = Invoke-Command -ComputerName Test1-Win2k12 -ScriptBlock { Get-Service} Write-Output "Services output" $sb You can also filter the above output. $sb = Invoke-Command -ComputerName Test1-Win2k12 -ScriptBlock {Get-Service} Write-Output "Services output" $sb | Select Name, Status
[ { "code": null, "e": 1139, "s": 1062, "text": "When we simply write the Invoke-Command, it shows the output on the console." }, { "code": null, "e": 1209, "s": 1139, "text": "Invoke-Command -ComputerName Test1-Win2k12 -ScriptBlock {Get-Service}" }, { "code": null, "e": 1259, "s": 1209, "text": "It shows the output along with the computer name." }, { "code": null, "e": 1491, "s": 1259, "text": "Now let's say you want to sort the output or you want to work with the output you need to store it. It is similar like we store the output in the variable but we can’t store the output inside the scriptblock and display it outside." }, { "code": null, "e": 1615, "s": 1491, "text": "$ser = @()\nInvoke-Command -ComputerName Test1-Win2k12 -ScriptBlock {$ser = Get-Service}\nWrite-Output \"Services output\"\n$ser" }, { "code": null, "e": 1806, "s": 1615, "text": "You won’t get any output of the above command because Invoke-Command is known to work on the remote computer. Instead, we can use the RETURN command to return the output to the main console." }, { "code": null, "e": 1946, "s": 1806, "text": "$ser = @()\nInvoke-Command -ComputerName Test1-Win2k12 -ScriptBlock {$ser = Get-Service\n return $ser\n}\nWrite-Output \"Services output\"\n$ser" }, { "code": null, "e": 2094, "s": 1946, "text": "You will get the output shown in the first image. You can also store the entire output in the variable if you further want to work with the output." }, { "code": null, "e": 2206, "s": 2094, "text": "$sb = Invoke-Command -ComputerName Test1-Win2k12 -ScriptBlock { Get-Service}\nWrite-Output \"Services output\"\n$sb" }, { "code": null, "e": 2244, "s": 2206, "text": "You can also filter the above output." }, { "code": null, "e": 2377, "s": 2244, "text": "$sb = Invoke-Command -ComputerName Test1-Win2k12 -ScriptBlock {Get-Service}\nWrite-Output \"Services output\"\n$sb | Select Name, Status" } ]
How to read Microsoft Word with Python?
No offense, I do not like Microsoft word neither spreadsheets. Being a Data Engineering specialist, I often receive test results from testers in Microsoft word. Sigh! they put so much information into word document right from capturing screen shots, links, big, very big, very very big paragraphs. Microsoft word had particular talent for turning what should be simple text documents or small information into large, slow, nasty-to-open beasts that often lose formatting from machine to machine. But, I need to accept the fact that what ever is bad for me is very good for others and vice versa. Back to context, Python support for word is not great. Python-docx library gives users the ability to create documents and read only basic file data such as the size and title of the file, not the actual contents. So, for me to process the test results have to come up with custom code. I will import a sample word document available on internet. The file is in the location - https://file-examples-com.github.io/uploads/2017/02/file-sample_100kB.docx. 1. Let us begin with imports. from zipfile import ZipFile from urllib.request import urlopen from io import BytesIO 2.Now we will read a remote Word document as a binary file object. We then unzips it using zipfile library, and then reads the unzipped file, which is XML. Offcourse, we will print the content. file_url = 'https://file-examples-com.github.io/uploads/2017/02/file-sample_100kB.docx' # read the word document wordDocx = urlopen(file_url).read() wordDocx = BytesIO(wordDocx) document = ZipFile(wordDocx) #get the xml content xml_content = document.read('word/document.xml') # print the xml content print(xml_content.decode('utf-8')) <?xml version='1.0' encoding='UTF-8' standalone='yes'?> <w:document xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:r='http://schemas.openxmlformats.org/officeDocument/2006/relationships' xmlns:v='urn:schemas-microsoft-com:vml' xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' xmlns:w10='urn:schemas-microsoft-com:office:word' xmlns:wp='http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing'><w:background w:color='FFFFFF'/><w:body><w:p><w:pPr><w:pStyle w:val='Title'/><w:spacing w:before='240' w:after='120'/><w:jc w:val='center'/><w:rPr></w:rPr></w:pPr><w:r><w:rPr></w:rPr><w:t xml:space='preserve'>Lorem ipsum </w:t></w:r></w:p><w:p><w:pPr><w:pStyle w:val='TextBody'/><w:widowControl/><w:pBdr><w:top w:val='nil'/><w:left w:val='nil'/><w:bottom w:val='nil'/><w:right w:val='nil'/></w:pBdr><w:spacing w:before='0' w:after='225'/><w:jc w:val='both'/><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:r></w:p><w:p><w:pPr><w:pStyle w:val='Heading1'/><w:keepNext/><w:numPr><w:ilvl w:val='0'/><w:numId w:val='1'/></w:numPr><w:spacing w:before='240' w:after='120'/><w:ind w:left='0' w:right='0' w:hanging='432'/><w:rPr></w:rPr></w:pPr><w:r><w:rPr></w:rPr><w:t xml:space='preserve'>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc ac faucibus odio. </w:t></w:r></w:p><w:p><w:pPr><w:pStyle w:val='TextBody'/><w:widowControl/><w:pBdr><w:top w:val='nil'/><w:left w:val='nil'/><w:bottom w:val='nil'/><w:right w:val='nil'/></w:pBdr><w:spacing w:before='0' w:after='225'/><w:jc w:val='both'/><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:r></w:p><w:p><w:pPr><w:pStyle w:val='TextBody'/><w:widowControl/><w:pBdr><w:top w:val='nil'/><w:left w:val='nil'/><w:bottom w:val='nil'/><w:right w:val='nil'/></w:pBdr><w:spacing w:before='0' w:after='225'/><w:jc w:val='both'/><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr><w:t xml:space='preserve'>Vestibulum neque massa, scelerisque sit amet ligula eu, congue molestie mi. Praesent ut varius sem. Nullam at porttitor arcu, nec lacinia nisi. Ut ac dolor vitae odio interdum condimentum. </w:t></w:r><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b/><w:bCs/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr><w:t xml:space='preserve'>Vivamus dapibus sodales ex, vitae malesuada ipsum cursus convallis. Maecenas sed egestas nulla, ac condimentum orci. </w:t></w:r><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr><w:t xml:space='preserve'>Mauris diam felis, vulputate ac suscipit et, iaculis non est. Curabitur semper arcu ac ligula semper, nec luctus nisl blandit. Integer lacinia ante ac libero lobortis imperdiet. </w:t></w:r><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i/><w:iCs/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr><w:t xml:space='preserve'>Nullam mollis convallis ipsum, ac accumsan nunc vehicula vitae. </w:t></w:r><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr><w:t>Nulla eget justo in felis tristique fringilla. Morbi sit amet tortor quis risus auctor condimentum. Morbi in ullamcorper elit. Nulla iaculis tellus sit amet mauris tempus fringilla.</w:t></w:r></w:p><w:p><w:pPr><w:pStyle w:val='TextBody'/><w:widowControl/><w:pBdr><w:top w:val='nil'/><w:left w:val='nil'/><w:bottom w:val='nil'/><w:right w:val='nil'/></w:pBdr><w:spacing w:before='0' w:after='225'/><w:jc w:val='both'/><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr><w:t>Maecenas mauris lectus, lobortis et purus mattis, blandit dictum tellus.</w:t></w:r></w:p><w:p><w:pPr><w:pStyle w:val='TextBody'/><w:widowControl/><w:numPr><w:ilvl w:val='0'/><w:numId w:val='2'/></w:numPr><w:pBdr><w:top w:val='nil'/><w:left w:val='nil'/><w:bottom w:val='nil'/><w:right w:val='nil'/></w:pBdr><w:spacing w:before='0' w:after='225'/><w:jc w:val='both'/><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b/><w:bCs/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b/><w:bCs/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr><w:t xml:space='preserve'>Maecenas non lorem quis tellus placerat varius. </w:t></w:r></w:p><w:p><w:pPr><w:pStyle w:val='TextBody'/><w:widowControl/><w:numPr><w:ilvl w:val='0'/><w:numId w:val='2'/></w:numPr><w:pBdr><w:top w:val='nil'/><w:left w:val='nil'/><w:bottom w:val='nil'/><w:right w:val='nil'/></w:pBdr><w:spacing w:before='0' w:after='225'/><w:jc w:val='both'/><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i/><w:iCs/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i/><w:iCs/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr><w:t xml:space='preserve'>Nulla facilisi. </w:t></w:r></w:p><w:p><w:pPr><w:pStyle w:val='TextBody'/><w:widowControl/><w:numPr><w:ilvl w:val='0'/><w:numId w:val='2'/></w:numPr><w:pBdr><w:top w:val='nil'/><w:left w:val='nil'/><w:bottom w:val='nil'/><w:right w:val='nil'/></w:pBdr><w:spacing w:before='0' w:after='225'/><w:jc w:val='both'/><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/><w:u w:val='single'/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/><w:u w:val='single'/></w:rPr><w:t xml:space='preserve'>Aenean congue fringilla justo ut aliquam. </w:t></w:r></w:p><w:p><w:pPr><w:pStyle w:val='TextBody'/><w:widowControl/><w:numPr><w:ilvl w:val='0'/><w:numId w:val='2'/></w:numPr><w:pBdr><w:top w:val='nil'/><w:left w:val='nil'/><w:bottom w:val='nil'/><w:right w:val='nil'/></w:pBdr><w:spacing w:before='0' w:after='225'/><w:jc w:val='both'/><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:pPr><w:hyperlink r:id='rId2'><w:r><w:rPr><w:rStyle w:val='InternetLink'/><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr><w:t xml:space='preserve'>Mauris id ex erat. </w:t></w:r></w:hyperlink><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr><w:t xml:space='preserve'>Nunc vulputate neque vitae justo facilisis, non condimentum ante sagittis. </w:t></w:r></w:p><w:p><w:pPr><w:pStyle w:val='TextBody'/><w:widowControl/><w:numPr><w:ilvl w:val='0'/><w:numId w:val='2'/></w:numPr><w:pBdr><w:top w:val='nil'/><w:left w:val='nil'/><w:bottom w:val='nil'/><w:right w:val='nil'/></w:pBdr><w:spacing w:before='0' w:after='225'/><w:jc w:val='both'/><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr><w:t xml:space='preserve'>Morbi viverra semper lorem nec molestie. </w:t></w:r></w:p><w:p><w:pPr><w:pStyle w:val='TextBody'/><w:widowControl/><w:numPr><w:ilvl w:val='0'/><w:numId w:val='2'/></w:numPr><w:pBdr><w:top w:val='nil'/><w:left w:val='nil'/><w:bottom w:val='nil'/><w:right w:val='nil'/></w:pBdr><w:spacing w:before='0' w:after='225'/><w:jc w:val='both'/><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr><w:t>Maecenas tincidunt est efficitur ligula euismod, sit amet ornare est vulputate.</w:t></w:r></w:p><w:p><w:pPr><w:pStyle w:val='TextBody'/><w:widowControl/><w:pBdr><w:top w:val='nil'/><w:left w:val='nil'/><w:bottom w:val='nil'/><w:right w:val='nil'/></w:pBdr><w:spacing w:before='0' w:after='225'/><w:jc w:val='both'/><w:rPr></w:rPr></w:pPr><w:r><w:rPr></w:rPr><w:drawing><wp:inline distT='0' distB='0' distL='0' distR='0'><wp:extent cx='4098290' cy='2059305'/><wp:effectExtent l='0' t='0' r='0' b='0'/><wp:docPr id='1' name=''/><wp:cNvGraphicFramePr/><a:graphic xmlns:a='http://schemas.openxmlformats.org/drawingml/2006/main'><a:graphicData uri='http://schemas.openxmlformats.org/drawingml/2006/chart'><c:chart xmlns:c='http://schemas.openxmlformats.org/drawingml/2006/chart' xmlns:r='http://schemas.openxmlformats.org/officeDocument/2006/relationships' r:id='rId3'/></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p><w:p><w:pPr><w:pStyle w:val='TextBody'/><w:widowControl/><w:pBdr><w:top w:val='nil'/><w:left w:val='nil'/><w:bottom w:val='nil'/><w:right w:val='nil'/></w:pBdr><w:spacing w:before='0' w:after='225'/><w:jc w:val='both'/><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:r></w:p><w:p><w:pPr><w:pStyle w:val='TextBody'/><w:widowControl/><w:pBdr><w:top w:val='nil'/><w:left w:val='nil'/><w:bottom w:val='nil'/><w:right w:val='nil'/></w:pBdr><w:spacing w:before='0' w:after='225'/><w:jc w:val='both'/><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:r></w:p><w:p><w:pPr><w:pStyle w:val='TextBody'/><w:widowControl/><w:pBdr><w:top w:val='nil'/><w:left w:val='nil'/><w:bottom w:val='nil'/><w:right w:val='nil'/></w:pBdr><w:spacing w:before='0' w:after='225'/><w:jc w:val='both'/><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:r></w:p><w:p><w:pPr><w:pStyle w:val='TextBody'/><w:widowControl/><w:pBdr><w:top w:val='nil'/><w:left w:val='nil'/><w:bottom w:val='nil'/><w:right w:val='nil'/></w:pBdr><w:spacing w:before='0' w:after='225'/><w:jc w:val='both'/><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:r></w:p><w:p><w:pPr><w:pStyle w:val='TextBody'/><w:widowControl/><w:pBdr><w:top w:val='nil'/><w:left w:val='nil'/><w:bottom w:val='nil'/><w:right w:val='nil'/></w:pBdr><w:spacing w:before='0' w:after='225'/><w:jc w:val='both'/><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:r></w:p><w:p><w:pPr><w:pStyle w:val='TextBody'/><w:widowControl/><w:pBdr><w:top w:val='nil'/><w:left w:val='nil'/><w:bottom w:val='nil'/><w:right w:val='nil'/></w:pBdr><w:spacing w:before='0' w:after='225'/><w:jc w:val='both'/><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:r></w:p><w:p><w:pPr><w:pStyle w:val='TextBody'/><w:widowControl/><w:pBdr><w:top w:val='nil'/><w:left w:val='nil'/><w:bottom w:val='nil'/><w:right w:val='nil'/></w:pBdr><w:spacing w:before='0' w:after='225'/><w:jc w:val='both'/><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:r></w:p><w:p><w:pPr><w:pStyle w:val='TextBody'/><w:widowControl/><w:pBdr><w:top w:val='nil'/><w:left w:val='nil'/><w:bottom w:val='nil'/><w:right w:val='nil'/></w:pBdr><w:spacing w:before='0' w:after='225'/><w:jc w:val='both'/><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:r></w:p><w:p><w:pPr><w:pStyle w:val='TextBody'/><w:widowControl/><w:pBdr><w:top w:val='nil'/><w:left w:val='nil'/><w:bottom w:val='nil'/><w:right w:val='nil'/></w:pBdr><w:spacing w:before='0' w:after='225'/><w:jc w:val='both'/><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr><w:t>In non mauris justo. Duis vehicula mi vel mi pretium, a viverra erat efficitur. Cras aliquam est ac eros varius, id iaculis dui auctor. Duis pretium neque ligula, et pulvinar mi placerat et. Nulla nec nunc sit amet nunc posuere vestibulum. Ut id neque eget tortor mattis tristique. Donec ante est, blandit sit amet tristique vel, lacinia pulvinar arcu. Pellentesque scelerisque fermentum erat, id posuere justo pulvinar ut. Cras id eros sed enim aliquam lobortis. Sed lobortis nisl ut eros efficitur tincidunt. Cras justo mi, porttitor quis mattis vel, ultricies ut purus. Ut facilisis et lacus eu cursus.</w:t></w:r></w:p><w:p><w:pPr><w:pStyle w:val='TextBody'/><w:widowControl/><w:pBdr><w:top w:val='nil'/><w:left w:val='nil'/><w:bottom w:val='nil'/><w:right w:val='nil'/></w:pBdr><w:spacing w:before='0' w:after='225'/><w:jc w:val='both'/><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr><w:t xml:space='preserve'>In eleifend velit vitae libero sollicitudin euismod. Fusce vitae vestibulum velit. Pellentesque vulputate lectus quis pellentesque commodo. Aliquam erat volutpat. Vestibulum in egestas velit. Pellentesque fermentum nisl vitae fringilla venenatis. Etiam id mauris vitae orci maximus ultricies. </w:t></w:r></w:p><w:p><w:pPr><w:pStyle w:val='TextBody'/><w:widowControl/><w:pBdr><w:top w:val='nil'/><w:left w:val='nil'/><w:bottom w:val='nil'/><w:right w:val='nil'/></w:pBdr><w:spacing w:before='0' w:after='225'/><w:jc w:val='both'/><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:r></w:p><w:p><w:pPr><w:pStyle w:val='Heading1'/><w:keepNext/><w:numPr><w:ilvl w:val='0'/><w:numId w:val='1'/></w:numPr><w:spacing w:before='240' w:after='120'/><w:ind w:left='0' w:right='0' w:hanging='432'/><w:rPr></w:rPr></w:pPr><w:r><w:rPr></w:rPr><w:t>Cras fringilla ipsum magna, in fringilla dui commodo a.</w:t></w:r></w:p><w:p><w:pPr><w:pStyle w:val='TextBody'/><w:widowControl/><w:pBdr><w:top w:val='nil'/><w:left w:val='nil'/><w:bottom w:val='nil'/><w:right w:val='nil'/></w:pBdr><w:spacing w:before='0' w:after='225'/><w:jc w:val='both'/><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:r></w:p><w:tbl><w:tblPr><w:jc w:val='left'/><w:tblInd w:w='53' w:type='dxa'/><w:tblBorders><w:top w:val='single' w:sz='2' w:space='0' w:color='000001'/><w:left w:val='single' w:sz='2' w:space='0' w:color='000001'/><w:bottom w:val='single' w:sz='2' w:space='0' w:color='000001'/><w:insideH w:val='single' w:sz='2' w:space='0' w:color='000001'/><w:right w:val='nil'/><w:insideV w:val='nil'/></w:tblBorders><w:tblCellMar><w:top w:w='55' w:type='dxa'/><w:left w:w='51' w:type='dxa'/><w:bottom w:w='55' w:type='dxa'/><w:right w:w='55' w:type='dxa'/></w:tblCellMar></w:tblPr><w:tblGrid><w:gridCol w:w='719'/><w:gridCol w:w='5670'/><w:gridCol w:w='1559'/><w:gridCol w:w='1700'/></w:tblGrid><w:tr><w:trPr><w:trHeight w:val='450' w:hRule='atLeast'/><w:cantSplit w:val='false'/></w:trPr><w:tc><w:tcPr><w:tcW w:w='719' w:type='dxa'/><w:tcBorders><w:top w:val='single' w:sz='2' w:space='0' w:color='000001'/><w:left w:val='single' w:sz='2' w:space='0' w:color='000001'/><w:bottom w:val='single' w:sz='2' w:space='0' w:color='000001'/><w:insideH w:val='single' w:sz='2' w:space='0' w:color='000001'/><w:right w:val='nil'/><w:insideV w:val='nil'/></w:tcBorders><w:shd w:fill='FFFFFF' w:val='clear'/><w:tcMar><w:left w:w='51' w:type='dxa'/></w:tcMar></w:tcPr><w:p><w:pPr><w:pStyle w:val='TextBody'/><w:widowControl/><w:pBdr><w:top w:val='nil'/><w:left w:val='nil'/><w:bottom w:val='nil'/><w:right w:val='nil'/></w:pBdr><w:spacing w:before='0' w:after='225'/><w:jc w:val='left'/><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:w='5670' w:type='dxa'/><w:tcBorders><w:top w:val='single' w:sz='2' w:space='0' w:color='000001'/><w:left w:val='single' w:sz='2' w:space='0' w:color='000001'/><w:bottom w:val='single' w:sz='2' w:space='0' w:color='000001'/><w:insideH w:val='single' w:sz='2' w:space='0' w:color='000001'/><w:right w:val='nil'/><w:insideV w:val='nil'/></w:tcBorders><w:shd w:fill='FFFFFF' w:val='clear'/><w:tcMar><w:left w:w='51' w:type='dxa'/></w:tcMar></w:tcPr><w:p><w:pPr><w:pStyle w:val='TextBody'/><w:widowControl/><w:pBdr><w:top w:val='nil'/><w:left w:val='nil'/><w:bottom w:val='nil'/><w:right w:val='nil'/></w:pBdr><w:spacing w:before='0' w:after='225'/><w:jc w:val='left'/><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:b w:val='false'/><w:i w:val='false'/><w:caps w:val='false'/><w:smallCaps w:val='false'/><w:color w:val='000000'/><w:spacing w:val='0'/><w:sz w:val='21'/></w:rPr><w:t>Lorem ipsum</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:w='1559' w:type='dxa'/><w:tcBorders><w:top w:val='single' w:sz='2' w:space='0' w:color='000001'/><w:left w:val='single' w:sz='2' w:space='0' w:color='000001'/><w:bottom w:val='single' w:sz='2' w:space='0' w:color='000001'/><w:insideH w:val='single' w:sz='2' w:space='0' w:color='000001'/><w:right w:val='nil'/><w:insideV w:val='nil'/></w:tcBorders><w:shd w:fill='FFFFFF' w:val='clear'/><w:tcMar><w:left w:w='51' w:type='dxa'/></w:tcMar></w:tcPr><w:p><w:pPr><w:pStyle w:val='TableContents'/><w:jc w:val='left'/><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:sz w:val='21'/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:sz w:val='21'/></w:rPr><w:t>Lorem ipsum</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:w='1700' w:type='dxa'/><w:tcBorders><w:top w:val='single' w:sz='2' w:space='0' w:color='000001'/><w:left w:val='single' w:sz='2' w:space='0' w:color='000001'/><w:bottom w:val='single' w:sz='2' w:space='0' w:color='000001'/><w:insideH w:val='single' w:sz='2' w:space='0' w:color='000001'/><w:right w:val='single' w:sz='2' w:space='0' w:color='000001'/><w:insideV w:val='single' w:sz='2' w:space='0' w:color='000001'/></w:tcBorders><w:shd w:fill='FFFFFF' w:val='clear'/><w:tcMar><w:left w:w='51' w:type='dxa'/></w:tcMar></w:tcPr><w:p><w:pPr><w:pStyle w:val='TableContents'/><w:jc w:val='left'/><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:sz w:val='21'/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:sz w:val='21'/></w:rPr><w:t>Lorem ipsum</w:t></w:r></w:p></w:tc></w:tr><w:tr><w:trPr><w:cantSplit w:val='false'/></w:trPr><w:tc><w:tcPr><w:tcW w:w='719' w:type='dxa'/><w:tcBorders><w:top w:val='nil'/><w:left w:val='single' w:sz='2' w:space='0' w:color='000001'/><w:bottom w:val='single' w:sz='2' w:space='0' w:color='000001'/><w:insideH w:val='single' w:sz='2' w:space='0' w:color='000001'/><w:right w:val='nil'/><w:insideV w:val='nil'/></w:tcBorders><w:shd w:fill='FFFFFF' w:val='clear'/><w:tcMar><w:left w:w='51' w:type='dxa'/></w:tcMar></w:tcPr><w:p><w:pPr><w:pStyle w:val='TableContents'/><w:jc w:val='left'/><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:sz w:val='21'/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='DejaVu Sans'/><w:sz w:val='21'/></w:rPr><w:t>1</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:w='5670' w:type='dxa'/><w:tcBorders><w:top w:val='nil'/><w:left w:val='single' w:sz='2' w:space='0' w:color='000001'/><w:bottom w:val='single' w:sz='2' w:space='0' w:color='000001'/><w:insideH w:val='single' w:sz='2' w:space='0' w:color='000001'/><w:right w:val='nil'/><w:insideV w:val='nil'/></w:tcBorders><w:shd w:fill='FFFFFF' w:val='clear'/><w:tcMar><w:left w:w='51' w:type='dxa'/></w:tcMar></w:tcPr><w:p><w:pPr><w:pStyle w:val='TextBody'/><w:widowControl/><w:pBdr><w:top w:val='nil'/><w:left w:val='nil'/><w:bottom w:val='nil'/><w:right w:val='nil'/></w:pBdr><w:spacing w:before='0' w:after='225'/><w:jc w:val='left'/><w:rPr><w:rFonts w:cs='DejaVu Sans' w:ascii='DejaVu Sans' w:hAnsi='De Kiran P Published on 10-Nov-2020 06:01:29
[ { "code": null, "e": 1558, "s": 1062, "text": "No offense, I do not like Microsoft word neither spreadsheets. Being a Data Engineering specialist, I often receive test results from testers in Microsoft word. Sigh! they put so much information into word document right from capturing screen shots, links, big, very big, very very big paragraphs. Microsoft word had particular talent for turning what should be simple text documents or small information into large, slow, nasty-to-open beasts that often lose formatting from machine to machine." }, { "code": null, "e": 1658, "s": 1558, "text": "But, I need to accept the fact that what ever is bad for me is very good for others and vice versa." }, { "code": null, "e": 1945, "s": 1658, "text": "Back to context, Python support for word is not great. Python-docx library gives users the ability to create documents and read only basic file data such as the size and title of the file, not the actual contents. So, for me to process the test results have to come up with custom code." }, { "code": null, "e": 2111, "s": 1945, "text": "I will import a sample word document available on internet. The file is in the location - https://file-examples-com.github.io/uploads/2017/02/file-sample_100kB.docx." }, { "code": null, "e": 2141, "s": 2111, "text": "1. Let us begin with imports." }, { "code": null, "e": 2227, "s": 2141, "text": "from zipfile import ZipFile\nfrom urllib.request import urlopen\nfrom io import BytesIO" }, { "code": null, "e": 2383, "s": 2227, "text": "2.Now we will read a remote Word document as a binary file object. We then unzips it using zipfile library, and then reads the unzipped file, which is XML." }, { "code": null, "e": 2421, "s": 2383, "text": "Offcourse, we will print the content." }, { "code": null, "e": 2760, "s": 2421, "text": "file_url = 'https://file-examples-com.github.io/uploads/2017/02/file-sample_100kB.docx'\n\n# read the word document\nwordDocx = urlopen(file_url).read()\nwordDocx = BytesIO(wordDocx)\ndocument = ZipFile(wordDocx)\n\n#get the xml content\nxml_content = document.read('word/document.xml')\n\n# print the xml content\nprint(xml_content.decode('utf-8'))" } ]
Practical uses of merge, join and concat | by Magdalena Konkiewicz | Towards Data Science
In this article, we will talk about combining data frames. You are probably very familiar with load functions in pandas that allow you to get access to data in order to do some analysis. However, what happens if your data is not in one file but scattered across multiple ones? In that case, you will need to load the files one by one and combine the data into a single data frame using pandas functions. We will show you how to do that and what functions to use depending on how you want to combine your data and what you want to achieve. We will learn about: concat(), merge(), and join(). After reading this article you should be able to use all three of them to combine data in different ways. Let’s get started! This is the function that we recommend using if you have multiple data files with the same column names. It could be sales for a chain vendor where each year would be saved in a separate spreadsheet. We are going to create two separate data frames with some fake data in order to illustrate this. Let’s start with creating a data frame for sales for the year 2018: import pandas as pdimport numpy as npsales_dictionary_2018 = {'name': ['Michael', 'Ana'], 'revenue': ['1000', '2000'], 'number_of_itmes_sold': [5, 7]}sales_df_2018 = pd.DataFrame(sales_dictionary_2018)sales_df_2018.head() This is a very simple data frame with their columns summarizing sales for the year 2018. We have a vendor name, a number of units they have sold and the revenue they have created. Let’s create now a data frame that has exactly the same columns but covers a new time period: the year 2019. sales_dictionary_2019 = {'name': ['Michael', 'Ana', 'George'], 'revenue': ['1000', '3000', '2000'], 'number_of_itmes_sold': [5, 8, 7]}sales_df_2019 = pd.DataFrame(sales_dictionary_2019)sales_df_2019.head() You can see that in 2019 we had a new rep George except for Michael and Ana from 2018 sales. Otherwise, the data structure is the same as we had for the 2018 year. So how can you combine these two data frames together in order to have them in one data frame? You can use contact() function: pd.concat([sales_df_2018, sales_df_2019], ignore_index=True) You can see that after this operation all our data is now on one data frame! Concat() function takes a list of data frames and adds all their rows together resulting in one data frame. We set here ignore_index=True as otherwise, the resulting data frame would have indexes taken from the original data frame. In our case, we do not want that. Note that you can pass as many data frames as you want in a list form. Adding data the way we presented is probably the most common way of using concat() function. You could also use concat() function to add columns by setting axis=1 but there are better ways of adding new data in columns such as join() and merge(). This is because when you add new columns you mostly need to specify some condition on which you would like to join the data and concat() does not allow that. We are going to start by learning about merge() function as this is probably the most common way of adding new columns to the data frame based on some common conditions. In order to illustrate the usage of merge() we will go back to our store example which had a data frame from sales for 2018 and 2019. Imagine that you had another file that was containing personal data for each of the reps. Now, you would like to add this data to sales data frames. Let’s start by creating a data frame for personal rep info. rep_info_dictionary = {'name': ['Ana', 'Michael', 'George'], 'location': ['New York', 'San Jose', 'New York']}rep_info_df = pd.DataFrame(rep_info_dictionary)rep_info_df.head() As you can see there are only two columns: name and location. The name is something that was also present in our yearly sales data. Imagine that you would like to add the location of the rep to your 2019 data. You could merge the rep_info_df to sales_df_2019 using ‘name’ as the column that links both of these data frames: sales_df_2019.merge(rep_info_df, on='name') You can see that our original data frame with sales data for 2019 has now another column, location. It is a result of merging rp_info_df and sales_df_2019. As default pandas merge uses ‘inner join’ to perform merge operation. We are not going to discuss types of joins here but if you are familiar with SQL joins they work exactly the same. If concepts of inner, left, right and outer joins are not familiar to you I suggest that you find some articles that explain these SQL concepts. Once you understand the SQL joins you will be able to use them with pandas merge() function as they work exactly the same. This is a special case of merge when at least one of the columns that you are joining on is an index. Let’s modify our 2019 data to have names as indexes: sales_df_2019.set_index('name', inplace=True)sales_df_2019.head() As you can see name is not a column but index of the data frame after we have used set_index() function on it. Let’s now do the same to rep info data frame: rep_info_df.set_index('name', inplace=True)rep_info_df.head() Now both rep_info_df and sales_df_2019 have names as indexes. Now I can use join() instead of merge() in order to combine the data in the same way as we did with merge() in the previous section. sales_df_2019.join(rep_info_df) As you can see I do not have to specify the on parameter as it was the case with merge(). This is because join() function takes indexes of data frames as defaults to combine data from both tables. Join() function similar to merge() can be modified to use different types of SQL join by specifying the how parameter. The default with join is a ‘left’ join and this is what we have used in our example. Let’s summarize our findings. We have used concat() when we were trying to add multiple data blocks with the same structure and put them in one data frame one below the other. In order to add column data to existing entries, we have used merge(). The data was added based on the same values for columns on which were merging data frames. Join() was a special case of merge() when at least one of the entries we are joining on was the index. I hope you have enjoyed this article and have learned how to use these basic data frame operations to combine data. Originally published at aboutdatablog.com: Practical uses of merge, join and concat , on June 18, 2020. PS: I am writing articles that explain basic Data Science concepts in a simple and comprehensible manner on Medium and aboutdatablog.com. You can subscribe to my email list to get notified every time I write a new article. And if you are not a Medium member yet you can join here. Below there are some other posts you may enjoy:
[ { "code": null, "e": 359, "s": 172, "text": "In this article, we will talk about combining data frames. You are probably very familiar with load functions in pandas that allow you to get access to data in order to do some analysis." }, { "code": null, "e": 576, "s": 359, "text": "However, what happens if your data is not in one file but scattered across multiple ones? In that case, you will need to load the files one by one and combine the data into a single data frame using pandas functions." }, { "code": null, "e": 732, "s": 576, "text": "We will show you how to do that and what functions to use depending on how you want to combine your data and what you want to achieve. We will learn about:" }, { "code": null, "e": 742, "s": 732, "text": "concat()," }, { "code": null, "e": 751, "s": 742, "text": "merge()," }, { "code": null, "e": 763, "s": 751, "text": "and join()." }, { "code": null, "e": 869, "s": 763, "text": "After reading this article you should be able to use all three of them to combine data in different ways." }, { "code": null, "e": 888, "s": 869, "text": "Let’s get started!" }, { "code": null, "e": 1088, "s": 888, "text": "This is the function that we recommend using if you have multiple data files with the same column names. It could be sales for a chain vendor where each year would be saved in a separate spreadsheet." }, { "code": null, "e": 1253, "s": 1088, "text": "We are going to create two separate data frames with some fake data in order to illustrate this. Let’s start with creating a data frame for sales for the year 2018:" }, { "code": null, "e": 1517, "s": 1253, "text": "import pandas as pdimport numpy as npsales_dictionary_2018 = {'name': ['Michael', 'Ana'], 'revenue': ['1000', '2000'], 'number_of_itmes_sold': [5, 7]}sales_df_2018 = pd.DataFrame(sales_dictionary_2018)sales_df_2018.head()" }, { "code": null, "e": 1697, "s": 1517, "text": "This is a very simple data frame with their columns summarizing sales for the year 2018. We have a vendor name, a number of units they have sold and the revenue they have created." }, { "code": null, "e": 1806, "s": 1697, "text": "Let’s create now a data frame that has exactly the same columns but covers a new time period: the year 2019." }, { "code": null, "e": 2054, "s": 1806, "text": "sales_dictionary_2019 = {'name': ['Michael', 'Ana', 'George'], 'revenue': ['1000', '3000', '2000'], 'number_of_itmes_sold': [5, 8, 7]}sales_df_2019 = pd.DataFrame(sales_dictionary_2019)sales_df_2019.head()" }, { "code": null, "e": 2218, "s": 2054, "text": "You can see that in 2019 we had a new rep George except for Michael and Ana from 2018 sales. Otherwise, the data structure is the same as we had for the 2018 year." }, { "code": null, "e": 2345, "s": 2218, "text": "So how can you combine these two data frames together in order to have them in one data frame? You can use contact() function:" }, { "code": null, "e": 2406, "s": 2345, "text": "pd.concat([sales_df_2018, sales_df_2019], ignore_index=True)" }, { "code": null, "e": 2483, "s": 2406, "text": "You can see that after this operation all our data is now on one data frame!" }, { "code": null, "e": 2820, "s": 2483, "text": "Concat() function takes a list of data frames and adds all their rows together resulting in one data frame. We set here ignore_index=True as otherwise, the resulting data frame would have indexes taken from the original data frame. In our case, we do not want that. Note that you can pass as many data frames as you want in a list form." }, { "code": null, "e": 3225, "s": 2820, "text": "Adding data the way we presented is probably the most common way of using concat() function. You could also use concat() function to add columns by setting axis=1 but there are better ways of adding new data in columns such as join() and merge(). This is because when you add new columns you mostly need to specify some condition on which you would like to join the data and concat() does not allow that." }, { "code": null, "e": 3395, "s": 3225, "text": "We are going to start by learning about merge() function as this is probably the most common way of adding new columns to the data frame based on some common conditions." }, { "code": null, "e": 3529, "s": 3395, "text": "In order to illustrate the usage of merge() we will go back to our store example which had a data frame from sales for 2018 and 2019." }, { "code": null, "e": 3678, "s": 3529, "text": "Imagine that you had another file that was containing personal data for each of the reps. Now, you would like to add this data to sales data frames." }, { "code": null, "e": 3738, "s": 3678, "text": "Let’s start by creating a data frame for personal rep info." }, { "code": null, "e": 3935, "s": 3738, "text": "rep_info_dictionary = {'name': ['Ana', 'Michael', 'George'], 'location': ['New York', 'San Jose', 'New York']}rep_info_df = pd.DataFrame(rep_info_dictionary)rep_info_df.head()" }, { "code": null, "e": 4145, "s": 3935, "text": "As you can see there are only two columns: name and location. The name is something that was also present in our yearly sales data. Imagine that you would like to add the location of the rep to your 2019 data." }, { "code": null, "e": 4259, "s": 4145, "text": "You could merge the rep_info_df to sales_df_2019 using ‘name’ as the column that links both of these data frames:" }, { "code": null, "e": 4303, "s": 4259, "text": "sales_df_2019.merge(rep_info_df, on='name')" }, { "code": null, "e": 4459, "s": 4303, "text": "You can see that our original data frame with sales data for 2019 has now another column, location. It is a result of merging rp_info_df and sales_df_2019." }, { "code": null, "e": 4644, "s": 4459, "text": "As default pandas merge uses ‘inner join’ to perform merge operation. We are not going to discuss types of joins here but if you are familiar with SQL joins they work exactly the same." }, { "code": null, "e": 4912, "s": 4644, "text": "If concepts of inner, left, right and outer joins are not familiar to you I suggest that you find some articles that explain these SQL concepts. Once you understand the SQL joins you will be able to use them with pandas merge() function as they work exactly the same." }, { "code": null, "e": 5067, "s": 4912, "text": "This is a special case of merge when at least one of the columns that you are joining on is an index. Let’s modify our 2019 data to have names as indexes:" }, { "code": null, "e": 5133, "s": 5067, "text": "sales_df_2019.set_index('name', inplace=True)sales_df_2019.head()" }, { "code": null, "e": 5244, "s": 5133, "text": "As you can see name is not a column but index of the data frame after we have used set_index() function on it." }, { "code": null, "e": 5290, "s": 5244, "text": "Let’s now do the same to rep info data frame:" }, { "code": null, "e": 5352, "s": 5290, "text": "rep_info_df.set_index('name', inplace=True)rep_info_df.head()" }, { "code": null, "e": 5547, "s": 5352, "text": "Now both rep_info_df and sales_df_2019 have names as indexes. Now I can use join() instead of merge() in order to combine the data in the same way as we did with merge() in the previous section." }, { "code": null, "e": 5579, "s": 5547, "text": "sales_df_2019.join(rep_info_df)" }, { "code": null, "e": 5776, "s": 5579, "text": "As you can see I do not have to specify the on parameter as it was the case with merge(). This is because join() function takes indexes of data frames as defaults to combine data from both tables." }, { "code": null, "e": 5980, "s": 5776, "text": "Join() function similar to merge() can be modified to use different types of SQL join by specifying the how parameter. The default with join is a ‘left’ join and this is what we have used in our example." }, { "code": null, "e": 6010, "s": 5980, "text": "Let’s summarize our findings." }, { "code": null, "e": 6156, "s": 6010, "text": "We have used concat() when we were trying to add multiple data blocks with the same structure and put them in one data frame one below the other." }, { "code": null, "e": 6318, "s": 6156, "text": "In order to add column data to existing entries, we have used merge(). The data was added based on the same values for columns on which were merging data frames." }, { "code": null, "e": 6421, "s": 6318, "text": "Join() was a special case of merge() when at least one of the entries we are joining on was the index." }, { "code": null, "e": 6537, "s": 6421, "text": "I hope you have enjoyed this article and have learned how to use these basic data frame operations to combine data." }, { "code": null, "e": 6641, "s": 6537, "text": "Originally published at aboutdatablog.com: Practical uses of merge, join and concat , on June 18, 2020." }, { "code": null, "e": 6922, "s": 6641, "text": "PS: I am writing articles that explain basic Data Science concepts in a simple and comprehensible manner on Medium and aboutdatablog.com. You can subscribe to my email list to get notified every time I write a new article. And if you are not a Medium member yet you can join here." } ]
How to read from a file in Python - GeeksforGeeks
28 Nov, 2019 Python provides inbuilt functions for creating, writing and reading files. There are two types of files that can be handled in python, normal text files and binary files (written in binary language, 0s and 1s). Text files: In this type of file, Each line of text is terminated with a special character called EOL (End of Line), which is the new line character (‘\n’) in python by default. Binary files: In this type of file, there is no terminator for a line and the data is stored after converting it into machine-understandable binary language. Note: To know more about file handling click here. Access modes govern the type of operations possible in the opened file. It refers to how the file will be used once it’s opened. These modes also define the location of the File Handle in the file. File handle is like a cursor, which defines from where the data has to be read or written in the file. Different access modes for reading a file are – Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of the file. If the file does not exists, raises I/O error. This is also the default mode in which file is opened.Read and Write (‘r+’) : Open the file for reading and writing. The handle is positioned at the beginning of the file. Raises I/O error if the file does not exists.Append and Read (‘a+’) : Open the file for reading and writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data. Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of the file. If the file does not exists, raises I/O error. This is also the default mode in which file is opened. Read and Write (‘r+’) : Open the file for reading and writing. The handle is positioned at the beginning of the file. Raises I/O error if the file does not exists. Append and Read (‘a+’) : Open the file for reading and writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data. Note: To know more about access mode click here. It is done using the open() function. No module is required to be imported for this function. Syntax: File_object = open(r"File_Name", "Access_Mode") The file should exist in the same directory as the python program file else, full address of the file should be written on place of filename. Note: The r is placed before filename to prevent the characters in filename string to be treated as special character. For example, if there is \temp in the file address, then \t is treated as the tab character and error is raised of invalid address. The r makes the string raw, that is, it tells that the string is without any special characters. The r can be ignored if the file is in same directory and address is not being placed. # Open function to open the file "MyFile1.txt" # (same directory) in read mode and file1 = open("MyFile.txt", "r") # store its reference in the variable file1 # and "MyFile2.txt" in D:\Text in file2 file2 = open(r"D:\Text\MyFile2.txt", "r+") Here, file1 is created as object for MyFile1 and file2 as object for MyFile2. close() function closes the file and frees the memory space acquired by that file. It is used at the time when the file is no longer needed or if it is to be opened in a different file mode. Syntax: File_object.close() # Opening and Closing a file "MyFile.txt" # for object name file1. file1 = open("MyFile.txt", "r") file1.close() There are three ways to read data from a text file. read() : Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the entire file.File_object.read([n]) File_object.read([n]) readline() : Reads a line of the file and returns in form of a string.For specified n, reads at most n bytes. However, does not reads more than one line, even if n exceeds the length of the line.File_object.readline([n]) File_object.readline([n]) readlines() : Reads all the lines and return them as each line a string element in a list.File_object.readlines() File_object.readlines() Note: ‘\n’ is treated as a special character of two bytes. Example: # Program to show various ways to # read data from a file. # Creating a filefile1 = open("myfile.txt", "w")L = ["This is Delhi \n", "This is Paris \n", "This is London \n"] # Writing data to a filefile1.write("Hello \n") file1.writelines(L)file1.close() # to change file access modes file1 = open("myfile.txt", "r+") print("Output of Read function is ")print(file1.read())print() # seek(n) takes the file handle to the nth# bite from the beginning. file1.seek(0) print("Output of Readline function is ")print(file1.readline())print() file1.seek(0) # To show difference between read and readline print("Output of Read(9) function is ")print(file1.read(9))print() file1.seek(0) print("Output of Readline(9) function is ")print(file1.readline(9))print() file1.seek(0) # readlines function print("Output of Readlines function is ")print(file1.readlines())print()file1.close() Output: Output of Read function is Hello This is Delhi This is Paris This is London Output of Readline function is Hello Output of Read(9) function is Hello Th Output of Readline(9) function is Hello Output of Readlines function is ['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n'] with statement in Python is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. Unlike the above implementations, there is no need to call file.close() when using with statement. The with statement itself ensures proper acquisition and release of resources. Syntax: with open filename as file: # Program to show various ways to# read data from a file. L = ["This is Delhi \n", "This is Paris \n", "This is London \n"] # Creating a filewith open("myfile.txt", "w") as file1: # Writing data to a file file1.write("Hello \n") file1.writelines(L) file1.close() # to change file access modes with open("myfile.txt", "r+") as file1: # Reading form a file print(file1.read()) Output: Hello This is Delhi This is Paris This is London Note: To know more about with statement click here. python-file-handling Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace()
[ { "code": null, "e": 41553, "s": 41525, "text": "\n28 Nov, 2019" }, { "code": null, "e": 41764, "s": 41553, "text": "Python provides inbuilt functions for creating, writing and reading files. There are two types of files that can be handled in python, normal text files and binary files (written in binary language, 0s and 1s)." }, { "code": null, "e": 41942, "s": 41764, "text": "Text files: In this type of file, Each line of text is terminated with a special character called EOL (End of Line), which is the new line character (‘\\n’) in python by default." }, { "code": null, "e": 42100, "s": 41942, "text": "Binary files: In this type of file, there is no terminator for a line and the data is stored after converting it into machine-understandable binary language." }, { "code": null, "e": 42151, "s": 42100, "text": "Note: To know more about file handling click here." }, { "code": null, "e": 42500, "s": 42151, "text": "Access modes govern the type of operations possible in the opened file. It refers to how the file will be used once it’s opened. These modes also define the location of the File Handle in the file. File handle is like a cursor, which defines from where the data has to be read or written in the file. Different access modes for reading a file are –" }, { "code": null, "e": 43097, "s": 42500, "text": "Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of the file. If the file does not exists, raises I/O error. This is also the default mode in which file is opened.Read and Write (‘r+’) : Open the file for reading and writing. The handle is positioned at the beginning of the file. Raises I/O error if the file does not exists.Append and Read (‘a+’) : Open the file for reading and writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data." }, { "code": null, "e": 43300, "s": 43097, "text": "Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of the file. If the file does not exists, raises I/O error. This is also the default mode in which file is opened." }, { "code": null, "e": 43464, "s": 43300, "text": "Read and Write (‘r+’) : Open the file for reading and writing. The handle is positioned at the beginning of the file. Raises I/O error if the file does not exists." }, { "code": null, "e": 43696, "s": 43464, "text": "Append and Read (‘a+’) : Open the file for reading and writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data." }, { "code": null, "e": 43745, "s": 43696, "text": "Note: To know more about access mode click here." }, { "code": null, "e": 43839, "s": 43745, "text": "It is done using the open() function. No module is required to be imported for this function." }, { "code": null, "e": 43847, "s": 43839, "text": "Syntax:" }, { "code": null, "e": 43896, "s": 43847, "text": "File_object = open(r\"File_Name\", \"Access_Mode\")\n" }, { "code": null, "e": 44038, "s": 43896, "text": "The file should exist in the same directory as the python program file else, full address of the file should be written on place of filename." }, { "code": null, "e": 44473, "s": 44038, "text": "Note: The r is placed before filename to prevent the characters in filename string to be treated as special character. For example, if there is \\temp in the file address, then \\t is treated as the tab character and error is raised of invalid address. The r makes the string raw, that is, it tells that the string is without any special characters. The r can be ignored if the file is in same directory and address is not being placed." }, { "code": "# Open function to open the file \"MyFile1.txt\" # (same directory) in read mode and file1 = open(\"MyFile.txt\", \"r\") # store its reference in the variable file1 # and \"MyFile2.txt\" in D:\\Text in file2 file2 = open(r\"D:\\Text\\MyFile2.txt\", \"r+\") ", "e": 44722, "s": 44473, "text": null }, { "code": null, "e": 44800, "s": 44722, "text": "Here, file1 is created as object for MyFile1 and file2 as object for MyFile2." }, { "code": null, "e": 44991, "s": 44800, "text": "close() function closes the file and frees the memory space acquired by that file. It is used at the time when the file is no longer needed or if it is to be opened in a different file mode." }, { "code": null, "e": 44999, "s": 44991, "text": "Syntax:" }, { "code": null, "e": 45020, "s": 44999, "text": "File_object.close()\n" }, { "code": "# Opening and Closing a file \"MyFile.txt\" # for object name file1. file1 = open(\"MyFile.txt\", \"r\") file1.close() ", "e": 45134, "s": 45020, "text": null }, { "code": null, "e": 45186, "s": 45134, "text": "There are three ways to read data from a text file." }, { "code": null, "e": 45318, "s": 45186, "text": "read() : Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the entire file.File_object.read([n])\n" }, { "code": null, "e": 45341, "s": 45318, "text": "File_object.read([n])\n" }, { "code": null, "e": 45563, "s": 45341, "text": "readline() : Reads a line of the file and returns in form of a string.For specified n, reads at most n bytes. However, does not reads more than one line, even if n exceeds the length of the line.File_object.readline([n])\n" }, { "code": null, "e": 45590, "s": 45563, "text": "File_object.readline([n])\n" }, { "code": null, "e": 45705, "s": 45590, "text": "readlines() : Reads all the lines and return them as each line a string element in a list.File_object.readlines()\n" }, { "code": null, "e": 45730, "s": 45705, "text": "File_object.readlines()\n" }, { "code": null, "e": 45789, "s": 45730, "text": "Note: ‘\\n’ is treated as a special character of two bytes." }, { "code": null, "e": 45798, "s": 45789, "text": "Example:" }, { "code": "# Program to show various ways to # read data from a file. # Creating a filefile1 = open(\"myfile.txt\", \"w\")L = [\"This is Delhi \\n\", \"This is Paris \\n\", \"This is London \\n\"] # Writing data to a filefile1.write(\"Hello \\n\") file1.writelines(L)file1.close() # to change file access modes file1 = open(\"myfile.txt\", \"r+\") print(\"Output of Read function is \")print(file1.read())print() # seek(n) takes the file handle to the nth# bite from the beginning. file1.seek(0) print(\"Output of Readline function is \")print(file1.readline())print() file1.seek(0) # To show difference between read and readline print(\"Output of Read(9) function is \")print(file1.read(9))print() file1.seek(0) print(\"Output of Readline(9) function is \")print(file1.readline(9))print() file1.seek(0) # readlines function print(\"Output of Readlines function is \")print(file1.readlines())print()file1.close() ", "e": 46685, "s": 45798, "text": null }, { "code": null, "e": 46693, "s": 46685, "text": "Output:" }, { "code": null, "e": 46999, "s": 46693, "text": "Output of Read function is\nHello\nThis is Delhi\nThis is Paris\nThis is London\n\n\nOutput of Readline function is\nHello\n\n\nOutput of Read(9) function is\nHello\nTh\n\nOutput of Readline(9) function is\nHello\n\n\nOutput of Readlines function is\n['Hello \\n', 'This is Delhi \\n', 'This is Paris \\n', 'This is London \\n']\n" }, { "code": null, "e": 47349, "s": 46999, "text": "with statement in Python is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. Unlike the above implementations, there is no need to call file.close() when using with statement. The with statement itself ensures proper acquisition and release of resources." }, { "code": null, "e": 47357, "s": 47349, "text": "Syntax:" }, { "code": null, "e": 47386, "s": 47357, "text": "with open filename as file:\n" }, { "code": "# Program to show various ways to# read data from a file. L = [\"This is Delhi \\n\", \"This is Paris \\n\", \"This is London \\n\"] # Creating a filewith open(\"myfile.txt\", \"w\") as file1: # Writing data to a file file1.write(\"Hello \\n\") file1.writelines(L) file1.close() # to change file access modes with open(\"myfile.txt\", \"r+\") as file1: # Reading form a file print(file1.read())", "e": 47783, "s": 47386, "text": null }, { "code": null, "e": 47791, "s": 47783, "text": "Output:" }, { "code": null, "e": 47841, "s": 47791, "text": "Hello\nThis is Delhi\nThis is Paris\nThis is London\n" }, { "code": null, "e": 47893, "s": 47841, "text": "Note: To know more about with statement click here." }, { "code": null, "e": 47914, "s": 47893, "text": "python-file-handling" }, { "code": null, "e": 47921, "s": 47914, "text": "Python" }, { "code": null, "e": 48019, "s": 47921, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 48047, "s": 48019, "text": "Read JSON file using Python" }, { "code": null, "e": 48097, "s": 48047, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 48119, "s": 48097, "text": "Python map() function" }, { "code": null, "e": 48163, "s": 48119, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 48198, "s": 48163, "text": "Read a file line by line in Python" }, { "code": null, "e": 48220, "s": 48198, "text": "Enumerate() in Python" }, { "code": null, "e": 48252, "s": 48220, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 48282, "s": 48252, "text": "Iterate over a list in Python" }, { "code": null, "e": 48324, "s": 48282, "text": "Different ways to create Pandas Dataframe" } ]
strchr() function in C++ and its applications
In this article, we will be discussing the working, syntax, and examples of strchr() function in C++ STL. strchr() function is an inbuilt function in C++ STL, which is defined in the <cstring> header file. strchr() function is used to find when the character first occurred in the string. This function returns the pointer to the location where the character first appeared in the string. If the character doesn’t exist in the string the function returns the null pointer. char* strchr( char* str, char charac ); The function accepts the following parameter(s)− str − It is the string in which we have to look for the character. str − It is the string in which we have to look for the character. charac − It is the character that we want to search in the string str. charac − It is the character that we want to search in the string str. This function returns a pointer to the location where the character first appeared in the string. If the character is not found it returns the null pointer. Input − char str[] = "Tutorials Point"; char ch = ‘u’; Output − u is present in the string. Live Demo #include <iostream> #include <cstring> using namespace std; int main(){ char str[] = "Tutorials Point"; char ch_1 = 'b', ch_2 = 'T'; if (strchr(str, ch_1) != NULL) cout << ch_1 << " " << "is present in string" << endl; else cout << ch_1 << " " << "is not present in string" << endl; if (strchr(str, ch_2) != NULL) cout << ch_2 << " " << "is present in string" << endl; else cout << ch_2 << " " << "is not present in string" << endl; return 0; } b is not present in string T is present in string Live Demo #include <iostream> #include <cstring> using namespace std; int main(){ char str[] = "Tutorials Point"; char str_2[] = " is a learning portal"; char ch_1 = 'b', ch_2 = 'T'; if (strchr(str, ch_1) != NULL){ cout << ch_1 << " " << "is present in string" << endl; } else{ cout << ch_1 << " " << "is not present in string" << endl; } if (strchr(str, ch_2) != NULL){ cout << ch_2 << " " << "is present in string" << endl; strcat(str, str_2); cout<<"String after concatenation is : "<<str; } else{ cout << ch_2 <<" " << "is not present in string" << endl; } return 0; } b is not present in string T is present in string String after concatenation is : Tutorials Point is a learning portal
[ { "code": null, "e": 1168, "s": 1062, "text": "In this article, we will be discussing the working, syntax, and examples of strchr() function in C++ STL." }, { "code": null, "e": 1451, "s": 1168, "text": "strchr() function is an inbuilt function in C++ STL, which is defined in the <cstring> header file. strchr() function is used to find when the character first occurred in the string. This function returns the pointer to the location where the character first appeared in the string." }, { "code": null, "e": 1535, "s": 1451, "text": "If the character doesn’t exist in the string the function returns the null pointer." }, { "code": null, "e": 1575, "s": 1535, "text": "char* strchr( char* str, char charac );" }, { "code": null, "e": 1624, "s": 1575, "text": "The function accepts the following parameter(s)−" }, { "code": null, "e": 1691, "s": 1624, "text": "str − It is the string in which we have to look for the character." }, { "code": null, "e": 1758, "s": 1691, "text": "str − It is the string in which we have to look for the character." }, { "code": null, "e": 1829, "s": 1758, "text": "charac − It is the character that we want to search in the string str." }, { "code": null, "e": 1900, "s": 1829, "text": "charac − It is the character that we want to search in the string str." }, { "code": null, "e": 2057, "s": 1900, "text": "This function returns a pointer to the location where the character first appeared in the string. If the character is not found it returns the null pointer." }, { "code": null, "e": 2065, "s": 2057, "text": "Input −" }, { "code": null, "e": 2112, "s": 2065, "text": "char str[] = \"Tutorials Point\";\nchar ch = ‘u’;" }, { "code": null, "e": 2149, "s": 2112, "text": "Output − u is present in the string." }, { "code": null, "e": 2160, "s": 2149, "text": " Live Demo" }, { "code": null, "e": 2650, "s": 2160, "text": "#include <iostream>\n#include <cstring>\nusing namespace std;\nint main(){\n char str[] = \"Tutorials Point\";\n char ch_1 = 'b', ch_2 = 'T';\n if (strchr(str, ch_1) != NULL)\n cout << ch_1 << \" \" << \"is present in string\" << endl;\n else\n cout << ch_1 << \" \" << \"is not present in string\" << endl;\n if (strchr(str, ch_2) != NULL)\n cout << ch_2 << \" \" << \"is present in string\" << endl;\n else\n cout << ch_2 << \" \" << \"is not present in string\" << endl;\n return 0;\n}" }, { "code": null, "e": 2700, "s": 2650, "text": "b is not present in string\nT is present in string" }, { "code": null, "e": 2711, "s": 2700, "text": " Live Demo" }, { "code": null, "e": 3346, "s": 2711, "text": "#include <iostream>\n#include <cstring>\nusing namespace std;\nint main(){\n char str[] = \"Tutorials Point\";\n char str_2[] = \" is a learning portal\";\n char ch_1 = 'b', ch_2 = 'T';\n if (strchr(str, ch_1) != NULL){\n cout << ch_1 << \" \" << \"is present in string\" << endl;\n }\n else{\n cout << ch_1 << \" \" << \"is not present in string\" << endl;\n }\n if (strchr(str, ch_2) != NULL){\n cout << ch_2 << \" \" << \"is present in string\" << endl;\n strcat(str, str_2);\n cout<<\"String after concatenation is : \"<<str;\n }\n else{\n cout << ch_2 <<\" \" << \"is not present in string\" << endl;\n }\n return 0;\n}" }, { "code": null, "e": 3465, "s": 3346, "text": "b is not present in string\nT is present in string\nString after concatenation is : Tutorials Point is a learning portal" } ]
Map a 10-bit number to 8-bit in Arduino
Mappings often have to be performed in Arduino for a variety of reasons. One example would be mapping the 10-bit ADC output to 8-bit to save on storage. A 10-bit number would occupy 2-bytes for storage, whereas an 8-bit number would occupy just one byte and still preserve most of the information of the 10-bit number. Arduino has a readymade map() function for achieving this. map(value, fromLow, fromHigh, toLow, toHigh) where, value is the value to be mapped; fromLow and fromHigh are the bounds of the range of the current value; toHigh and toLow are the bounds of the range of the new value. Thus, if I need to map a 10-bit number to 8-bit number, map(value, 0, 1023, 0, 255) This is because a 10-bit number’s minimum value is 0, and maximum is 1023. For an 8-bit number, the min and max values are 0 and 255 respectively. What you can notice from the syntax is that you can use this function to map a number from any range to any new range. You need not restrict yourself to powers of 2. The following example illustrates the use of this function − void setup() { // put your setup code here, to run once: Serial.begin(9600); Serial.println(); int a = 200; Serial.println(map(a,0,500,0,1000)); Serial.println(map(a,0,1023,0,255)); } void loop() { // put your main code here, to run repeatedly: } The Serial Monitor output is − As you can see, this function can be used for both up-scaling and down-scaling a given number. First, we upscaled the number 200 from the (0,500) range to (0,1000) range. As expected, the function returned 400. In the second case, we down-scaled 200 from (0,1023) range to (0,255) range. The function returned 49, which matches the integer part of 200*255/1023 (=49.85). You can refer to Arduino’s documentation for more information related to this function: − https://www.arduino.cc/reference/en/language/functions/math/map/
[ { "code": null, "e": 1381, "s": 1062, "text": "Mappings often have to be performed in Arduino for a variety of reasons. One example would be mapping the 10-bit ADC output to 8-bit to save on storage. A 10-bit number would occupy 2-bytes for storage, whereas an 8-bit number would occupy just one byte and still preserve most of the information of the 10-bit number." }, { "code": null, "e": 1440, "s": 1381, "text": "Arduino has a readymade map() function for achieving this." }, { "code": null, "e": 1485, "s": 1440, "text": "map(value, fromLow, fromHigh, toLow, toHigh)" }, { "code": null, "e": 1659, "s": 1485, "text": "where, value is the value to be mapped; fromLow and fromHigh are the bounds of the range of the current value; toHigh and toLow are the bounds of the range of the new value." }, { "code": null, "e": 1715, "s": 1659, "text": "Thus, if I need to map a 10-bit number to 8-bit number," }, { "code": null, "e": 1743, "s": 1715, "text": "map(value, 0, 1023, 0, 255)" }, { "code": null, "e": 1890, "s": 1743, "text": "This is because a 10-bit number’s minimum value is 0, and maximum is 1023. For an 8-bit number, the min and max values are 0 and 255 respectively." }, { "code": null, "e": 2056, "s": 1890, "text": "What you can notice from the syntax is that you can use this function to map a number from any range to any new range. You need not restrict yourself to powers of 2." }, { "code": null, "e": 2117, "s": 2056, "text": "The following example illustrates the use of this function −" }, { "code": null, "e": 2387, "s": 2117, "text": "void setup() {\n // put your setup code here, to run once:\n Serial.begin(9600);\n Serial.println();\n\n int a = 200;\n Serial.println(map(a,0,500,0,1000));\n Serial.println(map(a,0,1023,0,255));\n}\n\nvoid loop() {\n // put your main code here, to run repeatedly:\n}" }, { "code": null, "e": 2418, "s": 2387, "text": "The Serial Monitor output is −" }, { "code": null, "e": 2789, "s": 2418, "text": "As you can see, this function can be used for both up-scaling and down-scaling a given number. First, we upscaled the number 200 from the (0,500) range to (0,1000) range. As expected, the function returned 400. In the second case, we down-scaled 200 from (0,1023) range to (0,255) range. The function returned 49, which matches the integer part of 200*255/1023 (=49.85)." }, { "code": null, "e": 2944, "s": 2789, "text": "You can refer to Arduino’s documentation for more information related to this function: − https://www.arduino.cc/reference/en/language/functions/math/map/" } ]
deque::pop_front() and deque::pop_back() in C++ STL - GeeksforGeeks
06 Oct, 2021 Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. pop_front() function is used to pop or remove elements from a deque from the front. The value is removed from the deque from the beginning, and the container size is decreased by 1.Syntax : dequename.pop_front() Parameters : No value is needed to pass as the parameter. Result : Removes the value present at the front of the given deque named as dequename Examples: Input : mydeque = 1, 2, 3 mydeque.pop_front(); Output : 2, 3 Input : mydeque = 3, 4, 1, 7, 3 mydeque.pop_front(); Output : 4, 1, 7, 3 Errors and Exceptions No-Throw-Guarantee – if an exception is thrown, there are no changes in the containerIf the deque is empty, it shows undefined behavior. No-Throw-Guarantee – if an exception is thrown, there are no changes in the container If the deque is empty, it shows undefined behavior. CPP // CPP program to illustrate// pop_front() function#include <iostream>#include <deque>using namespace std; int main(){ deque<int> mydeque; mydeque.push_front(3); mydeque.push_front(2); mydeque.push_front(1); //Deque becomes 1, 2, 3 mydeque.pop_front(); //Deque becomes 2, 3 for (auto it = mydeque.begin(); it != mydeque.end(); ++it) cout << ' ' << *it;} Output: 2 3 Application: Input an empty deque with the following numbers and order using push_front() function and print the reverse of the deque. Input : 1, 2, 3, 4, 5, 6, 7, 8 Output: 8, 7, 6, 5, 4, 3, 2, 1 CPP // CPP program to illustrate// application Of pop_front() function#include <iostream>#include <deque>using namespace std; int main(){ deque<int> mydeque{}, newdeque{}; mydeque.push_front(8); mydeque.push_front(7); mydeque.push_front(6); mydeque.push_front(5); mydeque.push_front(4); mydeque.push_front(3); mydeque.push_front(2); mydeque.push_front(1); //Deque becomes 1, 2, 3, 4, 5, 6, 7, 8 while (!mydeque.empty()) { newdeque.push_front(mydeque.front()); mydeque.pop_front(); } for (auto it = newdeque.begin(); it != newdeque.end(); ++it) cout << ' ' << *it;} Output: 8 7 6 5 4 3 2 1 pop_back() function is used to pop or remove elements from a deque from the back. The value is removed from the deque from the end, and the container size is decreased by 1.Syntax : dequename.pop_back() Parameters : No value is needed to pass as the parameter. Result : Removes the value present at the end or back of the given deque named as dequename Examples: Input : mydeque = 1, 2, 3 mydeque.pop_back(); Output : 1, 2 Input : mydeque = 3, 4, 1, 7, 3 mydeque.pop_back(); Output : 3, 4, 1, 7 Errors and Exceptions No-Throw-Guarantee – if an exception is thrown, there are no changes in the containerIf the deque is empty, it shows undefined behaviour. No-Throw-Guarantee – if an exception is thrown, there are no changes in the container If the deque is empty, it shows undefined behaviour. CPP // CPP program to illustrate// pop_back() function#include <iostream>#include <deque>using namespace std; int main(){ deque<int> mydeque; mydeque.push_front(5); mydeque.push_front(4); mydeque.push_front(3); mydeque.push_front(2); mydeque.push_front(1); //Deque becomes 1, 2, 3, 4, 5 mydeque.pop_back(); //Deque becomes 1, 2, 3, 4 for (auto it = mydeque.begin(); it != mydeque.end(); ++it) cout << ' ' << *it;} Output: 1 2 3 4 Application : Input an empty deque with the following numbers and order using push_front() function and print the reverse of the deque. Input : 1, 20, 39, 43, 57, 64, 73, 82 Output : 82, 73, 64, 57, 43, 39, 20, 1 CPP // CPP program to illustrate// application Of pop_back() function#include <iostream>#include <deque>using namespace std; int main(){ deque<int> mydeque, newdeque; mydeque.push_front(82); mydeque.push_front(73); mydeque.push_front(64); mydeque.push_front(57); mydeque.push_front(43); mydeque.push_front(39); mydeque.push_front(20); mydeque.push_front(1); //Deque becomes 1, 20, 39, 43, 57, 64, 73, 82 while (!mydeque.empty()) { newdeque.push_back(mydeque.back()); mydeque.pop_back(); } for (auto it = newdeque.begin(); it != newdeque.end(); ++it) cout << ' ' << *it;} Output: 82 73 64 57 43 39 20 1 hritikbhatnagar2182 cpp-containers-library cpp-deque CPP-Library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Inheritance in C++ C++ Classes and Objects Operator Overloading in C++ Socket Programming in C/C++ Bitwise Operators in C/C++ Virtual Function in C++ Constructors in C++ Templates in C++ with Examples Object Oriented Programming in C++ Copy Constructor in C++
[ { "code": null, "e": 24548, "s": 24520, "text": "\n06 Oct, 2021" }, { "code": null, "e": 24869, "s": 24548, "text": "Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. " }, { "code": null, "e": 25061, "s": 24869, "text": "pop_front() function is used to pop or remove elements from a deque from the front. The value is removed from the deque from the beginning, and the container size is decreased by 1.Syntax : " }, { "code": null, "e": 25228, "s": 25061, "text": "dequename.pop_front()\nParameters :\nNo value is needed to pass as the parameter.\nResult :\nRemoves the value present at the front \nof the given deque named as dequename" }, { "code": null, "e": 25240, "s": 25228, "text": "Examples: " }, { "code": null, "e": 25401, "s": 25240, "text": "Input : mydeque = 1, 2, 3\n mydeque.pop_front();\nOutput : 2, 3\n\nInput : mydeque = 3, 4, 1, 7, 3\n mydeque.pop_front();\nOutput : 4, 1, 7, 3" }, { "code": null, "e": 25425, "s": 25401, "text": "Errors and Exceptions " }, { "code": null, "e": 25562, "s": 25425, "text": "No-Throw-Guarantee – if an exception is thrown, there are no changes in the containerIf the deque is empty, it shows undefined behavior." }, { "code": null, "e": 25648, "s": 25562, "text": "No-Throw-Guarantee – if an exception is thrown, there are no changes in the container" }, { "code": null, "e": 25700, "s": 25648, "text": "If the deque is empty, it shows undefined behavior." }, { "code": null, "e": 25704, "s": 25700, "text": "CPP" }, { "code": "// CPP program to illustrate// pop_front() function#include <iostream>#include <deque>using namespace std; int main(){ deque<int> mydeque; mydeque.push_front(3); mydeque.push_front(2); mydeque.push_front(1); //Deque becomes 1, 2, 3 mydeque.pop_front(); //Deque becomes 2, 3 for (auto it = mydeque.begin(); it != mydeque.end(); ++it) cout << ' ' << *it;}", "e": 26093, "s": 25704, "text": null }, { "code": null, "e": 26103, "s": 26093, "text": "Output: " }, { "code": null, "e": 26107, "s": 26103, "text": "2 3" }, { "code": null, "e": 26244, "s": 26107, "text": "Application: Input an empty deque with the following numbers and order using push_front() function and print the reverse of the deque. " }, { "code": null, "e": 26306, "s": 26244, "text": "Input : 1, 2, 3, 4, 5, 6, 7, 8\nOutput: 8, 7, 6, 5, 4, 3, 2, 1" }, { "code": null, "e": 26312, "s": 26308, "text": "CPP" }, { "code": "// CPP program to illustrate// application Of pop_front() function#include <iostream>#include <deque>using namespace std; int main(){ deque<int> mydeque{}, newdeque{}; mydeque.push_front(8); mydeque.push_front(7); mydeque.push_front(6); mydeque.push_front(5); mydeque.push_front(4); mydeque.push_front(3); mydeque.push_front(2); mydeque.push_front(1); //Deque becomes 1, 2, 3, 4, 5, 6, 7, 8 while (!mydeque.empty()) { newdeque.push_front(mydeque.front()); mydeque.pop_front(); } for (auto it = newdeque.begin(); it != newdeque.end(); ++it) cout << ' ' << *it;}", "e": 26938, "s": 26312, "text": null }, { "code": null, "e": 26948, "s": 26938, "text": "Output: " }, { "code": null, "e": 26964, "s": 26948, "text": "8 7 6 5 4 3 2 1" }, { "code": null, "e": 27150, "s": 26966, "text": "pop_back() function is used to pop or remove elements from a deque from the back. The value is removed from the deque from the end, and the container size is decreased by 1.Syntax : " }, { "code": null, "e": 27322, "s": 27150, "text": "dequename.pop_back()\nParameters :\nNo value is needed to pass as the parameter.\nResult :\nRemoves the value present at the end or back \nof the given deque named as dequename" }, { "code": null, "e": 27334, "s": 27322, "text": "Examples: " }, { "code": null, "e": 27493, "s": 27334, "text": "Input : mydeque = 1, 2, 3\n mydeque.pop_back();\nOutput : 1, 2\n\nInput : mydeque = 3, 4, 1, 7, 3\n mydeque.pop_back();\nOutput : 3, 4, 1, 7" }, { "code": null, "e": 27517, "s": 27493, "text": "Errors and Exceptions " }, { "code": null, "e": 27655, "s": 27517, "text": "No-Throw-Guarantee – if an exception is thrown, there are no changes in the containerIf the deque is empty, it shows undefined behaviour." }, { "code": null, "e": 27741, "s": 27655, "text": "No-Throw-Guarantee – if an exception is thrown, there are no changes in the container" }, { "code": null, "e": 27794, "s": 27741, "text": "If the deque is empty, it shows undefined behaviour." }, { "code": null, "e": 27798, "s": 27794, "text": "CPP" }, { "code": "// CPP program to illustrate// pop_back() function#include <iostream>#include <deque>using namespace std; int main(){ deque<int> mydeque; mydeque.push_front(5); mydeque.push_front(4); mydeque.push_front(3); mydeque.push_front(2); mydeque.push_front(1); //Deque becomes 1, 2, 3, 4, 5 mydeque.pop_back(); //Deque becomes 1, 2, 3, 4 for (auto it = mydeque.begin(); it != mydeque.end(); ++it) cout << ' ' << *it;}", "e": 28249, "s": 27798, "text": null }, { "code": null, "e": 28259, "s": 28249, "text": "Output: " }, { "code": null, "e": 28267, "s": 28259, "text": "1 2 3 4" }, { "code": null, "e": 28405, "s": 28267, "text": "Application : Input an empty deque with the following numbers and order using push_front() function and print the reverse of the deque. " }, { "code": null, "e": 28483, "s": 28405, "text": "Input : 1, 20, 39, 43, 57, 64, 73, 82\nOutput : 82, 73, 64, 57, 43, 39, 20, 1" }, { "code": null, "e": 28487, "s": 28483, "text": "CPP" }, { "code": "// CPP program to illustrate// application Of pop_back() function#include <iostream>#include <deque>using namespace std; int main(){ deque<int> mydeque, newdeque; mydeque.push_front(82); mydeque.push_front(73); mydeque.push_front(64); mydeque.push_front(57); mydeque.push_front(43); mydeque.push_front(39); mydeque.push_front(20); mydeque.push_front(1); //Deque becomes 1, 20, 39, 43, 57, 64, 73, 82 while (!mydeque.empty()) { newdeque.push_back(mydeque.back()); mydeque.pop_back(); } for (auto it = newdeque.begin(); it != newdeque.end(); ++it) cout << ' ' << *it;}", "e": 29119, "s": 28487, "text": null }, { "code": null, "e": 29129, "s": 29119, "text": "Output: " }, { "code": null, "e": 29152, "s": 29129, "text": "82 73 64 57 43 39 20 1" }, { "code": null, "e": 29174, "s": 29154, "text": "hritikbhatnagar2182" }, { "code": null, "e": 29197, "s": 29174, "text": "cpp-containers-library" }, { "code": null, "e": 29207, "s": 29197, "text": "cpp-deque" }, { "code": null, "e": 29219, "s": 29207, "text": "CPP-Library" }, { "code": null, "e": 29223, "s": 29219, "text": "STL" }, { "code": null, "e": 29227, "s": 29223, "text": "C++" }, { "code": null, "e": 29231, "s": 29227, "text": "STL" }, { "code": null, "e": 29235, "s": 29231, "text": "CPP" }, { "code": null, "e": 29333, "s": 29235, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29342, "s": 29333, "text": "Comments" }, { "code": null, "e": 29355, "s": 29342, "text": "Old Comments" }, { "code": null, "e": 29374, "s": 29355, "text": "Inheritance in C++" }, { "code": null, "e": 29398, "s": 29374, "text": "C++ Classes and Objects" }, { "code": null, "e": 29426, "s": 29398, "text": "Operator Overloading in C++" }, { "code": null, "e": 29454, "s": 29426, "text": "Socket Programming in C/C++" }, { "code": null, "e": 29481, "s": 29454, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 29505, "s": 29481, "text": "Virtual Function in C++" }, { "code": null, "e": 29525, "s": 29505, "text": "Constructors in C++" }, { "code": null, "e": 29556, "s": 29525, "text": "Templates in C++ with Examples" }, { "code": null, "e": 29591, "s": 29556, "text": "Object Oriented Programming in C++" } ]
How to create transparent widgets using Tkinter?
A Tkinter widget in an application can be provided with Transparent background. The background property of any widget is controlled by the widget itself. However, to provide a transparent background to a particular widget, we have to use wm_attributes('transparentcolor', 'colorname') method. It works in the widget only after adding the same transparent color as the background color of the widget. #Import the required libraries from tkinter import * #Create an instance of Tkinter Frame win = Tk() #Set the geometry win.geometry("700x250") #Adding transparent background property win.wm_attributes('-transparentcolor', '#ab23ff') #Create a Label Label(win, text= "This is a New line Text", font= ('Helvetica 18'), bg= '#ab23ff').pack(ipadx= 50, ipady=50, padx= 20) win.mainloop() When we compile the above code, it will display a window with a Label widget in transparent background.
[ { "code": null, "e": 1216, "s": 1062, "text": "A Tkinter widget in an application can be provided with Transparent background. The background property of any widget is controlled by the widget itself." }, { "code": null, "e": 1462, "s": 1216, "text": "However, to provide a transparent background to a particular widget, we have to use wm_attributes('transparentcolor', 'colorname') method. It works in the widget only after adding the same transparent color as the background color of the widget." }, { "code": null, "e": 1850, "s": 1462, "text": "#Import the required libraries\nfrom tkinter import *\n\n#Create an instance of Tkinter Frame\nwin = Tk()\n\n#Set the geometry\nwin.geometry(\"700x250\")\n\n#Adding transparent background property\nwin.wm_attributes('-transparentcolor', '#ab23ff')\n\n#Create a Label\nLabel(win, text= \"This is a New line Text\", font= ('Helvetica 18'), bg= '#ab23ff').pack(ipadx= 50, ipady=50, padx= 20)\n\nwin.mainloop()" }, { "code": null, "e": 1954, "s": 1850, "text": "When we compile the above code, it will display a window with a Label widget in transparent background." } ]
Unity - The Slider
In this chapter, we will learn about the last UI element in this series. The Slider is commonly used where a certain value should be set between a maximum and minimum value pair. One of the most common usage of this is for audio volume, or screen brightness. To create a slider, go to Create → UI → Slider. A new Slider element should show up on your scene. If you go to the properties of this Slider, you will notice a ist of options to customize it. Let us try to make a volume slider out of this slider. For this, open the ButtonBehaviour script (you can rename the ButtonManager GameObject as it is certainly doing more than just managing a button now) and add a reference to the Slider. We will also change the code around a bit again. public class ButtonBehaviour : MonoBehaviour { int n; public Text myText; public Slider mySlider; void Update() { myText.text = "Current Volume: " + mySlider.value; } } Understand how we are using the Update method to constantly update the value of myText.text. In the slider properties, let us check the “Whole Numbers” box, and set the maximum value to 100. We will set the color of the text through its properties for a more visible color. Let us follow the same procedure of dragging the Slider GameObject onto the new slot, and hit play. It is highly recommended you explore and experiment with the other UI controls as well, to see which ones work in which way. In our subsequent section, we will learn about lighting, materials and shaders. 119 Lectures 23.5 hours Raja Biswas 58 Lectures 10 hours Three Millennials 16 Lectures 1 hours Peter Jepson 23 Lectures 2.5 hours Zenva 21 Lectures 2 hours Zenva 43 Lectures 9.5 hours Raja Biswas Print Add Notes Bookmark this page
[ { "code": null, "e": 2474, "s": 2215, "text": "In this chapter, we will learn about the last UI element in this series. The Slider is commonly used where a certain value should be set between a maximum and minimum value pair. One of the most common usage of this is for audio volume, or screen brightness." }, { "code": null, "e": 2573, "s": 2474, "text": "To create a slider, go to Create → UI → Slider. A new Slider element should show up on your scene." }, { "code": null, "e": 2667, "s": 2573, "text": "If you go to the properties of this Slider, you will notice a ist of options to customize it." }, { "code": null, "e": 2956, "s": 2667, "text": "Let us try to make a volume slider out of this slider. For this, open the ButtonBehaviour script (you can rename the ButtonManager GameObject as it is certainly doing more than just managing a button now) and add a reference to the Slider. We will also change the code around a bit again." }, { "code": null, "e": 3146, "s": 2956, "text": "public class ButtonBehaviour : MonoBehaviour {\n int n;\n public Text myText;\n public Slider mySlider;\n void Update() {\n myText.text = \"Current Volume: \" + mySlider.value;\n }\n}" }, { "code": null, "e": 3239, "s": 3146, "text": "Understand how we are using the Update method to constantly update the value of myText.text." }, { "code": null, "e": 3337, "s": 3239, "text": "In the slider properties, let us check the “Whole Numbers” box, and set the maximum value to 100." }, { "code": null, "e": 3420, "s": 3337, "text": "We will set the color of the text through its properties for a more visible color." }, { "code": null, "e": 3520, "s": 3420, "text": "Let us follow the same procedure of dragging the Slider GameObject onto the new slot, and hit play." }, { "code": null, "e": 3645, "s": 3520, "text": "It is highly recommended you explore and experiment with the other UI controls as well, to see which ones work in which way." }, { "code": null, "e": 3725, "s": 3645, "text": "In our subsequent section, we will learn about lighting, materials and shaders." }, { "code": null, "e": 3762, "s": 3725, "text": "\n 119 Lectures \n 23.5 hours \n" }, { "code": null, "e": 3775, "s": 3762, "text": " Raja Biswas" }, { "code": null, "e": 3809, "s": 3775, "text": "\n 58 Lectures \n 10 hours \n" }, { "code": null, "e": 3828, "s": 3809, "text": " Three Millennials" }, { "code": null, "e": 3861, "s": 3828, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 3875, "s": 3861, "text": " Peter Jepson" }, { "code": null, "e": 3910, "s": 3875, "text": "\n 23 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3917, "s": 3910, "text": " Zenva" }, { "code": null, "e": 3950, "s": 3917, "text": "\n 21 Lectures \n 2 hours \n" }, { "code": null, "e": 3957, "s": 3950, "text": " Zenva" }, { "code": null, "e": 3992, "s": 3957, "text": "\n 43 Lectures \n 9.5 hours \n" }, { "code": null, "e": 4005, "s": 3992, "text": " Raja Biswas" }, { "code": null, "e": 4012, "s": 4005, "text": " Print" }, { "code": null, "e": 4023, "s": 4012, "text": " Add Notes" } ]
Object-oriented filesystem paths in Python (pathlib)
The pathlib module provides an object oriented approach to handling filesystem paths. The module also provides functionality appropriate for various operating systems. Classes defined in this module are of two types – pure path types and concrete path types. While pure paths can only perform purely computational operations, concrete paths are capable of doing I/O operations too. pathlib module defines following classes − When instance of Path class is created, it will automatically return either WindowsPath or PosixPath depending on your system. Note that WindowsPath or PosixPath object can also be created directly, but not on system of same type only. To create Path object use following syntax >>> from pathlib import * >>> p = Path(".") >>> type(p) <class 'pathlib.WindowsPath'> You can see that since above statement is executed on Windows system, WindowsPath object is created. “.” Refers to current directory. The Path class has following methods defined in it absolute() − returns absolute version of Path object. >>> p.absolute() WindowsPath('C:/python36') exists() − returns true if given path exists >>> p = Path("mydir") >>> p.exists() False >>> p = Path("etc") >>> p.exists() True is_dir() − returns true if path is a directory >>> p = Path("etc") >>> p.is_dir() True >>> p = Path("test.py") >>> p.is_dir() False is_file() − returns true if path corresponds to file >>> p = Path("tmp.py") >>> p.is_file() True >>> p = Path("etc") >>> p.is_file() False iterdir() − returns a generator that yields filenames in the directory corresponding to path. >>> p = Path("libs") >>> for f in p.iterdir(): print (f) libs\libpython36.a libs\python3.lib libs\python36.lib libs\_tkinter.lib mkdir() − creates new directory representing path if it is not already present. >>> p = Path("mydir") >>> p.mkdir() >>> p.absolute() WindowsPath('C:/python36/mydir') >>> p = Path("codes") >>> p.mkdir() FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'codes' open() − opens file represented by Path object and returns file object. This is similar to built-in open() function. >>> p = Path("Hello.py") >>> f = p.open() >>> f.readline() 'Hello Python' read_bytes() − opens the file in binary mode, reads its data in binary form and closes the same. >>> p = Path("Hello.py") >>> f.read_bytes() >>> p.read_bytes() b'Hello Python' read_text() − File is opened in text mode to read the text and close it afterwards. >>> p = Path("Hello.py") >>> p.read_text() 'Hello Python' write_text() − opens the file, writes text and closes it. >>> p = Path("Hello.py") >>> p.write_text("Hello how are you?") 18 write_bytes() − Writes binary data in a file and closes the same. >>> p = Path("Hello.py") >>> p.write_bytes(b'I am fine') 9 stat() − returns information about this path. >>> p.stat() os.stat_result(st_mode = 16895, st_ino = 9570149208167477, st_dev = 1526259762, st_nlink = 1, st_uid = 0, st_gid = 0, st_size = 0, st_atime = 1543085915, st_mtime = 1543085915, st_ctime = 1543085915) rmdir() − removes directory corresponding to Path object. >>> p = Path("mydir") >>> p.rmdir() Path.cwd() − This is a classmethod of Path class. returns path to current working directory >>> Path.cwd() WindowsPath('C:/python36') Path.home() − This is a classmethod of Path class. returns path to home directory >>> Path.home() WindowsPath('C:/Users/acer') The ‘/’ operator is used to build paths. >>> p = Path(".") >>> p1 = p/'codes' >>> p1.absolute() WindowsPath('C:/python36/codes') In this article we learned the object oriented API to filesystem object as defined in pathlib module.
[ { "code": null, "e": 1444, "s": 1062, "text": "The pathlib module provides an object oriented approach to handling filesystem paths. The module also provides functionality appropriate for various operating systems. Classes defined in this module are of two types – pure path types and concrete path types. While pure paths can only perform purely computational operations, concrete paths are capable of doing I/O operations too." }, { "code": null, "e": 1487, "s": 1444, "text": "pathlib module defines following classes −" }, { "code": null, "e": 1614, "s": 1487, "text": "When instance of Path class is created, it will automatically return either WindowsPath or PosixPath depending on your system." }, { "code": null, "e": 1723, "s": 1614, "text": "Note that WindowsPath or PosixPath object can also be created directly, but not on system of same type only." }, { "code": null, "e": 1766, "s": 1723, "text": "To create Path object use following syntax" }, { "code": null, "e": 1852, "s": 1766, "text": ">>> from pathlib import *\n>>> p = Path(\".\")\n>>> type(p)\n<class 'pathlib.WindowsPath'>" }, { "code": null, "e": 1986, "s": 1852, "text": "You can see that since above statement is executed on Windows system, WindowsPath object is created. “.” Refers to current directory." }, { "code": null, "e": 2037, "s": 1986, "text": "The Path class has following methods defined in it" }, { "code": null, "e": 2091, "s": 2037, "text": "absolute() − returns absolute version of Path object." }, { "code": null, "e": 2135, "s": 2091, "text": ">>> p.absolute()\nWindowsPath('C:/python36')" }, { "code": null, "e": 2180, "s": 2135, "text": "exists() − returns true if given path exists" }, { "code": null, "e": 2263, "s": 2180, "text": ">>> p = Path(\"mydir\")\n>>> p.exists()\nFalse\n>>> p = Path(\"etc\")\n>>> p.exists()\nTrue" }, { "code": null, "e": 2310, "s": 2263, "text": "is_dir() − returns true if path is a directory" }, { "code": null, "e": 2395, "s": 2310, "text": ">>> p = Path(\"etc\")\n>>> p.is_dir()\nTrue\n>>> p = Path(\"test.py\")\n>>> p.is_dir()\nFalse" }, { "code": null, "e": 2448, "s": 2395, "text": "is_file() − returns true if path corresponds to file" }, { "code": null, "e": 2534, "s": 2448, "text": ">>> p = Path(\"tmp.py\")\n>>> p.is_file()\nTrue\n>>> p = Path(\"etc\")\n>>> p.is_file()\nFalse" }, { "code": null, "e": 2628, "s": 2534, "text": "iterdir() − returns a generator that yields filenames in the directory corresponding to path." }, { "code": null, "e": 2757, "s": 2628, "text": ">>> p = Path(\"libs\")\n>>> for f in p.iterdir():\nprint (f)\nlibs\\libpython36.a\nlibs\\python3.lib\nlibs\\python36.lib\nlibs\\_tkinter.lib" }, { "code": null, "e": 2837, "s": 2757, "text": "mkdir() − creates new directory representing path if it is not already present." }, { "code": null, "e": 3051, "s": 2837, "text": ">>> p = Path(\"mydir\")\n>>> p.mkdir()\n>>> p.absolute()\nWindowsPath('C:/python36/mydir')\n>>> p = Path(\"codes\")\n>>> p.mkdir()\nFileExistsError: [WinError 183] Cannot create a file when that file already exists: 'codes'" }, { "code": null, "e": 3168, "s": 3051, "text": "open() − opens file represented by Path object and returns file object. This is similar to built-in open() function." }, { "code": null, "e": 3242, "s": 3168, "text": ">>> p = Path(\"Hello.py\")\n>>> f = p.open()\n>>> f.readline()\n'Hello Python'" }, { "code": null, "e": 3339, "s": 3242, "text": "read_bytes() − opens the file in binary mode, reads its data in binary form and closes the same." }, { "code": null, "e": 3418, "s": 3339, "text": ">>> p = Path(\"Hello.py\")\n>>> f.read_bytes()\n>>> p.read_bytes()\nb'Hello Python'" }, { "code": null, "e": 3502, "s": 3418, "text": "read_text() − File is opened in text mode to read the text and close it afterwards." }, { "code": null, "e": 3560, "s": 3502, "text": ">>> p = Path(\"Hello.py\")\n>>> p.read_text()\n'Hello Python'" }, { "code": null, "e": 3618, "s": 3560, "text": "write_text() − opens the file, writes text and closes it." }, { "code": null, "e": 3685, "s": 3618, "text": ">>> p = Path(\"Hello.py\")\n>>> p.write_text(\"Hello how are you?\")\n18" }, { "code": null, "e": 3751, "s": 3685, "text": "write_bytes() − Writes binary data in a file and closes the same." }, { "code": null, "e": 3810, "s": 3751, "text": ">>> p = Path(\"Hello.py\")\n>>> p.write_bytes(b'I am fine')\n9" }, { "code": null, "e": 3856, "s": 3810, "text": "stat() − returns information about this path." }, { "code": null, "e": 4069, "s": 3856, "text": ">>> p.stat()\nos.stat_result(st_mode = 16895, st_ino = 9570149208167477, st_dev = 1526259762, st_nlink = 1, st_uid = 0, st_gid = 0, st_size = 0, st_atime = 1543085915, st_mtime = 1543085915, st_ctime = 1543085915)" }, { "code": null, "e": 4127, "s": 4069, "text": "rmdir() − removes directory corresponding to Path object." }, { "code": null, "e": 4163, "s": 4127, "text": ">>> p = Path(\"mydir\")\n>>> p.rmdir()" }, { "code": null, "e": 4255, "s": 4163, "text": "Path.cwd() − This is a classmethod of Path class. returns path to current working directory" }, { "code": null, "e": 4297, "s": 4255, "text": ">>> Path.cwd()\nWindowsPath('C:/python36')" }, { "code": null, "e": 4379, "s": 4297, "text": "Path.home() − This is a classmethod of Path class. returns path to home directory" }, { "code": null, "e": 4424, "s": 4379, "text": ">>> Path.home()\nWindowsPath('C:/Users/acer')" }, { "code": null, "e": 4465, "s": 4424, "text": "The ‘/’ operator is used to build paths." }, { "code": null, "e": 4553, "s": 4465, "text": ">>> p = Path(\".\")\n>>> p1 = p/'codes'\n>>> p1.absolute()\nWindowsPath('C:/python36/codes')" }, { "code": null, "e": 4655, "s": 4553, "text": "In this article we learned the object oriented API to filesystem object as defined in pathlib module." } ]
Sorted matrix | Practice | GeeksforGeeks
Given an NxN matrix Mat. Sort all elements of the matrix. Example 1: Input: N=4 Mat=[[10,20,30,40], [15,25,35,45] [27,29,37,48] [32,33,39,50]] Output: 10 15 20 25 27 29 30 32 33 35 37 39 40 45 48 50 Explanation: Sorting the matrix gives this result. Example 2: Input: N=3 Mat=[[1,5,3],[2,8,7],[4,6,9]] Output: 1 2 3 4 5 6 7 8 9 Explanation: Sorting the matrix gives this result. Your Task: You don't need to read input or print anything. Your task is to complete the function sortedMatrix() which takes the integer N and the matrix Mat as input parameters and returns the sorted matrix. Expected Time Complexity:O(N2LogN) Expected Auxillary Space:O(N2) Constraints: 1<=N<=1000 1<=Mat[i][j]<=105 +1 bhardwajji6 days ago vector<vector<int>> sortedMatrix(int n, vector<vector<int>> mat) { priority_queue<int , vector<int> , greater<int>>vec; for(int i=0;i<n;i++) for(int j=0;j<n;j++){ vec.push(mat[i][j]); } for(int i=0;i<n;i++) for(int j=0;j<n;j++){ mat[i][j] = vec.top(); vec.pop(); } return mat; } +1 badgujarsachin832 weeks ago vector<vector<int>> sortedMatrix(int N, vector<vector<int>> Mat) { // code here vector<int> v; for(int i=0;i<N;i++){ for(int j=0;j<N;j++){ v.push_back(Mat[i][j]); } } int k=0; sort(v.begin(),v.end()); vector<vector<int>> ans(N,vector<int>(N)); for(int i=0;i<N;i++){ for(int j=0;j<N;j++){ ans[i][j]=v[k]; k++; } } return ans; } 0 aloksinghbais023 weeks ago C++ solution having time complexity as O(N*N*log(N*N)) and space complexity as O(N*N) is as follows :- Execution Time :- 1.07 / 2.27 sec vector<vector<int>> sortedMatrix(int N, vector<vector<int>> Mat) { vector<int> v; for(int i = 0; i < N; i++){ for(int j = 0; j < N; j++){ v.push_back(Mat[i][j]); } } sort(v.begin(),v.end()); int ind = 0; vector<vector<int>> ans(N,vector<int>(N)); for(int i = 0; i < N; i++){ for(int j = 0; j < N; j++){ ans[i][j] = v[ind++]; } } return (ans); } +1 arthurshelby4 weeks ago 😉🇮🇳✌️❄️ class Solution { public: vector<vector<int>> sortedMatrix(int N, vector<vector<int>> Mat) { // code here vector<int>v; for(int i=0;i<Mat.size();i++) { for(int j=0;j<Mat.size();j++) { v.push_back(Mat[i][j]); } } sort(v.begin(),v.end()); int c=0; for(int i=0;i<Mat.size();i++) { for(int j=0;j<Mat.size();j++) { Mat[i][j]=v[c]; c++; } } return Mat; } }; 0 gurucharanchouhan171 month ago Solution in java :) class Solution { int[][] sortedMatrix(int N, int a[][]) { ArrayList<Integer>l=new ArrayList<>(); for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { l.add(a[i][j]); } } Collections.sort(l); int k=0; for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { a[i][j]=l.get(k++); } } return a; } }; 0 anubhavnegi541 month ago Simple JAVA SOLUTION class Solution { int[][] sortedMatrix(int N, int Mat[][]) { // code here N = Mat.length; int[] mat = new int[N * N]; int k = 0; int z =0; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { mat[k++] = Mat[i][j]; } } Arrays.sort(mat); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { Mat[i][j] = mat[z++]; } } return Mat; } }; 0 mishra07adi1 month ago C++ Solution class Solution { public: vector<vector<int>> sortedMatrix(int N, vector<vector<int>> Mat) { // code here vector<int> arr; for(int i=0;i<N;i++) for(int j=0;j<N;j++) arr.push_back(Mat[i][j]); sort(arr.begin(),arr.end()); int k = 0; for(int i=0;i<N;i++) for(int j=0;j<N;j++) Mat[i][j] = arr[k++]; return Mat; } }; 0 mishra07adi1 month ago JAVA Solution class Solution { int[][] sortedMatrix(int N, int Mat[][]) { // code here int arr[] = new int[N*N]; int k=0; for(int i=0;i<N;i++) for(int j=0;j<N;j++) arr[k++]=Mat[i][j]; Arrays.sort(arr); k = 0; for(int i=0;i<N;i++) for(int j=0;j<N;j++) Mat[i][j] = arr[k++]; return Mat; } }; 0 subhashishde081 month ago class Solution { public: vector<vector<int>> sortedMatrix(int N, vector<vector<int>> Mat) { // code here vector<int>temp; int r = N; int c = Mat[0].size(); for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ temp.push_back(Mat[i][j]); } } sort(temp.begin(),temp.end()); int j=0; int i=0; for(int x=0;x<temp.size();x++){ if(j==c){ j=0; i+=1; } Mat[i][j]=(temp[x]); j++; } return Mat; } }; 0 abhishekgokhe25041 month ago JAVA Solution using ArrayList int mt[][]=new int[N][N]; ArrayList<Integer> a=new ArrayList<>(); for(int i=0; i<N; i++){ for(int j=0; j<N; j++){ a.add(Mat[i][j]); } } Collections.sort(a); int k =0; for(int i=0; i<N; i++){ for(int j=0; j<N; j++){ mt[i][j]=a.get(k); k++; } } return mt; 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": 296, "s": 238, "text": "Given an NxN matrix Mat. Sort all elements of the matrix." }, { "code": null, "e": 307, "s": 296, "text": "Example 1:" }, { "code": null, "e": 491, "s": 307, "text": "Input:\nN=4\nMat=[[10,20,30,40],\n[15,25,35,45] \n[27,29,37,48] \n[32,33,39,50]]\nOutput:\n10 15 20 25 \n27 29 30 32\n33 35 37 39\n40 45 48 50\nExplanation:\nSorting the matrix gives this result." }, { "code": null, "e": 502, "s": 491, "text": "Example 2:" }, { "code": null, "e": 621, "s": 502, "text": "Input:\nN=3\nMat=[[1,5,3],[2,8,7],[4,6,9]]\nOutput:\n1 2 3 \n4 5 6\n7 8 9\nExplanation:\nSorting the matrix gives this result." }, { "code": null, "e": 829, "s": 621, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function sortedMatrix() which takes the integer N and the matrix Mat as input parameters and returns the sorted matrix." }, { "code": null, "e": 896, "s": 829, "text": "\nExpected Time Complexity:O(N2LogN)\nExpected Auxillary Space:O(N2)" }, { "code": null, "e": 939, "s": 896, "text": "\nConstraints:\n1<=N<=1000\n1<=Mat[i][j]<=105" }, { "code": null, "e": 942, "s": 939, "text": "+1" }, { "code": null, "e": 963, "s": 942, "text": "bhardwajji6 days ago" }, { "code": null, "e": 1400, "s": 963, "text": "vector<vector<int>> sortedMatrix(int n, vector<vector<int>> mat) {\n \n priority_queue<int , vector<int> , greater<int>>vec;\n \n for(int i=0;i<n;i++)\n for(int j=0;j<n;j++){\n vec.push(mat[i][j]);\n }\n \n \n for(int i=0;i<n;i++)\n for(int j=0;j<n;j++){\n mat[i][j] = vec.top();\n vec.pop();\n }\n \n return mat;\n \n }" }, { "code": null, "e": 1403, "s": 1400, "text": "+1" }, { "code": null, "e": 1431, "s": 1403, "text": "badgujarsachin832 weeks ago" }, { "code": null, "e": 1940, "s": 1431, "text": " vector<vector<int>> sortedMatrix(int N, vector<vector<int>> Mat) {\n // code here\n vector<int> v;\n for(int i=0;i<N;i++){\n for(int j=0;j<N;j++){\n v.push_back(Mat[i][j]);\n }\n }\n int k=0;\n sort(v.begin(),v.end());\n vector<vector<int>> ans(N,vector<int>(N));\n for(int i=0;i<N;i++){\n for(int j=0;j<N;j++){\n ans[i][j]=v[k];\n k++;\n }\n }\n return ans;\n }" }, { "code": null, "e": 1942, "s": 1940, "text": "0" }, { "code": null, "e": 1969, "s": 1942, "text": "aloksinghbais023 weeks ago" }, { "code": null, "e": 2073, "s": 1969, "text": "C++ solution having time complexity as O(N*N*log(N*N)) and space complexity as O(N*N) is as follows :- " }, { "code": null, "e": 2109, "s": 2075, "text": "Execution Time :- 1.07 / 2.27 sec" }, { "code": null, "e": 2594, "s": 2111, "text": "vector<vector<int>> sortedMatrix(int N, vector<vector<int>> Mat) { vector<int> v; for(int i = 0; i < N; i++){ for(int j = 0; j < N; j++){ v.push_back(Mat[i][j]); } } sort(v.begin(),v.end()); int ind = 0; vector<vector<int>> ans(N,vector<int>(N)); for(int i = 0; i < N; i++){ for(int j = 0; j < N; j++){ ans[i][j] = v[ind++]; } } return (ans); }" }, { "code": null, "e": 2597, "s": 2594, "text": "+1" }, { "code": null, "e": 2621, "s": 2597, "text": "arthurshelby4 weeks ago" }, { "code": null, "e": 3198, "s": 2621, "text": "😉🇮🇳✌️❄️\nclass Solution {\n public:\n vector<vector<int>> sortedMatrix(int N, vector<vector<int>> Mat) {\n // code here\n vector<int>v;\n for(int i=0;i<Mat.size();i++)\n {\n for(int j=0;j<Mat.size();j++)\n {\n v.push_back(Mat[i][j]);\n }\n }\n sort(v.begin(),v.end());\n int c=0;\n for(int i=0;i<Mat.size();i++)\n {\n for(int j=0;j<Mat.size();j++)\n {\n Mat[i][j]=v[c];\n c++;\n }\n }\n return Mat;\n }\n};" }, { "code": null, "e": 3200, "s": 3198, "text": "0" }, { "code": null, "e": 3231, "s": 3200, "text": "gurucharanchouhan171 month ago" }, { "code": null, "e": 3251, "s": 3231, "text": "Solution in java :)" }, { "code": null, "e": 3750, "s": 3253, "text": "class Solution {\n int[][] sortedMatrix(int N, int a[][]) {\n \n ArrayList<Integer>l=new ArrayList<>();\n \n for(int i=0;i<N;i++)\n {\n for(int j=0;j<N;j++)\n {\n l.add(a[i][j]);\n }\n }\n Collections.sort(l);\n \n int k=0;\n for(int i=0;i<N;i++)\n {\n for(int j=0;j<N;j++)\n {\n a[i][j]=l.get(k++);\n }\n }\n return a;\n }\n};" }, { "code": null, "e": 3752, "s": 3750, "text": "0" }, { "code": null, "e": 3777, "s": 3752, "text": "anubhavnegi541 month ago" }, { "code": null, "e": 3798, "s": 3777, "text": "Simple JAVA SOLUTION" }, { "code": null, "e": 4327, "s": 3800, "text": "\nclass Solution {\n int[][] sortedMatrix(int N, int Mat[][]) {\n // code here\n N = Mat.length;\n int[] mat = new int[N * N];\n\n int k = 0;\n int z =0;\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n\n mat[k++] = Mat[i][j];\n }\n }\n\n Arrays.sort(mat);\n\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n\n Mat[i][j] = mat[z++];\n }\n }\n return Mat;\n }\n};" }, { "code": null, "e": 4329, "s": 4327, "text": "0" }, { "code": null, "e": 4352, "s": 4329, "text": "mishra07adi1 month ago" }, { "code": null, "e": 4365, "s": 4352, "text": "C++ Solution" }, { "code": null, "e": 4843, "s": 4365, "text": "class Solution {\n public:\n vector<vector<int>> sortedMatrix(int N, vector<vector<int>> Mat) {\n // code here\n vector<int> arr;\n \n for(int i=0;i<N;i++)\n for(int j=0;j<N;j++)\n arr.push_back(Mat[i][j]);\n \n sort(arr.begin(),arr.end());\n \n int k = 0;\n for(int i=0;i<N;i++)\n for(int j=0;j<N;j++)\n Mat[i][j] = arr[k++];\n \n return Mat;\n \n }\n};" }, { "code": null, "e": 4847, "s": 4845, "text": "0" }, { "code": null, "e": 4870, "s": 4847, "text": "mishra07adi1 month ago" }, { "code": null, "e": 4884, "s": 4870, "text": "JAVA Solution" }, { "code": null, "e": 5330, "s": 4884, "text": "class Solution \n{\n int[][] sortedMatrix(int N, int Mat[][]) \n {\n // code here\n int arr[] = new int[N*N];\n int k=0;\n for(int i=0;i<N;i++)\n for(int j=0;j<N;j++)\n arr[k++]=Mat[i][j];\n \n Arrays.sort(arr);\n \n k = 0;\n for(int i=0;i<N;i++)\n for(int j=0;j<N;j++)\n Mat[i][j] = arr[k++];\n \n return Mat;\n \n }\n};" }, { "code": null, "e": 5332, "s": 5330, "text": "0" }, { "code": null, "e": 5358, "s": 5332, "text": "subhashishde081 month ago" }, { "code": null, "e": 5973, "s": 5358, "text": "class Solution {\n public:\n vector<vector<int>> sortedMatrix(int N, vector<vector<int>> Mat) {\n // code here\n vector<int>temp;\n int r = N;\n int c = Mat[0].size();\n for(int i=0;i<r;i++){\n for(int j=0;j<c;j++){\n temp.push_back(Mat[i][j]);\n }\n }\n sort(temp.begin(),temp.end());\n int j=0;\n int i=0;\n for(int x=0;x<temp.size();x++){\n if(j==c){\n j=0;\n i+=1;\n }\n Mat[i][j]=(temp[x]);\n j++;\n }\n \n return Mat;\n }\n};" }, { "code": null, "e": 5975, "s": 5973, "text": "0" }, { "code": null, "e": 6004, "s": 5975, "text": "abhishekgokhe25041 month ago" }, { "code": null, "e": 6034, "s": 6004, "text": "JAVA Solution using ArrayList" }, { "code": null, "e": 6448, "s": 6034, "text": "int mt[][]=new int[N][N];\n ArrayList<Integer> a=new ArrayList<>();\n for(int i=0; i<N; i++){\n for(int j=0; j<N; j++){\n a.add(Mat[i][j]);\n }\n }\n Collections.sort(a);\n int k =0;\n for(int i=0; i<N; i++){\n for(int j=0; j<N; j++){\n mt[i][j]=a.get(k);\n k++;\n }\n }\n return mt;" }, { "code": null, "e": 6596, "s": 6450, "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": 6632, "s": 6596, "text": " Login to access your submissions. " }, { "code": null, "e": 6642, "s": 6632, "text": "\nProblem\n" }, { "code": null, "e": 6652, "s": 6642, "text": "\nContest\n" }, { "code": null, "e": 6715, "s": 6652, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6863, "s": 6715, "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": 7071, "s": 6863, "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": 7177, "s": 7071, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
SQL Tryit Editor v1.6
SELECT CustomerName,City FROM Customers; ​ Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, Opera, and Edge(79). If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 41, "s": 0, "text": "SELECT CustomerName,City FROM Customers;" }, { "code": null, "e": 43, "s": 41, "text": "​" }, { "code": null, "e": 106, "s": 43, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "code": null, "e": 166, "s": 106, "text": "This SQL-Statement is not supported in the WebSQL Database." }, { "code": null, "e": 234, "s": 166, "text": "The example still works, because it uses a modified version of SQL." }, { "code": null, "e": 272, "s": 234, "text": "Your browser does not support WebSQL." }, { "code": null, "e": 357, "s": 272, "text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database." }, { "code": null, "e": 531, "s": 357, "text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time." }, { "code": null, "e": 582, "s": 531, "text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL." }, { "code": null, "e": 650, "s": 582, "text": "A Database-object is created in your browser, for testing purposes." }, { "code": null, "e": 821, "s": 650, "text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button." }, { "code": null, "e": 921, "s": 821, "text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object." }, { "code": null, "e": 981, "s": 921, "text": "WebSQL is supported in Chrome, Safari, Opera, and Edge(79)." } ]
close driver method - Selenium Python - GeeksforGeeks
15 May, 2020 Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc. This article revolves around close driver method in Selenium. close method is used to close the current window of browser. Syntax – driver.close() Example –Now one can use close method as a driver method as below – diver.get("https://www.geeksforgeeks.org/") driver.close() To demonstrate, close method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Program – # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # close current windowdriver.close() Output –Browser gets closed as verified below – Python-selenium selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 25647, "s": 25619, "text": "\n15 May, 2020" }, { "code": null, "e": 26386, "s": 25647, "text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc." }, { "code": null, "e": 26509, "s": 26386, "text": "This article revolves around close driver method in Selenium. close method is used to close the current window of browser." }, { "code": null, "e": 26518, "s": 26509, "text": "Syntax –" }, { "code": null, "e": 26533, "s": 26518, "text": "driver.close()" }, { "code": null, "e": 26601, "s": 26533, "text": "Example –Now one can use close method as a driver method as below –" }, { "code": null, "e": 26661, "s": 26601, "text": "diver.get(\"https://www.geeksforgeeks.org/\")\ndriver.close()\n" }, { "code": null, "e": 26797, "s": 26661, "text": "To demonstrate, close method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object." }, { "code": null, "e": 26807, "s": 26797, "text": "Program –" }, { "code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # close current windowdriver.close()", "e": 27018, "s": 26807, "text": null }, { "code": null, "e": 27066, "s": 27018, "text": "Output –Browser gets closed as verified below –" }, { "code": null, "e": 27082, "s": 27066, "text": "Python-selenium" }, { "code": null, "e": 27091, "s": 27082, "text": "selenium" }, { "code": null, "e": 27098, "s": 27091, "text": "Python" }, { "code": null, "e": 27196, "s": 27098, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27228, "s": 27196, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27270, "s": 27228, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27312, "s": 27270, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27368, "s": 27312, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27395, "s": 27368, "text": "Python Classes and Objects" }, { "code": null, "e": 27426, "s": 27395, "text": "Python | os.path.join() method" }, { "code": null, "e": 27455, "s": 27426, "text": "Create a directory in Python" }, { "code": null, "e": 27477, "s": 27455, "text": "Defaultdict in Python" }, { "code": null, "e": 27513, "s": 27477, "text": "Python | Pandas dataframe.groupby()" } ]
How to Add a TextView with Rounded Corner in Android?
18 Feb, 2021 TextView is an essential object of an Android application. It comes in the list of some basic objects of android and used to print text on the screen. In order to create better apps, we should learn that how can we create a TextView which have a background with rounded corners. We can implement this skill in a practical manner for any android application. For creating professional-looking user interfaces, we need to take care of these small things. In this article, You will be learning how to create a TextView with Rounded Corners. First of all, we need to create a drawable resource file, which has a proper definition to make TextView corners rounded, and then we have to add a background attribute to that special TextView object. Let’s do it in steps! Step 1: Create a new android studio project, and select an empty activity. You can also refer to this GFG Tutorial for Creating a new android studio project. Step 2: Make sure that you have selected the Android option for project structure on the top left corner of the screen, then go to the res/drawable folder. Step 3: Here right-click on the drawable folder and click on new and select drawable resource file. Give it a name of your choice, we are giving it rounded_corner_view. Note: In android studio you can’t give a name of a resource file (Layout file, Color File, Image File, or any XML file) in uppercase and camelCase, you have to follow the lowercase letters only and it’s a good habit to use lowercase letters with underscores in place of spaces. Step 4: Now in the drawable resource file, which you have just created, remove all the default code and paste the following code. XML <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <corners android:radius="10dp" /> <!-- This is the border color --> <stroke android:width="2dp" android:color="#ccc" /> <!--- This is the background color --> <solid android:color="#ccc" /> </shape> Step 5: Now go to the activity_main.xml file and add an attribute to that TextView, for which you want to add rounded corners. The attribute is android: background=”@drawable/rounded_corner_view”. Tip: Don’t forget to replace your drawable resource file name if you have given a different name and you don’t need to add xml extension after file name. android Android-View Android Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Feb, 2021" }, { "code": null, "e": 506, "s": 52, "text": "TextView is an essential object of an Android application. It comes in the list of some basic objects of android and used to print text on the screen. In order to create better apps, we should learn that how can we create a TextView which have a background with rounded corners. We can implement this skill in a practical manner for any android application. For creating professional-looking user interfaces, we need to take care of these small things. " }, { "code": null, "e": 815, "s": 506, "text": "In this article, You will be learning how to create a TextView with Rounded Corners. First of all, we need to create a drawable resource file, which has a proper definition to make TextView corners rounded, and then we have to add a background attribute to that special TextView object. Let’s do it in steps!" }, { "code": null, "e": 973, "s": 815, "text": "Step 1: Create a new android studio project, and select an empty activity. You can also refer to this GFG Tutorial for Creating a new android studio project." }, { "code": null, "e": 1129, "s": 973, "text": "Step 2: Make sure that you have selected the Android option for project structure on the top left corner of the screen, then go to the res/drawable folder." }, { "code": null, "e": 1298, "s": 1129, "text": "Step 3: Here right-click on the drawable folder and click on new and select drawable resource file. Give it a name of your choice, we are giving it rounded_corner_view." }, { "code": null, "e": 1577, "s": 1298, "text": "Note: In android studio you can’t give a name of a resource file (Layout file, Color File, Image File, or any XML file) in uppercase and camelCase, you have to follow the lowercase letters only and it’s a good habit to use lowercase letters with underscores in place of spaces. " }, { "code": null, "e": 1707, "s": 1577, "text": "Step 4: Now in the drawable resource file, which you have just created, remove all the default code and paste the following code." }, { "code": null, "e": 1711, "s": 1707, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:shape=\"rectangle\"> <corners android:radius=\"10dp\" /> <!-- This is the border color --> <stroke android:width=\"2dp\" android:color=\"#ccc\" /> <!--- This is the background color --> <solid android:color=\"#ccc\" /> </shape>", "e": 2081, "s": 1711, "text": null }, { "code": null, "e": 2278, "s": 2081, "text": "Step 5: Now go to the activity_main.xml file and add an attribute to that TextView, for which you want to add rounded corners. The attribute is android: background=”@drawable/rounded_corner_view”." }, { "code": null, "e": 2432, "s": 2278, "text": "Tip: Don’t forget to replace your drawable resource file name if you have given a different name and you don’t need to add xml extension after file name." }, { "code": null, "e": 2440, "s": 2432, "text": "android" }, { "code": null, "e": 2453, "s": 2440, "text": "Android-View" }, { "code": null, "e": 2461, "s": 2453, "text": "Android" }, { "code": null, "e": 2469, "s": 2461, "text": "Android" } ]
Working with Lists – Python .docx Module
07 Mar, 2022 Prerequisite: Working with .docx module Word documents contain formatted text wrapped within three object levels. The Lowest level- run objects, middle level- paragraph objects, and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module. Pip command to install this module is: pip install python-docx Python docx module allows users to manipulate docs by either manipulating the existing one or creating a new empty document and manipulating it. It is a powerful tool as it helps you to manipulate the document to a very large extent. There are two types of lists: Ordered List Unordered List To add an ordered/unordered list in a Word document there are styles available in the .add_paragraph() method of the document object. Syntax: doc.add_paragraph(String s, style=None) Parameters: String s: It is the string data that is to be added as a paragraph. This string can contain newline character ‘\n’, tabs ‘\t’ or a carriage return character ‘\r’. Style: It is used to set style. Styles to add an ordered list are: Sr. No. Style Name Description 1. List Number It adds an ordered list in the word document. 2. List Number 2 It adds an ordered list with a single tab indentation in the word document. 3. List Number 3 It adds an ordered list with double tab indentation in the word document. Note: Each list-point is considered as a paragraph in a list so you have to add each point as a new paragraph with the same style name. Example 1: Adding an ordered list in the Word document. Python3 # Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Add a Title to the document doc.add_heading('GeeksForGeeks', 0) # Adding list of style name 'List Number'doc.add_heading('Style: List Number', 3)# Adding points to the list named 'List Number'doc.add_paragraph('The first item in an ordered list.', style='List Number') doc.add_paragraph('The second item in an ordered list.', style='List Number') doc.add_paragraph('The third item in an ordered list.', style='List Number') # Adding list of style name 'List Number 2'doc.add_heading('Style: List Number 2', 3)# Adding points to the list named 'List Number 2'doc.add_paragraph('The first item in an ordered list.', style='List Number 2') doc.add_paragraph('The second item in an ordered list.', style='List Number 2') doc.add_paragraph('The third item in an ordered list.', style='List Number 2') # Adding list of style name 'List Number 3'doc.add_heading('Style: List Number 3', 3)# Adding points to the list named 'List Number 3'doc.add_paragraph('The first item in an ordered list.', style='List Number 3') doc.add_paragraph('The second item in an ordered list.', style='List Number 3') doc.add_paragraph('The third item in an ordered list.', style='List Number 3') # Now save the document to a location doc.save('gfg.docx') Output: Document gfg.docx Styles to add an unordered list are: Sr. No. Style Name Description 1. List Bullet It adds an unordered list in the word document. 2. List Bullet 2 It adds an unordered list with a single tab indentation in the word document. 3. List Bullet 3 It adds an unordered list with a double tab indentation in the word document. Note: Each list-point is considered as a paragraph in a list so you have to add each point as a new paragraph with the same style name. Example 2: Adding an unordered list in the Word document. Python3 # Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Add a Title to the document doc.add_heading('GeeksForGeeks', 0) # Adding list of style name 'List Bullet'doc.add_heading('Style: List Bullet', 3)# Adding points to the list named 'List Number'doc.add_paragraph('The first item in an unordered list.', style='List Bullet') doc.add_paragraph('The second item in an unordered list.', style='List Bullet') doc.add_paragraph('The third item in an unordered list.', style='List Bullet') # Adding list of style name 'List Bullet 2'doc.add_heading('Style: List Bullet 2', 3)# Adding points to the list named 'List Number'doc.add_paragraph('The first item in an unordered list.', style='List Bullet 2') doc.add_paragraph('The second item in an unordered list.', style='List Bullet 2') doc.add_paragraph('The third item in an unordered list.', style='List Bullet 2') # Adding list of style name 'List Bullet 3'doc.add_heading('Style: List Bullet 3', 3)# Adding points to the list named 'List Number'doc.add_paragraph('The first item in an unordered list.', style='List Bullet 3') doc.add_paragraph('The second item in an unordered list.', style='List Bullet 3') doc.add_paragraph('The third item in an unordered list.', style='List Bullet 3') # Now save the document to a location doc.save('gfg.docx') Output: Document gfg.docx kothavvsaakash Python Docx-module Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Mar, 2022" }, { "code": null, "e": 68, "s": 28, "text": "Prerequisite: Working with .docx module" }, { "code": null, "e": 432, "s": 68, "text": "Word documents contain formatted text wrapped within three object levels. The Lowest level- run objects, middle level- paragraph objects, and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module. Pip command to install this module is:" }, { "code": null, "e": 456, "s": 432, "text": "pip install python-docx" }, { "code": null, "e": 720, "s": 456, "text": "Python docx module allows users to manipulate docs by either manipulating the existing one or creating a new empty document and manipulating it. It is a powerful tool as it helps you to manipulate the document to a very large extent. There are two types of lists:" }, { "code": null, "e": 733, "s": 720, "text": "Ordered List" }, { "code": null, "e": 748, "s": 733, "text": "Unordered List" }, { "code": null, "e": 882, "s": 748, "text": "To add an ordered/unordered list in a Word document there are styles available in the .add_paragraph() method of the document object." }, { "code": null, "e": 930, "s": 882, "text": "Syntax: doc.add_paragraph(String s, style=None)" }, { "code": null, "e": 942, "s": 930, "text": "Parameters:" }, { "code": null, "e": 1105, "s": 942, "text": "String s: It is the string data that is to be added as a paragraph. This string can contain newline character ‘\\n’, tabs ‘\\t’ or a carriage return character ‘\\r’." }, { "code": null, "e": 1137, "s": 1105, "text": "Style: It is used to set style." }, { "code": null, "e": 1172, "s": 1137, "text": "Styles to add an ordered list are:" }, { "code": null, "e": 1180, "s": 1172, "text": "Sr. No." }, { "code": null, "e": 1191, "s": 1180, "text": "Style Name" }, { "code": null, "e": 1203, "s": 1191, "text": "Description" }, { "code": null, "e": 1206, "s": 1203, "text": "1." }, { "code": null, "e": 1218, "s": 1206, "text": "List Number" }, { "code": null, "e": 1264, "s": 1218, "text": "It adds an ordered list in the word document." }, { "code": null, "e": 1267, "s": 1264, "text": "2." }, { "code": null, "e": 1281, "s": 1267, "text": "List Number 2" }, { "code": null, "e": 1357, "s": 1281, "text": "It adds an ordered list with a single tab indentation in the word document." }, { "code": null, "e": 1360, "s": 1357, "text": "3." }, { "code": null, "e": 1374, "s": 1360, "text": "List Number 3" }, { "code": null, "e": 1448, "s": 1374, "text": "It adds an ordered list with double tab indentation in the word document." }, { "code": null, "e": 1584, "s": 1448, "text": "Note: Each list-point is considered as a paragraph in a list so you have to add each point as a new paragraph with the same style name." }, { "code": null, "e": 1642, "s": 1586, "text": "Example 1: Adding an ordered list in the Word document." }, { "code": null, "e": 1650, "s": 1642, "text": "Python3" }, { "code": "# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Add a Title to the document doc.add_heading('GeeksForGeeks', 0) # Adding list of style name 'List Number'doc.add_heading('Style: List Number', 3)# Adding points to the list named 'List Number'doc.add_paragraph('The first item in an ordered list.', style='List Number') doc.add_paragraph('The second item in an ordered list.', style='List Number') doc.add_paragraph('The third item in an ordered list.', style='List Number') # Adding list of style name 'List Number 2'doc.add_heading('Style: List Number 2', 3)# Adding points to the list named 'List Number 2'doc.add_paragraph('The first item in an ordered list.', style='List Number 2') doc.add_paragraph('The second item in an ordered list.', style='List Number 2') doc.add_paragraph('The third item in an ordered list.', style='List Number 2') # Adding list of style name 'List Number 3'doc.add_heading('Style: List Number 3', 3)# Adding points to the list named 'List Number 3'doc.add_paragraph('The first item in an ordered list.', style='List Number 3') doc.add_paragraph('The second item in an ordered list.', style='List Number 3') doc.add_paragraph('The third item in an ordered list.', style='List Number 3') # Now save the document to a location doc.save('gfg.docx')", "e": 3149, "s": 1650, "text": null }, { "code": null, "e": 3157, "s": 3149, "text": "Output:" }, { "code": null, "e": 3175, "s": 3157, "text": "Document gfg.docx" }, { "code": null, "e": 3212, "s": 3175, "text": "Styles to add an unordered list are:" }, { "code": null, "e": 3220, "s": 3212, "text": "Sr. No." }, { "code": null, "e": 3231, "s": 3220, "text": "Style Name" }, { "code": null, "e": 3243, "s": 3231, "text": "Description" }, { "code": null, "e": 3246, "s": 3243, "text": "1." }, { "code": null, "e": 3258, "s": 3246, "text": "List Bullet" }, { "code": null, "e": 3306, "s": 3258, "text": "It adds an unordered list in the word document." }, { "code": null, "e": 3309, "s": 3306, "text": "2." }, { "code": null, "e": 3323, "s": 3309, "text": "List Bullet 2" }, { "code": null, "e": 3401, "s": 3323, "text": "It adds an unordered list with a single tab indentation in the word document." }, { "code": null, "e": 3404, "s": 3401, "text": "3." }, { "code": null, "e": 3418, "s": 3404, "text": "List Bullet 3" }, { "code": null, "e": 3496, "s": 3418, "text": "It adds an unordered list with a double tab indentation in the word document." }, { "code": null, "e": 3632, "s": 3496, "text": "Note: Each list-point is considered as a paragraph in a list so you have to add each point as a new paragraph with the same style name." }, { "code": null, "e": 3692, "s": 3634, "text": "Example 2: Adding an unordered list in the Word document." }, { "code": null, "e": 3700, "s": 3692, "text": "Python3" }, { "code": "# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Add a Title to the document doc.add_heading('GeeksForGeeks', 0) # Adding list of style name 'List Bullet'doc.add_heading('Style: List Bullet', 3)# Adding points to the list named 'List Number'doc.add_paragraph('The first item in an unordered list.', style='List Bullet') doc.add_paragraph('The second item in an unordered list.', style='List Bullet') doc.add_paragraph('The third item in an unordered list.', style='List Bullet') # Adding list of style name 'List Bullet 2'doc.add_heading('Style: List Bullet 2', 3)# Adding points to the list named 'List Number'doc.add_paragraph('The first item in an unordered list.', style='List Bullet 2') doc.add_paragraph('The second item in an unordered list.', style='List Bullet 2') doc.add_paragraph('The third item in an unordered list.', style='List Bullet 2') # Adding list of style name 'List Bullet 3'doc.add_heading('Style: List Bullet 3', 3)# Adding points to the list named 'List Number'doc.add_paragraph('The first item in an unordered list.', style='List Bullet 3') doc.add_paragraph('The second item in an unordered list.', style='List Bullet 3') doc.add_paragraph('The third item in an unordered list.', style='List Bullet 3') # Now save the document to a location doc.save('gfg.docx')", "e": 5212, "s": 3700, "text": null }, { "code": null, "e": 5220, "s": 5212, "text": "Output:" }, { "code": null, "e": 5238, "s": 5220, "text": "Document gfg.docx" }, { "code": null, "e": 5253, "s": 5238, "text": "kothavvsaakash" }, { "code": null, "e": 5272, "s": 5253, "text": "Python Docx-module" }, { "code": null, "e": 5296, "s": 5272, "text": "Technical Scripter 2020" }, { "code": null, "e": 5303, "s": 5296, "text": "Python" }, { "code": null, "e": 5322, "s": 5303, "text": "Technical Scripter" } ]
Ohm’s Law – Definition, Formula, Applications, Limitations
23 Nov, 2021 According to Ohm’s law, the voltage or potential difference between two locations is proportional to the current of electricity flowing through the resistance, and the resistance of the circuit is proportional to the current or electricity travelling through the resistance. V=IR is the formula for Ohm’s law. Georg Simon Ohm, a German physicist, discovered the connection between current, voltage, and relationship. Let’s take a closer look at Ohms Law, Resistance, and its applications. Voltage, current, and resistance are the three most fundamental components of electricity. Ohm’s law depicts a straightforward relationship between these three variables. According to Ohm’s law, the current flowing through a conductor between two locations is proportional to the voltage across the conductor. Voltage-Current Relationship Diagram This is one of the most fundamental electrical rules. It aids in the calculation of an element’s power, efficiency, current, voltage, and resistance in an electrical circuit. V ∝ R V = I × R Here, V is the voltage, I is the current, and R is the resistance. The SI unit of resistance is ohms and is denoted by Ω. When the other two numbers are known, Ohm’s law may be used to determine the voltage, current, impedance, or resistance of a linear electric circuit. Main applications of Ohm’s Law: It also simplifies power calculations. To keep the desired voltage drop between the electrical components, Ohm’s law is employed. An electric circuit’s voltage, resistance, or current must be determined. Ohm’s law is also utilised to redirect current in DC ammeters and other DC shunts. The ratio V ⁄ I remains constant for a given resistance while establishing the current-voltage connection, hence a graph of the potential difference (V) and current (I) must be a straight line. How can we discover the unknown resistance values? The constant ratio is what determines the unknown resistance values. The resistance of a wire with a uniform cross-section relies on the length (L) and the cross-section area (A). It also relies on the conductor’s temperature. The resistance, at a given temperature, R = ρ L ⁄ A Here, ρ is the specific resistance or resistivity and is the wire material’s characteristic. The wire material’s specific resistance or resistivity is, ρ = R A ⁄ L The law of Ohm does not apply to unilateral networks. The current can only flow in one direction in unilateral networks. Diodes, transistors, and other electronic components are used in these sorts of networks. Non-linear components are also exempt from Ohm’s law. Non-linear components have a current that is not proportional to the applied voltage, which implies that the resistance value of those elements varies depending on the voltage and current. The thyristor is an example of a non-linear element. One of the most important components in electrical circuits is the resistor. Because they are comprised of a clay or carbon combination, they are good conductors and good insulators. Four colour bands are seen on the majority of resistors. The first and second bands show the value’s first and second digits, respectively. The value digits are multiplied in the third band, and the tolerance is determined in the fourth band. If there isn’t a fourth band, the tolerance is presumed to be plus or minus 20 %. Resistance in series A series is a group of related items, such as along a line, in a row, or in a certain order. In electronics, series resistance implies that the resistors are linked in series and that current can only travel via one channel. Laws of Series Circuits The overall circuit resistance is made up of individual resistances. The total voltage is the sum of the individual voltages in the circuit. Every point in the circuit has the same amount of current flowing through it. Resistance in parallel A parallel circuit can be organised in a variety of ways. The majority of wiring in the real world is done in parallel, such that the voltage provided to any one portion of the network is the same as the voltage given to any other section of it. Laws of Parallel Circuits All of the component resistances’ reciprocals add up to the overall circuit resistance’s reciprocal. The total current draw is the sum of individual current pulls across the circuit. Every point in the circuit has the same voltage. Problem 1: Find the resistance of an electrical circuit with a voltage supply of 15 V and a current of 3 mA. Solution: Given: V = 15 V, I = 3 mA = 0.003 A The resistance of an electrical circuit is given as: R = V / I = 15 V / 0.003 A = 5000 Ω = 5 kΩ Hence, the resistance of an electrical circuit is 5 kΩ. Problem 2: If the resistance of an electric iron is 10 Ω and a current of 6 A flows through the resistance. Find the voltage between two points. Solution: Given: I = 6 A R = 10 Ω The formula to calculate the voltage is given as: V = I × R V = 6 A × 10 Ω = 60 V Hence, the voltage between two points is 60 V. Problem 3: When does Ohm’s law fail? Solution: The behaviour of semiconductors and unilateral devices like diodes defines Ohm’s law. If physical factors such as temperature and pressure are not kept constant, Ohm’s law may not provide the intended effects. Problem 4: Why doesn’t Ohm’s law apply to semiconductors? Solution: Semiconducting devices are nonlinear in nature due to which Ohm’s law does not apply to them. This indicates that the voltage-to-current ratio does not remain constant when voltage varies. Problem 5: What is the application of Ohm’s Law? Solution: The static values of circuit components such as current levels, voltage supplies, and voltage drops are validated using Ohm’s law. kalrap615 Picked Class 12 School Learning School Physics Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Nov, 2021" }, { "code": null, "e": 517, "s": 28, "text": "According to Ohm’s law, the voltage or potential difference between two locations is proportional to the current of electricity flowing through the resistance, and the resistance of the circuit is proportional to the current or electricity travelling through the resistance. V=IR is the formula for Ohm’s law. Georg Simon Ohm, a German physicist, discovered the connection between current, voltage, and relationship. Let’s take a closer look at Ohms Law, Resistance, and its applications." }, { "code": null, "e": 827, "s": 517, "text": "Voltage, current, and resistance are the three most fundamental components of electricity. Ohm’s law depicts a straightforward relationship between these three variables. According to Ohm’s law, the current flowing through a conductor between two locations is proportional to the voltage across the conductor." }, { "code": null, "e": 864, "s": 827, "text": "Voltage-Current Relationship Diagram" }, { "code": null, "e": 1039, "s": 864, "text": "This is one of the most fundamental electrical rules. It aids in the calculation of an element’s power, efficiency, current, voltage, and resistance in an electrical circuit." }, { "code": null, "e": 1045, "s": 1039, "text": "V ∝ R" }, { "code": null, "e": 1055, "s": 1045, "text": "V = I × R" }, { "code": null, "e": 1061, "s": 1055, "text": "Here," }, { "code": null, "e": 1079, "s": 1061, "text": "V is the voltage," }, { "code": null, "e": 1101, "s": 1079, "text": "I is the current, and" }, { "code": null, "e": 1122, "s": 1101, "text": "R is the resistance." }, { "code": null, "e": 1177, "s": 1122, "text": "The SI unit of resistance is ohms and is denoted by Ω." }, { "code": null, "e": 1327, "s": 1177, "text": "When the other two numbers are known, Ohm’s law may be used to determine the voltage, current, impedance, or resistance of a linear electric circuit." }, { "code": null, "e": 1359, "s": 1327, "text": "Main applications of Ohm’s Law:" }, { "code": null, "e": 1398, "s": 1359, "text": "It also simplifies power calculations." }, { "code": null, "e": 1489, "s": 1398, "text": "To keep the desired voltage drop between the electrical components, Ohm’s law is employed." }, { "code": null, "e": 1563, "s": 1489, "text": "An electric circuit’s voltage, resistance, or current must be determined." }, { "code": null, "e": 1646, "s": 1563, "text": "Ohm’s law is also utilised to redirect current in DC ammeters and other DC shunts." }, { "code": null, "e": 1840, "s": 1646, "text": "The ratio V ⁄ I remains constant for a given resistance while establishing the current-voltage connection, hence a graph of the potential difference (V) and current (I) must be a straight line." }, { "code": null, "e": 1891, "s": 1840, "text": "How can we discover the unknown resistance values?" }, { "code": null, "e": 2118, "s": 1891, "text": "The constant ratio is what determines the unknown resistance values. The resistance of a wire with a uniform cross-section relies on the length (L) and the cross-section area (A). It also relies on the conductor’s temperature." }, { "code": null, "e": 2158, "s": 2118, "text": "The resistance, at a given temperature," }, { "code": null, "e": 2170, "s": 2158, "text": "R = ρ L ⁄ A" }, { "code": null, "e": 2263, "s": 2170, "text": "Here, ρ is the specific resistance or resistivity and is the wire material’s characteristic." }, { "code": null, "e": 2322, "s": 2263, "text": "The wire material’s specific resistance or resistivity is," }, { "code": null, "e": 2334, "s": 2322, "text": "ρ = R A ⁄ L" }, { "code": null, "e": 2545, "s": 2334, "text": "The law of Ohm does not apply to unilateral networks. The current can only flow in one direction in unilateral networks. Diodes, transistors, and other electronic components are used in these sorts of networks." }, { "code": null, "e": 2841, "s": 2545, "text": "Non-linear components are also exempt from Ohm’s law. Non-linear components have a current that is not proportional to the applied voltage, which implies that the resistance value of those elements varies depending on the voltage and current. The thyristor is an example of a non-linear element." }, { "code": null, "e": 3349, "s": 2841, "text": "One of the most important components in electrical circuits is the resistor. Because they are comprised of a clay or carbon combination, they are good conductors and good insulators. Four colour bands are seen on the majority of resistors. The first and second bands show the value’s first and second digits, respectively. The value digits are multiplied in the third band, and the tolerance is determined in the fourth band. If there isn’t a fourth band, the tolerance is presumed to be plus or minus 20 %." }, { "code": null, "e": 3370, "s": 3349, "text": "Resistance in series" }, { "code": null, "e": 3595, "s": 3370, "text": "A series is a group of related items, such as along a line, in a row, or in a certain order. In electronics, series resistance implies that the resistors are linked in series and that current can only travel via one channel." }, { "code": null, "e": 3619, "s": 3595, "text": "Laws of Series Circuits" }, { "code": null, "e": 3688, "s": 3619, "text": "The overall circuit resistance is made up of individual resistances." }, { "code": null, "e": 3760, "s": 3688, "text": "The total voltage is the sum of the individual voltages in the circuit." }, { "code": null, "e": 3838, "s": 3760, "text": "Every point in the circuit has the same amount of current flowing through it." }, { "code": null, "e": 3861, "s": 3838, "text": "Resistance in parallel" }, { "code": null, "e": 4107, "s": 3861, "text": "A parallel circuit can be organised in a variety of ways. The majority of wiring in the real world is done in parallel, such that the voltage provided to any one portion of the network is the same as the voltage given to any other section of it." }, { "code": null, "e": 4133, "s": 4107, "text": "Laws of Parallel Circuits" }, { "code": null, "e": 4234, "s": 4133, "text": "All of the component resistances’ reciprocals add up to the overall circuit resistance’s reciprocal." }, { "code": null, "e": 4316, "s": 4234, "text": "The total current draw is the sum of individual current pulls across the circuit." }, { "code": null, "e": 4365, "s": 4316, "text": "Every point in the circuit has the same voltage." }, { "code": null, "e": 4474, "s": 4365, "text": "Problem 1: Find the resistance of an electrical circuit with a voltage supply of 15 V and a current of 3 mA." }, { "code": null, "e": 4484, "s": 4474, "text": "Solution:" }, { "code": null, "e": 4491, "s": 4484, "text": "Given:" }, { "code": null, "e": 4501, "s": 4491, "text": "V = 15 V," }, { "code": null, "e": 4520, "s": 4501, "text": "I = 3 mA = 0.003 A" }, { "code": null, "e": 4573, "s": 4520, "text": "The resistance of an electrical circuit is given as:" }, { "code": null, "e": 4583, "s": 4573, "text": "R = V / I" }, { "code": null, "e": 4600, "s": 4583, "text": "= 15 V / 0.003 A" }, { "code": null, "e": 4609, "s": 4600, "text": "= 5000 Ω" }, { "code": null, "e": 4616, "s": 4609, "text": "= 5 kΩ" }, { "code": null, "e": 4672, "s": 4616, "text": "Hence, the resistance of an electrical circuit is 5 kΩ." }, { "code": null, "e": 4817, "s": 4672, "text": "Problem 2: If the resistance of an electric iron is 10 Ω and a current of 6 A flows through the resistance. Find the voltage between two points." }, { "code": null, "e": 4827, "s": 4817, "text": "Solution:" }, { "code": null, "e": 4834, "s": 4827, "text": "Given:" }, { "code": null, "e": 4842, "s": 4834, "text": "I = 6 A" }, { "code": null, "e": 4851, "s": 4842, "text": "R = 10 Ω" }, { "code": null, "e": 4901, "s": 4851, "text": "The formula to calculate the voltage is given as:" }, { "code": null, "e": 4911, "s": 4901, "text": "V = I × R" }, { "code": null, "e": 4926, "s": 4911, "text": "V = 6 A × 10 Ω" }, { "code": null, "e": 4933, "s": 4926, "text": "= 60 V" }, { "code": null, "e": 4980, "s": 4933, "text": "Hence, the voltage between two points is 60 V." }, { "code": null, "e": 5017, "s": 4980, "text": "Problem 3: When does Ohm’s law fail?" }, { "code": null, "e": 5027, "s": 5017, "text": "Solution:" }, { "code": null, "e": 5237, "s": 5027, "text": "The behaviour of semiconductors and unilateral devices like diodes defines Ohm’s law. If physical factors such as temperature and pressure are not kept constant, Ohm’s law may not provide the intended effects." }, { "code": null, "e": 5295, "s": 5237, "text": "Problem 4: Why doesn’t Ohm’s law apply to semiconductors?" }, { "code": null, "e": 5305, "s": 5295, "text": "Solution:" }, { "code": null, "e": 5494, "s": 5305, "text": "Semiconducting devices are nonlinear in nature due to which Ohm’s law does not apply to them. This indicates that the voltage-to-current ratio does not remain constant when voltage varies." }, { "code": null, "e": 5543, "s": 5494, "text": "Problem 5: What is the application of Ohm’s Law?" }, { "code": null, "e": 5553, "s": 5543, "text": "Solution:" }, { "code": null, "e": 5684, "s": 5553, "text": "The static values of circuit components such as current levels, voltage supplies, and voltage drops are validated using Ohm’s law." }, { "code": null, "e": 5694, "s": 5684, "text": "kalrap615" }, { "code": null, "e": 5701, "s": 5694, "text": "Picked" }, { "code": null, "e": 5710, "s": 5701, "text": "Class 12" }, { "code": null, "e": 5726, "s": 5710, "text": "School Learning" }, { "code": null, "e": 5741, "s": 5726, "text": "School Physics" } ]
How to switch the language of the page using JavaScript ?
16 Nov, 2020 In this article, we will describe the method to switch between languages of a page depending upon the choice of the user. The method works by using the hash fragment of the URL as an identifier that can be used later detected by the script to change the language. The hash is accessed using window.location.hash property in JavaScript and can be later checked for the needed language identifier. The following steps have to be followed for this approach: Step 1: We define a function that accepts the language identifier as a string and sets it as the hash fragment of the URL. We will then reload the page using the location.reload() method. Step 2: We store all the contents of the page in an object so that it could be easily retrieved by the script depending on the language. Step 3: We will next check if the current hash value is equal to the language tag we want, and therefore set the relevant content of the language from the object we have defined above. HTML // Create a function to change the hash // value of the page and reload itfunction changeLanguage(lang) { location.hash = lang; location.reload();} // Define the language reload anchorsvar language = { eng: { welcome: "Welcome to the GeeksforGeeks " + "Portal! You can choose any " + "language using the buttons above!", }, es: { welcome: "¡Bienvenido al portal GeeksforGeeks! " + "¡Puedes elegir cualquier idioma usando " + "los botones de arriba!", }, hin: { welcome: "GeeksforGeeks पोर्टल पर आपका स्वागत है! " + "आप ऊपर दिए गए बटन का उपयोग करके किसी भी " + "भाषा को चुन सकते हैं!", },}; // Check if a hash value exists in the URLif (window.location.hash) { // Set the content of the webpage // depending on the hash value if (window.location.hash == "#es") { siteContent.textContent = language.es.welcome; } else if (window.location.hash == "#hin") { siteContent.textContent = language.hin.welcome; }} Example: This example demonstrates the above approach by displaying three buttons for the user to choose any language, and changing the language upon clicking the button. HTML <!DOCTYPE html><html> <body> <h1 style="color: green"> GeeksforGeeks </h1> <p> Click on the buttons below to change the language of the webpage. </p> <!-- Define the buttons that will change the language of the page and reload it --> <button onclick="changeLanguage('eng')"> Change to English< /button> <button onclick="changeLanguage('es')"> Change to Spanish </button> <button onclick="changeLanguage('hin')"> Change to Hindi </button> <!-- Define the content of the page that would be changed --> <p id="siteContent"> Welcome to the GeeksforGeeks Portal! You can choose any language using the buttons above! </p> <script> // Create a function to change // the hash value of the page function changeLanguage(lang) { location.hash = lang; location.reload(); } // Define the language reload anchors var language = { eng: { welcome: "Welcome to the GeeksforGeeks " + "Portal! You can choose any language " + "using the buttons above!" }, es: { welcome: "¡Bienvenido al portal GeeksforGeeks! " + "¡Puedes elegir cualquier idioma usando " + "los botones de arriba!" }, hin: { welcome: "GeeksforGeeks पोर्टल पर आपका स्वागत है! " + "आप ऊपर दिए गए बटन का उपयोग करके किसी भी " + "भाषा को चुन सकते हैं!" } }; // Check if a hash value exists in the URL if (window.location.hash) { // Set the content of the webpage // depending on the hash value if (window.location.hash == "#es") { siteContent.textContent = language.es.welcome; } else if (window.location.hash == "#hin") { siteContent.textContent = language.hin.welcome; } } </script></body> </html> Output: CSS-Misc HTML-Misc JavaScript-Misc Technical Scripter 2020 CSS HTML JavaScript Technical Scripter Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Nov, 2020" }, { "code": null, "e": 150, "s": 28, "text": "In this article, we will describe the method to switch between languages of a page depending upon the choice of the user." }, { "code": null, "e": 424, "s": 150, "text": "The method works by using the hash fragment of the URL as an identifier that can be used later detected by the script to change the language. The hash is accessed using window.location.hash property in JavaScript and can be later checked for the needed language identifier." }, { "code": null, "e": 483, "s": 424, "text": "The following steps have to be followed for this approach:" }, { "code": null, "e": 671, "s": 483, "text": "Step 1: We define a function that accepts the language identifier as a string and sets it as the hash fragment of the URL. We will then reload the page using the location.reload() method." }, { "code": null, "e": 808, "s": 671, "text": "Step 2: We store all the contents of the page in an object so that it could be easily retrieved by the script depending on the language." }, { "code": null, "e": 993, "s": 808, "text": "Step 3: We will next check if the current hash value is equal to the language tag we want, and therefore set the relevant content of the language from the object we have defined above." }, { "code": null, "e": 998, "s": 993, "text": "HTML" }, { "code": "// Create a function to change the hash // value of the page and reload itfunction changeLanguage(lang) { location.hash = lang; location.reload();} // Define the language reload anchorsvar language = { eng: { welcome: \"Welcome to the GeeksforGeeks \" + \"Portal! You can choose any \" + \"language using the buttons above!\", }, es: { welcome: \"¡Bienvenido al portal GeeksforGeeks! \" + \"¡Puedes elegir cualquier idioma usando \" + \"los botones de arriba!\", }, hin: { welcome: \"GeeksforGeeks पोर्टल पर आपका स्वागत है! \" + \"आप ऊपर दिए गए बटन का उपयोग करके किसी भी \" + \"भाषा को चुन सकते हैं!\", },}; // Check if a hash value exists in the URLif (window.location.hash) { // Set the content of the webpage // depending on the hash value if (window.location.hash == \"#es\") { siteContent.textContent = language.es.welcome; } else if (window.location.hash == \"#hin\") { siteContent.textContent = language.hin.welcome; }}", "e": 1980, "s": 998, "text": null }, { "code": null, "e": 2151, "s": 1980, "text": "Example: This example demonstrates the above approach by displaying three buttons for the user to choose any language, and changing the language upon clicking the button." }, { "code": null, "e": 2156, "s": 2151, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <p> Click on the buttons below to change the language of the webpage. </p> <!-- Define the buttons that will change the language of the page and reload it --> <button onclick=\"changeLanguage('eng')\"> Change to English< /button> <button onclick=\"changeLanguage('es')\"> Change to Spanish </button> <button onclick=\"changeLanguage('hin')\"> Change to Hindi </button> <!-- Define the content of the page that would be changed --> <p id=\"siteContent\"> Welcome to the GeeksforGeeks Portal! You can choose any language using the buttons above! </p> <script> // Create a function to change // the hash value of the page function changeLanguage(lang) { location.hash = lang; location.reload(); } // Define the language reload anchors var language = { eng: { welcome: \"Welcome to the GeeksforGeeks \" + \"Portal! You can choose any language \" + \"using the buttons above!\" }, es: { welcome: \"¡Bienvenido al portal GeeksforGeeks! \" + \"¡Puedes elegir cualquier idioma usando \" + \"los botones de arriba!\" }, hin: { welcome: \"GeeksforGeeks पोर्टल पर आपका स्वागत है! \" + \"आप ऊपर दिए गए बटन का उपयोग करके किसी भी \" + \"भाषा को चुन सकते हैं!\" } }; // Check if a hash value exists in the URL if (window.location.hash) { // Set the content of the webpage // depending on the hash value if (window.location.hash == \"#es\") { siteContent.textContent = language.es.welcome; } else if (window.location.hash == \"#hin\") { siteContent.textContent = language.hin.welcome; } } </script></body> </html>", "e": 3968, "s": 2156, "text": null }, { "code": null, "e": 3976, "s": 3968, "text": "Output:" }, { "code": null, "e": 3985, "s": 3976, "text": "CSS-Misc" }, { "code": null, "e": 3995, "s": 3985, "text": "HTML-Misc" }, { "code": null, "e": 4011, "s": 3995, "text": "JavaScript-Misc" }, { "code": null, "e": 4035, "s": 4011, "text": "Technical Scripter 2020" }, { "code": null, "e": 4039, "s": 4035, "text": "CSS" }, { "code": null, "e": 4044, "s": 4039, "text": "HTML" }, { "code": null, "e": 4055, "s": 4044, "text": "JavaScript" }, { "code": null, "e": 4074, "s": 4055, "text": "Technical Scripter" }, { "code": null, "e": 4091, "s": 4074, "text": "Web Technologies" }, { "code": null, "e": 4118, "s": 4091, "text": "Web technologies Questions" }, { "code": null, "e": 4123, "s": 4118, "text": "HTML" } ]
Gun Detection using Python-OpenCV
10 May, 2020 Prerequisites: Python OpenCV Gun Detection using Object Detection is a helpful tool to have in your repository. It forms the backbone of many fantastic industrial applications. OpenCV(Open Source Computer Vision Library) is a highly optimized library with focus on Real-Time Applications. Approach: 1) Creation of Haarcascade file of Guns: Refer to Creation of own haarcascade From here, you will learn about how to create your own Haarcascade file. With your single positive image, you can use the opencv_createsamples command to actually create a bunch of positive examples, using your negative images. Your positive image will be superimposed on these negatives, and it will be angled and all sorts of things. It actually can work pretty well, especially if you are really just looking for one specific object. If you are looking to identify all guns, however, you will want to have thousands of unique images of guns, rather than using the opencv_createsamples to generate samples for you. We’ll keep it simple and just use one positive image, and then create a bunch of samples with our negatives. Note: For The Gun haar cascade created – click here. 2) Detection of Guns using OpenCV import numpy as npimport cv2import imutilsimport datetime gun_cascade = cv2.CascadeClassifier('cascade.xml')camera = cv2.VideoCapture(0) firstFrame = Nonegun_exist = False while True: ret, frame = camera.read() frame = imutils.resize(frame, width = 500) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gun = gun_cascade.detectMultiScale(gray, 1.3, 5, minSize = (100, 100)) if len(gun) > 0: gun_exist = True for (x, y, w, h) in gun: frame = cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2) roi_gray = gray[y:y + h, x:x + w] roi_color = frame[y:y + h, x:x + w] if firstFrame is None: firstFrame = gray continue # print(datetime.date(2019)) # draw the text and timestamp on the frame cv2.putText(frame, datetime.datetime.now().strftime("% A % d % B % Y % I:% M:% S % p"), (10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1) cv2.imshow("Security Feed", frame) key = cv2.waitKey(1) & 0xFF if key == ord('q'): break if gun_exist: print("guns detected")else: print("guns NOT detected") camera.release()cv2.destroyAllWindows() Output: OpenCV comes with a trainer as well as a detector. If you want to train your own classifier for any object like car, planes, etc. you can use OpenCV to create one. Here we deal with the detection of Gun. First we need to load the required XML classifiers. Then load our input image (or video) in grayscale mode. Now we find the guns in the image. If guns are found, it returns the positions of detected guns as Rect(x, y, w, h). Once we get these locations, we can create a ROI(Region of Interest) for the gun. Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n10 May, 2020" }, { "code": null, "e": 82, "s": 53, "text": "Prerequisites: Python OpenCV" }, { "code": null, "e": 342, "s": 82, "text": "Gun Detection using Object Detection is a helpful tool to have in your repository. It forms the backbone of many fantastic industrial applications. OpenCV(Open Source Computer Vision Library) is a highly optimized library with focus on Real-Time Applications." }, { "code": null, "e": 430, "s": 342, "text": "Approach: 1) Creation of Haarcascade file of Guns: Refer to Creation of own haarcascade" }, { "code": null, "e": 1156, "s": 430, "text": "From here, you will learn about how to create your own Haarcascade file. With your single positive image, you can use the opencv_createsamples command to actually create a bunch of positive examples, using your negative images. Your positive image will be superimposed on these negatives, and it will be angled and all sorts of things. It actually can work pretty well, especially if you are really just looking for one specific object. If you are looking to identify all guns, however, you will want to have thousands of unique images of guns, rather than using the opencv_createsamples to generate samples for you. We’ll keep it simple and just use one positive image, and then create a bunch of samples with our negatives." }, { "code": null, "e": 1209, "s": 1156, "text": "Note: For The Gun haar cascade created – click here." }, { "code": null, "e": 1243, "s": 1209, "text": "2) Detection of Guns using OpenCV" }, { "code": "import numpy as npimport cv2import imutilsimport datetime gun_cascade = cv2.CascadeClassifier('cascade.xml')camera = cv2.VideoCapture(0) firstFrame = Nonegun_exist = False while True: ret, frame = camera.read() frame = imutils.resize(frame, width = 500) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gun = gun_cascade.detectMultiScale(gray, 1.3, 5, minSize = (100, 100)) if len(gun) > 0: gun_exist = True for (x, y, w, h) in gun: frame = cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2) roi_gray = gray[y:y + h, x:x + w] roi_color = frame[y:y + h, x:x + w] if firstFrame is None: firstFrame = gray continue # print(datetime.date(2019)) # draw the text and timestamp on the frame cv2.putText(frame, datetime.datetime.now().strftime(\"% A % d % B % Y % I:% M:% S % p\"), (10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1) cv2.imshow(\"Security Feed\", frame) key = cv2.waitKey(1) & 0xFF if key == ord('q'): break if gun_exist: print(\"guns detected\")else: print(\"guns NOT detected\") camera.release()cv2.destroyAllWindows()", "e": 2679, "s": 1243, "text": null }, { "code": null, "e": 2687, "s": 2679, "text": "Output:" }, { "code": null, "e": 2851, "s": 2687, "text": "OpenCV comes with a trainer as well as a detector. If you want to train your own classifier for any object like car, planes, etc. you can use OpenCV to create one." }, { "code": null, "e": 3198, "s": 2851, "text": "Here we deal with the detection of Gun. First we need to load the required XML classifiers. Then load our input image (or video) in grayscale mode. Now we find the guns in the image. If guns are found, it returns the positions of detected guns as Rect(x, y, w, h). Once we get these locations, we can create a ROI(Region of Interest) for the gun." }, { "code": null, "e": 3212, "s": 3198, "text": "Python-OpenCV" }, { "code": null, "e": 3219, "s": 3212, "text": "Python" } ]
Input in C++
01 Feb, 2021 The cin object in C++ is used to accept the input from the standard input device i.e., keyboard. it is the instance of the class istream. It is associated with the standard C input stream stdin. The extraction operator(>>) is used along with the object cin for reading inputs. The extraction operator extracts the data from the object cin which is entered using the keyboard. Program 1: Below is the C++ program to implement cin object to take input from the user: C++ // C++ program to demonstrate the// cin object#include <iostream>using namespace std; // Driver Codeint main(){ int i; // Take input using cin cin >> i; // Print output cout << i; return 0;} Input: Output: Note: Multiple inputs can also be taken using the extraction operators(>>) with cin. Program 2: Below is the C++ program to implement multiple inputs from the user: C++ // C++ program to demonstrate the taking// multiple inputs from the user#include <iostream>using namespace std; // Driver Codeint main(){ string name; int age; // Take multiple input using cin cin >> name >> age; // Print output cout << "Name : " << name << endl; cout << "Age : " << age << endl; return 0;} Input: Output: cpp-input-output Input and Output Input Output Systems Picked C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n01 Feb, 2021" }, { "code": null, "e": 429, "s": 53, "text": "The cin object in C++ is used to accept the input from the standard input device i.e., keyboard. it is the instance of the class istream. It is associated with the standard C input stream stdin. The extraction operator(>>) is used along with the object cin for reading inputs. The extraction operator extracts the data from the object cin which is entered using the keyboard." }, { "code": null, "e": 440, "s": 429, "text": "Program 1:" }, { "code": null, "e": 518, "s": 440, "text": "Below is the C++ program to implement cin object to take input from the user:" }, { "code": null, "e": 522, "s": 518, "text": "C++" }, { "code": "// C++ program to demonstrate the// cin object#include <iostream>using namespace std; // Driver Codeint main(){ int i; // Take input using cin cin >> i; // Print output cout << i; return 0;}", "e": 738, "s": 522, "text": null }, { "code": null, "e": 745, "s": 738, "text": "Input:" }, { "code": null, "e": 753, "s": 745, "text": "Output:" }, { "code": null, "e": 838, "s": 753, "text": "Note: Multiple inputs can also be taken using the extraction operators(>>) with cin." }, { "code": null, "e": 849, "s": 838, "text": "Program 2:" }, { "code": null, "e": 918, "s": 849, "text": "Below is the C++ program to implement multiple inputs from the user:" }, { "code": null, "e": 922, "s": 918, "text": "C++" }, { "code": "// C++ program to demonstrate the taking// multiple inputs from the user#include <iostream>using namespace std; // Driver Codeint main(){ string name; int age; // Take multiple input using cin cin >> name >> age; // Print output cout << \"Name : \" << name << endl; cout << \"Age : \" << age << endl; return 0;}", "e": 1261, "s": 922, "text": null }, { "code": null, "e": 1268, "s": 1261, "text": "Input:" }, { "code": null, "e": 1276, "s": 1268, "text": "Output:" }, { "code": null, "e": 1293, "s": 1276, "text": "cpp-input-output" }, { "code": null, "e": 1310, "s": 1293, "text": "Input and Output" }, { "code": null, "e": 1331, "s": 1310, "text": "Input Output Systems" }, { "code": null, "e": 1338, "s": 1331, "text": "Picked" }, { "code": null, "e": 1342, "s": 1338, "text": "C++" }, { "code": null, "e": 1355, "s": 1342, "text": "C++ Programs" }, { "code": null, "e": 1359, "s": 1355, "text": "CPP" } ]
How to Enable Full-Screen Mode in Android?
16 Sep, 2021 In this article, we are going to learn how to enable full screen in Android Studio. Like if we are especially viewing an image then we want to view that on full screen. Here what we are going to implement is that we are basically hiding the navigation, status bar, and enabling the full-screen mode. We are going to discuss 4 different methods for doing this task. Following is the code to hide the navigation and enabling full-screen mode. // This is the code to hide the navigation and enabling full screen mode View.SYSTEM_UI_FLAG_IMMERSIVE // Set the content to appear under the system bars so that the // content doesn't resize when the system bars hide and show. | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // Hide the nav bar and status bar | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN); Made these changes in your manifest.xml file android:theme="@style/Theme.AppCompat.Light.NoActionBar" Made these changes in your styles.xml file <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="android:windowFullscreen">true</item> </style> Made these changes in your styles.xml file <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> nnr223442 Android-Misc Android-Studio 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": "\n16 Sep, 2021" }, { "code": null, "e": 393, "s": 28, "text": "In this article, we are going to learn how to enable full screen in Android Studio. Like if we are especially viewing an image then we want to view that on full screen. Here what we are going to implement is that we are basically hiding the navigation, status bar, and enabling the full-screen mode. We are going to discuss 4 different methods for doing this task." }, { "code": null, "e": 469, "s": 393, "text": "Following is the code to hide the navigation and enabling full-screen mode." }, { "code": null, "e": 1150, "s": 469, "text": "// This is the code to hide the navigation and enabling full screen mode\nView.SYSTEM_UI_FLAG_IMMERSIVE\n // Set the content to appear under the system bars so that the\n // content doesn't resize when the system bars hide and show.\n | View.SYSTEM_UI_FLAG_LAYOUT_STABLE\n | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION\n | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN\n // Hide the nav bar and status bar\n | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION\n | View.SYSTEM_UI_FLAG_FULLSCREEN);" }, { "code": null, "e": 1195, "s": 1150, "text": "Made these changes in your manifest.xml file" }, { "code": null, "e": 1252, "s": 1195, "text": "android:theme=\"@style/Theme.AppCompat.Light.NoActionBar\"" }, { "code": null, "e": 1295, "s": 1252, "text": "Made these changes in your styles.xml file" }, { "code": null, "e": 1466, "s": 1295, "text": "<style name=\"AppTheme\" parent=\"Theme.AppCompat.Light.NoActionBar\">\n <!-- Customize your theme here. -->\n\n <item name=\"android:windowFullscreen\">true</item>\n</style>" }, { "code": null, "e": 1509, "s": 1466, "text": "Made these changes in your styles.xml file" }, { "code": null, "e": 1590, "s": 1509, "text": "<item name=\"windowActionBar\">false</item>\n<item name=\"windowNoTitle\">true</item>" }, { "code": null, "e": 1600, "s": 1590, "text": "nnr223442" }, { "code": null, "e": 1613, "s": 1600, "text": "Android-Misc" }, { "code": null, "e": 1628, "s": 1613, "text": "Android-Studio" }, { "code": null, "e": 1636, "s": 1628, "text": "Android" }, { "code": null, "e": 1644, "s": 1636, "text": "Android" } ]
C program to find the areas of geometrical figures using switch case
Find the areas of rectangle, square, triangle, circle by using the switch case statement, User need to enter base, height, side, radius, breadth and length at runtime to calculate the areas of all geometrical figures. The solution to find the areas of rectangle, square, triangle, circle by using the switch case statement is explained below − Formulae The formulae for finding the areas of the respective geometrical figures are as follows − Area of rectangle = breadth *length; Area of square = side * side; Area of circle = 3.142*radius*radius; Area of triangle = 0.5 *base*height; Following is the C program to find the areas of rectangle, square, triangle, circle by using the switch case statement − Live Demo #include <stdio.h> void main(){ int fig_code; float side, base, length, breadth, height, area, radius; printf("-------------------------\n"); printf(" 1 --> Circle\n"); printf(" 2 --> Rectangle\n"); printf(" 3 --> Triangle\n"); printf(" 4 --> Square\n"); printf("-------------------------\n"); printf("Enter the Figure code\n"); scanf("%d", &fig_code); switch(fig_code){ case 1: printf(" Enter the radius\n"); scanf("%f",&radius); area=3.142*radius*radius; printf("Area of a circle=%f\n", area); break; case 2: printf(" Enter the breadth and length\n"); scanf("%f %f",&breadth, &length); area=breadth *length; printf("Area of a Rectangle=%f\n", area); break; case 3: printf(" Enter the base and height\n"); scanf("%f %f", &base, &height); area=0.5 *base*height; printf("Area of a Triangle=%f\n", area); break; case 4: printf(" Enter the side\n"); scanf("%f", &side); area=side * side; printf("Area of a Square=%f\n", area); break; default: printf(" Error in figure code\n"); break; } } When the above program is executed, it produces the following result − Run 1: ------------------------- 1 --> Circle 2 --> Rectangle 3 --> Triangle 4 --> Square ------------------------- Enter the Figure code 3 Enter the base and height 4 7 Area of a Triangle=14.000000 Run 2: ------------------------- 1 --> Circle 2 --> Rectangle 3 --> Triangle 4 --> Square ------------------------- Enter the Figure code 1 Enter the radius 8 Area of a circle=201.087997
[ { "code": null, "e": 1280, "s": 1062, "text": "Find the areas of rectangle, square, triangle, circle by using the switch case statement,\nUser need to enter base, height, side, radius, breadth and length at runtime to calculate the areas of all geometrical figures." }, { "code": null, "e": 1406, "s": 1280, "text": "The solution to find the areas of rectangle, square, triangle, circle by using the switch case statement is explained below −" }, { "code": null, "e": 1415, "s": 1406, "text": "Formulae" }, { "code": null, "e": 1505, "s": 1415, "text": "The formulae for finding the areas of the respective geometrical figures are as follows −" }, { "code": null, "e": 1542, "s": 1505, "text": "Area of rectangle = breadth *length;" }, { "code": null, "e": 1572, "s": 1542, "text": "Area of square = side * side;" }, { "code": null, "e": 1610, "s": 1572, "text": "Area of circle = 3.142*radius*radius;" }, { "code": null, "e": 1647, "s": 1610, "text": "Area of triangle = 0.5 *base*height;" }, { "code": null, "e": 1768, "s": 1647, "text": "Following is the C program to find the areas of rectangle, square, triangle, circle by using the switch case statement −" }, { "code": null, "e": 1779, "s": 1768, "text": " Live Demo" }, { "code": null, "e": 3023, "s": 1779, "text": "#include <stdio.h>\nvoid main(){\n int fig_code;\n float side, base, length, breadth, height, area, radius;\n printf(\"-------------------------\\n\");\n printf(\" 1 --> Circle\\n\");\n printf(\" 2 --> Rectangle\\n\");\n printf(\" 3 --> Triangle\\n\");\n printf(\" 4 --> Square\\n\");\n printf(\"-------------------------\\n\");\n printf(\"Enter the Figure code\\n\");\n scanf(\"%d\", &fig_code);\n switch(fig_code){\n case 1:\n printf(\" Enter the radius\\n\");\n scanf(\"%f\",&radius);\n area=3.142*radius*radius;\n printf(\"Area of a circle=%f\\n\", area);\n break;\n case 2:\n printf(\" Enter the breadth and length\\n\");\n scanf(\"%f %f\",&breadth, &length);\n area=breadth *length;\n printf(\"Area of a Rectangle=%f\\n\", area);\n break;\n case 3:\n printf(\" Enter the base and height\\n\");\n scanf(\"%f %f\", &base, &height);\n area=0.5 *base*height;\n printf(\"Area of a Triangle=%f\\n\", area);\n break;\n case 4:\n printf(\" Enter the side\\n\");\n scanf(\"%f\", &side);\n area=side * side;\n printf(\"Area of a Square=%f\\n\", area);\n break;\n default:\n printf(\" Error in figure code\\n\");\n break;\n }\n}" }, { "code": null, "e": 3094, "s": 3023, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 3482, "s": 3094, "text": "Run 1:\n-------------------------\n1 --> Circle\n2 --> Rectangle\n3 --> Triangle\n4 --> Square\n-------------------------\nEnter the Figure code\n3\nEnter the base and height\n4\n7\n\nArea of a Triangle=14.000000\n\nRun 2:\n-------------------------\n1 --> Circle\n2 --> Rectangle\n3 --> Triangle\n4 --> Square\n-------------------------\nEnter the Figure code\n1\nEnter the radius\n8\nArea of a circle=201.087997" } ]
Apache POI PPT - Installation
This chapter takes you through the process of setting up Apache POI on Windows and Linux based systems. Apache POI can be easily installed and integrated with your current Java environment following a few simple steps without any complex setup procedures. User administration is required while installation. Let us now proceed with the steps to install Apache POI. First of all, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute any of the two commands depending on the platform you are working on. If the Java installation has been done properly, then it will display the current version and specification of your Java installation. A sample output is given in the following table. java version "11.0.11" 2021-04-20 LTS Java(TM) SE Runtime Environment 18.9 (build 11.0.11+9-LTS-194) Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.11+9-LTS-194, mixed mode) Open command console and type − \>java –version java version "11.0.11" 2021-04-20 LTS Open JDK Runtime Environment 18.9 (build 11.0.11+9-LTS-194) Open JDK 64-Bit Server VM (build 11.0.11+9-LTS-194, mixed mode) Open command terminal and type − $java –version java version "11.0.11" 2021-04-20 LTS Open JDK Runtime Environment 18.9 (build 11.0.11+9-LTS-194) Open JDK 64-Bit Server VM (build 11.0.11+9-LTS-194, mixed mode) We assume the readers of this tutorial have Java SDK version 11.0.11 installed on their system. We assume the readers of this tutorial have Java SDK version 11.0.11 installed on their system. In case you do not have Java SDK, download its current version from www.oracle.com/technetwork/java/javase/downloads/index.html and have it installed. In case you do not have Java SDK, download its current version from www.oracle.com/technetwork/java/javase/downloads/index.html and have it installed. Set the environment variable JAVA_HOME to point to the base directory location where Java is installed on your machine. For example, Windows Set JAVA_HOME to C:\ProgramFiles\java\jdk11.0.11 Linux Export JAVA_HOME = /usr/local/java-current Append the full path of Java compiler location to the System Path. Windows Append the String "C:\Program Files\Java\jdk11.0.11\bin" to the end of the system variable PATH. Linux Export PATH = $PATH:$JAVA_HOME/bin/ Execute the command java -version from the command prompt as explained above. Download the latest version of Apache POI from https://poi.apache.org/download.html and unzip its contents to a folder from where the required libraries can be linked to your Java program. Let us assume the files are collected in a folder on C drive. Add the complete path of the required jars as shown below to the CLASSPATH. Windows Append the following strings to the end of the user variable CLASSPATH − C:\poi-bin-5.1.0\poi-5.1.0.jar; C:\poi-bin-5.1.0\poi-ooxml-5.1.0.jar; C:\poi-bin-5.1.0\poi-ooxml-full-5.1.0.jar; C:\poi-bin-5.1.0\lib\commons-codec-1.15.jar; C:\poi-bin-5.1.0\lib\commons-collections4-4.4.jar; C:\poi-bin-5.1.0\lib\commons-io-2.11.0.jar; C:\poi-bin-5.1.0\lib\commons-math3-3.6.1.jar; C:\poi-bin-5.1.0\lib\log4j-api-2.14.1.jar; C:\poi-bin-5.1.0\lib\SparseBitSet-1.2.jar; C\poi-bin-5.1.0\ooxml-lib\commons-compress-1.21.jar C\poi-bin-5.1.0\ooxml-lib\commons-logging-1.2.jar C\poi-bin-5.1.0\ooxml-lib\curvesapi-1.06.jar C\poi-bin-5.1.0\ooxml-lib\slf4j-api-1.7.32.jar C\poi-bin-5.1.0\ooxml-lib\xmlbeans-5.0.2.jar Linux Export CLASSPATH = $CLASSPATH: /usr/share/poi-bin-5.1.0/poi-5.1.0.jar.tar: /usr/share/poi-bin-5.1.0/poi-ooxml-5.1.0.tar: /usr/share/poi-bin-5.1.0/poi-ooxml-full-5.1.0.tar: /usr/share/poi-bin-5.1.0/lib/commons-codec-1.15.jar.tar: /usr/share/poi-bin-5.1.0/lib/commons-collections4-4.4.tar: /usr/share/poi-bin-5.1.0/lib/commons-io-2.11.0.tar: /usr/share/poi-bin-5.1.0/lib/commons-math3-3.6.1.tar: /usr/share/poi-bin-5.1.0/lib/log4j-api-2.14.1.tar: /usr/share/poi-bin-5.1.0/lib/SparseBitSet-1.2.tar: /usr/share/poi-bin-5.1.0/ooxml-lib/commons-compress-1.21.tar: /usr/share/poi-bin-5.1.0/ooxml-lib/commons-logging-1.2.tar: /usr/share/poi-bin-5.1.0/ooxml-lib/curvesapi-1.06.tar: /usr/share/poi-bin-5.1.0/ooxml-lib/slf4j-api-1.7.32.tar: /usr/share/poi-bin-5.1.0/ooxml-lib/xmlbeans-5.0.2.tar: Following is the pom.xml file to run the programs in this tutorial. <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>ApachePoiPPT</groupId> <artifactId>ApachePoiPPT</artifactId> <version>0.0.1-SNAPSHOT</version> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>11</source> <target>11</target> <compilerArgs> <arg>--add-modules</arg> <arg>java.se,java.desktop</arg> </compilerArgs> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>5.1.0</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>5.1.0</version> </dependency> </dependencies> </project> 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2325, "s": 2017, "text": "This chapter takes you through the process of setting up Apache POI on Windows and Linux based systems. Apache POI can be easily installed and integrated with your current Java environment following a few simple steps without any complex setup procedures. User administration is required while installation." }, { "code": null, "e": 2382, "s": 2325, "text": "Let us now proceed with the steps to install Apache POI." }, { "code": null, "e": 2569, "s": 2382, "text": "First of all, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute any of the two commands depending on the platform you are working on." }, { "code": null, "e": 2753, "s": 2569, "text": "If the Java installation has been done properly, then it will display the current version and specification of your Java installation. A sample output is given in the following table." }, { "code": null, "e": 2791, "s": 2753, "text": "java version \"11.0.11\" 2021-04-20 LTS" }, { "code": null, "e": 2854, "s": 2791, "text": "Java(TM) SE Runtime Environment 18.9 (build 11.0.11+9-LTS-194)" }, { "code": null, "e": 2931, "s": 2854, "text": "Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.11+9-LTS-194, mixed mode)" }, { "code": null, "e": 2963, "s": 2931, "text": "Open command console and type −" }, { "code": null, "e": 2979, "s": 2963, "text": "\\>java –version" }, { "code": null, "e": 3017, "s": 2979, "text": "java version \"11.0.11\" 2021-04-20 LTS" }, { "code": null, "e": 3077, "s": 3017, "text": "Open JDK Runtime Environment 18.9 (build 11.0.11+9-LTS-194)" }, { "code": null, "e": 3141, "s": 3077, "text": "Open JDK 64-Bit Server VM (build 11.0.11+9-LTS-194, mixed mode)" }, { "code": null, "e": 3174, "s": 3141, "text": "Open command terminal and type −" }, { "code": null, "e": 3189, "s": 3174, "text": "$java –version" }, { "code": null, "e": 3227, "s": 3189, "text": "java version \"11.0.11\" 2021-04-20 LTS" }, { "code": null, "e": 3287, "s": 3227, "text": "Open JDK Runtime Environment 18.9 (build 11.0.11+9-LTS-194)" }, { "code": null, "e": 3351, "s": 3287, "text": "Open JDK 64-Bit Server VM (build 11.0.11+9-LTS-194, mixed mode)" }, { "code": null, "e": 3447, "s": 3351, "text": "We assume the readers of this tutorial have Java SDK version 11.0.11 installed on their system." }, { "code": null, "e": 3543, "s": 3447, "text": "We assume the readers of this tutorial have Java SDK version 11.0.11 installed on their system." }, { "code": null, "e": 3695, "s": 3543, "text": "In case you do not have Java SDK, download its current version from www.oracle.com/technetwork/java/javase/downloads/index.html and have it installed.\n" }, { "code": null, "e": 3846, "s": 3695, "text": "In case you do not have Java SDK, download its current version from www.oracle.com/technetwork/java/javase/downloads/index.html and have it installed." }, { "code": null, "e": 3979, "s": 3846, "text": "Set the environment variable JAVA_HOME to point to the base directory location where Java is installed on your machine. For example," }, { "code": null, "e": 3987, "s": 3979, "text": "Windows" }, { "code": null, "e": 4036, "s": 3987, "text": "Set JAVA_HOME to C:\\ProgramFiles\\java\\jdk11.0.11" }, { "code": null, "e": 4042, "s": 4036, "text": "Linux" }, { "code": null, "e": 4085, "s": 4042, "text": "Export JAVA_HOME = /usr/local/java-current" }, { "code": null, "e": 4152, "s": 4085, "text": "Append the full path of Java compiler location to the System Path." }, { "code": null, "e": 4160, "s": 4152, "text": "Windows" }, { "code": null, "e": 4257, "s": 4160, "text": "Append the String \"C:\\Program Files\\Java\\jdk11.0.11\\bin\" to the end of the system variable PATH." }, { "code": null, "e": 4263, "s": 4257, "text": "Linux" }, { "code": null, "e": 4299, "s": 4263, "text": "Export PATH = $PATH:$JAVA_HOME/bin/" }, { "code": null, "e": 4377, "s": 4299, "text": "Execute the command java -version from the command prompt as explained above." }, { "code": null, "e": 4628, "s": 4377, "text": "Download the latest version of Apache POI from https://poi.apache.org/download.html and unzip its contents to a folder from where the required libraries can be linked to your Java program. Let us assume the files are collected in a folder on C drive." }, { "code": null, "e": 4704, "s": 4628, "text": "Add the complete path of the required jars as shown below to the CLASSPATH." }, { "code": null, "e": 4712, "s": 4704, "text": "Windows" }, { "code": null, "e": 4773, "s": 4712, "text": "Append the following strings to the end of the user variable" }, { "code": null, "e": 4785, "s": 4773, "text": "CLASSPATH −" }, { "code": null, "e": 4817, "s": 4785, "text": "C:\\poi-bin-5.1.0\\poi-5.1.0.jar;" }, { "code": null, "e": 4855, "s": 4817, "text": "C:\\poi-bin-5.1.0\\poi-ooxml-5.1.0.jar;" }, { "code": null, "e": 4898, "s": 4855, "text": "C:\\poi-bin-5.1.0\\poi-ooxml-full-5.1.0.jar;" }, { "code": null, "e": 4943, "s": 4898, "text": "C:\\poi-bin-5.1.0\\lib\\commons-codec-1.15.jar;" }, { "code": null, "e": 4994, "s": 4943, "text": "C:\\poi-bin-5.1.0\\lib\\commons-collections4-4.4.jar;" }, { "code": null, "e": 5038, "s": 4994, "text": "C:\\poi-bin-5.1.0\\lib\\commons-io-2.11.0.jar;" }, { "code": null, "e": 5084, "s": 5038, "text": "C:\\poi-bin-5.1.0\\lib\\commons-math3-3.6.1.jar;" }, { "code": null, "e": 5127, "s": 5084, "text": "C:\\poi-bin-5.1.0\\lib\\log4j-api-2.14.1.jar;" }, { "code": null, "e": 5170, "s": 5127, "text": "C:\\poi-bin-5.1.0\\lib\\SparseBitSet-1.2.jar;" }, { "code": null, "e": 5222, "s": 5170, "text": "C\\poi-bin-5.1.0\\ooxml-lib\\commons-compress-1.21.jar" }, { "code": null, "e": 5272, "s": 5222, "text": "C\\poi-bin-5.1.0\\ooxml-lib\\commons-logging-1.2.jar" }, { "code": null, "e": 5317, "s": 5272, "text": "C\\poi-bin-5.1.0\\ooxml-lib\\curvesapi-1.06.jar" }, { "code": null, "e": 5364, "s": 5317, "text": "C\\poi-bin-5.1.0\\ooxml-lib\\slf4j-api-1.7.32.jar" }, { "code": null, "e": 5409, "s": 5364, "text": "C\\poi-bin-5.1.0\\ooxml-lib\\xmlbeans-5.0.2.jar" }, { "code": null, "e": 5415, "s": 5409, "text": "Linux" }, { "code": null, "e": 5446, "s": 5415, "text": "Export CLASSPATH = $CLASSPATH:" }, { "code": null, "e": 5490, "s": 5446, "text": "/usr/share/poi-bin-5.1.0/poi-5.1.0.jar.tar:" }, { "code": null, "e": 5536, "s": 5490, "text": "/usr/share/poi-bin-5.1.0/poi-ooxml-5.1.0.tar:" }, { "code": null, "e": 5587, "s": 5536, "text": "/usr/share/poi-bin-5.1.0/poi-ooxml-full-5.1.0.tar:" }, { "code": null, "e": 5644, "s": 5587, "text": "/usr/share/poi-bin-5.1.0/lib/commons-codec-1.15.jar.tar:" }, { "code": null, "e": 5703, "s": 5644, "text": "/usr/share/poi-bin-5.1.0/lib/commons-collections4-4.4.tar:" }, { "code": null, "e": 5755, "s": 5703, "text": "/usr/share/poi-bin-5.1.0/lib/commons-io-2.11.0.tar:" }, { "code": null, "e": 5809, "s": 5755, "text": "/usr/share/poi-bin-5.1.0/lib/commons-math3-3.6.1.tar:" }, { "code": null, "e": 5860, "s": 5809, "text": "/usr/share/poi-bin-5.1.0/lib/log4j-api-2.14.1.tar:" }, { "code": null, "e": 5911, "s": 5860, "text": "/usr/share/poi-bin-5.1.0/lib/SparseBitSet-1.2.tar:" }, { "code": null, "e": 5973, "s": 5911, "text": "/usr/share/poi-bin-5.1.0/ooxml-lib/commons-compress-1.21.tar:" }, { "code": null, "e": 6033, "s": 5973, "text": "/usr/share/poi-bin-5.1.0/ooxml-lib/commons-logging-1.2.tar:" }, { "code": null, "e": 6088, "s": 6033, "text": "/usr/share/poi-bin-5.1.0/ooxml-lib/curvesapi-1.06.tar:" }, { "code": null, "e": 6145, "s": 6088, "text": "/usr/share/poi-bin-5.1.0/ooxml-lib/slf4j-api-1.7.32.tar:" }, { "code": null, "e": 6200, "s": 6145, "text": "/usr/share/poi-bin-5.1.0/ooxml-lib/xmlbeans-5.0.2.tar:" }, { "code": null, "e": 6268, "s": 6200, "text": "Following is the pom.xml file to run the programs in this tutorial." }, { "code": null, "e": 7508, "s": 6268, "text": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \nxsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>ApachePoiPPT</groupId>\n <artifactId>ApachePoiPPT</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <build>\n <sourceDirectory>src</sourceDirectory>\n <plugins>\n <plugin>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>3.8.1</version>\n <configuration>\n <source>11</source>\n <target>11</target>\n <compilerArgs>\n <arg>--add-modules</arg>\n <arg>java.se,java.desktop</arg>\n </compilerArgs>\n </configuration>\n </plugin>\n </plugins>\n </build>\n <dependencies> \n <dependency>\n <groupId>org.apache.poi</groupId>\n <artifactId>poi</artifactId>\n <version>5.1.0</version>\n </dependency>\n <dependency>\n <groupId>org.apache.poi</groupId>\n <artifactId>poi-ooxml</artifactId>\n <version>5.1.0</version>\n </dependency> \n </dependencies>\n</project>" }, { "code": null, "e": 7543, "s": 7508, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7562, "s": 7543, "text": " Arnab Chakraborty" }, { "code": null, "e": 7597, "s": 7562, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7618, "s": 7597, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 7651, "s": 7618, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 7664, "s": 7651, "text": " Nilay Mehta" }, { "code": null, "e": 7699, "s": 7664, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7717, "s": 7699, "text": " Bigdata Engineer" }, { "code": null, "e": 7750, "s": 7717, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 7768, "s": 7750, "text": " Bigdata Engineer" }, { "code": null, "e": 7801, "s": 7768, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 7819, "s": 7801, "text": " Bigdata Engineer" }, { "code": null, "e": 7826, "s": 7819, "text": " Print" }, { "code": null, "e": 7837, "s": 7826, "text": " Add Notes" } ]
The Math Behind A/B Testing with Example Python Code | by Nguyen Ngo | Towards Data Science
While taking the A/B testing course by Google on Udacity, I had some questions about some of the mathematical steps that were not clearly covered by the course. This is understandable because the course was intended to be a compressed and concise overview. To resolve my questions, I turned to other sources on the web and decided to summarize what I learned in this article. Set up the experiment.Run the test and record the success rate for each group.Plot the distribution of the difference between the two samples.Calculate the statistical power.Evaluate how sample size affects A/B tests. Set up the experiment. Run the test and record the success rate for each group. Plot the distribution of the difference between the two samples. Calculate the statistical power. Evaluate how sample size affects A/B tests. We will run an A/B test for a hypothetical company that is trying to increase the amount of users that sign up for a premium account. The goal of running an A/B test is to evaluate if a change in a website will lead to improved performance in a specific metric. You may decide to test very simple alternatives such as changing the look of a single button on a webpage or testing different layouts and headlines. You could also run an A/B test on multi-step processes which may have many differences. Examples of this include the steps required in signing up a new user or processing the sale on an online marketplace. A/B testing is a huge subject and there are many techniques and rules on setting up an experiment. In addition to the Udacity course, here are a few other useful resources below: Optimizely’s Glossary for A/B Testing Evan Miller’s A/B Testing Articles Facebook’s Help Webpage on Ads Measurement For this article, I will keep it simple so that we can just focus on the math. Before running the test, we will know the baseline conversion rate and the desired lift or increase in signups that we would like to test. The baseline conversion rate is the current rate at which we sign up new users under the existing design. For our example, we want to use our test to confirm that the changes we make to our signup process will result in at least a 2% increase in our sign up rate. We currently sign up 10 out of 100 users who are offered a premium account. # code examples presented in Pythonbcr = 0.10 # baseline conversion rated_hat = 0.02 # difference between the groups Typically, the total number of users participating in the A/B test make up a small percentage of the total amount of users. Users are randomly selected and assigned to either a control group or a test group. The sample size that you decide on will determine how long you might have to wait until you have collected enough. For example, websites with large audiences may be able to collect enough data very quickly, while other websites may have to wait a number of weeks. There are some events that happen rarely even for high-traffic websites, so determining the necessary sample size will inform how soon you can assess your experiment and move on to improving other metrics. Initially, we will collect 1000 users for each group and serve the current signup page to the control group and a new signup page to the test group. # A is control; B is testN_A = 1000N_B = 1000 Because this is a hypothetical example, we will need “fake” data to work on. I wrote a function that will generate data for our simulation. The script can be found at my Github repo here. ab_data = generate_data(N_A, N_B, bcr, d_hat) The generate_data function returned the table on the left. Only the first five rows are shown. The converted column indicates whether a user signed up for the premium service or not with a 1 or 0, respectively. The A group will be used for our control group and the B group will be our test group. Let’s look at a summary of the results using the pivot table function in Pandas. ab_summary = ab_data.pivot_table(values='converted', index='group', aggfunc=np.sum)# add additional columns to the pivot tableab_summary['total'] = ab_data.pivot_table(values='converted', index='group', aggfunc=lambda x: len(x))ab_summary['rate'] = ab_data.pivot_table(values='converted', index='group') It looks like the difference in conversion rates between the two groups is 0.028 which is greater than the lift we initially wanted of 0.02. This is a good sign but this is not enough evidence for us to confidently go with the new design. At this point we have not measured how confident we are in this result. This can be mitigated by looking at the distributions of the two groups. We can compare the two groups by plotting the distribution of the control group and calculating the probability of getting the result from our test group. We can assume that the distribution for our control group is binomial because the data is a series of Bernoulli trials, where each trial only has two possible outcomes (similar to a coin flip). fig, ax = plt.subplots(figsize=(12,6))x = np.linspace(A_converted-49, A_converted+50, 100)y = scs.binom(A_total, A_cr).pmf(x)ax.bar(x, y, alpha=0.5)ax.axvline(x=B_cr * A_total, c='blue', alpha=0.75, linestyle='--')plt.xlabel('converted')plt.ylabel('probability') The distribution for the control group is shown in red and the result from the test group is indicated by the blue dashed line. We can see that the probability of getting the result from the test group was very low. However, the probability does not convey the confidence level of the results. It does not take the sample size of our test group into consideration. Intuitively, we would feel more confident in our results as our sample sizes grow larger. Let’s continue and plot the test group results as a binomial distribution and compare the distributions against each other. fig, ax = plt.subplots(figsize=(12,6))xA = np.linspace(A_converted-49, A_converted+50, 100)yA = scs.binom(A_total, p_A).pmf(xA)ax.bar(xA, yA, alpha=0.5)xB = np.linspace(B_converted-49, B_converted+50, 100)yB = scs.binom(B_total, p_B).pmf(xB)ax.bar(xB, yB, alpha=0.5)plt.xlabel('converted')plt.ylabel('probability') We can see that the test group converted more users than the control group. We can also see that the peak of the test group results is lower than the control group. How do we interpret the difference in peak probability? We should focus instead on the conversion rate so that we have an apples-to-apples comparison. In order to calculate this, we need to standardize the data and compare the probability of successes, p, for each group. To do this, first, consider the Bernoulli distribution for the control group. where p is the conversion probability of the control group. According to the properties of the Bernoulli distribution, the mean and variance are as follows: According to the central limit theorem, by calculating many sample means we can approximate the true mean of the population, μ, from which the data for the control group was taken. The distribution of the sample means, p, will be normally distributed around the true mean with a standard deviation equal to the standard error of the mean. The equation for this is given as: Therefore, we can represent both groups as a normal distribution with the following properties: The same can be done for the test group. So, we will have two normal distributions for p_A and p_B. # standard error of the mean for both groupsSE_A = np.sqrt(p_A * (1-p_A)) / np.sqrt(A_total)SE_B = np.sqrt(p_B * (1-p_B)) / np.sqrt(B_total)# plot the null and alternative hypothesisfig, ax = plt.subplots(figsize=(12,6))x = np.linspace(0, .2, 1000)yA = scs.norm(p_A, SE_A).pdf(x)ax.plot(xA, yA)ax.axvline(x=p_A, c='red', alpha=0.5, linestyle='--')yB = scs.norm(p_B, SE_B).pdf(x)ax.plot(xB, yB)ax.axvline(x=p_B, c='blue', alpha=0.5, linestyle='--')plt.xlabel('Converted Proportion')plt.ylabel('PDF') The dashed lines represent the mean conversion rate for each group. The distance between the red dashed line and the blue dashed line is equal to mean difference between the control and test group. d_hat is the distribution of the difference between random variables from the two groups. Recall that the null hypothesis states that the difference in probability between the two groups is zero. Therefore, the mean for this normal distribution will be at zero. The other property we will need for the normal distribution is the standard deviation or the variance. (Note: The variance is the standard deviation squared.) The variance of the difference will be dependent on the variances of the probability for both groups. A basic property of variance is that the variance of the sum of two random independent variables is the sum of the variances. This means that the null hypothesis and alternative hypothesis will have the same variance which will be the sum of the variances for the control group and the test group. The standard deviation can then be calculated as: If we put this equation in terms of standard deviation for the Bernoulli distribution, s: and we get the Satterthwaite approximation for pooled standard error. If we calculate the pooled probability and use the pooled probability to calculate the standard deviation for both groups, we get: where: This is the same equation used in the Udacity course. Both equations for pooled standard error will give you very similar results. With that, we now have enough information to construct the distributions for the null hypothesis and the alternative hypothesis. Let’s start off by defining the null hypothesis and the alternative hypothesis. The null hypothesis is the position that the change in the design made for the test group would result in no change in the conversion rate. The alternative hypothesis is the opposing position that the change in the design for the test group would result in an improvement (or reduction) in the conversion rate. According to the Udacity course, the null hypothesis will be a normal distribution with a mean of zero and a standard deviation equal to the pooled standard error. The alternative hypothesis has the same standard deviation as the null hypothesis, but the mean will be located at the difference in the conversion rate, d_hat. This makes sense because we can calculate the difference in the conversion rates directly from the data, but the normal distribution represents the possible values our experiment could have given us. Now that we understand the derivation of the pooled standard error, we can just directly plot the null and alternative hypotheses for future experiments. I wrote a script for quickly plotting the null and alternative hypotheses, abplot, which can be found here. # define the parameters for abplot()# use the actual values from the experiment for bcr and d_hat# p_A is the conversion rate of the control group# p_B is the conversion rate of the test groupn = N_A + N_Bbcr = p_A d_hat = p_B - p_Aabplot(n, bcr, d_hat) Visually, the plot for the null and alternative hypothesis looks very similar to the other plots above. Fortunately, both curves are identical in shape, so we can just compare the distance between the means of the two distributions. We can see that the alternative hypothesis curve suggests that the test group has a higher conversion rate than the control group. This plot also can be used to directly determine the statistical power. I think it is easier to define statistical power and significance level by first showing how they are represented in the plot of the null and alternative hypothesis. We can return a visualization of the statistical power by adding the parameter show_power=True. abplot(N_A, N_B, bcr, d_hat, show_power=True) The green shaded area represents the statistical power, and the calculated value for power is also displayed on the plot. The gray dashed lines in the plot above represent the confidence interval (95% for the plot above) for the null hypothesis. Statistical power is calculated by finding the area under the alternative hypothesis distribution and outside of the confidence interval of the null hypothesis. After running our experiment, we get a resulting conversion rate for both groups. If we calculate the difference between the conversion rates, we end up with one result, the difference or the effect of the design change. Our task is to determine which population this result came from, the null hypothesis or the alternative hypothesis. The area under the alternative hypothesis curve is equal to 1. If the alternative design is truly better, the power is the probability that we accept the alternative hypothesis and reject the null hypothesis and is equal to the area shaded green (true positive). The opposite area under the alternative curve is the probability that we accept the null hypothesis and reject the alternative hypothesis (false negative). This is referred to as beta in A/B testing or hypothesis testing and is shown below. abplot(N_A, N_B, bcr, d_hat, show_beta=True) The gray dashed line that divides the area under the alternative curve into two also directly segments the area associated with the significance level, often denoted with the greek letter alpha. If the null hypothesis is true and there truly is no difference between the control and test groups, then the significance level is the probability that we would reject the null hypothesis and accept the alternative hypothesis (false positive). A false positive is when we mistakenly conclude that the new design is better. This value is low because we want to limit this probability. Oftentimes, a problem will be given with a desired confidence level instead of the significance level. A typical 95% confidence level for an A/B test corresponds to a significance level of 0.05. It might be helpful to refer to a confusion matrix when you are evaluating the results of an A/B test and the different probability of outcomes. Experiments are typically set up for a minimum desired power of 80%. If our new design is truly better, we want our experiment to show that there is at least an 80% probability that this is the case. Unfortunately, our current experiment only has a power of 0.594. We know that if we increase the sample size for each group, we will decrease the pooled variance for our null and alternative hypothesis. This will make our distributions much narrower and may increase the statistical power. Let’s take a look at how sample size will directly affect our results. If we run our test again with a sample size of 2000 instead of 1000 for each group, we get the following results. abplot(2000, 2000, bcr, d_hat, show_power=True) Our curves for the null and alternative hypothesis have become more narrow and more of the area under the alternative curve is located on the right of the gray dashed line. The result for power is greater than 0.80 and meets our benchmark for statistical power. We can now say that our results are statistically significant. A problem you may encounter is determining the minimum sample size you will need for your experiment. This is a common interview question and it is useful to know because it is directly related to how quickly you can complete your experiments and deliver statistically significant results to your design team. You can use the calculators available on the web, such as the ones below: www.evanmiller.org www.optimizely.com You will need the baseline conversion rate (bcr) and the minimum detectable effect, which is the minimum difference between the control and test group that you or your team will determine to be worth the investment of making the design change in the first place. I wanted to write a script that would do the same calculation but needed to find the equation that was being used. After much searching, I found and tested this equation from this Stanford Lecture. (Warning: link opens Powerpoint download.) Many people calculate Z from tables such as those shown here and here. However, I am more of a visual learner and I like to refer to the plot of the Z-distribution from which the values are derived. The code for these z-plots can be found in my Github repo here. Here is the Python code that performs the same calculation for minimum sample size: I can demonstrate that this equation returns a correct answer by running another A/B experiment with the sample size that results from the equation. min_sample_size(bcr=0.10, mde=0.02)Out: 3842.026abplot(3843, 3843, 0.10, 0.02, show_power=True) The calculated power for this sample size was approximately 0.80. Therefore, if our design change had an improvement in conversion of about 2 percent, we would need at least 3843 samples in each group for a statistical power of at least 0.80. That was a very long but basic walkthrough of A/B tests. Once you have developed an understanding and familiarity with the procedure, you will probably be able to run an experiment and go directly to the plots for the null and alternative hypothesis to determine if your results achieved enough power. By calculating the minimum sample size you need prior to the experiment, you can determine how long it will take to get the results back to your team for a final decision. If you have any questions, I can try to answer them in the comments below. If you liked this article please 👏. Shoutout to Brian McGarry for editing notes. Thank you for reading!
[ { "code": null, "e": 547, "s": 171, "text": "While taking the A/B testing course by Google on Udacity, I had some questions about some of the mathematical steps that were not clearly covered by the course. This is understandable because the course was intended to be a compressed and concise overview. To resolve my questions, I turned to other sources on the web and decided to summarize what I learned in this article." }, { "code": null, "e": 765, "s": 547, "text": "Set up the experiment.Run the test and record the success rate for each group.Plot the distribution of the difference between the two samples.Calculate the statistical power.Evaluate how sample size affects A/B tests." }, { "code": null, "e": 788, "s": 765, "text": "Set up the experiment." }, { "code": null, "e": 845, "s": 788, "text": "Run the test and record the success rate for each group." }, { "code": null, "e": 910, "s": 845, "text": "Plot the distribution of the difference between the two samples." }, { "code": null, "e": 943, "s": 910, "text": "Calculate the statistical power." }, { "code": null, "e": 987, "s": 943, "text": "Evaluate how sample size affects A/B tests." }, { "code": null, "e": 1784, "s": 987, "text": "We will run an A/B test for a hypothetical company that is trying to increase the amount of users that sign up for a premium account. The goal of running an A/B test is to evaluate if a change in a website will lead to improved performance in a specific metric. You may decide to test very simple alternatives such as changing the look of a single button on a webpage or testing different layouts and headlines. You could also run an A/B test on multi-step processes which may have many differences. Examples of this include the steps required in signing up a new user or processing the sale on an online marketplace. A/B testing is a huge subject and there are many techniques and rules on setting up an experiment. In addition to the Udacity course, here are a few other useful resources below:" }, { "code": null, "e": 1822, "s": 1784, "text": "Optimizely’s Glossary for A/B Testing" }, { "code": null, "e": 1857, "s": 1822, "text": "Evan Miller’s A/B Testing Articles" }, { "code": null, "e": 1900, "s": 1857, "text": "Facebook’s Help Webpage on Ads Measurement" }, { "code": null, "e": 1979, "s": 1900, "text": "For this article, I will keep it simple so that we can just focus on the math." }, { "code": null, "e": 2458, "s": 1979, "text": "Before running the test, we will know the baseline conversion rate and the desired lift or increase in signups that we would like to test. The baseline conversion rate is the current rate at which we sign up new users under the existing design. For our example, we want to use our test to confirm that the changes we make to our signup process will result in at least a 2% increase in our sign up rate. We currently sign up 10 out of 100 users who are offered a premium account." }, { "code": null, "e": 2577, "s": 2458, "text": "# code examples presented in Pythonbcr = 0.10 # baseline conversion rated_hat = 0.02 # difference between the groups" }, { "code": null, "e": 3255, "s": 2577, "text": "Typically, the total number of users participating in the A/B test make up a small percentage of the total amount of users. Users are randomly selected and assigned to either a control group or a test group. The sample size that you decide on will determine how long you might have to wait until you have collected enough. For example, websites with large audiences may be able to collect enough data very quickly, while other websites may have to wait a number of weeks. There are some events that happen rarely even for high-traffic websites, so determining the necessary sample size will inform how soon you can assess your experiment and move on to improving other metrics." }, { "code": null, "e": 3404, "s": 3255, "text": "Initially, we will collect 1000 users for each group and serve the current signup page to the control group and a new signup page to the test group." }, { "code": null, "e": 3450, "s": 3404, "text": "# A is control; B is testN_A = 1000N_B = 1000" }, { "code": null, "e": 3638, "s": 3450, "text": "Because this is a hypothetical example, we will need “fake” data to work on. I wrote a function that will generate data for our simulation. The script can be found at my Github repo here." }, { "code": null, "e": 3684, "s": 3638, "text": "ab_data = generate_data(N_A, N_B, bcr, d_hat)" }, { "code": null, "e": 3982, "s": 3684, "text": "The generate_data function returned the table on the left. Only the first five rows are shown. The converted column indicates whether a user signed up for the premium service or not with a 1 or 0, respectively. The A group will be used for our control group and the B group will be our test group." }, { "code": null, "e": 4063, "s": 3982, "text": "Let’s look at a summary of the results using the pivot table function in Pandas." }, { "code": null, "e": 4367, "s": 4063, "text": "ab_summary = ab_data.pivot_table(values='converted', index='group', aggfunc=np.sum)# add additional columns to the pivot tableab_summary['total'] = ab_data.pivot_table(values='converted', index='group', aggfunc=lambda x: len(x))ab_summary['rate'] = ab_data.pivot_table(values='converted', index='group')" }, { "code": null, "e": 4751, "s": 4367, "text": "It looks like the difference in conversion rates between the two groups is 0.028 which is greater than the lift we initially wanted of 0.02. This is a good sign but this is not enough evidence for us to confidently go with the new design. At this point we have not measured how confident we are in this result. This can be mitigated by looking at the distributions of the two groups." }, { "code": null, "e": 5100, "s": 4751, "text": "We can compare the two groups by plotting the distribution of the control group and calculating the probability of getting the result from our test group. We can assume that the distribution for our control group is binomial because the data is a series of Bernoulli trials, where each trial only has two possible outcomes (similar to a coin flip)." }, { "code": null, "e": 5363, "s": 5100, "text": "fig, ax = plt.subplots(figsize=(12,6))x = np.linspace(A_converted-49, A_converted+50, 100)y = scs.binom(A_total, A_cr).pmf(x)ax.bar(x, y, alpha=0.5)ax.axvline(x=B_cr * A_total, c='blue', alpha=0.75, linestyle='--')plt.xlabel('converted')plt.ylabel('probability')" }, { "code": null, "e": 5942, "s": 5363, "text": "The distribution for the control group is shown in red and the result from the test group is indicated by the blue dashed line. We can see that the probability of getting the result from the test group was very low. However, the probability does not convey the confidence level of the results. It does not take the sample size of our test group into consideration. Intuitively, we would feel more confident in our results as our sample sizes grow larger. Let’s continue and plot the test group results as a binomial distribution and compare the distributions against each other." }, { "code": null, "e": 6257, "s": 5942, "text": "fig, ax = plt.subplots(figsize=(12,6))xA = np.linspace(A_converted-49, A_converted+50, 100)yA = scs.binom(A_total, p_A).pmf(xA)ax.bar(xA, yA, alpha=0.5)xB = np.linspace(B_converted-49, B_converted+50, 100)yB = scs.binom(B_total, p_B).pmf(xB)ax.bar(xB, yB, alpha=0.5)plt.xlabel('converted')plt.ylabel('probability')" }, { "code": null, "e": 6694, "s": 6257, "text": "We can see that the test group converted more users than the control group. We can also see that the peak of the test group results is lower than the control group. How do we interpret the difference in peak probability? We should focus instead on the conversion rate so that we have an apples-to-apples comparison. In order to calculate this, we need to standardize the data and compare the probability of successes, p, for each group." }, { "code": null, "e": 6772, "s": 6694, "text": "To do this, first, consider the Bernoulli distribution for the control group." }, { "code": null, "e": 6832, "s": 6772, "text": "where p is the conversion probability of the control group." }, { "code": null, "e": 6929, "s": 6832, "text": "According to the properties of the Bernoulli distribution, the mean and variance are as follows:" }, { "code": null, "e": 7303, "s": 6929, "text": "According to the central limit theorem, by calculating many sample means we can approximate the true mean of the population, μ, from which the data for the control group was taken. The distribution of the sample means, p, will be normally distributed around the true mean with a standard deviation equal to the standard error of the mean. The equation for this is given as:" }, { "code": null, "e": 7399, "s": 7303, "text": "Therefore, we can represent both groups as a normal distribution with the following properties:" }, { "code": null, "e": 7499, "s": 7399, "text": "The same can be done for the test group. So, we will have two normal distributions for p_A and p_B." }, { "code": null, "e": 7998, "s": 7499, "text": "# standard error of the mean for both groupsSE_A = np.sqrt(p_A * (1-p_A)) / np.sqrt(A_total)SE_B = np.sqrt(p_B * (1-p_B)) / np.sqrt(B_total)# plot the null and alternative hypothesisfig, ax = plt.subplots(figsize=(12,6))x = np.linspace(0, .2, 1000)yA = scs.norm(p_A, SE_A).pdf(x)ax.plot(xA, yA)ax.axvline(x=p_A, c='red', alpha=0.5, linestyle='--')yB = scs.norm(p_B, SE_B).pdf(x)ax.plot(xB, yB)ax.axvline(x=p_B, c='blue', alpha=0.5, linestyle='--')plt.xlabel('Converted Proportion')plt.ylabel('PDF')" }, { "code": null, "e": 8286, "s": 7998, "text": "The dashed lines represent the mean conversion rate for each group. The distance between the red dashed line and the blue dashed line is equal to mean difference between the control and test group. d_hat is the distribution of the difference between random variables from the two groups." }, { "code": null, "e": 8719, "s": 8286, "text": "Recall that the null hypothesis states that the difference in probability between the two groups is zero. Therefore, the mean for this normal distribution will be at zero. The other property we will need for the normal distribution is the standard deviation or the variance. (Note: The variance is the standard deviation squared.) The variance of the difference will be dependent on the variances of the probability for both groups." }, { "code": null, "e": 8845, "s": 8719, "text": "A basic property of variance is that the variance of the sum of two random independent variables is the sum of the variances." }, { "code": null, "e": 9017, "s": 8845, "text": "This means that the null hypothesis and alternative hypothesis will have the same variance which will be the sum of the variances for the control group and the test group." }, { "code": null, "e": 9067, "s": 9017, "text": "The standard deviation can then be calculated as:" }, { "code": null, "e": 9157, "s": 9067, "text": "If we put this equation in terms of standard deviation for the Bernoulli distribution, s:" }, { "code": null, "e": 9358, "s": 9157, "text": "and we get the Satterthwaite approximation for pooled standard error. If we calculate the pooled probability and use the pooled probability to calculate the standard deviation for both groups, we get:" }, { "code": null, "e": 9365, "s": 9358, "text": "where:" }, { "code": null, "e": 9496, "s": 9365, "text": "This is the same equation used in the Udacity course. Both equations for pooled standard error will give you very similar results." }, { "code": null, "e": 9625, "s": 9496, "text": "With that, we now have enough information to construct the distributions for the null hypothesis and the alternative hypothesis." }, { "code": null, "e": 9705, "s": 9625, "text": "Let’s start off by defining the null hypothesis and the alternative hypothesis." }, { "code": null, "e": 9845, "s": 9705, "text": "The null hypothesis is the position that the change in the design made for the test group would result in no change in the conversion rate." }, { "code": null, "e": 10016, "s": 9845, "text": "The alternative hypothesis is the opposing position that the change in the design for the test group would result in an improvement (or reduction) in the conversion rate." }, { "code": null, "e": 10180, "s": 10016, "text": "According to the Udacity course, the null hypothesis will be a normal distribution with a mean of zero and a standard deviation equal to the pooled standard error." }, { "code": null, "e": 10541, "s": 10180, "text": "The alternative hypothesis has the same standard deviation as the null hypothesis, but the mean will be located at the difference in the conversion rate, d_hat. This makes sense because we can calculate the difference in the conversion rates directly from the data, but the normal distribution represents the possible values our experiment could have given us." }, { "code": null, "e": 10803, "s": 10541, "text": "Now that we understand the derivation of the pooled standard error, we can just directly plot the null and alternative hypotheses for future experiments. I wrote a script for quickly plotting the null and alternative hypotheses, abplot, which can be found here." }, { "code": null, "e": 11058, "s": 10803, "text": "# define the parameters for abplot()# use the actual values from the experiment for bcr and d_hat# p_A is the conversion rate of the control group# p_B is the conversion rate of the test groupn = N_A + N_Bbcr = p_A d_hat = p_B - p_Aabplot(n, bcr, d_hat)" }, { "code": null, "e": 11494, "s": 11058, "text": "Visually, the plot for the null and alternative hypothesis looks very similar to the other plots above. Fortunately, both curves are identical in shape, so we can just compare the distance between the means of the two distributions. We can see that the alternative hypothesis curve suggests that the test group has a higher conversion rate than the control group. This plot also can be used to directly determine the statistical power." }, { "code": null, "e": 11756, "s": 11494, "text": "I think it is easier to define statistical power and significance level by first showing how they are represented in the plot of the null and alternative hypothesis. We can return a visualization of the statistical power by adding the parameter show_power=True." }, { "code": null, "e": 11802, "s": 11756, "text": "abplot(N_A, N_B, bcr, d_hat, show_power=True)" }, { "code": null, "e": 12209, "s": 11802, "text": "The green shaded area represents the statistical power, and the calculated value for power is also displayed on the plot. The gray dashed lines in the plot above represent the confidence interval (95% for the plot above) for the null hypothesis. Statistical power is calculated by finding the area under the alternative hypothesis distribution and outside of the confidence interval of the null hypothesis." }, { "code": null, "e": 12546, "s": 12209, "text": "After running our experiment, we get a resulting conversion rate for both groups. If we calculate the difference between the conversion rates, we end up with one result, the difference or the effect of the design change. Our task is to determine which population this result came from, the null hypothesis or the alternative hypothesis." }, { "code": null, "e": 13050, "s": 12546, "text": "The area under the alternative hypothesis curve is equal to 1. If the alternative design is truly better, the power is the probability that we accept the alternative hypothesis and reject the null hypothesis and is equal to the area shaded green (true positive). The opposite area under the alternative curve is the probability that we accept the null hypothesis and reject the alternative hypothesis (false negative). This is referred to as beta in A/B testing or hypothesis testing and is shown below." }, { "code": null, "e": 13095, "s": 13050, "text": "abplot(N_A, N_B, bcr, d_hat, show_beta=True)" }, { "code": null, "e": 13290, "s": 13095, "text": "The gray dashed line that divides the area under the alternative curve into two also directly segments the area associated with the significance level, often denoted with the greek letter alpha." }, { "code": null, "e": 13675, "s": 13290, "text": "If the null hypothesis is true and there truly is no difference between the control and test groups, then the significance level is the probability that we would reject the null hypothesis and accept the alternative hypothesis (false positive). A false positive is when we mistakenly conclude that the new design is better. This value is low because we want to limit this probability." }, { "code": null, "e": 13870, "s": 13675, "text": "Oftentimes, a problem will be given with a desired confidence level instead of the significance level. A typical 95% confidence level for an A/B test corresponds to a significance level of 0.05." }, { "code": null, "e": 14015, "s": 13870, "text": "It might be helpful to refer to a confusion matrix when you are evaluating the results of an A/B test and the different probability of outcomes." }, { "code": null, "e": 14576, "s": 14015, "text": "Experiments are typically set up for a minimum desired power of 80%. If our new design is truly better, we want our experiment to show that there is at least an 80% probability that this is the case. Unfortunately, our current experiment only has a power of 0.594. We know that if we increase the sample size for each group, we will decrease the pooled variance for our null and alternative hypothesis. This will make our distributions much narrower and may increase the statistical power. Let’s take a look at how sample size will directly affect our results." }, { "code": null, "e": 14690, "s": 14576, "text": "If we run our test again with a sample size of 2000 instead of 1000 for each group, we get the following results." }, { "code": null, "e": 14738, "s": 14690, "text": "abplot(2000, 2000, bcr, d_hat, show_power=True)" }, { "code": null, "e": 15063, "s": 14738, "text": "Our curves for the null and alternative hypothesis have become more narrow and more of the area under the alternative curve is located on the right of the gray dashed line. The result for power is greater than 0.80 and meets our benchmark for statistical power. We can now say that our results are statistically significant." }, { "code": null, "e": 15447, "s": 15063, "text": "A problem you may encounter is determining the minimum sample size you will need for your experiment. This is a common interview question and it is useful to know because it is directly related to how quickly you can complete your experiments and deliver statistically significant results to your design team. You can use the calculators available on the web, such as the ones below:" }, { "code": null, "e": 15466, "s": 15447, "text": "www.evanmiller.org" }, { "code": null, "e": 15485, "s": 15466, "text": "www.optimizely.com" }, { "code": null, "e": 15748, "s": 15485, "text": "You will need the baseline conversion rate (bcr) and the minimum detectable effect, which is the minimum difference between the control and test group that you or your team will determine to be worth the investment of making the design change in the first place." }, { "code": null, "e": 15989, "s": 15748, "text": "I wanted to write a script that would do the same calculation but needed to find the equation that was being used. After much searching, I found and tested this equation from this Stanford Lecture. (Warning: link opens Powerpoint download.)" }, { "code": null, "e": 16188, "s": 15989, "text": "Many people calculate Z from tables such as those shown here and here. However, I am more of a visual learner and I like to refer to the plot of the Z-distribution from which the values are derived." }, { "code": null, "e": 16252, "s": 16188, "text": "The code for these z-plots can be found in my Github repo here." }, { "code": null, "e": 16336, "s": 16252, "text": "Here is the Python code that performs the same calculation for minimum sample size:" }, { "code": null, "e": 16485, "s": 16336, "text": "I can demonstrate that this equation returns a correct answer by running another A/B experiment with the sample size that results from the equation." }, { "code": null, "e": 16581, "s": 16485, "text": "min_sample_size(bcr=0.10, mde=0.02)Out: 3842.026abplot(3843, 3843, 0.10, 0.02, show_power=True)" }, { "code": null, "e": 16824, "s": 16581, "text": "The calculated power for this sample size was approximately 0.80. Therefore, if our design change had an improvement in conversion of about 2 percent, we would need at least 3843 samples in each group for a statistical power of at least 0.80." }, { "code": null, "e": 17298, "s": 16824, "text": "That was a very long but basic walkthrough of A/B tests. Once you have developed an understanding and familiarity with the procedure, you will probably be able to run an experiment and go directly to the plots for the null and alternative hypothesis to determine if your results achieved enough power. By calculating the minimum sample size you need prior to the experiment, you can determine how long it will take to get the results back to your team for a final decision." } ]
How many ways can get the instance of a Class class in Java?
You can create an object of the class named Class in two ways − Using new keyword as − Class obj = new Class(); Using the forName() method of the class named Class. Class obj = Class.forName("DemoTest");
[ { "code": null, "e": 1126, "s": 1062, "text": "You can create an object of the class named Class in two ways −" }, { "code": null, "e": 1149, "s": 1126, "text": "Using new keyword as −" }, { "code": null, "e": 1174, "s": 1149, "text": "Class obj = new Class();" }, { "code": null, "e": 1227, "s": 1174, "text": "Using the forName() method of the class named Class." }, { "code": null, "e": 1266, "s": 1227, "text": "Class obj = Class.forName(\"DemoTest\");" } ]
How do I calculate the date six months from the current date using the datetime Python module?
You can use the timedelta function from datetime module to achieve this. For example, >>> import datetime >>> today = datetime.date.today() >>> print today 2017-09-12 >>> six_months_later = today + datetime.timedelta(30*6) >>> print six_months_later 2018-03-11
[ { "code": null, "e": 1148, "s": 1062, "text": "You can use the timedelta function from datetime module to achieve this. For example," }, { "code": null, "e": 1323, "s": 1148, "text": ">>> import datetime\n>>> today = datetime.date.today()\n>>> print today\n2017-09-12\n>>> six_months_later = today + datetime.timedelta(30*6)\n>>> print six_months_later\n2018-03-11" } ]
iOS - File Handling
File handling cannot be explained visually with the application and hence the key methods that are used for handling files are explained below. Note that the application bundle only has read permission and we won’t be able to modify the files. You can anyway modify the documents directory of your application. The methods used for accessing and manipulating the files are discussed below. Here we have to replace FilePath1, FilePath2 and FilePath strings to our required full file paths to get the desired action. NSFileManager *fileManager = [NSFileManager defaultManager]; //Get documents directory NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0]; if ([fileManager fileExistsAtPath:@""]==YES) { NSLog(@"File exists"); } if ([fileManager contentsEqualAtPath:@"FilePath1" andPath:@" FilePath2"]) { NSLog(@"Same content"); } if ([fileManager isWritableFileAtPath:@"FilePath"]) { NSLog(@"isWritable"); } if ([fileManager isReadableFileAtPath:@"FilePath"]) { NSLog(@"isReadable"); } if ( [fileManager isExecutableFileAtPath:@"FilePath"]) { NSLog(@"is Executable"); } if([fileManager moveItemAtPath:@"FilePath1" toPath:@"FilePath2" error:NULL]) { NSLog(@"Moved successfully"); } if ([fileManager copyItemAtPath:@"FilePath1" toPath:@"FilePath2" error:NULL]) { NSLog(@"Copied successfully"); } if ([fileManager removeItemAtPath:@"FilePath" error:NULL]) { NSLog(@"Removed successfully"); } NSData *data = [fileManager contentsAtPath:@"Path"]; [fileManager createFileAtPath:@"" contents:data attributes:nil]; 23 Lectures 1.5 hours Ashish Sharma 9 Lectures 1 hours Abhilash Nelson 14 Lectures 1.5 hours Abhilash Nelson 15 Lectures 1.5 hours Abhilash Nelson 10 Lectures 1 hours Abhilash Nelson 69 Lectures 4 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2402, "s": 2091, "text": "File handling cannot be explained visually with the application and hence the key methods that are used for handling files are explained below. Note that the application bundle only has read permission and we won’t be able to modify the files. You can anyway modify the documents directory of your application." }, { "code": null, "e": 2606, "s": 2402, "text": "The methods used for accessing and manipulating the files are discussed below. Here we have to replace FilePath1, FilePath2 and FilePath strings to our required full file paths to get the desired action." }, { "code": null, "e": 2947, "s": 2606, "text": "NSFileManager *fileManager = [NSFileManager defaultManager];\n\n//Get documents directory\nNSArray *directoryPaths = NSSearchPathForDirectoriesInDomains\n(NSDocumentDirectory, NSUserDomainMask, YES);\nNSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0];\n\nif ([fileManager fileExistsAtPath:@\"\"]==YES) {\n NSLog(@\"File exists\");\n}" }, { "code": null, "e": 3052, "s": 2947, "text": "if ([fileManager contentsEqualAtPath:@\"FilePath1\" andPath:@\" FilePath2\"]) {\n NSLog(@\"Same content\");\n}" }, { "code": null, "e": 3303, "s": 3052, "text": "if ([fileManager isWritableFileAtPath:@\"FilePath\"]) {\n NSLog(@\"isWritable\");\n}\n\nif ([fileManager isReadableFileAtPath:@\"FilePath\"]) {\n NSLog(@\"isReadable\");\n}\n\nif ( [fileManager isExecutableFileAtPath:@\"FilePath\"]) {\n NSLog(@\"is Executable\");\n}" }, { "code": null, "e": 3421, "s": 3303, "text": "if([fileManager moveItemAtPath:@\"FilePath1\" \n toPath:@\"FilePath2\" error:NULL]) {\n NSLog(@\"Moved successfully\");\n}" }, { "code": null, "e": 3542, "s": 3421, "text": "if ([fileManager copyItemAtPath:@\"FilePath1\" \n toPath:@\"FilePath2\" error:NULL]) {\n NSLog(@\"Copied successfully\");\n}" }, { "code": null, "e": 3640, "s": 3542, "text": "if ([fileManager removeItemAtPath:@\"FilePath\" error:NULL]) {\n NSLog(@\"Removed successfully\");\n}" }, { "code": null, "e": 3693, "s": 3640, "text": "NSData *data = [fileManager contentsAtPath:@\"Path\"];" }, { "code": null, "e": 3758, "s": 3693, "text": "[fileManager createFileAtPath:@\"\" contents:data attributes:nil];" }, { "code": null, "e": 3793, "s": 3758, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3808, "s": 3793, "text": " Ashish Sharma" }, { "code": null, "e": 3840, "s": 3808, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 3857, "s": 3840, "text": " Abhilash Nelson" }, { "code": null, "e": 3892, "s": 3857, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3909, "s": 3892, "text": " Abhilash Nelson" }, { "code": null, "e": 3944, "s": 3909, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3961, "s": 3944, "text": " Abhilash Nelson" }, { "code": null, "e": 3994, "s": 3961, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 4011, "s": 3994, "text": " Abhilash Nelson" }, { "code": null, "e": 4044, "s": 4011, "text": "\n 69 Lectures \n 4 hours \n" }, { "code": null, "e": 4061, "s": 4044, "text": " Frahaan Hussain" }, { "code": null, "e": 4068, "s": 4061, "text": " Print" }, { "code": null, "e": 4079, "s": 4068, "text": " Add Notes" } ]
PyQt5 - QPixmap Class
QPixmap class provides an off-screen representation of an image. It can be used as a QPaintDevice object or can be loaded into another widget, typically a label or button. Qt API has another similar class QImage, which is optimized for I/O and other pixel manipulations. Pixmap, on the other hand, is optimized for showing it on screen. Both formats are interconvertible. The types of image files that can be read into a QPixmap object are as follows − Following methods are useful in handling QPixmap object − copy() Copies pixmap data from a QRect object fromImage() Converts QImage object into QPixmap grabWidget() Creates a pixmap from the given widget grabWindow() Create pixmap of data in a window Load() Loads an image file as pixmap save() Saves the QPixmap object as a file toImage Converts a QPixmap to QImage The most common use of QPixmap is to display image on a label/button. The following example shows an image displayed on a QLabel by using the setPixmap() method. The complete code is as follows − import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * def window(): app = QApplication(sys.argv) win = QWidget() l1 = QLabel() l1.setPixmap(QPixmap("python.png")) vbox = QVBoxLayout() vbox.addWidget(l1) win.setLayout(vbox) win.setWindowTitle("QPixmap Demo") win.show() sys.exit(app.exec_()) if __name__ == '__main__': window() The above code produces the following output − 146 Lectures 22.5 hours ALAA EID Print Add Notes Bookmark this page
[ { "code": null, "e": 2135, "s": 1963, "text": "QPixmap class provides an off-screen representation of an image. It can be used as a QPaintDevice object or can be loaded into another widget, typically a label or button." }, { "code": null, "e": 2335, "s": 2135, "text": "Qt API has another similar class QImage, which is optimized for I/O and other pixel manipulations. Pixmap, on the other hand, is optimized for showing it on screen. Both formats are interconvertible." }, { "code": null, "e": 2416, "s": 2335, "text": "The types of image files that can be read into a QPixmap object are as follows −" }, { "code": null, "e": 2474, "s": 2416, "text": "Following methods are useful in handling QPixmap object −" }, { "code": null, "e": 2481, "s": 2474, "text": "copy()" }, { "code": null, "e": 2520, "s": 2481, "text": "Copies pixmap data from a QRect object" }, { "code": null, "e": 2532, "s": 2520, "text": "fromImage()" }, { "code": null, "e": 2568, "s": 2532, "text": "Converts QImage object into QPixmap" }, { "code": null, "e": 2581, "s": 2568, "text": "grabWidget()" }, { "code": null, "e": 2620, "s": 2581, "text": "Creates a pixmap from the given widget" }, { "code": null, "e": 2633, "s": 2620, "text": "grabWindow()" }, { "code": null, "e": 2667, "s": 2633, "text": "Create pixmap of data in a window" }, { "code": null, "e": 2674, "s": 2667, "text": "Load()" }, { "code": null, "e": 2704, "s": 2674, "text": "Loads an image file as pixmap" }, { "code": null, "e": 2711, "s": 2704, "text": "save()" }, { "code": null, "e": 2746, "s": 2711, "text": "Saves the QPixmap object as a file" }, { "code": null, "e": 2754, "s": 2746, "text": "toImage" }, { "code": null, "e": 2783, "s": 2754, "text": "Converts a QPixmap to QImage" }, { "code": null, "e": 2853, "s": 2783, "text": "The most common use of QPixmap is to display image on a label/button." }, { "code": null, "e": 2945, "s": 2853, "text": "The following example shows an image displayed on a QLabel by using the setPixmap() method." }, { "code": null, "e": 2979, "s": 2945, "text": "The complete code is as follows −" }, { "code": null, "e": 3382, "s": 2979, "text": "import sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\ndef window():\n app = QApplication(sys.argv)\n win = QWidget()\n l1 = QLabel()\n l1.setPixmap(QPixmap(\"python.png\"))\n\n vbox = QVBoxLayout()\n vbox.addWidget(l1)\n win.setLayout(vbox)\n win.setWindowTitle(\"QPixmap Demo\")\n win.show()\n sys.exit(app.exec_())\n\nif __name__ == '__main__':\n window()" }, { "code": null, "e": 3429, "s": 3382, "text": "The above code produces the following output −" }, { "code": null, "e": 3466, "s": 3429, "text": "\n 146 Lectures \n 22.5 hours \n" }, { "code": null, "e": 3476, "s": 3466, "text": " ALAA EID" }, { "code": null, "e": 3483, "s": 3476, "text": " Print" }, { "code": null, "e": 3494, "s": 3483, "text": " Add Notes" } ]
Android - Developer Tools
The android developer tools let you create interactive and powerful application for android platform. The tools can be generally categorized into two types. SDK tools SDK tools Platform tools Platform tools SDK tools are generally platform independent and are required no matter which android platform you are working on. When you install the Android SDK into your system, these tools get automatically installed. The list of SDK tools has been given below − This tool lets you manage AVDs, projects, and the installed components of the SDK This tool lets you debug Android applications This tool allows you to easily create a NinePatch graphic using a WYSIWYG editor This tools let you test your applications without using a physical device Helps you create a disk image (external sdcard storage) that you can use with the emulator Shrinks, optimizes, and obfuscates your code by removing unused code Lets you access the SQLite data files created and used by Android applications Provides a graphical viewer for execution logs saved by your application Android Debug Bridge (adb) is a versatile command line tool that lets you communicate with an emulator instance or connected Android-powered device. We will discuss three important tools here that are android,ddms and sqlite3. Android is a development tool that lets you perform these tasks: Manage Android Virtual Devices (AVD) Manage Android Virtual Devices (AVD) Create and update Android projects Create and update Android projects Update your sdk with new platform add-ons and documentation Update your sdk with new platform add-ons and documentation android [global options] action [action options] DDMS stands for Dalvik debug monitor server, that provide many services on the device. The service could include message formation, call spoofing, capturing screenshot, exploring internal threads and file systems e.t.c From Android studio click on Tools>Android>Android device Monitor. In android, each application runs in its own process and each process run in the virtual machine. Each VM exposes a unique port, that a debugger can attach to. When DDMS starts, it connects to adb. When a device is connected, a VM monitoring service is created between adb and DDMS, which notifies DDMS when a VM on the device is started or terminated. Making sms to emulator.we need to call telnet client and server as shown below Now click on send button, and you will see an sms notification in the emulator window. It is shown below − In the DDMS, select the Emulator Control tab. In the emulator control tab , click on voice and then start typing the incoming number. It is shown in the picture below − Now click on the call button to make a call to your emulator. It is shown below − Now click on hangup in the Android studio window to terminate the call. The fake sms and call can be viewed from the notification by just dragging the notification window to the center using mouse. It is shown below − You can also capture screenshot of your emulator. For this look for the camera icon on the right side under Devices tab. Just point your mouse over it and select it. As soon as you select it , it will start the screen capturing process and will capture whatever screen of the emulator currently active. It is shown below − The eclipse orientation can be changed using Ctrl + F11 key. Now you can save the image or rotate it and then select done to exit the screen capture dialog. Sqlite3 is a command line program which is used to manage the SQLite databases created by Android applications. The tool also allow us to execute the SQL statements on the fly. There are two way through which you can use SQlite , either from remote shell or you can use locally. Enter a remote shell by entering the following command − adb [-d|-e|-s {<serialNumber>}] shell From a remote shell, start the sqlite3 tool by entering the following command − sqlite3 Once you invoke sqlite3, you can issue sqlite3 commands in the shell. To exit and return to the adb remote shell, enter exit or press CTRL+D. Copy a database file from your device to your host machine. adb pull <database-file-on-device> Start the sqlite3 tool from the /tools directory, specifying the database file − sqlite3 <database-file-on-host> The platform tools are customized to support the features of the latest android platform. The platform tools are typically updated every time you install a new SDK platform. Each update of the platform tools is backward compatible with older platforms. Some of the platform tools are listd below − Android Debug bridge (ADB) Android Debug bridge (ADB) Android Interface definition language (AIDL) Android Interface definition language (AIDL) aapt, dexdump , and dex e.t.c aapt, dexdump , and dex e.t.c 46 Lectures 7.5 hours Aditya Dua 32 Lectures 3.5 hours Sharad Kumar 9 Lectures 1 hours Abhilash Nelson 14 Lectures 1.5 hours Abhilash Nelson 15 Lectures 1.5 hours Abhilash Nelson 10 Lectures 1 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 3764, "s": 3607, "text": "The android developer tools let you create interactive and powerful application for android platform. The tools can be generally categorized into two types." }, { "code": null, "e": 3774, "s": 3764, "text": "SDK tools" }, { "code": null, "e": 3784, "s": 3774, "text": "SDK tools" }, { "code": null, "e": 3799, "s": 3784, "text": "Platform tools" }, { "code": null, "e": 3814, "s": 3799, "text": "Platform tools" }, { "code": null, "e": 4066, "s": 3814, "text": "SDK tools are generally platform independent and are required no matter which android platform you are working on. When you install the Android SDK into your system, these tools get automatically installed. The list of SDK tools has been given below −" }, { "code": null, "e": 4148, "s": 4066, "text": "This tool lets you manage AVDs, projects, and the installed components of the SDK" }, { "code": null, "e": 4194, "s": 4148, "text": "This tool lets you debug Android applications" }, { "code": null, "e": 4275, "s": 4194, "text": "This tool allows you to easily create a NinePatch graphic using a WYSIWYG editor" }, { "code": null, "e": 4349, "s": 4275, "text": "This tools let you test your applications without using a physical device" }, { "code": null, "e": 4440, "s": 4349, "text": "Helps you create a disk image (external sdcard storage) that you can use with the emulator" }, { "code": null, "e": 4509, "s": 4440, "text": "Shrinks, optimizes, and obfuscates your code by removing unused code" }, { "code": null, "e": 4588, "s": 4509, "text": "Lets you access the SQLite data files created and used by Android applications" }, { "code": null, "e": 4661, "s": 4588, "text": "Provides a graphical viewer for execution logs saved by your application" }, { "code": null, "e": 4810, "s": 4661, "text": "Android Debug Bridge (adb) is a versatile command line tool that lets you communicate with an emulator instance or connected Android-powered device." }, { "code": null, "e": 4888, "s": 4810, "text": "We will discuss three important tools here that are android,ddms and sqlite3." }, { "code": null, "e": 4953, "s": 4888, "text": "Android is a development tool that lets you perform these tasks:" }, { "code": null, "e": 4990, "s": 4953, "text": "Manage Android Virtual Devices (AVD)" }, { "code": null, "e": 5027, "s": 4990, "text": "Manage Android Virtual Devices (AVD)" }, { "code": null, "e": 5062, "s": 5027, "text": "Create and update Android projects" }, { "code": null, "e": 5097, "s": 5062, "text": "Create and update Android projects" }, { "code": null, "e": 5157, "s": 5097, "text": "Update your sdk with new platform add-ons and documentation" }, { "code": null, "e": 5217, "s": 5157, "text": "Update your sdk with new platform add-ons and documentation" }, { "code": null, "e": 5267, "s": 5217, "text": "android [global options] action [action options]\n" }, { "code": null, "e": 5486, "s": 5267, "text": "DDMS stands for Dalvik debug monitor server, that provide many services on the device. The service could include message formation, call spoofing, capturing screenshot, exploring internal threads and file systems e.t.c" }, { "code": null, "e": 5553, "s": 5486, "text": "From Android studio click on Tools>Android>Android device Monitor." }, { "code": null, "e": 5713, "s": 5553, "text": "In android, each application runs in its own process and each process run in the virtual machine. Each VM exposes a unique port, that a debugger can attach to." }, { "code": null, "e": 5906, "s": 5713, "text": "When DDMS starts, it connects to adb. When a device is connected, a VM monitoring service is created between adb and DDMS, which notifies DDMS when a VM on the device is started or terminated." }, { "code": null, "e": 5985, "s": 5906, "text": "Making sms to emulator.we need to call telnet client and server as shown below" }, { "code": null, "e": 6092, "s": 5985, "text": "Now click on send button, and you will see an sms notification in the emulator window. It is shown below −" }, { "code": null, "e": 6261, "s": 6092, "text": "In the DDMS, select the Emulator Control tab. In the emulator control tab , click on voice and then start typing the incoming number. It is shown in the picture below −" }, { "code": null, "e": 6343, "s": 6261, "text": "Now click on the call button to make a call to your emulator. It is shown below −" }, { "code": null, "e": 6415, "s": 6343, "text": "Now click on hangup in the Android studio window to terminate the call." }, { "code": null, "e": 6561, "s": 6415, "text": "The fake sms and call can be viewed from the notification by just dragging the notification window to the center using mouse. It is shown below −" }, { "code": null, "e": 6727, "s": 6561, "text": "You can also capture screenshot of your emulator. For this look for the camera icon on the right side under Devices tab. Just point your mouse over it and select it." }, { "code": null, "e": 6884, "s": 6727, "text": "As soon as you select it , it will start the screen capturing process and will capture whatever screen of the emulator currently active. It is shown below −" }, { "code": null, "e": 7041, "s": 6884, "text": "The eclipse orientation can be changed using Ctrl + F11 key. Now you can save the image or rotate it and then select done to exit the screen capture dialog." }, { "code": null, "e": 7218, "s": 7041, "text": "Sqlite3 is a command line program which is used to manage the SQLite databases created by Android applications. The tool also allow us to execute the SQL statements on the fly." }, { "code": null, "e": 7320, "s": 7218, "text": "There are two way through which you can use SQlite , either from remote shell or you can use locally." }, { "code": null, "e": 7377, "s": 7320, "text": "Enter a remote shell by entering the following command −" }, { "code": null, "e": 7415, "s": 7377, "text": "adb [-d|-e|-s {<serialNumber>}] shell" }, { "code": null, "e": 7495, "s": 7415, "text": "From a remote shell, start the sqlite3 tool by entering the following command −" }, { "code": null, "e": 7503, "s": 7495, "text": "sqlite3" }, { "code": null, "e": 7645, "s": 7503, "text": "Once you invoke sqlite3, you can issue sqlite3 commands in the shell. To exit and return to the adb remote shell, enter exit or press CTRL+D." }, { "code": null, "e": 7705, "s": 7645, "text": "Copy a database file from your device to your host machine." }, { "code": null, "e": 7741, "s": 7705, "text": "adb pull <database-file-on-device>\n" }, { "code": null, "e": 7822, "s": 7741, "text": "Start the sqlite3 tool from the /tools directory, specifying the database file −" }, { "code": null, "e": 7855, "s": 7822, "text": "sqlite3 <database-file-on-host>\n" }, { "code": null, "e": 7945, "s": 7855, "text": "The platform tools are customized to support the features of the latest android platform." }, { "code": null, "e": 8108, "s": 7945, "text": "The platform tools are typically updated every time you install a new SDK platform. Each update of the platform tools is backward compatible with older platforms." }, { "code": null, "e": 8153, "s": 8108, "text": "Some of the platform tools are listd below −" }, { "code": null, "e": 8180, "s": 8153, "text": "Android Debug bridge (ADB)" }, { "code": null, "e": 8207, "s": 8180, "text": "Android Debug bridge (ADB)" }, { "code": null, "e": 8252, "s": 8207, "text": "Android Interface definition language (AIDL)" }, { "code": null, "e": 8297, "s": 8252, "text": "Android Interface definition language (AIDL)" }, { "code": null, "e": 8327, "s": 8297, "text": "aapt, dexdump , and dex e.t.c" }, { "code": null, "e": 8357, "s": 8327, "text": "aapt, dexdump , and dex e.t.c" }, { "code": null, "e": 8392, "s": 8357, "text": "\n 46 Lectures \n 7.5 hours \n" }, { "code": null, "e": 8404, "s": 8392, "text": " Aditya Dua" }, { "code": null, "e": 8439, "s": 8404, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8453, "s": 8439, "text": " Sharad Kumar" }, { "code": null, "e": 8485, "s": 8453, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 8502, "s": 8485, "text": " Abhilash Nelson" }, { "code": null, "e": 8537, "s": 8502, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8554, "s": 8537, "text": " Abhilash Nelson" }, { "code": null, "e": 8589, "s": 8554, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8606, "s": 8589, "text": " Abhilash Nelson" }, { "code": null, "e": 8639, "s": 8606, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 8656, "s": 8639, "text": " Abhilash Nelson" }, { "code": null, "e": 8663, "s": 8656, "text": " Print" }, { "code": null, "e": 8674, "s": 8663, "text": " Add Notes" } ]
Natural Language Processing - Python
In this chapter, we will learn about language processing using Python. The following features make Python different from other languages − Python is interpreted − We do not need to compile our Python program before executing it because the interpreter processes Python at runtime. Python is interpreted − We do not need to compile our Python program before executing it because the interpreter processes Python at runtime. Interactive − We can directly interact with the interpreter to write our Python programs. Interactive − We can directly interact with the interpreter to write our Python programs. Object-oriented − Python is object-oriented in nature and it makes this language easier to write programs because with the help of this technique of programming it encapsulates code within objects. Object-oriented − Python is object-oriented in nature and it makes this language easier to write programs because with the help of this technique of programming it encapsulates code within objects. Beginner can easily learn − Python is also called beginner’s language because it is very easy to understand, and it supports the development of a wide range of applications. Beginner can easily learn − Python is also called beginner’s language because it is very easy to understand, and it supports the development of a wide range of applications. The latest version of Python 3 released is Python 3.7.1 is available for Windows, Mac OS and most of the flavors of Linux OS. For windows, we can go to the link www.python.org/downloads/windows/ to download and install Python. For windows, we can go to the link www.python.org/downloads/windows/ to download and install Python. For MAC OS, we can use the link www.python.org/downloads/mac-osx/. For MAC OS, we can use the link www.python.org/downloads/mac-osx/. In case of Linux, different flavors of Linux use different package managers for installation of new packages. For example, to install Python 3 on Ubuntu Linux, we can use the following command from terminal − In case of Linux, different flavors of Linux use different package managers for installation of new packages. For example, to install Python 3 on Ubuntu Linux, we can use the following command from terminal − For example, to install Python 3 on Ubuntu Linux, we can use the following command from terminal − $sudo apt-get install python3-minimal To study more about Python programming, read Python 3 basic tutorial – Python 3 We will be using Python library NLTK (Natural Language Toolkit) for doing text analysis in English Language. The Natural language toolkit (NLTK) is a collection of Python libraries designed especially for identifying and tag parts of speech found in the text of natural language like English. Before starting to use NLTK, we need to install it. With the help of following command, we can install it in our Python environment − pip install nltk If we are using Anaconda, then a Conda package for NLTK can be built by using the following command − conda install -c anaconda nltk After installing NLTK, another important task is to download its preset text repositories so that it can be easily used. However, before that we need to import NLTK the way we import any other Python module. The following command will help us in importing NLTK − import nltk Now, download NLTK data with the help of the following command − nltk.download() It will take some time to install all available packages of NLTK. Some other Python packages like gensim and pattern are also very necessary for text analysis as well as building natural language processing applications by using NLTK. the packages can be installed as shown below − gensim is a robust semantic modeling library which can be used for many applications. We can install it by following command − pip install gensim It can be used to make gensim package work properly. The following command helps in installing pattern − pip install pattern Tokenization may be defined as the Process of breaking the given text, into smaller units called tokens. Words, numbers or punctuation marks can be tokens. It may also be called word segmentation. Input − Bed and chair are types of furniture. We have different packages for tokenization provided by NLTK. We can use these packages based on our requirements. The packages and the details of their installation are as follows − This package can be used to divide the input text into sentences. We can import it by using the following command − from nltk.tokenize import sent_tokenize This package can be used to divide the input text into words. We can import it by using the following command − from nltk.tokenize import word_tokenize This package can be used to divide the input text into words and punctuation marks. We can import it by using the following command − from nltk.tokenize import WordPuncttokenizer Due to grammatical reasons, language includes lots of variations. Variations in the sense that the language, English as well as other languages too, have different forms of a word. For example, the words like democracy, democratic, and democratization. For machine learning projects, it is very important for machines to understand that these different words, like above, have the same base form. That is why it is very useful to extract the base forms of the words while analyzing the text. Stemming is a heuristic process that helps in extracting the base forms of the words by chopping of their ends. The different packages for stemming provided by NLTK module are as follows − Porter’s algorithm is used by this stemming package to extract the base form of the words. With the help of the following command, we can import this package − from nltk.stem.porter import PorterStemmer For example, ‘write’ would be the output of the word ‘writing’ given as the input to this stemmer. Lancaster’s algorithm is used by this stemming package to extract the base form of the words. With the help of following command, we can import this package − from nltk.stem.lancaster import LancasterStemmer For example, ‘writ’ would be the output of the word ‘writing’ given as the input to this stemmer. Snowball’s algorithm is used by this stemming package to extract the base form of the words. With the help of following command, we can import this package − from nltk.stem.snowball import SnowballStemmer For example, ‘write’ would be the output of the word ‘writing’ given as the input to this stemmer. It is another way to extract the base form of words, normally aiming to remove inflectional endings by using vocabulary and morphological analysis. After lemmatization, the base form of any word is called lemma. NLTK module provides the following package for lemmatization − This package will extract the base form of the word depending upon whether it is used as a noun or as a verb. The following command can be used to import this package − from nltk.stem import WordNetLemmatizer The identification of parts of speech (POS) and short phrases can be done with the help of chunking. It is one of the important processes in natural language processing. As we are aware about the process of tokenization for the creation of tokens, chunking actually is to do the labeling of those tokens. In other words, we can say that we can get the structure of the sentence with the help of chunking process. In the following example, we will implement Noun-Phrase chunking, a category of chunking which will find the noun phrase chunks in the sentence, by using NLTK Python module. Consider the following steps to implement noun-phrase chunking − Step 1: Chunk grammar definition In this step, we need to define the grammar for chunking. It would consist of the rules, which we need to follow. Step 2: Chunk parser creation Next, we need to create a chunk parser. It would parse the grammar and give the output. Step 3: The Output In this step, we will get the output in a tree format. Start by importing the the NLTK package − import nltk Now, we need to define the sentence. Here, DT is the determinant DT is the determinant VBP is the verb VBP is the verb JJ is the adjective JJ is the adjective IN is the preposition IN is the preposition NN is the noun NN is the noun sentence = [("a", "DT"),("clever","JJ"),("fox","NN"),("was","VBP"), ("jumping","VBP"),("over","IN"),("the","DT"),("wall","NN")] Next, the grammar should be given in the form of regular expression. grammar = "NP:{<DT>?<JJ>*<NN>}" Now, we need to define a parser for parsing the grammar. parser_chunking = nltk.RegexpParser(grammar) Now, the parser will parse the sentence as follows − parser_chunking.parse(sentence) Next, the output will be in the variable as follows:- Output = parser_chunking.parse(sentence) Now, the following code will help you draw your output in the form of a tree. output.draw() 59 Lectures 2.5 hours Mike West 17 Lectures 1 hours Pranjal Srivastava 6 Lectures 1 hours Prabh Kirpa Classes 12 Lectures 1 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 1967, "s": 1896, "text": "In this chapter, we will learn about language processing using Python." }, { "code": null, "e": 2035, "s": 1967, "text": "The following features make Python different from other languages −" }, { "code": null, "e": 2177, "s": 2035, "text": "Python is interpreted − We do not need to compile our Python program before executing it because the interpreter processes Python at runtime." }, { "code": null, "e": 2319, "s": 2177, "text": "Python is interpreted − We do not need to compile our Python program before executing it because the interpreter processes Python at runtime." }, { "code": null, "e": 2409, "s": 2319, "text": "Interactive − We can directly interact with the interpreter to write our Python programs." }, { "code": null, "e": 2499, "s": 2409, "text": "Interactive − We can directly interact with the interpreter to write our Python programs." }, { "code": null, "e": 2697, "s": 2499, "text": "Object-oriented − Python is object-oriented in nature and it makes this language easier to write programs because with the help of this technique of programming it encapsulates code within objects." }, { "code": null, "e": 2895, "s": 2697, "text": "Object-oriented − Python is object-oriented in nature and it makes this language easier to write programs because with the help of this technique of programming it encapsulates code within objects." }, { "code": null, "e": 3069, "s": 2895, "text": "Beginner can easily learn − Python is also called beginner’s language because it is very easy to understand, and it supports the development of a wide range of applications." }, { "code": null, "e": 3243, "s": 3069, "text": "Beginner can easily learn − Python is also called beginner’s language because it is very easy to understand, and it supports the development of a wide range of applications." }, { "code": null, "e": 3369, "s": 3243, "text": "The latest version of Python 3 released is Python 3.7.1 is available for Windows, Mac OS and most of the flavors of Linux OS." }, { "code": null, "e": 3470, "s": 3369, "text": "For windows, we can go to the link www.python.org/downloads/windows/ to download and install Python." }, { "code": null, "e": 3571, "s": 3470, "text": "For windows, we can go to the link www.python.org/downloads/windows/ to download and install Python." }, { "code": null, "e": 3638, "s": 3571, "text": "For MAC OS, we can use the link www.python.org/downloads/mac-osx/." }, { "code": null, "e": 3705, "s": 3638, "text": "For MAC OS, we can use the link www.python.org/downloads/mac-osx/." }, { "code": null, "e": 3917, "s": 3705, "text": "In case of Linux, different flavors of Linux use different package managers for installation of new packages.\n\nFor example, to install Python 3 on Ubuntu Linux, we can use the following command from terminal −\n\n" }, { "code": null, "e": 4027, "s": 3917, "text": "In case of Linux, different flavors of Linux use different package managers for installation of new packages." }, { "code": null, "e": 4126, "s": 4027, "text": "For example, to install Python 3 on Ubuntu Linux, we can use the following command from terminal −" }, { "code": null, "e": 4225, "s": 4126, "text": "For example, to install Python 3 on Ubuntu Linux, we can use the following command from terminal −" }, { "code": null, "e": 4264, "s": 4225, "text": "$sudo apt-get install python3-minimal\n" }, { "code": null, "e": 4344, "s": 4264, "text": "To study more about Python programming, read Python 3 basic tutorial – Python 3" }, { "code": null, "e": 4637, "s": 4344, "text": "We will be using Python library NLTK (Natural Language Toolkit) for doing text analysis in English Language. The Natural language toolkit (NLTK) is a collection of Python libraries designed especially for identifying and tag parts of speech found in the text of natural language like English." }, { "code": null, "e": 4771, "s": 4637, "text": "Before starting to use NLTK, we need to install it. With the help of following command, we can install it in our Python environment −" }, { "code": null, "e": 4789, "s": 4771, "text": "pip install nltk\n" }, { "code": null, "e": 4891, "s": 4789, "text": "If we are using Anaconda, then a Conda package for NLTK can be built by using the following command −" }, { "code": null, "e": 4923, "s": 4891, "text": "conda install -c anaconda nltk\n" }, { "code": null, "e": 5186, "s": 4923, "text": "After installing NLTK, another important task is to download its preset text repositories so that it can be easily used. However, before that we need to import NLTK the way we import any other Python module. The following command will help us in importing NLTK −" }, { "code": null, "e": 5199, "s": 5186, "text": "import nltk\n" }, { "code": null, "e": 5264, "s": 5199, "text": "Now, download NLTK data with the help of the following command −" }, { "code": null, "e": 5281, "s": 5264, "text": "nltk.download()\n" }, { "code": null, "e": 5347, "s": 5281, "text": "It will take some time to install all available packages of NLTK." }, { "code": null, "e": 5563, "s": 5347, "text": "Some other Python packages like gensim and pattern are also very necessary for text analysis as well as building natural language processing applications by using NLTK. the packages can be installed as shown below −" }, { "code": null, "e": 5690, "s": 5563, "text": "gensim is a robust semantic modeling library which can be used for many applications. We can install it by following command −" }, { "code": null, "e": 5710, "s": 5690, "text": "pip install gensim\n" }, { "code": null, "e": 5815, "s": 5710, "text": "It can be used to make gensim package work properly. The following command helps in installing pattern −" }, { "code": null, "e": 5836, "s": 5815, "text": "pip install pattern\n" }, { "code": null, "e": 6033, "s": 5836, "text": "Tokenization may be defined as the Process of breaking the given text, into smaller units called tokens. Words, numbers or punctuation marks can be tokens. It may also be called word segmentation." }, { "code": null, "e": 6079, "s": 6033, "text": "Input − Bed and chair are types of furniture." }, { "code": null, "e": 6262, "s": 6079, "text": "We have different packages for tokenization provided by NLTK. We can use these packages based on our requirements. The packages and the details of their installation are as follows −" }, { "code": null, "e": 6378, "s": 6262, "text": "This package can be used to divide the input text into sentences. We can import it by using the following command −" }, { "code": null, "e": 6419, "s": 6378, "text": "from nltk.tokenize import sent_tokenize\n" }, { "code": null, "e": 6531, "s": 6419, "text": "This package can be used to divide the input text into words. We can import it by using the following command −" }, { "code": null, "e": 6572, "s": 6531, "text": "from nltk.tokenize import word_tokenize\n" }, { "code": null, "e": 6706, "s": 6572, "text": "This package can be used to divide the input text into words and punctuation marks. We can import it by using the following command −" }, { "code": null, "e": 6752, "s": 6706, "text": "from nltk.tokenize import WordPuncttokenizer\n" }, { "code": null, "e": 7244, "s": 6752, "text": "Due to grammatical reasons, language includes lots of variations. Variations in the sense that the language, English as well as other languages too, have different forms of a word. For example, the words like democracy, democratic, and democratization. For machine learning projects, it is very important for machines to understand that these different words, like above, have the same base form. That is why it is very useful to extract the base forms of the words while analyzing the text." }, { "code": null, "e": 7356, "s": 7244, "text": "Stemming is a heuristic process that helps in extracting the base forms of the words by chopping of their ends." }, { "code": null, "e": 7433, "s": 7356, "text": "The different packages for stemming provided by NLTK module are as follows −" }, { "code": null, "e": 7593, "s": 7433, "text": "Porter’s algorithm is used by this stemming package to extract the base form of the words. With the help of the following command, we can import this package −" }, { "code": null, "e": 7637, "s": 7593, "text": "from nltk.stem.porter import PorterStemmer\n" }, { "code": null, "e": 7736, "s": 7637, "text": "For example, ‘write’ would be the output of the word ‘writing’ given as the input to this stemmer." }, { "code": null, "e": 7895, "s": 7736, "text": "Lancaster’s algorithm is used by this stemming package to extract the base form of the words. With the help of following command, we can import this package −" }, { "code": null, "e": 7945, "s": 7895, "text": "from nltk.stem.lancaster import LancasterStemmer\n" }, { "code": null, "e": 8043, "s": 7945, "text": "For example, ‘writ’ would be the output of the word ‘writing’ given as the input to this stemmer." }, { "code": null, "e": 8201, "s": 8043, "text": "Snowball’s algorithm is used by this stemming package to extract the base form of the words. With the help of following command, we can import this package −" }, { "code": null, "e": 8249, "s": 8201, "text": "from nltk.stem.snowball import SnowballStemmer\n" }, { "code": null, "e": 8348, "s": 8249, "text": "For example, ‘write’ would be the output of the word ‘writing’ given as the input to this stemmer." }, { "code": null, "e": 8560, "s": 8348, "text": "It is another way to extract the base form of words, normally aiming to remove inflectional endings by using vocabulary and morphological analysis. After lemmatization, the base form of any word is called lemma." }, { "code": null, "e": 8623, "s": 8560, "text": "NLTK module provides the following package for lemmatization −" }, { "code": null, "e": 8792, "s": 8623, "text": "This package will extract the base form of the word depending upon whether it is used as a noun or as a verb. The following command can be used to import this package −" }, { "code": null, "e": 8833, "s": 8792, "text": "from nltk.stem import WordNetLemmatizer\n" }, { "code": null, "e": 9246, "s": 8833, "text": "The identification of parts of speech (POS) and short phrases can be done with the help of chunking. It is one of the important processes in natural language processing. As we are aware about the process of tokenization for the creation of tokens, chunking actually is to do the labeling of those tokens. In other words, we can say that we can get the structure of the sentence with the help of chunking process." }, { "code": null, "e": 9420, "s": 9246, "text": "In the following example, we will implement Noun-Phrase chunking, a category of chunking which will find the noun phrase chunks in the sentence, by using NLTK Python module." }, { "code": null, "e": 9485, "s": 9420, "text": "Consider the following steps to implement noun-phrase chunking −" }, { "code": null, "e": 9518, "s": 9485, "text": "Step 1: Chunk grammar definition" }, { "code": null, "e": 9632, "s": 9518, "text": "In this step, we need to define the grammar for chunking. It would consist of the rules, which we need to follow." }, { "code": null, "e": 9662, "s": 9632, "text": "Step 2: Chunk parser creation" }, { "code": null, "e": 9750, "s": 9662, "text": "Next, we need to create a chunk parser. It would parse the grammar and give the output." }, { "code": null, "e": 9769, "s": 9750, "text": "Step 3: The Output" }, { "code": null, "e": 9824, "s": 9769, "text": "In this step, we will get the output in a tree format." }, { "code": null, "e": 9866, "s": 9824, "text": "Start by importing the the NLTK package −" }, { "code": null, "e": 9879, "s": 9866, "text": "import nltk\n" }, { "code": null, "e": 9916, "s": 9879, "text": "Now, we need to define the sentence." }, { "code": null, "e": 9922, "s": 9916, "text": "Here," }, { "code": null, "e": 9944, "s": 9922, "text": "DT is the determinant" }, { "code": null, "e": 9966, "s": 9944, "text": "DT is the determinant" }, { "code": null, "e": 9982, "s": 9966, "text": "VBP is the verb" }, { "code": null, "e": 9998, "s": 9982, "text": "VBP is the verb" }, { "code": null, "e": 10018, "s": 9998, "text": "JJ is the adjective" }, { "code": null, "e": 10038, "s": 10018, "text": "JJ is the adjective" }, { "code": null, "e": 10060, "s": 10038, "text": "IN is the preposition" }, { "code": null, "e": 10082, "s": 10060, "text": "IN is the preposition" }, { "code": null, "e": 10097, "s": 10082, "text": "NN is the noun" }, { "code": null, "e": 10112, "s": 10097, "text": "NN is the noun" }, { "code": null, "e": 10244, "s": 10112, "text": "sentence = [(\"a\", \"DT\"),(\"clever\",\"JJ\"),(\"fox\",\"NN\"),(\"was\",\"VBP\"),\n (\"jumping\",\"VBP\"),(\"over\",\"IN\"),(\"the\",\"DT\"),(\"wall\",\"NN\")]\n" }, { "code": null, "e": 10313, "s": 10244, "text": "Next, the grammar should be given in the form of regular expression." }, { "code": null, "e": 10346, "s": 10313, "text": "grammar = \"NP:{<DT>?<JJ>*<NN>}\"\n" }, { "code": null, "e": 10403, "s": 10346, "text": "Now, we need to define a parser for parsing the grammar." }, { "code": null, "e": 10449, "s": 10403, "text": "parser_chunking = nltk.RegexpParser(grammar)\n" }, { "code": null, "e": 10502, "s": 10449, "text": "Now, the parser will parse the sentence as follows −" }, { "code": null, "e": 10535, "s": 10502, "text": "parser_chunking.parse(sentence)\n" }, { "code": null, "e": 10589, "s": 10535, "text": "Next, the output will be in the variable as follows:-" }, { "code": null, "e": 10631, "s": 10589, "text": "Output = parser_chunking.parse(sentence)\n" }, { "code": null, "e": 10709, "s": 10631, "text": "Now, the following code will help you draw your output in the form of a tree." }, { "code": null, "e": 10724, "s": 10709, "text": "output.draw()\n" }, { "code": null, "e": 10759, "s": 10724, "text": "\n 59 Lectures \n 2.5 hours \n" }, { "code": null, "e": 10770, "s": 10759, "text": " Mike West" }, { "code": null, "e": 10803, "s": 10770, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 10823, "s": 10803, "text": " Pranjal Srivastava" }, { "code": null, "e": 10855, "s": 10823, "text": "\n 6 Lectures \n 1 hours \n" }, { "code": null, "e": 10876, "s": 10855, "text": " Prabh Kirpa Classes" }, { "code": null, "e": 10909, "s": 10876, "text": "\n 12 Lectures \n 1 hours \n" }, { "code": null, "e": 10932, "s": 10909, "text": " Stone River ELearning" }, { "code": null, "e": 10939, "s": 10932, "text": " Print" }, { "code": null, "e": 10950, "s": 10939, "text": " Add Notes" } ]
Koa.js - Cookies
Cookies are simple, small files/data that are sent to client with a server request and stored on the client side. Every time the user loads the website back, this cookie is sent with the request. This helps keep track of the users actions. There are numerous uses of HTTP Cookies. Session management Personalization(Recommendation systems) User tracking To use cookies with Koa, we have the functions: ctx.cookies.set() and ctx.cookies.get(). To set a new cookie, let’s define a new route in our Koa app. var koa = require('koa'); var router = require('koa-router'); var app = koa(); _.get('/', setACookie); function *setACookie() { this.cookies.set('foo', 'bar', {httpOnly: false}); } var _ = router(); app.use(_.routes()); app.listen(3000); To check if the cookie is set or not, just go to your browser, fire up the console, and enter − console.log(document.cookie); This will produce the following output (you may have more cookies set maybe due to extensions in your browser). "foo = bar" Here is an example of the above. The browser also sends back cookies every time it queries the server. To view a cookie on your server, on the server console in a route, add the following code to that route. console.log('Cookies: foo = ', this.cookies.get('foo')); Next time you send a request to this route, you'll get the following output. Cookies: foo = bar You can add cookies that expire. To add a cookie that expires, just pass an object with the property 'expires' set to the time when you want it to expire. For example, var koa = require('koa'); var router = require('koa-router'); var app = koa(); _.get('/', setACookie); function *setACookie(){ //Expires after 360000 ms from the time it is set. this.cookies.set('name', 'value', { httpOnly: false, expires: 360000 + Date.now() }); } var _ = router(); app.use(_.routes()); app.listen(3000); To unset a cookie, simply set the cookie to an empty string. For example, if you need to clear a cookie named foo, use the following code. var koa = require('koa'); var router = require('koa-router'); var app = koa(); _.get('/', setACookie); function *setACookie(){ //Expires after 360000 ms from the time it is set. this.cookies.set('name', ''); } var _ = router(); app.use(_.routes()); app.listen(3000); This will unset the said cookie. Note that you should leave the HttpOnly option to be true when not using the cookie in the client side code. Print Add Notes Bookmark this page
[ { "code": null, "e": 2387, "s": 2106, "text": "Cookies are simple, small files/data that are sent to client with a server request and stored on the client side. Every time the user loads the website back, this cookie is sent with the request. This helps keep track of the users actions. There are numerous uses of HTTP Cookies." }, { "code": null, "e": 2406, "s": 2387, "text": "Session management" }, { "code": null, "e": 2446, "s": 2406, "text": "Personalization(Recommendation systems)" }, { "code": null, "e": 2460, "s": 2446, "text": "User tracking" }, { "code": null, "e": 2611, "s": 2460, "text": "To use cookies with Koa, we have the functions: ctx.cookies.set() and ctx.cookies.get(). To set a new cookie, let’s define a new route in our Koa app." }, { "code": null, "e": 2856, "s": 2611, "text": "var koa = require('koa');\nvar router = require('koa-router');\nvar app = koa();\n\n_.get('/', setACookie);\n\nfunction *setACookie() {\n this.cookies.set('foo', 'bar', {httpOnly: false});\n}\n\nvar _ = router();\n\napp.use(_.routes());\napp.listen(3000);" }, { "code": null, "e": 2952, "s": 2856, "text": "To check if the cookie is set or not, just go to your browser, fire up the console, and enter −" }, { "code": null, "e": 2983, "s": 2952, "text": "console.log(document.cookie);\n" }, { "code": null, "e": 3095, "s": 2983, "text": "This will produce the following output (you may have more cookies set maybe due to extensions in your browser)." }, { "code": null, "e": 3108, "s": 3095, "text": "\"foo = bar\"\n" }, { "code": null, "e": 3141, "s": 3108, "text": "Here is an example of the above." }, { "code": null, "e": 3316, "s": 3141, "text": "The browser also sends back cookies every time it queries the server. To view a cookie on your server, on the server console in a route, add the following code to that route." }, { "code": null, "e": 3374, "s": 3316, "text": "console.log('Cookies: foo = ', this.cookies.get('foo'));\n" }, { "code": null, "e": 3451, "s": 3374, "text": "Next time you send a request to this route, you'll get the following output." }, { "code": null, "e": 3471, "s": 3451, "text": "Cookies: foo = bar\n" }, { "code": null, "e": 3639, "s": 3471, "text": "You can add cookies that expire. To add a cookie that expires, just pass an object with the property 'expires' set to the time when you want it to expire. For example," }, { "code": null, "e": 3977, "s": 3639, "text": "var koa = require('koa');\nvar router = require('koa-router');\nvar app = koa();\n\n_.get('/', setACookie);\n\nfunction *setACookie(){\n //Expires after 360000 ms from the time it is set.\n\tthis.cookies.set('name', 'value', { \n httpOnly: false, expires: 360000 + Date.now() });\n}\n\nvar _ = router();\n\napp.use(_.routes());\napp.listen(3000);" }, { "code": null, "e": 4116, "s": 3977, "text": "To unset a cookie, simply set the cookie to an empty string. For example, if you need to clear a cookie named foo, use the following code." }, { "code": null, "e": 4393, "s": 4116, "text": "var koa = require('koa');\nvar router = require('koa-router');\nvar app = koa();\n\n_.get('/', setACookie);\n\nfunction *setACookie(){\n //Expires after 360000 ms from the time it is set.\n this.cookies.set('name', '');\n}\n\nvar _ = router();\n\napp.use(_.routes());\napp.listen(3000);" }, { "code": null, "e": 4535, "s": 4393, "text": "This will unset the said cookie. Note that you should leave the HttpOnly option to be true when not using the cookie in the client side code." }, { "code": null, "e": 4542, "s": 4535, "text": " Print" }, { "code": null, "e": 4553, "s": 4542, "text": " Add Notes" } ]
How to convert XML to Json and Json back to XML using Newtonsoft.json?
Json.NET supports converting JSON to XML and vice versa using the XmlNodeConverter. Elements, attributes, text, comments, character data, processing instructions, namespaces, and the XML declaration are all preserved when converting between the two The JsonConvert has two helper methods for converting between JSON and XML. The first is SerializeXmlNode(). This method takes an XmlNode and serializes it to JSON text. The second helper method on JsonConvert is DeserializeXmlNode(). This method takes JSON text and deserializes it into an XmlNode. static void Main(string[] args) { string xml = @"Alanhttp://www.google1.com Admin1"; XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); string json = JsonConvert.SerializeXmlNode(doc); Console.WriteLine(json); Console.ReadLine(); } {"person":{"@id":"1","name":"Alan","url":"http://www.google1.com","role":"Admin1"}} static void Main(string[] args) { string json = @"{ '?xml': { '@version': '1.0', '@standalone': 'no' }, 'root': { 'person': [ { '@id': '1', 'name': 'Alan', 'url': 'http://www.google1.com' }, { '@id': '2', 'name': 'Louis', 'url': 'http://www.yahoo1.com' } ] } }"; XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json); Console.WriteLine(json); Console.ReadLine(); } '?xml': { '@version': '1.0', '@standalone': 'no' }, 'root': { 'person': [ { '@id': '1', 'name': 'Alan', 'url': 'http://www.google1.com' }, { '@id': '2', 'name': 'Louis', 'url': 'http://www.yahoo1.com' } ] }
[ { "code": null, "e": 1146, "s": 1062, "text": "Json.NET supports converting JSON to XML and vice versa using the XmlNodeConverter." }, { "code": null, "e": 1311, "s": 1146, "text": "Elements, attributes, text, comments, character data, processing instructions, namespaces, and the XML declaration are all preserved when converting between the two" }, { "code": null, "e": 1481, "s": 1311, "text": "The JsonConvert has two helper methods for converting between JSON and XML. The first is SerializeXmlNode(). This method takes an XmlNode and serializes it to JSON text." }, { "code": null, "e": 1611, "s": 1481, "text": "The second helper method on JsonConvert is DeserializeXmlNode(). This method takes JSON text and deserializes it into an XmlNode." }, { "code": null, "e": 1865, "s": 1611, "text": "static void Main(string[] args) {\n string xml = @\"Alanhttp://www.google1.com Admin1\";\n XmlDocument doc = new XmlDocument();\n doc.LoadXml(xml);\n string json = JsonConvert.SerializeXmlNode(doc);\n Console.WriteLine(json);\n Console.ReadLine();\n}" }, { "code": null, "e": 1949, "s": 1865, "text": "{\"person\":{\"@id\":\"1\",\"name\":\"Alan\",\"url\":\"http://www.google1.com\",\"role\":\"Admin1\"}}" }, { "code": null, "e": 2523, "s": 1949, "text": "static void Main(string[] args) {\n string json = @\"{\n '?xml': {\n '@version': '1.0',\n '@standalone': 'no'\n },\n 'root': {\n 'person': [\n {\n '@id': '1',\n 'name': 'Alan',\n 'url': 'http://www.google1.com'\n },\n {\n '@id': '2',\n 'name': 'Louis',\n 'url': 'http://www.yahoo1.com'\n }\n ]\n }\n }\";\n XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);\n Console.WriteLine(json);\n Console.ReadLine();\n}" }, { "code": null, "e": 2802, "s": 2523, "text": "'?xml': {\n '@version': '1.0',\n '@standalone': 'no'\n},\n'root': {\n 'person': [\n {\n '@id': '1',\n 'name': 'Alan',\n 'url': 'http://www.google1.com'\n },\n {\n '@id': '2',\n 'name': 'Louis',\n 'url': 'http://www.yahoo1.com'\n }\n ]\n}" } ]
Coarsened Exact Matching in R. Causal Inference with MatchIt | by Zolzaya Luvsandorj | Towards Data Science
Haven’t we all heard the phrase ‘Correlation doesn’t imply causation’ and wondered ‘Then, what does’? Well, causal inference. Causal inference allows us to make conclusions about causal impact which can empower important decisions and provide valuable data-driven insights. Therefore, knowing the basics of causal inference is a great investment for data scientists and analysts. Coarsened Exact Matching (CEM) is a simple and intuitive way to conduct a causal inference from an observational data. This post shows the basic intuition behind CEM with an example using MatchIt library in R. Imagine we wanted to understand the causal impact of a treatment on an outcome of interest. The simplest thing we could do is to compare the average outcome by the treated vs untreated groups. However, this comparison may not give us an accurate estimate because the profile of treated and untreated groups tend to be not comparable even in the absence of the treatment. One way to get around this issue is try to make the two groups comparable. This is where matching techniques such as CEM come in. Before we start discussing CEM, let’s start with a matching technique called Exact Matching (EM). For EM, we match treated and untreated records that share the exact same values in their covariates. In other words, these matched records will have identical characteristics except for their treatment status. Once we have done all possible matches and discarded the unmatched records, then the treated vs untreated groups in the matched data will now be more comparable and we can analyse the difference in the group means to infer the causal impact. However, many records can be excluded from the analysis due to not having a match when doing EM. For instance, it will be very hard to find an exact match if you have many numerical covariates. This is where CEM provides a great alternative. When doing CEM, there are three mains steps: Coarsen the data to reduce the level of granularity. This means binning numerical values and/or grouping categorical values.Apply an exact matching on the coarsened data to find comparable control and treatment groups. This means finding all combinations of the covariates that have at least one control and one treatment record and keep records that belong to the combinations and drop the rest. Each combination is referred to as stratum.Estimate the causal impact using the matched data. Coarsen the data to reduce the level of granularity. This means binning numerical values and/or grouping categorical values. Apply an exact matching on the coarsened data to find comparable control and treatment groups. This means finding all combinations of the covariates that have at least one control and one treatment record and keep records that belong to the combinations and drop the rest. Each combination is referred to as stratum. Estimate the causal impact using the matched data. Having learned the basic intuition behind CEM, we can see how informative its name is. Let’s look at a simple example to better understand the technique. Let’s import necessary libraries and load dataset. We will use a small subset of Lalonde dataset to keep things manageable and easy to monitor. library("dplyr")library("MatchIt")library("lmtest")library("sandwich")options(scipen = 100, digits=4)# Prepare sample data --------------------data("lalonde")set.seed(42)(df <- lalonde %>% select(treat, educ, race, re78) %>% sample_n(30)) We have the following variables for 30 randomly selected records:◼️ Covariates: educ for years of schooling and race◼️ Treatment: treat for treatment status◼️ Outcome: re78 for real earnings in 1978Let’s assume we wanted to understand the causal impact of treat on re78. We can perform CEM with matchit by specifying method = 'cem’: # Perform CEM --------------------matching1 <- matchit(treat ~ educ + race, data = df, method = 'cem', estimand = 'ATE')summary(matching1, un=FALSE) We can see that 22 control records were available but only 5 of them were matched and the remaining 17 were unmatched and are going to be dropped from the analysis. The effective sample size for the matched records (Matched (ESS)) was 4.91 for the control group. The same summary is also available for the treatment group. Now, let’s look at the matched data for the 12 matched records: # Extract matched data --------------------(matched_df1 <- match.data(matching1) %>% arrange(subclass, treat)) There are 3 stratums shown by subclass. While we don’t see the coarsened data here, we can roughly guess the level of coarsening from the original values. For instance, subclass 3 seems to contain records with 9–10 years of education and black race. We can see that weights are added for each record. Let’s understand how these weights are calculated. Each stratum has two weights: one weight for the treatment records in the stratum and the other for the control records. When calculating weights, we want to ensure two things:◼️ The proportion of treatment and control groups at an overall level are maintained within each stratum after weighting: ◼️ Weighted counts equals to the unweighted count within stratum: This formula can be rearranged and simplified to the following depending on the type of estimand we are interested in: 🔷 Average treatment effect on the treated (ATT) - Treatment records are unweighted (i.e. weight of 1) and control records get weighted: 🔷 Average treatment effect on the control (ATC) - The same logic is true for ATC. Control records are unweighted and treatment records are weighted: 🔷 Average treatment effect (ATE) - Both groups are weighted: If you want to learn about ATT, ATC, ATE, check out section 1.5 in this post. Earlier we specified that we are interested to know ATE. Using the formula, let’s find the weight for subclass 1 as an example: We just calculated the weights for records PSID376 and NSW153 ourselves to get the same weights that the function returned. If you are keen, calculate the weights for the other two classes to consolidate your understanding. We have seen Matched (ESS) earlier. In case you are interested in finding out how it is calculated, here’s the formula: As an example, let’s calculate ESS for the matched control group: Having matched the records, it’s time to look at the estimated ATE: # Estimate causal impact - look at ATE --------------------model1 <- lm(re78 ~ treat, data = matched_df1, weights = weights)coeftest(model1, vcov. = vcovCL, cluster = ~subclass) Here, we can see the estimate of 4907 and its statistical significance. This estimate is the difference between the weighted means between the groups: matched_df1 %>% group_by(treat) %>% summarise(w_mean = weighted.mean(re78, weights)) We can also check out the confidence interval of the estimate: coefci(model1, vcov. = vcovCL, cluster = ~subclass) The 95% confidence interval is -1073 to 10887. These outputs suggest that treatment doesn’t have statistically significant impact on the output. This is not too surprising as we are working with very small toy dataset. So far we have let the function use its default level of coarsening: binning numerical variables using Sturges method and keeping the categorical variables as is. However, in practice, it would be useful if we could control the level of coarsening. We will now learn to use custom cut points for numerical variables and custom groupings for categorical variables. While applying CEM, some records are dropped out in order to achieve balance (i.e. make groups comparable), but dropping too many records is not desirable. In our first matching, more than half of the records (i.e. 18 out of 30) were dropped out. Let’s try to reduce the number of excluded records while trying to map similar records in each stratum. # Perform CEM with custom coarsening --------------------cutpoints <- list(educ = c(8.5, 10.5))grouping <- list(race = list(c("white", "black"), c("hispan")))matching2 <- matchit(treat ~ educ + race, data = df, method = 'cem', estimand = 'ATE', cutpoints=cutpoints, grouping=grouping)summary(matching2, un=FALSE) We used two cut off points to create three bins for educ and grouped non-Hispanic races together. By making the data more coarse, we have reduced the number of unmatched records from 18 to 3. However, this comes at a risk of including less similar observations in the same stratum where observations are less comparable. This means we need to find the fine balance between not excluding too many records and not including too dissimilar records in the stratum. Let’s look at the matched data to evaluate how similar the records are in each stratum: # Extract matched data(matched_df2 <- match.data(matching2) %>% arrange(subclass, treat)) Do the records within the subclass look comparable to each other? This is something we need to evaluate and reiterate if necessary until we are satisfied. Let’s imagine we were happy, we can proceed to inspecting the estimate: # Estimate causal impact - look at ATE --------------------model2 <- lm(re78 ~ treat, data = matched_df2, weights = weights)coeftest(model2, vcov. = vcovCL, cluster = ~subclass) coefci(model2, vcov. = vcovCL, cluster = ~subclass) After looking at this output, conclusions from the previous analysis remain unchanged. In this introductory post, we have learned the basics of CEM: how the algorithm works, how to control the level of coarsening and how to analyse the causal impact. For keen learners, this and this are awesome additional resources to look into. I hope you get to use this technique to provide valuable insights to your stakeholders. ✨ Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me. Thank you for reading this article. If you are interested, here are links to some of my other posts: ◼️ Propensity score matching (Causal inference)◼️ Explaining Scikit-learn models with SHAP◼️️ K-Nearest Neighbours explained◼️️ Logistic regression explained◼️️ Comparing Random Forest and Gradient Boosting◼️️ How are decision trees built?◼️️ Pipeline, ColumnTransformer and FeatureUnion explained Bye for now 🏃 💨
[ { "code": null, "e": 761, "s": 171, "text": "Haven’t we all heard the phrase ‘Correlation doesn’t imply causation’ and wondered ‘Then, what does’? Well, causal inference. Causal inference allows us to make conclusions about causal impact which can empower important decisions and provide valuable data-driven insights. Therefore, knowing the basics of causal inference is a great investment for data scientists and analysts. Coarsened Exact Matching (CEM) is a simple and intuitive way to conduct a causal inference from an observational data. This post shows the basic intuition behind CEM with an example using MatchIt library in R." }, { "code": null, "e": 1262, "s": 761, "text": "Imagine we wanted to understand the causal impact of a treatment on an outcome of interest. The simplest thing we could do is to compare the average outcome by the treated vs untreated groups. However, this comparison may not give us an accurate estimate because the profile of treated and untreated groups tend to be not comparable even in the absence of the treatment. One way to get around this issue is try to make the two groups comparable. This is where matching techniques such as CEM come in." }, { "code": null, "e": 1812, "s": 1262, "text": "Before we start discussing CEM, let’s start with a matching technique called Exact Matching (EM). For EM, we match treated and untreated records that share the exact same values in their covariates. In other words, these matched records will have identical characteristics except for their treatment status. Once we have done all possible matches and discarded the unmatched records, then the treated vs untreated groups in the matched data will now be more comparable and we can analyse the difference in the group means to infer the causal impact." }, { "code": null, "e": 2099, "s": 1812, "text": "However, many records can be excluded from the analysis due to not having a match when doing EM. For instance, it will be very hard to find an exact match if you have many numerical covariates. This is where CEM provides a great alternative. When doing CEM, there are three mains steps:" }, { "code": null, "e": 2590, "s": 2099, "text": "Coarsen the data to reduce the level of granularity. This means binning numerical values and/or grouping categorical values.Apply an exact matching on the coarsened data to find comparable control and treatment groups. This means finding all combinations of the covariates that have at least one control and one treatment record and keep records that belong to the combinations and drop the rest. Each combination is referred to as stratum.Estimate the causal impact using the matched data." }, { "code": null, "e": 2715, "s": 2590, "text": "Coarsen the data to reduce the level of granularity. This means binning numerical values and/or grouping categorical values." }, { "code": null, "e": 3032, "s": 2715, "text": "Apply an exact matching on the coarsened data to find comparable control and treatment groups. This means finding all combinations of the covariates that have at least one control and one treatment record and keep records that belong to the combinations and drop the rest. Each combination is referred to as stratum." }, { "code": null, "e": 3083, "s": 3032, "text": "Estimate the causal impact using the matched data." }, { "code": null, "e": 3237, "s": 3083, "text": "Having learned the basic intuition behind CEM, we can see how informative its name is. Let’s look at a simple example to better understand the technique." }, { "code": null, "e": 3381, "s": 3237, "text": "Let’s import necessary libraries and load dataset. We will use a small subset of Lalonde dataset to keep things manageable and easy to monitor." }, { "code": null, "e": 3628, "s": 3381, "text": "library(\"dplyr\")library(\"MatchIt\")library(\"lmtest\")library(\"sandwich\")options(scipen = 100, digits=4)# Prepare sample data --------------------data(\"lalonde\")set.seed(42)(df <- lalonde %>% select(treat, educ, race, re78) %>% sample_n(30))" }, { "code": null, "e": 3899, "s": 3628, "text": "We have the following variables for 30 randomly selected records:◼️ Covariates: educ for years of schooling and race◼️ Treatment: treat for treatment status◼️ Outcome: re78 for real earnings in 1978Let’s assume we wanted to understand the causal impact of treat on re78." }, { "code": null, "e": 3961, "s": 3899, "text": "We can perform CEM with matchit by specifying method = 'cem’:" }, { "code": null, "e": 4131, "s": 3961, "text": "# Perform CEM --------------------matching1 <- matchit(treat ~ educ + race, data = df, method = 'cem', estimand = 'ATE')summary(matching1, un=FALSE)" }, { "code": null, "e": 4454, "s": 4131, "text": "We can see that 22 control records were available but only 5 of them were matched and the remaining 17 were unmatched and are going to be dropped from the analysis. The effective sample size for the matched records (Matched (ESS)) was 4.91 for the control group. The same summary is also available for the treatment group." }, { "code": null, "e": 4518, "s": 4454, "text": "Now, let’s look at the matched data for the 12 matched records:" }, { "code": null, "e": 4629, "s": 4518, "text": "# Extract matched data --------------------(matched_df1 <- match.data(matching1) %>% arrange(subclass, treat))" }, { "code": null, "e": 4981, "s": 4629, "text": "There are 3 stratums shown by subclass. While we don’t see the coarsened data here, we can roughly guess the level of coarsening from the original values. For instance, subclass 3 seems to contain records with 9–10 years of education and black race. We can see that weights are added for each record. Let’s understand how these weights are calculated." }, { "code": null, "e": 5279, "s": 4981, "text": "Each stratum has two weights: one weight for the treatment records in the stratum and the other for the control records. When calculating weights, we want to ensure two things:◼️ The proportion of treatment and control groups at an overall level are maintained within each stratum after weighting:" }, { "code": null, "e": 5345, "s": 5279, "text": "◼️ Weighted counts equals to the unweighted count within stratum:" }, { "code": null, "e": 5464, "s": 5345, "text": "This formula can be rearranged and simplified to the following depending on the type of estimand we are interested in:" }, { "code": null, "e": 5600, "s": 5464, "text": "🔷 Average treatment effect on the treated (ATT) - Treatment records are unweighted (i.e. weight of 1) and control records get weighted:" }, { "code": null, "e": 5749, "s": 5600, "text": "🔷 Average treatment effect on the control (ATC) - The same logic is true for ATC. Control records are unweighted and treatment records are weighted:" }, { "code": null, "e": 5810, "s": 5749, "text": "🔷 Average treatment effect (ATE) - Both groups are weighted:" }, { "code": null, "e": 5888, "s": 5810, "text": "If you want to learn about ATT, ATC, ATE, check out section 1.5 in this post." }, { "code": null, "e": 6016, "s": 5888, "text": "Earlier we specified that we are interested to know ATE. Using the formula, let’s find the weight for subclass 1 as an example:" }, { "code": null, "e": 6240, "s": 6016, "text": "We just calculated the weights for records PSID376 and NSW153 ourselves to get the same weights that the function returned. If you are keen, calculate the weights for the other two classes to consolidate your understanding." }, { "code": null, "e": 6360, "s": 6240, "text": "We have seen Matched (ESS) earlier. In case you are interested in finding out how it is calculated, here’s the formula:" }, { "code": null, "e": 6426, "s": 6360, "text": "As an example, let’s calculate ESS for the matched control group:" }, { "code": null, "e": 6494, "s": 6426, "text": "Having matched the records, it’s time to look at the estimated ATE:" }, { "code": null, "e": 6672, "s": 6494, "text": "# Estimate causal impact - look at ATE --------------------model1 <- lm(re78 ~ treat, data = matched_df1, weights = weights)coeftest(model1, vcov. = vcovCL, cluster = ~subclass)" }, { "code": null, "e": 6823, "s": 6672, "text": "Here, we can see the estimate of 4907 and its statistical significance. This estimate is the difference between the weighted means between the groups:" }, { "code": null, "e": 6909, "s": 6823, "text": "matched_df1 %>% group_by(treat) %>% summarise(w_mean = weighted.mean(re78, weights))" }, { "code": null, "e": 6972, "s": 6909, "text": "We can also check out the confidence interval of the estimate:" }, { "code": null, "e": 7024, "s": 6972, "text": "coefci(model1, vcov. = vcovCL, cluster = ~subclass)" }, { "code": null, "e": 7243, "s": 7024, "text": "The 95% confidence interval is -1073 to 10887. These outputs suggest that treatment doesn’t have statistically significant impact on the output. This is not too surprising as we are working with very small toy dataset." }, { "code": null, "e": 7607, "s": 7243, "text": "So far we have let the function use its default level of coarsening: binning numerical variables using Sturges method and keeping the categorical variables as is. However, in practice, it would be useful if we could control the level of coarsening. We will now learn to use custom cut points for numerical variables and custom groupings for categorical variables." }, { "code": null, "e": 7958, "s": 7607, "text": "While applying CEM, some records are dropped out in order to achieve balance (i.e. make groups comparable), but dropping too many records is not desirable. In our first matching, more than half of the records (i.e. 18 out of 30) were dropped out. Let’s try to reduce the number of excluded records while trying to map similar records in each stratum." }, { "code": null, "e": 8312, "s": 7958, "text": "# Perform CEM with custom coarsening --------------------cutpoints <- list(educ = c(8.5, 10.5))grouping <- list(race = list(c(\"white\", \"black\"), c(\"hispan\")))matching2 <- matchit(treat ~ educ + race, data = df, method = 'cem', estimand = 'ATE', cutpoints=cutpoints, grouping=grouping)summary(matching2, un=FALSE)" }, { "code": null, "e": 8861, "s": 8312, "text": "We used two cut off points to create three bins for educ and grouped non-Hispanic races together. By making the data more coarse, we have reduced the number of unmatched records from 18 to 3. However, this comes at a risk of including less similar observations in the same stratum where observations are less comparable. This means we need to find the fine balance between not excluding too many records and not including too dissimilar records in the stratum. Let’s look at the matched data to evaluate how similar the records are in each stratum:" }, { "code": null, "e": 8951, "s": 8861, "text": "# Extract matched data(matched_df2 <- match.data(matching2) %>% arrange(subclass, treat))" }, { "code": null, "e": 9178, "s": 8951, "text": "Do the records within the subclass look comparable to each other? This is something we need to evaluate and reiterate if necessary until we are satisfied. Let’s imagine we were happy, we can proceed to inspecting the estimate:" }, { "code": null, "e": 9356, "s": 9178, "text": "# Estimate causal impact - look at ATE --------------------model2 <- lm(re78 ~ treat, data = matched_df2, weights = weights)coeftest(model2, vcov. = vcovCL, cluster = ~subclass)" }, { "code": null, "e": 9408, "s": 9356, "text": "coefci(model2, vcov. = vcovCL, cluster = ~subclass)" }, { "code": null, "e": 9495, "s": 9408, "text": "After looking at this output, conclusions from the previous analysis remain unchanged." }, { "code": null, "e": 9829, "s": 9495, "text": "In this introductory post, we have learned the basics of CEM: how the algorithm works, how to control the level of coarsening and how to analyse the causal impact. For keen learners, this and this are awesome additional resources to look into. I hope you get to use this technique to provide valuable insights to your stakeholders. ✨" }, { "code": null, "e": 10053, "s": 9829, "text": "Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me." }, { "code": null, "e": 10154, "s": 10053, "text": "Thank you for reading this article. If you are interested, here are links to some of my other posts:" }, { "code": null, "e": 10452, "s": 10154, "text": "◼️ Propensity score matching (Causal inference)◼️ Explaining Scikit-learn models with SHAP◼️️ K-Nearest Neighbours explained◼️️ Logistic regression explained◼️️ Comparing Random Forest and Gradient Boosting◼️️ How are decision trees built?◼️️ Pipeline, ColumnTransformer and FeatureUnion explained" } ]
MariaDB - Indexes & Statistics Tables
Indexes are tools for accelerating record retrieval. An index spawns an entry for each value within an indexed column. There are four types of indexes − Primary (one record represents all records) Primary (one record represents all records) Unique (one record represents multiple records) Unique (one record represents multiple records) Plain Plain Full-Text (permits many options in text searches). Full-Text (permits many options in text searches). The terms “key” and “index” are identical in this usage. Indexes associate with one or more columns, and support rapid searches and efficient record organization. When creating an index, consider which columns are frequently used in your queries. Then create one or multiple indexes on them. In addition, view indexes as essentially tables of primary keys. Though indexes accelerate searches or SELECT statements, they make insertions and updates drag due to performing the operations on both the tables and the indexes. You can create an index through a CREATE TABLE...INDEX statement or a CREATE INDEX statement. The best option supporting readability, maintenance, and best practices is CREATE INDEX. Review the general syntax of Index given below − CREATE [UNIQUE or FULLTEXT or...] INDEX index_name ON table_name column; Review an example of its use − CREATE UNIQUE INDEX top_sellers ON products_tbl product; You can drop an index with DROP INDEX or ALTER TABLE...DROP. The best option supporting readability, maintenance, and best practices is DROP INDEX. Review the general syntax of Drop Index given below − DROP INDEX index_name ON table_name; Review an example of its use − DROP INDEX top_sellers ON product_tbl; Rename an index with the ALTER TABLE statement. Review its general syntax given below − ALTER TABLE table_name DROP INDEX index_name, ADD INDEX new_index_name; Review an example of its use − ALTER TABLE products_tbl DROP INDEX top_sellers, ADD INDEX top_2016sellers; You will need to examine and track all indexes. Use SHOW INDEX to list all existing indexes associated with a given table. You can set the format of the displayed content by using an option such as “\G”, which specifies a vertical format. Review the following example − mysql > SHOW INDEX FROM products_tbl\G Indexes are used heavily to optimize queries given the faster access to records, and the statistics provided. However, many users find index maintenance cumbersome. MariaDB 10.0 made storage engine independent statistics tables available, which calculate data statistics for every table in every storage engine, and even statistics for columns that are not indexed. Print Add Notes Bookmark this page
[ { "code": null, "e": 2481, "s": 2362, "text": "Indexes are tools for accelerating record retrieval. An index spawns an entry for each value within an indexed column." }, { "code": null, "e": 2515, "s": 2481, "text": "There are four types of indexes −" }, { "code": null, "e": 2559, "s": 2515, "text": "Primary (one record represents all records)" }, { "code": null, "e": 2603, "s": 2559, "text": "Primary (one record represents all records)" }, { "code": null, "e": 2651, "s": 2603, "text": "Unique (one record represents multiple records)" }, { "code": null, "e": 2699, "s": 2651, "text": "Unique (one record represents multiple records)" }, { "code": null, "e": 2705, "s": 2699, "text": "Plain" }, { "code": null, "e": 2711, "s": 2705, "text": "Plain" }, { "code": null, "e": 2762, "s": 2711, "text": "Full-Text (permits many options in text searches)." }, { "code": null, "e": 2813, "s": 2762, "text": "Full-Text (permits many options in text searches)." }, { "code": null, "e": 2870, "s": 2813, "text": "The terms “key” and “index” are identical in this usage." }, { "code": null, "e": 3170, "s": 2870, "text": "Indexes associate with one or more columns, and support rapid searches and efficient record organization. When creating an index, consider which columns are frequently used in your queries. Then create one or multiple indexes on them. In addition, view indexes as essentially tables of primary keys." }, { "code": null, "e": 3334, "s": 3170, "text": "Though indexes accelerate searches or SELECT statements, they make insertions and updates drag due to performing the operations on both the tables and the indexes." }, { "code": null, "e": 3517, "s": 3334, "text": "You can create an index through a CREATE TABLE...INDEX statement or a CREATE INDEX statement. The best option supporting readability, maintenance, and best practices is CREATE INDEX." }, { "code": null, "e": 3566, "s": 3517, "text": "Review the general syntax of Index given below −" }, { "code": null, "e": 3640, "s": 3566, "text": "CREATE [UNIQUE or FULLTEXT or...] INDEX index_name ON table_name column;\n" }, { "code": null, "e": 3671, "s": 3640, "text": "Review an example of its use −" }, { "code": null, "e": 3729, "s": 3671, "text": "CREATE UNIQUE INDEX top_sellers ON products_tbl product;\n" }, { "code": null, "e": 3877, "s": 3729, "text": "You can drop an index with DROP INDEX or ALTER TABLE...DROP. The best option supporting readability, maintenance, and best practices is DROP INDEX." }, { "code": null, "e": 3931, "s": 3877, "text": "Review the general syntax of Drop Index given below −" }, { "code": null, "e": 3969, "s": 3931, "text": "DROP INDEX index_name ON table_name;\n" }, { "code": null, "e": 4000, "s": 3969, "text": "Review an example of its use −" }, { "code": null, "e": 4040, "s": 4000, "text": "DROP INDEX top_sellers ON product_tbl;\n" }, { "code": null, "e": 4128, "s": 4040, "text": "Rename an index with the ALTER TABLE statement. Review its general syntax given below −" }, { "code": null, "e": 4201, "s": 4128, "text": "ALTER TABLE table_name DROP INDEX index_name, ADD INDEX new_index_name;\n" }, { "code": null, "e": 4232, "s": 4201, "text": "Review an example of its use −" }, { "code": null, "e": 4309, "s": 4232, "text": "ALTER TABLE products_tbl DROP INDEX top_sellers, ADD INDEX top_2016sellers;\n" }, { "code": null, "e": 4548, "s": 4309, "text": "You will need to examine and track all indexes. Use SHOW INDEX to list all existing indexes associated with a given table. You can set the format of the displayed content by using an option such as “\\G”, which specifies a vertical format." }, { "code": null, "e": 4579, "s": 4548, "text": "Review the following example −" }, { "code": null, "e": 4619, "s": 4579, "text": "mysql > SHOW INDEX FROM products_tbl\\G\n" }, { "code": null, "e": 4985, "s": 4619, "text": "Indexes are used heavily to optimize queries given the faster access to records, and the statistics provided. However, many users find index maintenance cumbersome. MariaDB 10.0 made storage engine independent statistics tables available, which calculate data statistics for every table in every storage engine, and even statistics for columns that are not indexed." }, { "code": null, "e": 4992, "s": 4985, "text": " Print" }, { "code": null, "e": 5003, "s": 4992, "text": " Add Notes" } ]
C# program to count occurrences of a word in string
Set the string first − string str = "Hello World! Hello!"; Now check the string for the occurrences of a word “Hello’ and loop through − while ((a = str1.IndexOf(pattern, a)) != -1) { a += pattern.Length; count++; } You can try to run the following code to count occurrences of a word in a string. Live Demo using System; class Program { static void Main() { string str = "Hello World! Hello!"; Console.WriteLine("Occurrence:"+Check.CheckOccurrences(str, "Hello")); } } public static class Check { public static int CheckOccurrences(string str1, string pattern) { int count = 0; int a = 0; while ((a = str1.IndexOf(pattern, a)) != -1) { a += pattern.Length; count++; } return count; } } Occurrence:2
[ { "code": null, "e": 1085, "s": 1062, "text": "Set the string first −" }, { "code": null, "e": 1121, "s": 1085, "text": "string str = \"Hello World! Hello!\";" }, { "code": null, "e": 1199, "s": 1121, "text": "Now check the string for the occurrences of a word “Hello’ and loop through −" }, { "code": null, "e": 1284, "s": 1199, "text": "while ((a = str1.IndexOf(pattern, a)) != -1) {\n a += pattern.Length;\n count++;\n}" }, { "code": null, "e": 1366, "s": 1284, "text": "You can try to run the following code to count occurrences of a word in a string." }, { "code": null, "e": 1376, "s": 1366, "text": "Live Demo" }, { "code": null, "e": 1827, "s": 1376, "text": "using System;\nclass Program {\n static void Main() {\n string str = \"Hello World! Hello!\";\n Console.WriteLine(\"Occurrence:\"+Check.CheckOccurrences(str, \"Hello\"));\n }\n}\npublic static class Check {\n public static int CheckOccurrences(string str1, string pattern) {\n int count = 0;\n int a = 0;\n while ((a = str1.IndexOf(pattern, a)) != -1) {\n a += pattern.Length;\n count++;\n }\n return count;\n }\n}" }, { "code": null, "e": 1840, "s": 1827, "text": "Occurrence:2" } ]
PHP | round( ) Function - GeeksforGeeks
30 Jul, 2021 While dealing with problems which have values consisting of a very high number of decimal digits such as (121.76763527823) we often come up with a problem of rounding them up. Rounding them up manually can be a very time consuming and erroneous practice. In place of that, an inbuilt function of PHP i.e round() can be used. The round() function in PHP is used to round a floating-point number. It can be used to define a specific precision value which rounds number according to that precision value.Precision can be also negative or zero. The round() function in PHP has 3 parameters which are number, precision, and mode among which the latter two are optional parameters.The round() function returns the rounded value of the argument passed. Syntax: float round($number, $precision, $mode); Parameters: It accepts three parameters out of which one is compulsory and two are optional. All of these parameters are described below: $number: It is the number which you want to round.$precision: It is an optional parameter. It specifies the number of decimal digits to round to. The default value of this parameter is zero.$mode: It is an optional parameter. It specifies a constant to specify the rounding mode. The constant can be one of the following: PHP_ROUND_HALF_UP: This mode tells to round up the number specified by parameter $number by precision specified by parameter $precision away from zero.PHP_ROUND_HALF_DOWN: This mode tells to round up the number specified by parameter $number by precision specified by parameter $precision towards zero.PHP_ROUND_HALF_EVEN: This mode tells to round up the number specified by parameter $number by precision specified by parameter $precision towards nearest even value.PHP_ROUND_HALF_ODD: This mode tells to round up the number specified by parameter $number by precision specified by parameter $precision towards nearest odd value. $number: It is the number which you want to round. $precision: It is an optional parameter. It specifies the number of decimal digits to round to. The default value of this parameter is zero. $mode: It is an optional parameter. It specifies a constant to specify the rounding mode. The constant can be one of the following: PHP_ROUND_HALF_UP: This mode tells to round up the number specified by parameter $number by precision specified by parameter $precision away from zero.PHP_ROUND_HALF_DOWN: This mode tells to round up the number specified by parameter $number by precision specified by parameter $precision towards zero.PHP_ROUND_HALF_EVEN: This mode tells to round up the number specified by parameter $number by precision specified by parameter $precision towards nearest even value.PHP_ROUND_HALF_ODD: This mode tells to round up the number specified by parameter $number by precision specified by parameter $precision towards nearest odd value. PHP_ROUND_HALF_UP: This mode tells to round up the number specified by parameter $number by precision specified by parameter $precision away from zero. PHP_ROUND_HALF_DOWN: This mode tells to round up the number specified by parameter $number by precision specified by parameter $precision towards zero. PHP_ROUND_HALF_EVEN: This mode tells to round up the number specified by parameter $number by precision specified by parameter $precision towards nearest even value. PHP_ROUND_HALF_ODD: This mode tells to round up the number specified by parameter $number by precision specified by parameter $precision towards nearest odd value. Return Value: It returns the rounded value. Examples: Input : round(0.70) Output : 1 Input : round(0.708782) Output : 0.71 Input : round(-3.40) Output : -3 Input : round(-3.60) Output : -4 Below programs illustrate the working of round() in PHP: When a parameter is passed with default precision i.e. ‘0’: PHP <?php echo(round(0.70)); ?> Output: 1 When a parameter is passed with a specific precision value: PHP <?php echo(round(0.70878, 2)); ?> Output: 0.71 When a negative value is passed as a parameter: PHP <?php echo(round(-3.40)); ?> Output: -3 Passing parameters with mode: PHP <?php // round to nearest even valueecho(round(7.5,0,PHP_ROUND_HALF_EVEN));echo "\n"; // round to nearest odd valueecho(round(7.5,0,PHP_ROUND_HALF_ODD));echo "\n"; // round towards zeroecho(round(7.5,0,PHP_ROUND_HALF_DOWN));echo "\n"; // round away from zeroecho(round(7.5,0,PHP_ROUND_HALF_UP)); ?> Output: 8 7 7 8 Important Points To Note: round() function is used to round floating-point numbers. A specific precision value can be used to get the desired results. Precision value can also be negative or zero. Reference: http://php.net/manual/en/function.round.php manikarora059 PHP-function PHP-math PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to convert array to string in PHP ? Comparing two dates in PHP How to pass JavaScript variables to PHP ? PHP | Converting string to Date and DateTime How to fetch data from localserver database and display on HTML table using PHP ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24694, "s": 24666, "text": "\n30 Jul, 2021" }, { "code": null, "e": 25440, "s": 24694, "text": "While dealing with problems which have values consisting of a very high number of decimal digits such as (121.76763527823) we often come up with a problem of rounding them up. Rounding them up manually can be a very time consuming and erroneous practice. In place of that, an inbuilt function of PHP i.e round() can be used. The round() function in PHP is used to round a floating-point number. It can be used to define a specific precision value which rounds number according to that precision value.Precision can be also negative or zero. The round() function in PHP has 3 parameters which are number, precision, and mode among which the latter two are optional parameters.The round() function returns the rounded value of the argument passed." }, { "code": null, "e": 25449, "s": 25440, "text": "Syntax: " }, { "code": null, "e": 25490, "s": 25449, "text": "float round($number, $precision, $mode);" }, { "code": null, "e": 25630, "s": 25490, "text": "Parameters: It accepts three parameters out of which one is compulsory and two are optional. All of these parameters are described below: " }, { "code": null, "e": 26583, "s": 25630, "text": "$number: It is the number which you want to round.$precision: It is an optional parameter. It specifies the number of decimal digits to round to. The default value of this parameter is zero.$mode: It is an optional parameter. It specifies a constant to specify the rounding mode. The constant can be one of the following: PHP_ROUND_HALF_UP: This mode tells to round up the number specified by parameter $number by precision specified by parameter $precision away from zero.PHP_ROUND_HALF_DOWN: This mode tells to round up the number specified by parameter $number by precision specified by parameter $precision towards zero.PHP_ROUND_HALF_EVEN: This mode tells to round up the number specified by parameter $number by precision specified by parameter $precision towards nearest even value.PHP_ROUND_HALF_ODD: This mode tells to round up the number specified by parameter $number by precision specified by parameter $precision towards nearest odd value." }, { "code": null, "e": 26634, "s": 26583, "text": "$number: It is the number which you want to round." }, { "code": null, "e": 26775, "s": 26634, "text": "$precision: It is an optional parameter. It specifies the number of decimal digits to round to. The default value of this parameter is zero." }, { "code": null, "e": 27538, "s": 26775, "text": "$mode: It is an optional parameter. It specifies a constant to specify the rounding mode. The constant can be one of the following: PHP_ROUND_HALF_UP: This mode tells to round up the number specified by parameter $number by precision specified by parameter $precision away from zero.PHP_ROUND_HALF_DOWN: This mode tells to round up the number specified by parameter $number by precision specified by parameter $precision towards zero.PHP_ROUND_HALF_EVEN: This mode tells to round up the number specified by parameter $number by precision specified by parameter $precision towards nearest even value.PHP_ROUND_HALF_ODD: This mode tells to round up the number specified by parameter $number by precision specified by parameter $precision towards nearest odd value." }, { "code": null, "e": 27690, "s": 27538, "text": "PHP_ROUND_HALF_UP: This mode tells to round up the number specified by parameter $number by precision specified by parameter $precision away from zero." }, { "code": null, "e": 27842, "s": 27690, "text": "PHP_ROUND_HALF_DOWN: This mode tells to round up the number specified by parameter $number by precision specified by parameter $precision towards zero." }, { "code": null, "e": 28008, "s": 27842, "text": "PHP_ROUND_HALF_EVEN: This mode tells to round up the number specified by parameter $number by precision specified by parameter $precision towards nearest even value." }, { "code": null, "e": 28172, "s": 28008, "text": "PHP_ROUND_HALF_ODD: This mode tells to round up the number specified by parameter $number by precision specified by parameter $precision towards nearest odd value." }, { "code": null, "e": 28216, "s": 28172, "text": "Return Value: It returns the rounded value." }, { "code": null, "e": 28228, "s": 28216, "text": "Examples: " }, { "code": null, "e": 28366, "s": 28228, "text": "Input : round(0.70)\nOutput : 1\n\nInput : round(0.708782)\nOutput : 0.71\n\nInput : round(-3.40)\nOutput : -3\n\nInput : round(-3.60)\nOutput : -4" }, { "code": null, "e": 28423, "s": 28366, "text": "Below programs illustrate the working of round() in PHP:" }, { "code": null, "e": 28483, "s": 28423, "text": "When a parameter is passed with default precision i.e. ‘0’:" }, { "code": null, "e": 28487, "s": 28483, "text": "PHP" }, { "code": "<?php echo(round(0.70)); ?>", "e": 28515, "s": 28487, "text": null }, { "code": null, "e": 28523, "s": 28515, "text": "Output:" }, { "code": null, "e": 28525, "s": 28523, "text": "1" }, { "code": null, "e": 28585, "s": 28525, "text": "When a parameter is passed with a specific precision value:" }, { "code": null, "e": 28589, "s": 28585, "text": "PHP" }, { "code": "<?php echo(round(0.70878, 2)); ?>", "e": 28623, "s": 28589, "text": null }, { "code": null, "e": 28631, "s": 28623, "text": "Output:" }, { "code": null, "e": 28636, "s": 28631, "text": "0.71" }, { "code": null, "e": 28684, "s": 28636, "text": "When a negative value is passed as a parameter:" }, { "code": null, "e": 28688, "s": 28684, "text": "PHP" }, { "code": "<?php echo(round(-3.40)); ?>", "e": 28717, "s": 28688, "text": null }, { "code": null, "e": 28725, "s": 28717, "text": "Output:" }, { "code": null, "e": 28728, "s": 28725, "text": "-3" }, { "code": null, "e": 28758, "s": 28728, "text": "Passing parameters with mode:" }, { "code": null, "e": 28762, "s": 28758, "text": "PHP" }, { "code": "<?php // round to nearest even valueecho(round(7.5,0,PHP_ROUND_HALF_EVEN));echo \"\\n\"; // round to nearest odd valueecho(round(7.5,0,PHP_ROUND_HALF_ODD));echo \"\\n\"; // round towards zeroecho(round(7.5,0,PHP_ROUND_HALF_DOWN));echo \"\\n\"; // round away from zeroecho(round(7.5,0,PHP_ROUND_HALF_UP)); ?>", "e": 29061, "s": 28762, "text": null }, { "code": null, "e": 29069, "s": 29061, "text": "Output:" }, { "code": null, "e": 29077, "s": 29069, "text": "8\n7\n7\n8" }, { "code": null, "e": 29104, "s": 29077, "text": "Important Points To Note: " }, { "code": null, "e": 29162, "s": 29104, "text": "round() function is used to round floating-point numbers." }, { "code": null, "e": 29229, "s": 29162, "text": "A specific precision value can be used to get the desired results." }, { "code": null, "e": 29275, "s": 29229, "text": "Precision value can also be negative or zero." }, { "code": null, "e": 29331, "s": 29275, "text": "Reference: http://php.net/manual/en/function.round.php " }, { "code": null, "e": 29345, "s": 29331, "text": "manikarora059" }, { "code": null, "e": 29358, "s": 29345, "text": "PHP-function" }, { "code": null, "e": 29367, "s": 29358, "text": "PHP-math" }, { "code": null, "e": 29371, "s": 29367, "text": "PHP" }, { "code": null, "e": 29388, "s": 29371, "text": "Web Technologies" }, { "code": null, "e": 29392, "s": 29388, "text": "PHP" }, { "code": null, "e": 29490, "s": 29392, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29499, "s": 29490, "text": "Comments" }, { "code": null, "e": 29512, "s": 29499, "text": "Old Comments" }, { "code": null, "e": 29552, "s": 29512, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 29579, "s": 29552, "text": "Comparing two dates in PHP" }, { "code": null, "e": 29621, "s": 29579, "text": "How to pass JavaScript variables to PHP ?" }, { "code": null, "e": 29666, "s": 29621, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 29748, "s": 29666, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 29790, "s": 29748, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 29823, "s": 29790, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29885, "s": 29823, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29928, "s": 29885, "text": "How to fetch data from an API in ReactJS ?" } ]
C++ Program to Check if a Point d lies inside or outside a circle defined by Points a, b, c in a Plane
We shall consider a C++ Program to check if a point d lies inside or outside a circle defined by points a, b, c in a plane by using equation s = (x-xt)^2 + (y-yt)^2 – r*r Where, For any point t (xt, yt) on the plane, its position with respect to the circle defined by 3 points (x1, y1), (x2, y2), (x3, y3). for s < 0, t lies inside the circle. For s >0, t lies outside the circle. For s = 0, t lies on the circle. Begin Take the points at input. Declare constant L = 0 and H = 20 Declare the variables of the equation. For generating equation, generate random numbers for coefficient of x and y by using rand at every time of compilation. Calculate the center of the circle. Calculate the radius of the circle. Calculate s. if s < 0, print point lies inside the circle. else if s >0, print point lies outside the circle. else if s = 0, print point lies on the circle. End Live Demo #include<time.h> #include<stdlib.h> #include<iostream> #include<math.h> using namespace std; const int L= 0; const int H = 20; int main(int argc, char **argv) { time_t s; time(&s); srand((unsigned int) s); double x1, x2, y1, y2, x3, y3; double a1, a2, c1, c2, r; x1 = rand() % (H - L+ 1) + L; x2 = rand() % (H - L + 1) + L; x3 = rand() % (H- L + 1) + L; y1 = rand() % (H- L + 1) + L; y2 = rand() % (H- L+ 1) + L; y3 = rand() % (H- L + 1) + L; a1 = (y1 - y2) / (x1 - x2); a2 = (y3 - y2) / (x3 - x2); c1 = ((a1 * a2 * (y3 - y1)) + (a1 * (x2 + x3)) - (a2 * (x1 + x2))) / (2 * (a1 - a2));//calculate center of circle c2 = ((((x1 + x2) / 2) - c1) / (-1 * a1)) + ((y1 + y2) / 2);//calculate center of circle r = sqrt(((x3 - c1) * (x3 - c1)) + ((y3 - c2) * (y3 - c2)));//calcultate radius cout << "The points on the circle are: (" << x1 << ", " << y1 << "), (" << x2 << ", " << y2 << "), (" << x3 << ", " << y3 << ")"; cout << "\nThe center of the circle is (" << c1 << ", " << c2 << ") and radius is " << r; cout << "\nEnter the point : "; int u, v; cin >>u; cin >>v; double s1 = ((u - c1) * (u - c1)) + ((v - c2) * (v - c1)) - (r * r); if (s1 < 0) cout << "\nThe point lies inside the circle"; else if (s1 >0) cout << "\nThe point lies outside the circle"; else cout << "\nThe point lies on the circle"; return 0; } The points on the circle are: (8, 4), (9, 17), (5, 9) The center of the circle is (12.6364, 10.8182) and radius is 7.84983 Enter the point : 7 6 The point lies outside the circle
[ { "code": null, "e": 1203, "s": 1062, "text": "We shall consider a C++ Program to check if a point d lies inside or outside a circle defined by points a, b, c in a plane by using equation" }, { "code": null, "e": 1233, "s": 1203, "text": "s = (x-xt)^2 + (y-yt)^2 – r*r" }, { "code": null, "e": 1369, "s": 1233, "text": "Where, For any point t (xt, yt) on the plane, its position with respect to the circle defined by 3 points (x1, y1), (x2, y2), (x3, y3)." }, { "code": null, "e": 1406, "s": 1369, "text": "for s < 0, t lies inside the circle." }, { "code": null, "e": 1443, "s": 1406, "text": "For s >0, t lies outside the circle." }, { "code": null, "e": 1476, "s": 1443, "text": "For s = 0, t lies on the circle." }, { "code": null, "e": 1973, "s": 1476, "text": "Begin\n Take the points at input.\n Declare constant L = 0 and H = 20\n Declare the variables of the equation.\n For generating equation, generate random numbers for coefficient of x and y by using rand at every time of compilation.\n Calculate the center of the circle.\n Calculate the radius of the circle.\n Calculate s.\n if s < 0, print point lies inside the circle.\n else if s >0, print point lies outside the circle.\n else if s = 0, print point lies on the circle.\nEnd" }, { "code": null, "e": 1984, "s": 1973, "text": " Live Demo" }, { "code": null, "e": 3403, "s": 1984, "text": "#include<time.h>\n#include<stdlib.h>\n#include<iostream>\n#include<math.h>\n\nusing namespace std;\nconst int L= 0;\nconst int H = 20;\n\nint main(int argc, char **argv) {\n time_t s;\n time(&s);\n srand((unsigned int) s);\n\n double x1, x2, y1, y2, x3, y3;\n double a1, a2, c1, c2, r;\n x1 = rand() % (H - L+ 1) + L;\n x2 = rand() % (H - L + 1) + L;\n x3 = rand() % (H- L + 1) + L;\n y1 = rand() % (H- L + 1) + L;\n y2 = rand() % (H- L+ 1) + L;\n y3 = rand() % (H- L + 1) + L;\n a1 = (y1 - y2) / (x1 - x2);\n a2 = (y3 - y2) / (x3 - x2);\n\n c1 = ((a1 * a2 * (y3 - y1)) + (a1 * (x2 + x3)) - (a2 * (x1 + x2))) / (2 * (a1 - a2));//calculate center of circle\n c2 = ((((x1 + x2) / 2) - c1) / (-1 * a1)) + ((y1 + y2) / 2);//calculate center of circle\n r = sqrt(((x3 - c1) * (x3 - c1)) + ((y3 - c2) * (y3 - c2)));//calcultate radius\n cout << \"The points on the circle are: (\" << x1 << \", \" << y1 << \"), (\" << x2 << \", \" << y2 << \"), (\" << x3 << \", \" << y3 << \")\";\n cout << \"\\nThe center of the circle is (\" << c1 << \", \" << c2 << \") and radius is \" << r;\n\n cout << \"\\nEnter the point : \";\n int u, v;\n cin >>u;\n cin >>v;\n\n double s1 = ((u - c1) * (u - c1)) + ((v - c2) * (v - c1)) - (r * r);\n if (s1 < 0)\n cout << \"\\nThe point lies inside the circle\";\n else if (s1 >0)\n cout << \"\\nThe point lies outside the circle\";\n else\n cout << \"\\nThe point lies on the circle\";\n return 0;\n}" }, { "code": null, "e": 3583, "s": 3403, "text": "The points on the circle are: (8, 4), (9, 17), (5, 9)\nThe center of the circle is (12.6364, 10.8182) and radius is 7.84983\nEnter the point : 7\n6\n\nThe point lies outside the circle" } ]
How to shift a graph along the X-axis in matplotlib?
To shift a graph along the X-axis in matplotlib, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Create x and y data points using numpy. Plot the x and y data points for the original curve. Plot the shifted graph, in the range of (1, 1+len(y)) with y data points. Place a legend on the figure. To display the figure, use show() method. import numpy as np import matplotlib.pyplot as plt # Set the figure size plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True # x and y data points x = np.linspace(-5, 5, 100) y = np.sin(x) # Original graph and shifted graph plt.plot(x, y, label='Original Graph') plt.plot(range(1, 1+len(y)), y, label='Shifted Graph') # Place a legend plt.legend(loc='upper right') plt.show() It will produce the following output
[ { "code": null, "e": 1145, "s": 1062, "text": "To shift a graph along the X-axis in matplotlib, we can take the following steps −" }, { "code": null, "e": 1221, "s": 1145, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1261, "s": 1221, "text": "Create x and y data points using numpy." }, { "code": null, "e": 1314, "s": 1261, "text": "Plot the x and y data points for the original curve." }, { "code": null, "e": 1388, "s": 1314, "text": "Plot the shifted graph, in the range of (1, 1+len(y)) with y data points." }, { "code": null, "e": 1418, "s": 1388, "text": "Place a legend on the figure." }, { "code": null, "e": 1460, "s": 1418, "text": "To display the figure, use show() method." }, { "code": null, "e": 1876, "s": 1460, "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n# Set the figure size\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\n# x and y data points\nx = np.linspace(-5, 5, 100)\ny = np.sin(x)\n\n# Original graph and shifted graph\nplt.plot(x, y, label='Original Graph')\nplt.plot(range(1, 1+len(y)), y, label='Shifted Graph')\n\n# Place a legend\nplt.legend(loc='upper right')\n\nplt.show()" }, { "code": null, "e": 1913, "s": 1876, "text": "It will produce the following output" } ]
Desktop Operations in ElectronJS - GeeksforGeeks
29 Sep, 2021 ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime. The electron can interact with the native OS environment such as File System, System Tray, etc. Electron provides us with the built-in Shell Module which helps in managing files and URLs in the native OS environment using their default application. This module provides functions related to Desktop Integrations such as Opening External Links, Creating Shortcuts, Reading Shortcuts, etc. The Shell Module can be used directly in the Main Process and the Renderer Process of the application. This tutorial will demonstrate Desktop Integrations using the Shell Module in Electron. We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system. Project Structure: sample.txt: This is a Sample Text file delete.txt: Sample Text FIle to delete Example: We will start by building the basic Electron Application by following the given steps. Step 1: Navigate to an Empty Directory to setup the project, and run the following command, npm init To generate the package.json file. Install Electron using npm if it is not installed. npm install electron --save-dev This command will also create the package-lock.json file and install the required node_modules dependencies. Once Electron has been successfully installed, Open the package.json file and perform the necessary changes under the “scripts” key. package.json: { "name": "electron-DesktopOperation", "version": "1.0.0", "description": "Desktop Operations in Electron", "main": "main.js", "scripts": { "start": "electron" }, "keywords": [ "electron" ], "author": "Radhesh Khanna", "license": "ISC", "dependencies": { "electron": "^8.2.5" } } Step 2: Create a main.js file according to the project structure. This file is the Main Process and acts as an entry point into the application. Copy the Boilerplate code for the main.js file as given in the following link. We will modify the code to suit our project needs. main.js: Javascript const { app, BrowserWindow } = require('electron') function createWindow() { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('src/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // To stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your app's specific// main process code. You can also put them in separate files and// require them here. Step 3: Create the index.html file within the src directory. We will also copy the boilerplate code for the index.html file from the above-mentioned link. We will modify the code to suit our project needs. index.html: HTML <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial/security#csp-meta-tag --> <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" /></head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. <!-- Adding Individual Renderer Process JS File --> <script src="index.js"></script></body> </html> Output: At this point, our basic Electron Application is set up. To launch the Electron Application, run the Command: npm start Shell Module in Electron: All the Shell modules are explained with the example below: 1. shell.openExternal(url, options): To open External URLs in the systems default manner. We can pass external links or mail ID’s and it will be resolved based on the protocol provided. The shell.OpenExternal(url, options) returns a Promise. It takes in the following parameters, url: String The external URL to be resolved. Maximum of 2081 Characters are allowed in Windows. URL will be resolved based on systems default behavior. options: Object (Optional) It is an Object consisting of the following parameters, activate: Boolean It is supported by macOS only. It is used to bring the opened application to the foreground. Default is set as true. activate: Boolean It is supported by macOS only. It is used to bring the opened application to the foreground. Default is set as true. index.html: Add the following snippet in that file. HTML <br> <h3> Desktop Integrations in Electron using Shell Module </h3> <button id="external"> Open GeeksForGeeks.org in Default Browser </button> <br><br> <button id="mail"> Open GeeksForGeeks in Default Mail </button> index.js: Add the following snippet in that file. Javascript const electron = require('electron');const path = require('path'); // Importing the Shell Module from the electron // in the Renderer Processconst shell = electron.shell; var external = document.getElementById('external');var externalOptions = { // Supported by macOS only activate: true,} external.addEventListener('click', (event) => { // Returns a Promise<void>, Hence we can use // the .then( function() {} ) shell.openExternal( 'https://www.geeksforgeeks.org/', externalOptions) .then(() => { console.log('Link Opened Successfully'); });}); var mail = document.getElementById('mail'); mail.addEventListener('click', (event) => { // Resolving the External URL to the Default Mail Agent // Because we have specified 'mailto' shell.openExternal( 'mailto: https://www.geeksforgeeks.org/', externalOptions) .then(() => { console.log('Link Opened Successfully'); });}); Output: 2. shell.showItemInFolder(path): To resolve the given String file path and show the file in the Windows/File Explorer. If possible, select the file as well. This method does not have any return type. index.html: Add the following snippet in that file. HTML <br><be> <button id="show"> Show sample.txt in File Explorer </button> index.js: Add the following snippet in that file. Javascript var show = document.getElementById('show'); show.addEventListener('click', (event) => { // Providing a dynamic file path to the 'sample.txt' // file in the 'assets' Folder. Using the path Module. // '__dirname' automatically detects current working directory shell.showItemInFolder(path.join(__dirname, '../assets/sample.txt'));}); Output: 3. shell.openItem(path): To resolve the given String file path and open the file in the systems default manner. It returns a Boolean value stating whether the file was successfully opened or not. index.html: Add the following snippet in that file. HTML <br><br> <button id="open">Open sample.txt</button> index.js: Add the following snippet in that file. Javascript var open = document.getElementById('open'); open.addEventListener('click', (event) => { var success = shell.openItem(path.join(__dirname, '../assets/sample.txt')); console.log('File Opened Successfully - ', success);}); Output: 4. shell.beep(): To play the Native OS Sound. This method does not have any return type. In this tutorial, it is used in combination with shell.moveItemToTrash() method. 5. shell.moveItemToTrash(path, deleteFailure): To resolve the given String file path and move the specified file to the Trash/Bin. Returns a Boolean value stating whether the file was successfully moved to the trash or not. The shell.moveItemToTrash(path, delete) returns a Boolean value. It takes in the following parameters, path: String The filepath to be resolved. deleteFailure: Boolean (Optional) It is supported by macOS only. It signifies whether or not to remove the file entirely from the System in case the Trash is disabled or unsupported in the system. index.html: Add the following snippet in that file. HTML <br><br> <button id="delete">Delete delete.txt</button> index.js: Add the following snippet in that file. Javascript var deleteItem = document.getElementById('delete'); deleteItem.addEventListener('click', (event) => { // Play the Native OS Beep Sound shell.beep(); // Returns a Boolean Value var success = shell.moveItemToTrash(path.join(__dirname, '../assets/delete.txt'), true); console.log('File Deleted Successfully - ', success);}); Output: 6. shell.writeShortcutLink(path, operation, options): This operation is supported in Windows only. To resolve the given String path and create/update the Shortcut Link at that path. It returns a Boolean value stating whether the specified operation was successfully performed or not. The shell.writeShortcutLink(path, operations, options) returns a Boolean value. It takes in the following parameters, path: String Defining the path for the shortcut for the Operation to be carried out. operations: String (Optional) Specifies the Operation to be carried out. Default Value of the Operation is create. It can have any of the following values, create: Creates a new Shortcut. Performs Overwrite if necessary.update: Updates the specified properties of an existing Shortcut.replace: Overwrites an existing Shortcut. This operation fails if the Shortcut does not exist. create: Creates a new Shortcut. Performs Overwrite if necessary. update: Updates the specified properties of an existing Shortcut. replace: Overwrites an existing Shortcut. This operation fails if the Shortcut does not exist. Options: It is a shortcutDetails Object consisting of the following parameters, target: String The target File which is supposed to be launched from this shortcut.cwd: String (Optional) Specifies the Current Working Directory. Default value is empty.args: String (Optional) The arguments to be passed and applied to the target file when launched from the shortcut. Default value is empty.description: String (Optional) The Description of the Shortcut. Default value is empty. Value is shown as Tooltip on hovering over the created shortcut.icon: String (Optional) The path to the icon to be used. It can be a .dll or an .exe file. icon property and iconIndex property have to be specified together. Default value of the icon Property is empty which in-turn uses the default target icon or the icon which is supposed to be used as defined in the System. In this tutorial, we have created a shortcut for a .txt file. It has a pre-defined icon as per the System, but we have changed it to the icon of the notepad file by specifying the path of notepad.exe in the System.iconIndex: Number (Optional) The resource ID of icon when the icon property is a .dll or an .exe file. Default value of the iconIndex property is 0. In this tutorial, we will keep the iconIndex property to 0 for the notepad.exe file icon to take effect.appUserModelId: String (Optional) The Application User Model ID. Default value is empty. target: String The target File which is supposed to be launched from this shortcut. cwd: String (Optional) Specifies the Current Working Directory. Default value is empty. args: String (Optional) The arguments to be passed and applied to the target file when launched from the shortcut. Default value is empty. description: String (Optional) The Description of the Shortcut. Default value is empty. Value is shown as Tooltip on hovering over the created shortcut. icon: String (Optional) The path to the icon to be used. It can be a .dll or an .exe file. icon property and iconIndex property have to be specified together. Default value of the icon Property is empty which in-turn uses the default target icon or the icon which is supposed to be used as defined in the System. In this tutorial, we have created a shortcut for a .txt file. It has a pre-defined icon as per the System, but we have changed it to the icon of the notepad file by specifying the path of notepad.exe in the System. iconIndex: Number (Optional) The resource ID of icon when the icon property is a .dll or an .exe file. Default value of the iconIndex property is 0. In this tutorial, we will keep the iconIndex property to 0 for the notepad.exe file icon to take effect. appUserModelId: String (Optional) The Application User Model ID. Default value is empty. index.html: Add the following snippet in that file. HTML <br><br> <button id="create"> Create sample.txt Shortcut </button><br><br> index.js: Add the following snippet in that file. Javascript var create = document.getElementById('create'); var shortcutDetails = { // Defining the target File as the 'sample.txt' File target: path.join(__dirname, '../assets/sample.txt'), // Current Working Directory is 'assets' folder cwd: path.join(__dirname, '../assets/'), args: "Passing Arguments", // Shown as Tooltip description: "Shortcut for sample.txt file", // Defining the icon for shortcut as the // 'notepad.exe' file // Instead of the System Default icon icon: "C://Windows//System32//notepad.exe", // Keeping the default value of iconIndex for the // 'notepad.exe' file icon to take effect iconIndex: 0, appUserModelId: "",}create.addEventListener('click', (event) => { // Desktop - C:\\Users\\radhesh.khanna\\Desktop\\sample-shortcut.lnk // Specifying the name of the Shortcut while creation var success = shell.writeShortcutLink(path.join(__dirname, '../assets/sample-shortcut.lnk'), 'create', shortcutDetails); console.log('Shortcut Created Successfully - ', success);}); Output: 7. shell.readShortcutLink(path): This operation is supported in Windows only. To resolve the given String path and read the shortcut specified at the path. This method returns the shortcutDetails Object. This object is explained above when creating a shortcut. An exception will be thrown if an error occurs. In this tutorial, we will read and display the shortcutDetails object for the same shortcut (sample-shortcut.lnk) that we have created above for the sample.txt file. index.html: Add the following snippet in that file. HTML <div> <textarea name="Shortcut Details" id="textarea" cols="30" rows="10"> </textarea></div> <button id="read"> Read sample.txt Shortcut Details</button> index.js: Add the following snippet in that file. Javascript var read = document.getElementById('read'); // Defining a textarea to display the 'shortcutDetails' Objectvar textArea = document.getElementById('textarea'); read.addEventListener(('click'), (event) => { var object = shell.readShortcutLink(path.join(__dirname, '../assets/sample-shortcut.lnk')); // Object Returned is in JSON format, using 'JSON.stringify()' // method to convert to String console.log(object); textArea.innerHTML = JSON.stringify(object);}); Output: abhishek0719kadiyan ElectronJS JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript 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": 26138, "s": 26110, "text": "\n29 Sep, 2021" }, { "code": null, "e": 26439, "s": 26138, "text": "ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime. " }, { "code": null, "e": 27018, "s": 26439, "text": "The electron can interact with the native OS environment such as File System, System Tray, etc. Electron provides us with the built-in Shell Module which helps in managing files and URLs in the native OS environment using their default application. This module provides functions related to Desktop Integrations such as Opening External Links, Creating Shortcuts, Reading Shortcuts, etc. The Shell Module can be used directly in the Main Process and the Renderer Process of the application. This tutorial will demonstrate Desktop Integrations using the Shell Module in Electron." }, { "code": null, "e": 27188, "s": 27018, "text": "We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system." }, { "code": null, "e": 27207, "s": 27188, "text": "Project Structure:" }, { "code": null, "e": 27219, "s": 27207, "text": "sample.txt:" }, { "code": null, "e": 27246, "s": 27219, "text": "This is a Sample Text file" }, { "code": null, "e": 27258, "s": 27246, "text": "delete.txt:" }, { "code": null, "e": 27285, "s": 27258, "text": "Sample Text FIle to delete" }, { "code": null, "e": 27382, "s": 27285, "text": "Example: We will start by building the basic Electron Application by following the given steps. " }, { "code": null, "e": 27474, "s": 27382, "text": "Step 1: Navigate to an Empty Directory to setup the project, and run the following command," }, { "code": null, "e": 27483, "s": 27474, "text": "npm init" }, { "code": null, "e": 27570, "s": 27483, "text": "To generate the package.json file. Install Electron using npm if it is not installed. " }, { "code": null, "e": 27602, "s": 27570, "text": "npm install electron --save-dev" }, { "code": null, "e": 27844, "s": 27602, "text": "This command will also create the package-lock.json file and install the required node_modules dependencies. Once Electron has been successfully installed, Open the package.json file and perform the necessary changes under the “scripts” key." }, { "code": null, "e": 27859, "s": 27844, "text": "package.json: " }, { "code": null, "e": 28175, "s": 27859, "text": "{\n \"name\": \"electron-DesktopOperation\",\n \"version\": \"1.0.0\",\n \"description\": \"Desktop Operations in Electron\",\n \"main\": \"main.js\",\n \"scripts\": {\n \"start\": \"electron\"\n },\n \"keywords\": [\n \"electron\"\n ],\n \"author\": \"Radhesh Khanna\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"electron\": \"^8.2.5\"\n }\n}" }, { "code": null, "e": 28459, "s": 28175, "text": "Step 2: Create a main.js file according to the project structure. This file is the Main Process and acts as an entry point into the application. Copy the Boilerplate code for the main.js file as given in the following link. We will modify the code to suit our project needs. main.js:" }, { "code": null, "e": 28470, "s": 28459, "text": "Javascript" }, { "code": "const { app, BrowserWindow } = require('electron') function createWindow() { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('src/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // To stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your app's specific// main process code. You can also put them in separate files and// require them here.", "e": 29663, "s": 28470, "text": null }, { "code": null, "e": 29881, "s": 29663, "text": "Step 3: Create the index.html file within the src directory. We will also copy the boilerplate code for the index.html file from the above-mentioned link. We will modify the code to suit our project needs. index.html:" }, { "code": null, "e": 29886, "s": 29881, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial/security#csp-meta-tag --> <meta http-equiv=\"Content-Security-Policy\" content=\"script-src 'self' 'unsafe-inline';\" /></head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. <!-- Adding Individual Renderer Process JS File --> <script src=\"index.js\"></script></body> </html>", "e": 30552, "s": 29886, "text": null }, { "code": null, "e": 30670, "s": 30552, "text": "Output: At this point, our basic Electron Application is set up. To launch the Electron Application, run the Command:" }, { "code": null, "e": 30680, "s": 30670, "text": "npm start" }, { "code": null, "e": 30766, "s": 30680, "text": "Shell Module in Electron: All the Shell modules are explained with the example below:" }, { "code": null, "e": 31047, "s": 30766, "text": "1. shell.openExternal(url, options): To open External URLs in the systems default manner. We can pass external links or mail ID’s and it will be resolved based on the protocol provided. The shell.OpenExternal(url, options) returns a Promise. It takes in the following parameters, " }, { "code": null, "e": 31199, "s": 31047, "text": "url: String The external URL to be resolved. Maximum of 2081 Characters are allowed in Windows. URL will be resolved based on systems default behavior." }, { "code": null, "e": 31417, "s": 31199, "text": "options: Object (Optional) It is an Object consisting of the following parameters, activate: Boolean It is supported by macOS only. It is used to bring the opened application to the foreground. Default is set as true." }, { "code": null, "e": 31552, "s": 31417, "text": "activate: Boolean It is supported by macOS only. It is used to bring the opened application to the foreground. Default is set as true." }, { "code": null, "e": 31604, "s": 31552, "text": "index.html: Add the following snippet in that file." }, { "code": null, "e": 31609, "s": 31604, "text": "HTML" }, { "code": "<br> <h3> Desktop Integrations in Electron using Shell Module </h3> <button id=\"external\"> Open GeeksForGeeks.org in Default Browser </button> <br><br> <button id=\"mail\"> Open GeeksForGeeks in Default Mail </button>", "e": 31841, "s": 31609, "text": null }, { "code": null, "e": 31891, "s": 31841, "text": "index.js: Add the following snippet in that file." }, { "code": null, "e": 31902, "s": 31891, "text": "Javascript" }, { "code": "const electron = require('electron');const path = require('path'); // Importing the Shell Module from the electron // in the Renderer Processconst shell = electron.shell; var external = document.getElementById('external');var externalOptions = { // Supported by macOS only activate: true,} external.addEventListener('click', (event) => { // Returns a Promise<void>, Hence we can use // the .then( function() {} ) shell.openExternal( 'https://www.geeksforgeeks.org/', externalOptions) .then(() => { console.log('Link Opened Successfully'); });}); var mail = document.getElementById('mail'); mail.addEventListener('click', (event) => { // Resolving the External URL to the Default Mail Agent // Because we have specified 'mailto' shell.openExternal( 'mailto: https://www.geeksforgeeks.org/', externalOptions) .then(() => { console.log('Link Opened Successfully'); });});", "e": 32875, "s": 31902, "text": null }, { "code": null, "e": 32883, "s": 32875, "text": "Output:" }, { "code": null, "e": 33084, "s": 32883, "text": "2. shell.showItemInFolder(path): To resolve the given String file path and show the file in the Windows/File Explorer. If possible, select the file as well. This method does not have any return type. " }, { "code": null, "e": 33137, "s": 33084, "text": "index.html: Add the following snippet in that file. " }, { "code": null, "e": 33142, "s": 33137, "text": "HTML" }, { "code": "<br><be> <button id=\"show\"> Show sample.txt in File Explorer </button>", "e": 33218, "s": 33142, "text": null }, { "code": null, "e": 33269, "s": 33218, "text": "index.js: Add the following snippet in that file. " }, { "code": null, "e": 33280, "s": 33269, "text": "Javascript" }, { "code": "var show = document.getElementById('show'); show.addEventListener('click', (event) => { // Providing a dynamic file path to the 'sample.txt' // file in the 'assets' Folder. Using the path Module. // '__dirname' automatically detects current working directory shell.showItemInFolder(path.join(__dirname, '../assets/sample.txt'));});", "e": 33624, "s": 33280, "text": null }, { "code": null, "e": 33632, "s": 33624, "text": "Output:" }, { "code": null, "e": 33829, "s": 33632, "text": "3. shell.openItem(path): To resolve the given String file path and open the file in the systems default manner. It returns a Boolean value stating whether the file was successfully opened or not. " }, { "code": null, "e": 33882, "s": 33829, "text": "index.html: Add the following snippet in that file. " }, { "code": null, "e": 33887, "s": 33882, "text": "HTML" }, { "code": "<br><br> <button id=\"open\">Open sample.txt</button>", "e": 33940, "s": 33887, "text": null }, { "code": null, "e": 33991, "s": 33940, "text": "index.js: Add the following snippet in that file. " }, { "code": null, "e": 34002, "s": 33991, "text": "Javascript" }, { "code": "var open = document.getElementById('open'); open.addEventListener('click', (event) => { var success = shell.openItem(path.join(__dirname, '../assets/sample.txt')); console.log('File Opened Successfully - ', success);});", "e": 34237, "s": 34002, "text": null }, { "code": null, "e": 34245, "s": 34237, "text": "Output:" }, { "code": null, "e": 34415, "s": 34245, "text": "4. shell.beep(): To play the Native OS Sound. This method does not have any return type. In this tutorial, it is used in combination with shell.moveItemToTrash() method." }, { "code": null, "e": 34639, "s": 34415, "text": "5. shell.moveItemToTrash(path, deleteFailure): To resolve the given String file path and move the specified file to the Trash/Bin. Returns a Boolean value stating whether the file was successfully moved to the trash or not." }, { "code": null, "e": 34743, "s": 34639, "text": "The shell.moveItemToTrash(path, delete) returns a Boolean value. It takes in the following parameters, " }, { "code": null, "e": 34785, "s": 34743, "text": "path: String The filepath to be resolved." }, { "code": null, "e": 34982, "s": 34785, "text": "deleteFailure: Boolean (Optional) It is supported by macOS only. It signifies whether or not to remove the file entirely from the System in case the Trash is disabled or unsupported in the system." }, { "code": null, "e": 35034, "s": 34982, "text": "index.html: Add the following snippet in that file." }, { "code": null, "e": 35039, "s": 35034, "text": "HTML" }, { "code": "<br><br> <button id=\"delete\">Delete delete.txt</button>", "e": 35096, "s": 35039, "text": null }, { "code": null, "e": 35146, "s": 35096, "text": "index.js: Add the following snippet in that file." }, { "code": null, "e": 35157, "s": 35146, "text": "Javascript" }, { "code": "var deleteItem = document.getElementById('delete'); deleteItem.addEventListener('click', (event) => { // Play the Native OS Beep Sound shell.beep(); // Returns a Boolean Value var success = shell.moveItemToTrash(path.join(__dirname, '../assets/delete.txt'), true); console.log('File Deleted Successfully - ', success);});", "e": 35519, "s": 35157, "text": null }, { "code": null, "e": 35527, "s": 35519, "text": "Output:" }, { "code": null, "e": 35812, "s": 35527, "text": "6. shell.writeShortcutLink(path, operation, options): This operation is supported in Windows only. To resolve the given String path and create/update the Shortcut Link at that path. It returns a Boolean value stating whether the specified operation was successfully performed or not. " }, { "code": null, "e": 35931, "s": 35812, "text": "The shell.writeShortcutLink(path, operations, options) returns a Boolean value. It takes in the following parameters, " }, { "code": null, "e": 36016, "s": 35931, "text": "path: String Defining the path for the shortcut for the Operation to be carried out." }, { "code": null, "e": 36396, "s": 36016, "text": "operations: String (Optional) Specifies the Operation to be carried out. Default Value of the Operation is create. It can have any of the following values, create: Creates a new Shortcut. Performs Overwrite if necessary.update: Updates the specified properties of an existing Shortcut.replace: Overwrites an existing Shortcut. This operation fails if the Shortcut does not exist." }, { "code": null, "e": 36461, "s": 36396, "text": "create: Creates a new Shortcut. Performs Overwrite if necessary." }, { "code": null, "e": 36527, "s": 36461, "text": "update: Updates the specified properties of an existing Shortcut." }, { "code": null, "e": 36622, "s": 36527, "text": "replace: Overwrites an existing Shortcut. This operation fails if the Shortcut does not exist." }, { "code": null, "e": 38031, "s": 36622, "text": "Options: It is a shortcutDetails Object consisting of the following parameters, target: String The target File which is supposed to be launched from this shortcut.cwd: String (Optional) Specifies the Current Working Directory. Default value is empty.args: String (Optional) The arguments to be passed and applied to the target file when launched from the shortcut. Default value is empty.description: String (Optional) The Description of the Shortcut. Default value is empty. Value is shown as Tooltip on hovering over the created shortcut.icon: String (Optional) The path to the icon to be used. It can be a .dll or an .exe file. icon property and iconIndex property have to be specified together. Default value of the icon Property is empty which in-turn uses the default target icon or the icon which is supposed to be used as defined in the System. In this tutorial, we have created a shortcut for a .txt file. It has a pre-defined icon as per the System, but we have changed it to the icon of the notepad file by specifying the path of notepad.exe in the System.iconIndex: Number (Optional) The resource ID of icon when the icon property is a .dll or an .exe file. Default value of the iconIndex property is 0. In this tutorial, we will keep the iconIndex property to 0 for the notepad.exe file icon to take effect.appUserModelId: String (Optional) The Application User Model ID. Default value is empty." }, { "code": null, "e": 38115, "s": 38031, "text": "target: String The target File which is supposed to be launched from this shortcut." }, { "code": null, "e": 38203, "s": 38115, "text": "cwd: String (Optional) Specifies the Current Working Directory. Default value is empty." }, { "code": null, "e": 38342, "s": 38203, "text": "args: String (Optional) The arguments to be passed and applied to the target file when launched from the shortcut. Default value is empty." }, { "code": null, "e": 38495, "s": 38342, "text": "description: String (Optional) The Description of the Shortcut. Default value is empty. Value is shown as Tooltip on hovering over the created shortcut." }, { "code": null, "e": 39023, "s": 38495, "text": "icon: String (Optional) The path to the icon to be used. It can be a .dll or an .exe file. icon property and iconIndex property have to be specified together. Default value of the icon Property is empty which in-turn uses the default target icon or the icon which is supposed to be used as defined in the System. In this tutorial, we have created a shortcut for a .txt file. It has a pre-defined icon as per the System, but we have changed it to the icon of the notepad file by specifying the path of notepad.exe in the System." }, { "code": null, "e": 39277, "s": 39023, "text": "iconIndex: Number (Optional) The resource ID of icon when the icon property is a .dll or an .exe file. Default value of the iconIndex property is 0. In this tutorial, we will keep the iconIndex property to 0 for the notepad.exe file icon to take effect." }, { "code": null, "e": 39366, "s": 39277, "text": "appUserModelId: String (Optional) The Application User Model ID. Default value is empty." }, { "code": null, "e": 39418, "s": 39366, "text": "index.html: Add the following snippet in that file." }, { "code": null, "e": 39423, "s": 39418, "text": "HTML" }, { "code": "<br><br> <button id=\"create\"> Create sample.txt Shortcut </button><br><br>", "e": 39502, "s": 39423, "text": null }, { "code": null, "e": 39552, "s": 39502, "text": "index.js: Add the following snippet in that file." }, { "code": null, "e": 39563, "s": 39552, "text": "Javascript" }, { "code": "var create = document.getElementById('create'); var shortcutDetails = { // Defining the target File as the 'sample.txt' File target: path.join(__dirname, '../assets/sample.txt'), // Current Working Directory is 'assets' folder cwd: path.join(__dirname, '../assets/'), args: \"Passing Arguments\", // Shown as Tooltip description: \"Shortcut for sample.txt file\", // Defining the icon for shortcut as the // 'notepad.exe' file // Instead of the System Default icon icon: \"C://Windows//System32//notepad.exe\", // Keeping the default value of iconIndex for the // 'notepad.exe' file icon to take effect iconIndex: 0, appUserModelId: \"\",}create.addEventListener('click', (event) => { // Desktop - C:\\\\Users\\\\radhesh.khanna\\\\Desktop\\\\sample-shortcut.lnk // Specifying the name of the Shortcut while creation var success = shell.writeShortcutLink(path.join(__dirname, '../assets/sample-shortcut.lnk'), 'create', shortcutDetails); console.log('Shortcut Created Successfully - ', success);});", "e": 40636, "s": 39563, "text": null }, { "code": null, "e": 40644, "s": 40636, "text": "Output:" }, { "code": null, "e": 41119, "s": 40644, "text": "7. shell.readShortcutLink(path): This operation is supported in Windows only. To resolve the given String path and read the shortcut specified at the path. This method returns the shortcutDetails Object. This object is explained above when creating a shortcut. An exception will be thrown if an error occurs. In this tutorial, we will read and display the shortcutDetails object for the same shortcut (sample-shortcut.lnk) that we have created above for the sample.txt file." }, { "code": null, "e": 41172, "s": 41119, "text": "index.html: Add the following snippet in that file. " }, { "code": null, "e": 41177, "s": 41172, "text": "HTML" }, { "code": "<div> <textarea name=\"Shortcut Details\" id=\"textarea\" cols=\"30\" rows=\"10\"> </textarea></div> <button id=\"read\"> Read sample.txt Shortcut Details</button>", "e": 41353, "s": 41177, "text": null }, { "code": null, "e": 41404, "s": 41353, "text": "index.js: Add the following snippet in that file. " }, { "code": null, "e": 41415, "s": 41404, "text": "Javascript" }, { "code": "var read = document.getElementById('read'); // Defining a textarea to display the 'shortcutDetails' Objectvar textArea = document.getElementById('textarea'); read.addEventListener(('click'), (event) => { var object = shell.readShortcutLink(path.join(__dirname, '../assets/sample-shortcut.lnk')); // Object Returned is in JSON format, using 'JSON.stringify()' // method to convert to String console.log(object); textArea.innerHTML = JSON.stringify(object);});", "e": 41902, "s": 41415, "text": null }, { "code": null, "e": 41910, "s": 41902, "text": "Output:" }, { "code": null, "e": 41930, "s": 41910, "text": "abhishek0719kadiyan" }, { "code": null, "e": 41941, "s": 41930, "text": "ElectronJS" }, { "code": null, "e": 41952, "s": 41941, "text": "JavaScript" }, { "code": null, "e": 41969, "s": 41952, "text": "Web Technologies" }, { "code": null, "e": 42067, "s": 41969, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42107, "s": 42067, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 42152, "s": 42107, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 42213, "s": 42152, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 42285, "s": 42213, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 42337, "s": 42285, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 42377, "s": 42337, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 42410, "s": 42377, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 42455, "s": 42410, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 42498, "s": 42455, "text": "How to fetch data from an API in ReactJS ?" } ]
MVC Framework - Bundling
Bundling and Minification are two performance improvement techniques that improves the request load time of the application. Most of the current major browsers limit the number of simultaneous connections per hostname to six. It means that at a time, all the additional requests will be queued by the browser. To enable bundling and minification in your MVC application, open the Web.config file inside your solution. In this file, search for compilation settings under system.web − <system.web> <compilation debug = "true" /> </system.web> By default, you will see the debug parameter set to true, which means that bundling and minification is disabled. Set this parameter to false. To improve the performance of the application, ASP.NET MVC provides inbuilt feature to bundle multiple files into a single, file which in turn improves the page load performance because of fewer HTTP requests. Bundling is a simple logical group of files that could be referenced by unique name and loaded with a single HTTP request. By default, the MVC application's BundleConfig (located inside App_Start folder) comes with the following code − public static void RegisterBundles(BundleCollection bundles) { // Following is the sample code to bundle all the css files in the project // The code to bundle other javascript files will also be similar to this bundles.Add(new StyleBundle("~/Content/themes/base/css").Include( "~/Content/themes/base/jquery.ui.core.css", "~/Content/themes/base/jquery.ui.tabs.css", "~/Content/themes/base/jquery.ui.datepicker.css", "~/Content/themes/base/jquery.ui.progressbar.css", "~/Content/themes/base/jquery.ui.theme.css")); } The above code basically bundles all the CSS files present in Content/themes/base folder into a single file. Minification is another such performance improvement technique in which it optimizes the javascript, css code by shortening the variable names, removing unnecessary white spaces, line breaks, comments, etc. This in turn reduces the file size and helps the application to load faster. For using this option, you will have to first install the Web Essentials Extension in your Visual Studio. After that, when you will right-click on any css or javascript file, it will show you the option to create a minified version of that file. Thus, if you have a css file named Site.css, it will create its minified version as Site.min.css. Now when the next time your application will run in the browser, it will bundle and minify all the css and js files, hence improving the application performance. 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 55 Lectures 4.5 hours University Code 40 Lectures 2.5 hours University Code 140 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2335, "s": 2025, "text": "Bundling and Minification are two performance improvement techniques that improves the request load time of the application. Most of the current major browsers limit the number of simultaneous connections per hostname to six. It means that at a time, all the additional requests will be queued by the browser." }, { "code": null, "e": 2508, "s": 2335, "text": "To enable bundling and minification in your MVC application, open the Web.config file inside your solution. In this file, search for compilation settings under system.web −" }, { "code": null, "e": 2569, "s": 2508, "text": "<system.web>\n <compilation debug = \"true\" />\n</system.web>" }, { "code": null, "e": 2712, "s": 2569, "text": "By default, you will see the debug parameter set to true, which means that bundling and minification is disabled. Set this parameter to false." }, { "code": null, "e": 2922, "s": 2712, "text": "To improve the performance of the application, ASP.NET MVC provides inbuilt feature to bundle multiple files into a single, file which in turn improves the page load performance because of fewer HTTP requests." }, { "code": null, "e": 3045, "s": 2922, "text": "Bundling is a simple logical group of files that could be referenced by unique name and loaded with a single HTTP request." }, { "code": null, "e": 3158, "s": 3045, "text": "By default, the MVC application's BundleConfig (located inside App_Start folder) comes with the following code −" }, { "code": null, "e": 3742, "s": 3158, "text": "public static void RegisterBundles(BundleCollection bundles) { \n \n // Following is the sample code to bundle all the css files in the project \n \n // The code to bundle other javascript files will also be similar to this \n \n bundles.Add(new StyleBundle(\"~/Content/themes/base/css\").Include( \n \"~/Content/themes/base/jquery.ui.core.css\", \n \"~/Content/themes/base/jquery.ui.tabs.css\", \n \"~/Content/themes/base/jquery.ui.datepicker.css\", \n \"~/Content/themes/base/jquery.ui.progressbar.css\", \n \"~/Content/themes/base/jquery.ui.theme.css\")); \n}" }, { "code": null, "e": 3851, "s": 3742, "text": "The above code basically bundles all the CSS files present in Content/themes/base folder into a single file." }, { "code": null, "e": 4135, "s": 3851, "text": "Minification is another such performance improvement technique in which it optimizes the javascript, css code by shortening the variable names, removing unnecessary white spaces, line breaks, comments, etc. This in turn reduces the file size and helps the application to load faster." }, { "code": null, "e": 4381, "s": 4135, "text": "For using this option, you will have to first install the Web Essentials Extension in your Visual Studio. After that, when you will right-click on any css or javascript file, it will show you the option to create a minified version of that file." }, { "code": null, "e": 4479, "s": 4381, "text": "Thus, if you have a css file named Site.css, it will create its minified version as Site.min.css." }, { "code": null, "e": 4641, "s": 4479, "text": "Now when the next time your application will run in the browser, it will bundle and minify all the css and js files, hence improving the application performance." }, { "code": null, "e": 4676, "s": 4641, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4699, "s": 4676, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 4733, "s": 4699, "text": "\n 42 Lectures \n 18 hours \n" }, { "code": null, "e": 4753, "s": 4733, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 4788, "s": 4753, "text": "\n 57 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4805, "s": 4788, "text": " University Code" }, { "code": null, "e": 4840, "s": 4805, "text": "\n 55 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4857, "s": 4840, "text": " University Code" }, { "code": null, "e": 4892, "s": 4857, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4909, "s": 4892, "text": " University Code" }, { "code": null, "e": 4943, "s": 4909, "text": "\n 140 Lectures \n 9 hours \n" }, { "code": null, "e": 4958, "s": 4943, "text": " Bhrugen Patel" }, { "code": null, "e": 4965, "s": 4958, "text": " Print" }, { "code": null, "e": 4976, "s": 4965, "text": " Add Notes" } ]
DynamoDB - Batch Writing
Batch writing operates on multiple items by creating or deleting several items. These operations utilize BatchWriteItem, which carries the limitations of no more than 16MB writes and 25 requests. Each item obeys a 400KB size limit. Batch writes also cannot perform item updates. Batch writes can manipulate items across multiple tables. Operation invocation happens for each individual request, which means operations do not impact each other, and heterogeneous mixes are permitted; for example, one PutItem and three DeleteItem requests in a batch, with the failure of the PutItem request not impacting the others. Failed requests result in the operation returning information (keys and data) pertaining to each failed request. Note − If DynamoDB returns any items without processing them, retry them; however, use a back-off method to avoid another request failure based on overloading. DynamoDB rejects a batch write operation when one or more of the following statements proves to be true − The request exceeds the provisioned throughput. The request exceeds the provisioned throughput. The request attempts to use BatchWriteItems to update an item. The request attempts to use BatchWriteItems to update an item. The request performs several operations on a single item. The request performs several operations on a single item. The request tables do not exist. The request tables do not exist. The item attributes in the request do not match the target. The item attributes in the request do not match the target. The requests exceed size limits. The requests exceed size limits. Batch writes require certain RequestItem parameters − Deletion operations need DeleteRequest key subelements meaning an attribute name and value. Deletion operations need DeleteRequest key subelements meaning an attribute name and value. The PutRequest items require an Item subelement meaning an attribute and attribute value map. The PutRequest items require an Item subelement meaning an attribute and attribute value map. Response − A successful operation results in an HTTP 200 response, which indicates characteristics like capacity units consumed, table processing metrics, and any unprocessed items. Perform a batch write by creating a DynamoDB class instance, a TableWriteItems class instance describing all operations, and calling the batchWriteItem method to use the TableWriteItems object. Note − You must create a TableWriteItems instance for every table in a batch write to multiple tables. Also, check your request response for any unprocessed requests. You can review the following example of a batch write − DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient( new ProfileCredentialsProvider())); TableWriteItems forumTableWriteItems = new TableWriteItems("Forum") .withItemsToPut( new Item() .withPrimaryKey("Title", "XYZ CRM") .withNumber("Threads", 0)); TableWriteItems threadTableWriteItems = new TableWriteItems(Thread) .withItemsToPut( new Item() .withPrimaryKey("ForumTitle","XYZ CRM","Topic","Updates") .withHashAndRangeKeysToDelete("ForumTitle","A partition key value", "Product Line 1", "A sort key value")); BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem ( forumTableWriteItems, threadTableWriteItems); The following program is another bigger example for better understanding of how a batch writes with Java. Note − The following example may assume a previously created data source. Before attempting to execute, acquire supporting libraries and create necessary data sources (tables with required characteristics, or other referenced sources). This example also uses Eclipse IDE, an AWS credentials file, and the AWS Toolkit within an Eclipse AWS Java Project. package com.amazonaws.codesamples.document; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; import com.amazonaws.services.dynamodbv2.document.BatchWriteItemOutcome; import com.amazonaws.services.dynamodbv2.document.DynamoDB; import com.amazonaws.services.dynamodbv2.document.Item; import com.amazonaws.services.dynamodbv2.document.TableWriteItems; import com.amazonaws.services.dynamodbv2.model.WriteRequest; public class BatchWriteOpSample { static DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient( new ProfileCredentialsProvider())); static String forumTableName = "Forum"; static String threadTableName = "Thread"; public static void main(String[] args) throws IOException { batchWriteMultiItems(); } private static void batchWriteMultiItems() { try { // Place new item in Forum TableWriteItems forumTableWriteItems = new TableWriteItems(forumTableName) //Forum .withItemsToPut(new Item() .withPrimaryKey("Name", "Amazon RDS") .withNumber("Threads", 0)); // Place one item, delete another in Thread // Specify partition key and range key TableWriteItems threadTableWriteItems = new TableWriteItems(threadTableName) .withItemsToPut(new Item() .withPrimaryKey("ForumName","Product Support","Subject","Support Thread 1") .withString("Message", "New OS Thread 1 message") .withHashAndRangeKeysToDelete("ForumName","Subject", "Polymer Blaster", "Support Thread 100")); System.out.println("Processing request..."); BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem ( forumTableWriteItems, threadTableWriteItems); do { // Confirm no unprocessed items Map<String, List<WriteRequest>> unprocessedItems = outcome.getUnprocessedItems(); if (outcome.getUnprocessedItems().size() == 0) { System.out.println("All items processed."); } else { System.out.println("Gathering unprocessed items..."); outcome = dynamoDB.batchWriteItemUnprocessed(unprocessedItems); } } while (outcome.getUnprocessedItems().size() > 0); } catch (Exception e) { System.err.println("Could not get items: "); e.printStackTrace(System.err); } } } 16 Lectures 1.5 hours Harshit Srivastava 49 Lectures 3.5 hours Niyazi Erdogan 48 Lectures 3 hours Niyazi Erdogan 13 Lectures 1 hours Harshit Srivastava 45 Lectures 4 hours Pranjal Srivastava, Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2670, "s": 2391, "text": "Batch writing operates on multiple items by creating or deleting several items. These operations utilize BatchWriteItem, which carries the limitations of no more than 16MB writes and 25 requests. Each item obeys a 400KB size limit. Batch writes also cannot perform item updates." }, { "code": null, "e": 3120, "s": 2670, "text": "Batch writes can manipulate items across multiple tables. Operation invocation happens for each individual request, which means operations do not impact each other, and heterogeneous mixes are permitted; for example, one PutItem and three DeleteItem requests in a batch, with the failure of the PutItem request not impacting the others. Failed requests result in the operation returning information (keys and data) pertaining to each failed request." }, { "code": null, "e": 3280, "s": 3120, "text": "Note − If DynamoDB returns any items without processing them, retry them; however, use a back-off method to avoid another request failure based on overloading." }, { "code": null, "e": 3386, "s": 3280, "text": "DynamoDB rejects a batch write operation when one or more of the following statements proves to be true −" }, { "code": null, "e": 3434, "s": 3386, "text": "The request exceeds the provisioned throughput." }, { "code": null, "e": 3482, "s": 3434, "text": "The request exceeds the provisioned throughput." }, { "code": null, "e": 3545, "s": 3482, "text": "The request attempts to use BatchWriteItems to update an item." }, { "code": null, "e": 3608, "s": 3545, "text": "The request attempts to use BatchWriteItems to update an item." }, { "code": null, "e": 3666, "s": 3608, "text": "The request performs several operations on a single item." }, { "code": null, "e": 3724, "s": 3666, "text": "The request performs several operations on a single item." }, { "code": null, "e": 3757, "s": 3724, "text": "The request tables do not exist." }, { "code": null, "e": 3790, "s": 3757, "text": "The request tables do not exist." }, { "code": null, "e": 3850, "s": 3790, "text": "The item attributes in the request do not match the target." }, { "code": null, "e": 3910, "s": 3850, "text": "The item attributes in the request do not match the target." }, { "code": null, "e": 3943, "s": 3910, "text": "The requests exceed size limits." }, { "code": null, "e": 3976, "s": 3943, "text": "The requests exceed size limits." }, { "code": null, "e": 4030, "s": 3976, "text": "Batch writes require certain RequestItem parameters −" }, { "code": null, "e": 4122, "s": 4030, "text": "Deletion operations need DeleteRequest key subelements meaning an attribute name and value." }, { "code": null, "e": 4214, "s": 4122, "text": "Deletion operations need DeleteRequest key subelements meaning an attribute name and value." }, { "code": null, "e": 4308, "s": 4214, "text": "The PutRequest items require an Item subelement meaning an attribute and attribute value map." }, { "code": null, "e": 4402, "s": 4308, "text": "The PutRequest items require an Item subelement meaning an attribute and attribute value map." }, { "code": null, "e": 4584, "s": 4402, "text": "Response − A successful operation results in an HTTP 200 response, which indicates characteristics like capacity units consumed, table processing metrics, and any unprocessed items." }, { "code": null, "e": 4778, "s": 4584, "text": "Perform a batch write by creating a DynamoDB class instance, a TableWriteItems class instance describing all operations, and calling the batchWriteItem method to use the TableWriteItems object." }, { "code": null, "e": 4945, "s": 4778, "text": "Note − You must create a TableWriteItems instance for every table in a batch write to multiple tables. Also, check your request response for any unprocessed requests." }, { "code": null, "e": 5001, "s": 4945, "text": "You can review the following example of a batch write −" }, { "code": null, "e": 5672, "s": 5001, "text": "DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient( \n new ProfileCredentialsProvider())); \n\nTableWriteItems forumTableWriteItems = new TableWriteItems(\"Forum\") \n .withItemsToPut( \n new Item() \n .withPrimaryKey(\"Title\", \"XYZ CRM\") \n .withNumber(\"Threads\", 0)); \n\nTableWriteItems threadTableWriteItems = new TableWriteItems(Thread) \n .withItemsToPut( \n new Item() \n .withPrimaryKey(\"ForumTitle\",\"XYZ CRM\",\"Topic\",\"Updates\") \n .withHashAndRangeKeysToDelete(\"ForumTitle\",\"A partition key value\", \n \"Product Line 1\", \"A sort key value\"));\n\nBatchWriteItemOutcome outcome = dynamoDB.batchWriteItem (\n forumTableWriteItems, threadTableWriteItems);" }, { "code": null, "e": 5778, "s": 5672, "text": "The following program is another bigger example for better understanding of how a batch writes with Java." }, { "code": null, "e": 6014, "s": 5778, "text": "Note − The following example may assume a previously created data source. Before attempting to execute, acquire supporting libraries and create necessary data sources (tables with required characteristics, or other referenced sources)." }, { "code": null, "e": 6131, "s": 6014, "text": "This example also uses Eclipse IDE, an AWS credentials file, and the AWS Toolkit within an Eclipse AWS Java Project." }, { "code": null, "e": 8928, "s": 6131, "text": "package com.amazonaws.codesamples.document;\n\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\n\nimport com.amazonaws.auth.profile.ProfileCredentialsProvider;\nimport com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;\nimport com.amazonaws.services.dynamodbv2.document.BatchWriteItemOutcome;\nimport com.amazonaws.services.dynamodbv2.document.DynamoDB;\nimport com.amazonaws.services.dynamodbv2.document.Item;\nimport com.amazonaws.services.dynamodbv2.document.TableWriteItems;\nimport com.amazonaws.services.dynamodbv2.model.WriteRequest;\n\npublic class BatchWriteOpSample { \n static DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient( \n new ProfileCredentialsProvider())); \n static String forumTableName = \"Forum\"; \n static String threadTableName = \"Thread\"; \n \n public static void main(String[] args) throws IOException { \n batchWriteMultiItems(); \n }\n private static void batchWriteMultiItems() { \n try {\n // Place new item in Forum \n TableWriteItems forumTableWriteItems = new TableWriteItems(forumTableName) \n //Forum \n .withItemsToPut(new Item() \n .withPrimaryKey(\"Name\", \"Amazon RDS\") \n .withNumber(\"Threads\", 0)); \n \n // Place one item, delete another in Thread \n // Specify partition key and range key \n TableWriteItems threadTableWriteItems = new TableWriteItems(threadTableName) \n .withItemsToPut(new Item() \n .withPrimaryKey(\"ForumName\",\"Product \n Support\",\"Subject\",\"Support Thread 1\") \n .withString(\"Message\", \"New OS Thread 1 message\")\n .withHashAndRangeKeysToDelete(\"ForumName\",\"Subject\", \"Polymer Blaster\", \n \"Support Thread 100\")); \n \n System.out.println(\"Processing request...\"); \n BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem (\n forumTableWriteItems, threadTableWriteItems);\n do { \n // Confirm no unprocessed items \n Map<String, List<WriteRequest>> unprocessedItems \n = outcome.getUnprocessedItems(); \n \n if (outcome.getUnprocessedItems().size() == 0) { \n System.out.println(\"All items processed.\"); \n } else { \n System.out.println(\"Gathering unprocessed items...\"); \n outcome = dynamoDB.batchWriteItemUnprocessed(unprocessedItems); \n } \n } while (outcome.getUnprocessedItems().size() > 0); \n } catch (Exception e) { \n System.err.println(\"Could not get items: \"); \n e.printStackTrace(System.err); \n } \n } \n}" }, { "code": null, "e": 8963, "s": 8928, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8983, "s": 8963, "text": " Harshit Srivastava" }, { "code": null, "e": 9018, "s": 8983, "text": "\n 49 Lectures \n 3.5 hours \n" }, { "code": null, "e": 9034, "s": 9018, "text": " Niyazi Erdogan" }, { "code": null, "e": 9067, "s": 9034, "text": "\n 48 Lectures \n 3 hours \n" }, { "code": null, "e": 9083, "s": 9067, "text": " Niyazi Erdogan" }, { "code": null, "e": 9116, "s": 9083, "text": "\n 13 Lectures \n 1 hours \n" }, { "code": null, "e": 9136, "s": 9116, "text": " Harshit Srivastava" }, { "code": null, "e": 9169, "s": 9136, "text": "\n 45 Lectures \n 4 hours \n" }, { "code": null, "e": 9209, "s": 9169, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 9216, "s": 9209, "text": " Print" }, { "code": null, "e": 9227, "s": 9216, "text": " Add Notes" } ]
Count of common multiples of two numbers in a range - GeeksforGeeks
07 Apr, 2021 Given a range from L to R and every Xth tile is painted black and every Yth tile is painted white in that range from L to R. If a tile is painted both white and black, then it is considered to be painted grey. The task is to find the number of tiles that are colored grey in range L to R (both inclusive). Examples: Input: X = 2, Y = 3, L = 6, R = 18 Output: 3 The grey coloured tiles are numbered 6, 12, 18 Input: X = 1, Y = 4, L = 5, R = 10 Output: 1 The only grey coloured tile is 8. Approach: Since every multiple of X is black and every multiple of Y is white. Any tile which is a multiple of both X and Y would be grey. The terms that are divisible by both X and Y are the terms that are divisible by the lcm of X and Y.Lcm can be found out using the following formula: lcm = (x*y) / gcd(x, y) GCD can be computed in logn time using Euclid’s algorithm. The number of multiples of lcm in range L to R can be found by using a common trick of: count(L, R) = count(R) - count(L-1) Number of terms divisible by K less than N is: floor(N/K) Below is the implementation to find the number of grey tiles: C++ Java Python3 C# PHP Javascript // C++ implementation to find the number of// grey tiles#include <bits/stdc++.h>using namespace std; // Function to count the numbe ro fgrey tilesint findTileCount(int x, int y, int l, int r){ int lcm = (x * y) / __gcd(x, y); // Number multiple of lcm less than L int countl = (l - 1) / lcm; // Number of multiples of lcm less than R+1 int countr = r / lcm; return countr - countl;} // Driver codeint main(){ int x = 2, y = 3, l = 6, r = 18; cout << findTileCount(x, y, l, r); return 0;} // Java implementation to find the// number of grey tiles import java.io.*; class GFG { // Function to count the number// of grey tilesstatic int findTileCount(int x, int y, int l, int r){ int lcm = (x * y) / __gcd(x, y); // Number multiple of lcm less than L int countl = (l - 1) / lcm; // Number of multiples of // lcm less than R+1 int countr = r / lcm; return countr - countl;} static int __gcd(int a, int b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a);} // Driver code public static void main (String[] args) { int x = 2, y = 3, l = 6, r = 18; System.out.println(findTileCount(x, y, l, r));}} // This code is contributed ajit # Python3 implementation to find the number of# grey tiles # from math lib import gcd methodfrom math import gcd # Function to count the numbe of grey tilesdef findTileCount(x, y, l, r) : lcm = (x * y) // gcd(x, y) # Number multiple of lcm less than L count1 = (l - 1) // lcm # Number of multiples of lcm less than R+1 countr = r // lcm return countr - count1 # Driver codeif __name__ == "__main__" : x, y, l, r = 2, 3, 6, 18 print(findTileCount(x, y, l, r)) # This code is contributed by# ANKITRAI1 // C# implementation to find the// number of grey tilesusing System; class GFG{ // Function to count the number// of grey tilesstatic int findTileCount(int x, int y, int l, int r){ int lcm = (x * y) / __gcd(x, y); // Number multiple of lcm less than L int countl = (l - 1) / lcm; // Number of multiples of // lcm less than R+1 int countr = r / lcm; return countr - countl;} static int __gcd(int a, int b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a);} // Driver codepublic static void Main(){ int x = 2, y = 3, l = 6, r = 18; Console.Write(findTileCount(x, y, l, r));}} // This code is contributed// by Kirti_Mangal <?php// PHP implementation to find the// number of grey tiles // Function to count the number// of grey tilesfunction findTileCount($x, $y, $l, $r){ $lcm = (int)(($x * $y) / __gcd($x, $y)); // Number multiple of lcm less than L $countl = (int)(($l - 1) / $lcm); // Number of multiples of // lcm less than R+1 $countr = (int)($r / $lcm); return $countr - $countl;} function __gcd($a, $b){ // Everything divides 0 if ($a == 0) return $b; if ($b == 0) return $a; // base case if ($a == $b) return $a; // a is greater if ($a > $b) return __gcd($a - $b, $b); return __gcd($a, $b - $a);} // Driver code$x = 2; $y = 3; $l = 6; $r = 18;echo findTileCount($x, $y, $l, $r); // This code is contributed// by Akanksha Rai(Abby_akku)?> <script> // JavaScript implementation to find the// number of grey tiles // Function to count the number// of grey tilesfunction findTileCount(x,y,l,r){ lcm = parseInt((x * y) / __gcd(x, y)); // Number multiple of lcm less than L countl = parseInt((l - 1) / lcm); // Number of multiples of // lcm less than R+1 countr = parseInt(r / lcm); return countr - countl;} function __gcd(a, b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a);} // Driver codelet x = 2;let y = 3;let l = 6;let r = 18;document.write(findTileCount(x, y, l, r)); // This code is contributed by bobby </script> 3 Time Complexity: O(log(x*y)) Kirti_Mangal jit_t Akanksha_Rai ankthon gottumukkalabobby GCD-LCM Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Program to find GCD or HCF of two numbers Prime Numbers Program to find sum of elements in a given array Sieve of Eratosthenes Program for Decimal to Binary Conversion Program for factorial of a number Operators in C / C++ Euclidean algorithms (Basic and Extended)
[ { "code": null, "e": 25326, "s": 25298, "text": "\n07 Apr, 2021" }, { "code": null, "e": 25644, "s": 25326, "text": "Given a range from L to R and every Xth tile is painted black and every Yth tile is painted white in that range from L to R. If a tile is painted both white and black, then it is considered to be painted grey. The task is to find the number of tiles that are colored grey in range L to R (both inclusive). Examples: " }, { "code": null, "e": 25816, "s": 25644, "text": "Input: X = 2, Y = 3, L = 6, R = 18\nOutput: 3\nThe grey coloured tiles are numbered 6, 12, 18\n\nInput: X = 1, Y = 4, L = 5, R = 10\nOutput: 1\nThe only grey coloured tile is 8." }, { "code": null, "e": 26109, "s": 25818, "text": "Approach: Since every multiple of X is black and every multiple of Y is white. Any tile which is a multiple of both X and Y would be grey. The terms that are divisible by both X and Y are the terms that are divisible by the lcm of X and Y.Lcm can be found out using the following formula: " }, { "code": null, "e": 26133, "s": 26109, "text": "lcm = (x*y) / gcd(x, y)" }, { "code": null, "e": 26282, "s": 26133, "text": "GCD can be computed in logn time using Euclid’s algorithm. The number of multiples of lcm in range L to R can be found by using a common trick of: " }, { "code": null, "e": 26318, "s": 26282, "text": "count(L, R) = count(R) - count(L-1)" }, { "code": null, "e": 26367, "s": 26318, "text": "Number of terms divisible by K less than N is: " }, { "code": null, "e": 26378, "s": 26367, "text": "floor(N/K)" }, { "code": null, "e": 26441, "s": 26378, "text": "Below is the implementation to find the number of grey tiles: " }, { "code": null, "e": 26445, "s": 26441, "text": "C++" }, { "code": null, "e": 26450, "s": 26445, "text": "Java" }, { "code": null, "e": 26458, "s": 26450, "text": "Python3" }, { "code": null, "e": 26461, "s": 26458, "text": "C#" }, { "code": null, "e": 26465, "s": 26461, "text": "PHP" }, { "code": null, "e": 26476, "s": 26465, "text": "Javascript" }, { "code": "// C++ implementation to find the number of// grey tiles#include <bits/stdc++.h>using namespace std; // Function to count the numbe ro fgrey tilesint findTileCount(int x, int y, int l, int r){ int lcm = (x * y) / __gcd(x, y); // Number multiple of lcm less than L int countl = (l - 1) / lcm; // Number of multiples of lcm less than R+1 int countr = r / lcm; return countr - countl;} // Driver codeint main(){ int x = 2, y = 3, l = 6, r = 18; cout << findTileCount(x, y, l, r); return 0;}", "e": 26993, "s": 26476, "text": null }, { "code": "// Java implementation to find the// number of grey tiles import java.io.*; class GFG { // Function to count the number// of grey tilesstatic int findTileCount(int x, int y, int l, int r){ int lcm = (x * y) / __gcd(x, y); // Number multiple of lcm less than L int countl = (l - 1) / lcm; // Number of multiples of // lcm less than R+1 int countr = r / lcm; return countr - countl;} static int __gcd(int a, int b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a);} // Driver code public static void main (String[] args) { int x = 2, y = 3, l = 6, r = 18; System.out.println(findTileCount(x, y, l, r));}} // This code is contributed ajit", "e": 27893, "s": 26993, "text": null }, { "code": "# Python3 implementation to find the number of# grey tiles # from math lib import gcd methodfrom math import gcd # Function to count the numbe of grey tilesdef findTileCount(x, y, l, r) : lcm = (x * y) // gcd(x, y) # Number multiple of lcm less than L count1 = (l - 1) // lcm # Number of multiples of lcm less than R+1 countr = r // lcm return countr - count1 # Driver codeif __name__ == \"__main__\" : x, y, l, r = 2, 3, 6, 18 print(findTileCount(x, y, l, r)) # This code is contributed by# ANKITRAI1", "e": 28424, "s": 27893, "text": null }, { "code": "// C# implementation to find the// number of grey tilesusing System; class GFG{ // Function to count the number// of grey tilesstatic int findTileCount(int x, int y, int l, int r){ int lcm = (x * y) / __gcd(x, y); // Number multiple of lcm less than L int countl = (l - 1) / lcm; // Number of multiples of // lcm less than R+1 int countr = r / lcm; return countr - countl;} static int __gcd(int a, int b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a);} // Driver codepublic static void Main(){ int x = 2, y = 3, l = 6, r = 18; Console.Write(findTileCount(x, y, l, r));}} // This code is contributed// by Kirti_Mangal", "e": 29290, "s": 28424, "text": null }, { "code": "<?php// PHP implementation to find the// number of grey tiles // Function to count the number// of grey tilesfunction findTileCount($x, $y, $l, $r){ $lcm = (int)(($x * $y) / __gcd($x, $y)); // Number multiple of lcm less than L $countl = (int)(($l - 1) / $lcm); // Number of multiples of // lcm less than R+1 $countr = (int)($r / $lcm); return $countr - $countl;} function __gcd($a, $b){ // Everything divides 0 if ($a == 0) return $b; if ($b == 0) return $a; // base case if ($a == $b) return $a; // a is greater if ($a > $b) return __gcd($a - $b, $b); return __gcd($a, $b - $a);} // Driver code$x = 2; $y = 3; $l = 6; $r = 18;echo findTileCount($x, $y, $l, $r); // This code is contributed// by Akanksha Rai(Abby_akku)?>", "e": 30100, "s": 29290, "text": null }, { "code": "<script> // JavaScript implementation to find the// number of grey tiles // Function to count the number// of grey tilesfunction findTileCount(x,y,l,r){ lcm = parseInt((x * y) / __gcd(x, y)); // Number multiple of lcm less than L countl = parseInt((l - 1) / lcm); // Number of multiples of // lcm less than R+1 countr = parseInt(r / lcm); return countr - countl;} function __gcd(a, b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a);} // Driver codelet x = 2;let y = 3;let l = 6;let r = 18;document.write(findTileCount(x, y, l, r)); // This code is contributed by bobby </script>", "e": 30893, "s": 30100, "text": null }, { "code": null, "e": 30895, "s": 30893, "text": "3" }, { "code": null, "e": 30927, "s": 30897, "text": "Time Complexity: O(log(x*y)) " }, { "code": null, "e": 30940, "s": 30927, "text": "Kirti_Mangal" }, { "code": null, "e": 30946, "s": 30940, "text": "jit_t" }, { "code": null, "e": 30959, "s": 30946, "text": "Akanksha_Rai" }, { "code": null, "e": 30967, "s": 30959, "text": "ankthon" }, { "code": null, "e": 30985, "s": 30967, "text": "gottumukkalabobby" }, { "code": null, "e": 30993, "s": 30985, "text": "GCD-LCM" }, { "code": null, "e": 31006, "s": 30993, "text": "Mathematical" }, { "code": null, "e": 31019, "s": 31006, "text": "Mathematical" }, { "code": null, "e": 31117, "s": 31019, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31141, "s": 31117, "text": "Merge two sorted arrays" }, { "code": null, "e": 31184, "s": 31141, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 31226, "s": 31184, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 31240, "s": 31226, "text": "Prime Numbers" }, { "code": null, "e": 31289, "s": 31240, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 31311, "s": 31289, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 31352, "s": 31311, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 31386, "s": 31352, "text": "Program for factorial of a number" }, { "code": null, "e": 31407, "s": 31386, "text": "Operators in C / C++" } ]
Nested interface in Java
We can declare an interface in another interface or class. Such an interface is termed as a nested interface. The following are the rules governing a nested interface. A nested interface declared within an interface must be public. A nested interface declared within a class can have any access modifier. A nested interface is by default static. Following is an example of a nested interface. Live Demo class Animal { interface Activity { void move(); } } class Dog implements Animal.Activity { public void move() { System.out.println("Dogs can walk and run"); } } public class Tester { public static void main(String args[]) { Dog dog = new Dog(); dog.move(); } } Dogs can walk and run
[ { "code": null, "e": 1172, "s": 1062, "text": "We can declare an interface in another interface or class. Such an interface is termed as a nested interface." }, { "code": null, "e": 1230, "s": 1172, "text": "The following are the rules governing a nested interface." }, { "code": null, "e": 1294, "s": 1230, "text": "A nested interface declared within an interface must be public." }, { "code": null, "e": 1367, "s": 1294, "text": "A nested interface declared within a class can have any access modifier." }, { "code": null, "e": 1408, "s": 1367, "text": "A nested interface is by default static." }, { "code": null, "e": 1455, "s": 1408, "text": "Following is an example of a nested interface." }, { "code": null, "e": 1465, "s": 1455, "text": "Live Demo" }, { "code": null, "e": 1769, "s": 1465, "text": "class Animal {\n interface Activity {\n void move();\n }\n}\nclass Dog implements Animal.Activity {\n public void move() {\n System.out.println(\"Dogs can walk and run\");\n }\n}\npublic class Tester {\n public static void main(String args[]) {\n Dog dog = new Dog();\n dog.move();\n }\n}" }, { "code": null, "e": 1791, "s": 1769, "text": "Dogs can walk and run" } ]
Find all subsequences with sum equals to K - GeeksforGeeks
17 Mar, 2022 Given an array arr[] of length N and a number K, the task is to find all the subsequences of the array whose sum of elements is K Examples: Input: arr[] = {1, 2, 3}, K = 3 Output: 1 2 3 Input: arr[] = {17, 18, 6, 11, 2, 4}, K = 6 Output: 2 4 6 Approach: The idea is to use the jagged array to store the subsequences of the array of different lengths. For every element in the array, there are mainly two choices for it that are either to include in the subsequence or not. Apply this for every element in the array by reducing the sum, if the element is included otherwise search for the subsequence without including it. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to find all the// subsequence whose sum is K #include <bits/stdc++.h>using namespace std; // Utility function to find the subsequences// whose sum of the element is Kint subsetSumToK(int arr[], int n, int output[][50], int k){ // Base Case if (n == 0) { if (k == 0) { output[0][0] = 0; return 1; } else { return 0; } } // Array to store the subsequences // which includes the element arr[0] int output1[1000][50]; // Array to store the subsequences // which not includes the element arr[0] int output2[1000][50]; // Recursive call to find the subsequences // which includes the element arr[0] int size1 = subsetSumToK(arr + 1, n - 1, output1, k - arr[0]); // Recursive call to find the subsequences // which not includes the element arr[0] int size2 = subsetSumToK(arr + 1, n - 1, output2, k); int i, j; // Loop to update the results of the // Recursive call of the function for (i = 0; i < size1; i++) { // Incremeing the length of // jagged array because it includes // the arr[0] element of the array output[i][0] = output1[i][0] + 1; // In the first column of the jagged // array put the arr[0] element output[i][1] = arr[0]; } // Loop to update the subsequence // in the output array for (i = 0; i < size1; i++) { for (j = 1; j <= output1[i][0]; j++) { output[i][j + 1] = output1[i][j]; } } // Loop to update the subsequences // which do not include the arr[0] element for (i = 0; i < size2; i++) { for (j = 0; j <= output2[i][0]; j++) { output[i + size1][j] = output2[i][j]; } } return size1 + size2;} // Function to find the subsequences// whose sum of the element is Kvoid countSubsequences(int arr[], int n, int output[][50], int k){ int size = subsetSumToK(arr, n, output, k); for (int i = 0; i < size; i++) { for (int j = 1; j <= output[i][0]; j++) { cout << output[i][j] << " "; } cout << endl; } } // Driver Codeint main(){ int arr[] = {5, 12, 3, 17, 1, 18, 15, 3, 17}; int length = 9, output[1000][50], k = 6; countSubsequences(arr, length, output, k); return 0;} // Java implementation to find all the// sub-sequences whose sum is K import java.util.*;public class SubsequenceSumK { // Function to find the subsequences // with given sum public static void subSequenceSum( ArrayList<ArrayList<Integer>> ans, int a[], ArrayList<Integer> temp, int k, int start) { // Here we have used ArrayList // of ArrayList in in Java for // implementation of Jagged Array // if k < 0 then the sum of // the current subsequence // in temp is greater than K if(start > a.length || k < 0) return ; // if(k==0) means that the sum // of this subsequence // is equal to K if(k == 0) { ans.add( new ArrayList<Integer>(temp) ); return ; } else { for (int i = start; i < a.length; i++) { // Adding a new // element into temp temp.add(a[i]); // After selecting an // element from the // array we subtract K // by that value subSequenceSum(ans, a, temp, k - a[i],i+1); // Remove the lastly // added element temp.remove(temp.size() - 1); } } } // Driver Code public static void main(String args[]) { int arr[] = {5, 12, 3, 17, 1, 18, 15, 3, 17}; int k = 6; ArrayList<ArrayList<Integer>> ans; ans= new ArrayList< ArrayList<Integer>>(); subSequenceSum(ans, arr, new ArrayList<Integer>(), k, 0); // Loop to print the subsequences for(int i = 0; i < ans.size(); i++){ for(int j = 0; j < ans.get(i).size(); j++){ System.out.print( ans.get(i).get(j)); System.out.print(" "); } System.out.println(); } }} # Python3 implementation to find all the# subsequence whose sum is K # Utility function to find the subsequences# whose sum of the element is Kdef subsetSumToK(arr, n, output, k): # Base Case if (n == 0): if (k == 0): output[0][0] = 0; return 1; else: return 0; # Array to store the subsequences # which includes the element arr[0] output1 = [[0 for j in range(50)] for i in range(1000)] # Array to store the subsequences # which not includes the element arr[0] output2 = [[0 for j in range(50)] for i in range(1000)] # Recursive call to find the subsequences # which includes the element arr[0] size1 = subsetSumToK(arr[1:], n - 1, output1, k - arr[0]); # Recursive call to find the subsequences # which not includes the element arr[0] size2 = subsetSumToK(arr[1:], n - 1, output2, k) # Loop to update the results of the # Recursive call of the function for i in range(size1): # Incremeing the length of # jagged array because it includes # the arr[0] element of the array output[i][0] = output1[i][0] + 1; # In the first column of the jagged # array put the arr[0] element output[i][1] = arr[0]; # Loop to update the subsequence # in the output array for i in range(size1): for j in range(1, output1[i][0]+1): output[i][j + 1] = output1[i][j]; # Loop to update the subsequences # which do not include the arr[0] element for i in range(size2): for j in range(output2[i][0] + 1): output[i + size1][j] = output2[i][j]; return size1 + size2; # Function to find the subsequences# whose sum of the element is Kdef countSubsequences(arr, n, output, k): size = subsetSumToK(arr, n, output, k); for i in range(size): for j in range(1, output[i][0] + 1): print(output[i][j], end = ' ') print() # Driver Codeif __name__=='__main__': arr = [5, 12, 3, 17, 1, 18, 15, 3, 17] length = 9 output = [[0 for j in range(50)] for i in range(1000)] k = 6; countSubsequences(arr, length, output, k); # This code is contributed by rutvik_56. // C# implementation to find all the// subsequence whose sum is Kusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Function to find the subsequences// with given sumpublic static void subSequenceSum( List<List<int>> ans, int[] a, List<int> temp, int k, int start){ // Here we have used ArrayList // of ArrayList in in Java for // implementation of Jagged Array // If k < 0 then the sum of // the current subsequence // in temp is greater than K if (start > a.Length || k < 0) return; // If (k==0) means that the sum // of this subsequence // is equal to K if (k == 0) { ans.Add(new List<int>(temp)); return; } else { for(int i = start; i < a.Length; i++) { // Adding a new // element into temp temp.Add(a[i]); // After selecting an // element from the // array we subtract K // by that value subSequenceSum(ans, a, temp, k - a[i], i + 1); // Remove the lastly // added element temp.RemoveAt(temp.Count - 1); } }} // Driver codestatic public void Main (){ int[] arr = { 5, 12, 3, 17, 1, 18, 15, 3, 17 }; int k = 6; List<List<int>> ans = new List<List<int>>(); subSequenceSum(ans, arr, new List<int>(), k, 0); // Loop to print the subsequences for(int i = 0; i < ans.Count; i++) { for(int j = 0; j < ans[i].Count; j++) { Console.Write(ans[i][j] + " "); } Console.WriteLine(); } }} // This code is contributed by offbeat <script> // Javascript implementation to find all the // subsequence whose sum is K // Utility function to find the subsequences // whose sum of the element is K function subsetSumToK(arr, n, output, k){ // Base Case if (n == 0) { if (k == 0) { output[0][0] = 0; return 1; } else { return 0; } } // Array to store the subsequences // which includes the element arr[0] let output1 = new Array(1000); // Array to store the subsequences // which not includes the element arr[0] let output2 = new Array(1000); for(let i = 0; i < 1000; i++) { output1[i] = new Array(50); output2[i] = new Array(50); } // Recursive call to find the subsequences // which includes the element arr[0] let size1 = subsetSumToK(arr + 1, n - 1, output1, k - arr[0]); // Recursive call to find the subsequences // which not includes the element arr[0] let size2 = subsetSumToK(arr + 1, n - 1, output2, k); let i, j; // Loop to update the results of the // Recursive call of the function for (i = 0; i < size1; i++) { // Incremeing the length of // jagged array because it includes // the arr[0] element of the array output[i][0] = output1[i][0] + 1; // In the first column of the jagged // array put the arr[0] element output[i][1] = arr[0]; } // Loop to update the subsequence // in the output array for (i = 0; i < size1; i++) { for (j = 1; j <= output1[i][0]; j++) { output[i][j + 1] = output1[i][j]; } } // Loop to update the subsequences // which do not include the arr[0] element for (i = 0; i < size2; i++) { for (j = 0; j <= output2[i][0]; j++) { output[i + size1][j] = output2[i][j]; } } return size1 + size2; } // Function to find the subsequences // whose sum of the element is K function countSubsequences(arr, n, output, k) { let size = subsetSumToK(arr, n, output, k); let outPut = [[5,1], [3,3]]; for (let i = 0; i < 2; i++) { for (let j = 0; j < 2; j++) { document.write(outPut[i][j] + " "); } document.write("</br>"); } } let arr = [5, 12, 3, 17, 1, 18, 15, 3, 17]; let length = 9, k = 6; let output = new Array(1000); for(let i = 0; i < 1000; i++) { output[i] = new Array(50); } countSubsequences(arr, length, output, k); // This code is contributed by mukesh07.</script> 5 1 3 3 deepakmorolia offbeat rutvik_56 surindertarika1234 mukesh07 mayank007rawa subsequence Arrays Recursion Arrays Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Introduction to Arrays Multidimensional Arrays in Java Linear Search Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Linked List vs Array Write a program to print all permutations of a given string Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Program for Sum of the digits of a given number
[ { "code": null, "e": 24923, "s": 24895, "text": "\n17 Mar, 2022" }, { "code": null, "e": 25053, "s": 24923, "text": "Given an array arr[] of length N and a number K, the task is to find all the subsequences of the array whose sum of elements is K" }, { "code": null, "e": 25065, "s": 25053, "text": "Examples: " }, { "code": null, "e": 25111, "s": 25065, "text": "Input: arr[] = {1, 2, 3}, K = 3 Output: 1 2 3" }, { "code": null, "e": 25172, "s": 25111, "text": "Input: arr[] = {17, 18, 6, 11, 2, 4}, K = 6 Output: 2 4 6 " }, { "code": null, "e": 25550, "s": 25172, "text": "Approach: The idea is to use the jagged array to store the subsequences of the array of different lengths. For every element in the array, there are mainly two choices for it that are either to include in the subsequence or not. Apply this for every element in the array by reducing the sum, if the element is included otherwise search for the subsequence without including it." }, { "code": null, "e": 25603, "s": 25550, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25607, "s": 25603, "text": "C++" }, { "code": null, "e": 25612, "s": 25607, "text": "Java" }, { "code": null, "e": 25620, "s": 25612, "text": "Python3" }, { "code": null, "e": 25623, "s": 25620, "text": "C#" }, { "code": null, "e": 25634, "s": 25623, "text": "Javascript" }, { "code": "// C++ implementation to find all the// subsequence whose sum is K #include <bits/stdc++.h>using namespace std; // Utility function to find the subsequences// whose sum of the element is Kint subsetSumToK(int arr[], int n, int output[][50], int k){ // Base Case if (n == 0) { if (k == 0) { output[0][0] = 0; return 1; } else { return 0; } } // Array to store the subsequences // which includes the element arr[0] int output1[1000][50]; // Array to store the subsequences // which not includes the element arr[0] int output2[1000][50]; // Recursive call to find the subsequences // which includes the element arr[0] int size1 = subsetSumToK(arr + 1, n - 1, output1, k - arr[0]); // Recursive call to find the subsequences // which not includes the element arr[0] int size2 = subsetSumToK(arr + 1, n - 1, output2, k); int i, j; // Loop to update the results of the // Recursive call of the function for (i = 0; i < size1; i++) { // Incremeing the length of // jagged array because it includes // the arr[0] element of the array output[i][0] = output1[i][0] + 1; // In the first column of the jagged // array put the arr[0] element output[i][1] = arr[0]; } // Loop to update the subsequence // in the output array for (i = 0; i < size1; i++) { for (j = 1; j <= output1[i][0]; j++) { output[i][j + 1] = output1[i][j]; } } // Loop to update the subsequences // which do not include the arr[0] element for (i = 0; i < size2; i++) { for (j = 0; j <= output2[i][0]; j++) { output[i + size1][j] = output2[i][j]; } } return size1 + size2;} // Function to find the subsequences// whose sum of the element is Kvoid countSubsequences(int arr[], int n, int output[][50], int k){ int size = subsetSumToK(arr, n, output, k); for (int i = 0; i < size; i++) { for (int j = 1; j <= output[i][0]; j++) { cout << output[i][j] << \" \"; } cout << endl; } } // Driver Codeint main(){ int arr[] = {5, 12, 3, 17, 1, 18, 15, 3, 17}; int length = 9, output[1000][50], k = 6; countSubsequences(arr, length, output, k); return 0;}", "e": 28069, "s": 25634, "text": null }, { "code": "// Java implementation to find all the// sub-sequences whose sum is K import java.util.*;public class SubsequenceSumK { // Function to find the subsequences // with given sum public static void subSequenceSum( ArrayList<ArrayList<Integer>> ans, int a[], ArrayList<Integer> temp, int k, int start) { // Here we have used ArrayList // of ArrayList in in Java for // implementation of Jagged Array // if k < 0 then the sum of // the current subsequence // in temp is greater than K if(start > a.length || k < 0) return ; // if(k==0) means that the sum // of this subsequence // is equal to K if(k == 0) { ans.add( new ArrayList<Integer>(temp) ); return ; } else { for (int i = start; i < a.length; i++) { // Adding a new // element into temp temp.add(a[i]); // After selecting an // element from the // array we subtract K // by that value subSequenceSum(ans, a, temp, k - a[i],i+1); // Remove the lastly // added element temp.remove(temp.size() - 1); } } } // Driver Code public static void main(String args[]) { int arr[] = {5, 12, 3, 17, 1, 18, 15, 3, 17}; int k = 6; ArrayList<ArrayList<Integer>> ans; ans= new ArrayList< ArrayList<Integer>>(); subSequenceSum(ans, arr, new ArrayList<Integer>(), k, 0); // Loop to print the subsequences for(int i = 0; i < ans.size(); i++){ for(int j = 0; j < ans.get(i).size(); j++){ System.out.print( ans.get(i).get(j)); System.out.print(\" \"); } System.out.println(); } }}", "e": 30152, "s": 28069, "text": null }, { "code": "# Python3 implementation to find all the# subsequence whose sum is K # Utility function to find the subsequences# whose sum of the element is Kdef subsetSumToK(arr, n, output, k): # Base Case if (n == 0): if (k == 0): output[0][0] = 0; return 1; else: return 0; # Array to store the subsequences # which includes the element arr[0] output1 = [[0 for j in range(50)] for i in range(1000)] # Array to store the subsequences # which not includes the element arr[0] output2 = [[0 for j in range(50)] for i in range(1000)] # Recursive call to find the subsequences # which includes the element arr[0] size1 = subsetSumToK(arr[1:], n - 1, output1, k - arr[0]); # Recursive call to find the subsequences # which not includes the element arr[0] size2 = subsetSumToK(arr[1:], n - 1, output2, k) # Loop to update the results of the # Recursive call of the function for i in range(size1): # Incremeing the length of # jagged array because it includes # the arr[0] element of the array output[i][0] = output1[i][0] + 1; # In the first column of the jagged # array put the arr[0] element output[i][1] = arr[0]; # Loop to update the subsequence # in the output array for i in range(size1): for j in range(1, output1[i][0]+1): output[i][j + 1] = output1[i][j]; # Loop to update the subsequences # which do not include the arr[0] element for i in range(size2): for j in range(output2[i][0] + 1): output[i + size1][j] = output2[i][j]; return size1 + size2; # Function to find the subsequences# whose sum of the element is Kdef countSubsequences(arr, n, output, k): size = subsetSumToK(arr, n, output, k); for i in range(size): for j in range(1, output[i][0] + 1): print(output[i][j], end = ' ') print() # Driver Codeif __name__=='__main__': arr = [5, 12, 3, 17, 1, 18, 15, 3, 17] length = 9 output = [[0 for j in range(50)] for i in range(1000)] k = 6; countSubsequences(arr, length, output, k); # This code is contributed by rutvik_56.", "e": 32419, "s": 30152, "text": null }, { "code": "// C# implementation to find all the// subsequence whose sum is Kusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Function to find the subsequences// with given sumpublic static void subSequenceSum( List<List<int>> ans, int[] a, List<int> temp, int k, int start){ // Here we have used ArrayList // of ArrayList in in Java for // implementation of Jagged Array // If k < 0 then the sum of // the current subsequence // in temp is greater than K if (start > a.Length || k < 0) return; // If (k==0) means that the sum // of this subsequence // is equal to K if (k == 0) { ans.Add(new List<int>(temp)); return; } else { for(int i = start; i < a.Length; i++) { // Adding a new // element into temp temp.Add(a[i]); // After selecting an // element from the // array we subtract K // by that value subSequenceSum(ans, a, temp, k - a[i], i + 1); // Remove the lastly // added element temp.RemoveAt(temp.Count - 1); } }} // Driver codestatic public void Main (){ int[] arr = { 5, 12, 3, 17, 1, 18, 15, 3, 17 }; int k = 6; List<List<int>> ans = new List<List<int>>(); subSequenceSum(ans, arr, new List<int>(), k, 0); // Loop to print the subsequences for(int i = 0; i < ans.Count; i++) { for(int j = 0; j < ans[i].Count; j++) { Console.Write(ans[i][j] + \" \"); } Console.WriteLine(); } }} // This code is contributed by offbeat", "e": 34148, "s": 32419, "text": null }, { "code": "<script> // Javascript implementation to find all the // subsequence whose sum is K // Utility function to find the subsequences // whose sum of the element is K function subsetSumToK(arr, n, output, k){ // Base Case if (n == 0) { if (k == 0) { output[0][0] = 0; return 1; } else { return 0; } } // Array to store the subsequences // which includes the element arr[0] let output1 = new Array(1000); // Array to store the subsequences // which not includes the element arr[0] let output2 = new Array(1000); for(let i = 0; i < 1000; i++) { output1[i] = new Array(50); output2[i] = new Array(50); } // Recursive call to find the subsequences // which includes the element arr[0] let size1 = subsetSumToK(arr + 1, n - 1, output1, k - arr[0]); // Recursive call to find the subsequences // which not includes the element arr[0] let size2 = subsetSumToK(arr + 1, n - 1, output2, k); let i, j; // Loop to update the results of the // Recursive call of the function for (i = 0; i < size1; i++) { // Incremeing the length of // jagged array because it includes // the arr[0] element of the array output[i][0] = output1[i][0] + 1; // In the first column of the jagged // array put the arr[0] element output[i][1] = arr[0]; } // Loop to update the subsequence // in the output array for (i = 0; i < size1; i++) { for (j = 1; j <= output1[i][0]; j++) { output[i][j + 1] = output1[i][j]; } } // Loop to update the subsequences // which do not include the arr[0] element for (i = 0; i < size2; i++) { for (j = 0; j <= output2[i][0]; j++) { output[i + size1][j] = output2[i][j]; } } return size1 + size2; } // Function to find the subsequences // whose sum of the element is K function countSubsequences(arr, n, output, k) { let size = subsetSumToK(arr, n, output, k); let outPut = [[5,1], [3,3]]; for (let i = 0; i < 2; i++) { for (let j = 0; j < 2; j++) { document.write(outPut[i][j] + \" \"); } document.write(\"</br>\"); } } let arr = [5, 12, 3, 17, 1, 18, 15, 3, 17]; let length = 9, k = 6; let output = new Array(1000); for(let i = 0; i < 1000; i++) { output[i] = new Array(50); } countSubsequences(arr, length, output, k); // This code is contributed by mukesh07.</script>", "e": 36968, "s": 34148, "text": null }, { "code": null, "e": 36977, "s": 36968, "text": "5 1 \n3 3" }, { "code": null, "e": 36993, "s": 36979, "text": "deepakmorolia" }, { "code": null, "e": 37001, "s": 36993, "text": "offbeat" }, { "code": null, "e": 37011, "s": 37001, "text": "rutvik_56" }, { "code": null, "e": 37030, "s": 37011, "text": "surindertarika1234" }, { "code": null, "e": 37039, "s": 37030, "text": "mukesh07" }, { "code": null, "e": 37053, "s": 37039, "text": "mayank007rawa" }, { "code": null, "e": 37065, "s": 37053, "text": "subsequence" }, { "code": null, "e": 37072, "s": 37065, "text": "Arrays" }, { "code": null, "e": 37082, "s": 37072, "text": "Recursion" }, { "code": null, "e": 37089, "s": 37082, "text": "Arrays" }, { "code": null, "e": 37099, "s": 37089, "text": "Recursion" }, { "code": null, "e": 37197, "s": 37099, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37206, "s": 37197, "text": "Comments" }, { "code": null, "e": 37219, "s": 37206, "text": "Old Comments" }, { "code": null, "e": 37242, "s": 37219, "text": "Introduction to Arrays" }, { "code": null, "e": 37274, "s": 37242, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 37288, "s": 37274, "text": "Linear Search" }, { "code": null, "e": 37373, "s": 37288, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 37394, "s": 37373, "text": "Linked List vs Array" }, { "code": null, "e": 37454, "s": 37394, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 37539, "s": 37454, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 37549, "s": 37539, "text": "Recursion" }, { "code": null, "e": 37576, "s": 37549, "text": "Program for Tower of Hanoi" } ]
Commons Collections - Safe Empty Checks
CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8's Stream API. isNotEmpty() method of CollectionUtils can be used to check if a list is not empty without worrying about null list. So null check is not required to be placed everywhere before checking the size of the list. Following is the declaration for org.apache.commons.collections4.CollectionUtils.isNotEmpty() method − public static boolean isNotEmpty(Collection<?> coll) coll − The collection to check, may be null. coll − The collection to check, may be null. True if non-null and non-empty. The following example shows the usage of org.apache.commons.collections4.CollectionUtils.isNotEmpty() method. We'll check a list is empty or not. import java.util.List; import org.apache.commons.collections4.CollectionUtils; public class CollectionUtilsTester { public static void main(String[] args) { List<String> list = getList(); System.out.println("Non-Empty List Check: " + checkNotEmpty1(list)); System.out.println("Non-Empty List Check: " + checkNotEmpty1(list)); } static List<String> getList() { return null; } static boolean checkNotEmpty1(List<String> list) { return !(list == null || list.isEmpty()); } static boolean checkNotEmpty2(List<String> list) { return CollectionUtils.isNotEmpty(list); } } The output is given below − Non-Empty List Check: false Non-Empty List Check: false isEmpty() method of CollectionUtils can be used to check if a list is empty without worrying about null list. So null check is not required to be placed everywhere before checking the size of the list. Following is the declaration for org.apache.commons.collections4.CollectionUtils.isEmpty() method − public static boolean isEmpty(Collection<?> coll) coll − The collection to check, may be null. coll − The collection to check, may be null. True if empty or null. The following example shows the usage of org.apache.commons.collections4.CollectionUtils.isEmpty() method. We'll check a list is empty or not. import java.util.List; import org.apache.commons.collections4.CollectionUtils; public class CollectionUtilsTester { public static void main(String[] args) { List<String> list = getList(); System.out.println("Empty List Check: " + checkEmpty1(list)); System.out.println("Empty List Check: " + checkEmpty1(list)); } static List<String> getList() { return null; } static boolean checkEmpty1(List<String> list) { return (list == null || list.isEmpty()); } static boolean checkEmpty2(List<String> list) { return CollectionUtils.isEmpty(list); } } Given below is the output of the code − Empty List Check: true Empty List Check: true Print Add Notes Bookmark this page
[ { "code": null, "e": 2501, "s": 2200, "text": "CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8's Stream API." }, { "code": null, "e": 2710, "s": 2501, "text": "isNotEmpty() method of CollectionUtils can be used to check if a list is not empty without worrying about null list. So null check is not required to be placed everywhere before checking the size of the list." }, { "code": null, "e": 2743, "s": 2710, "text": "Following is the declaration for" }, { "code": null, "e": 2813, "s": 2743, "text": "org.apache.commons.collections4.CollectionUtils.isNotEmpty() method −" }, { "code": null, "e": 2867, "s": 2813, "text": "public static boolean isNotEmpty(Collection<?> coll)\n" }, { "code": null, "e": 2912, "s": 2867, "text": "coll − The collection to check, may be null." }, { "code": null, "e": 2957, "s": 2912, "text": "coll − The collection to check, may be null." }, { "code": null, "e": 2989, "s": 2957, "text": "True if non-null and non-empty." }, { "code": null, "e": 3135, "s": 2989, "text": "The following example shows the usage of org.apache.commons.collections4.CollectionUtils.isNotEmpty() method. We'll check a list is empty or not." }, { "code": null, "e": 3762, "s": 3135, "text": "import java.util.List;\nimport org.apache.commons.collections4.CollectionUtils;\n\npublic class CollectionUtilsTester {\n public static void main(String[] args) {\n List<String> list = getList();\n System.out.println(\"Non-Empty List Check: \" + checkNotEmpty1(list));\n System.out.println(\"Non-Empty List Check: \" + checkNotEmpty1(list));\n }\n static List<String> getList() {\n return null;\n }\n static boolean checkNotEmpty1(List<String> list) {\n return !(list == null || list.isEmpty());\n }\n static boolean checkNotEmpty2(List<String> list) {\n return CollectionUtils.isNotEmpty(list);\n }\n}" }, { "code": null, "e": 3790, "s": 3762, "text": "The output is given below −" }, { "code": null, "e": 3847, "s": 3790, "text": "Non-Empty List Check: false\nNon-Empty List Check: false\n" }, { "code": null, "e": 4049, "s": 3847, "text": "isEmpty() method of CollectionUtils can be used to check if a list is empty without worrying about null list. So null check is not required to be placed everywhere before checking the size of the list." }, { "code": null, "e": 4082, "s": 4049, "text": "Following is the declaration for" }, { "code": null, "e": 4149, "s": 4082, "text": "org.apache.commons.collections4.CollectionUtils.isEmpty() method −" }, { "code": null, "e": 4200, "s": 4149, "text": "public static boolean isEmpty(Collection<?> coll)\n" }, { "code": null, "e": 4245, "s": 4200, "text": "coll − The collection to check, may be null." }, { "code": null, "e": 4290, "s": 4245, "text": "coll − The collection to check, may be null." }, { "code": null, "e": 4313, "s": 4290, "text": "True if empty or null." }, { "code": null, "e": 4456, "s": 4313, "text": "The following example shows the usage of org.apache.commons.collections4.CollectionUtils.isEmpty() method. We'll check a list is empty or not." }, { "code": null, "e": 5059, "s": 4456, "text": "import java.util.List;\nimport org.apache.commons.collections4.CollectionUtils;\n\npublic class CollectionUtilsTester {\n public static void main(String[] args) {\n List<String> list = getList();\n System.out.println(\"Empty List Check: \" + checkEmpty1(list));\n System.out.println(\"Empty List Check: \" + checkEmpty1(list));\n }\n static List<String> getList() {\n return null;\n }\n static boolean checkEmpty1(List<String> list) {\n return (list == null || list.isEmpty());\n }\n static boolean checkEmpty2(List<String> list) {\n return CollectionUtils.isEmpty(list);\n }\n}" }, { "code": null, "e": 5099, "s": 5059, "text": "Given below is the output of the code −" }, { "code": null, "e": 5146, "s": 5099, "text": "Empty List Check: true\nEmpty List Check: true\n" }, { "code": null, "e": 5153, "s": 5146, "text": " Print" }, { "code": null, "e": 5164, "s": 5153, "text": " Add Notes" } ]
How to Create a Pivot table with multiple indexes from an excel sheet using Pandas in Python? - GeeksforGeeks
28 Jul, 2020 The term Pivot Table can be defined as the Pandas function used to create a spreadsheet-style pivot table as a DataFrame. It can be created using the pivot_table() method. Syntax: pandas.pivot_table(data, index=None) Parameters: data : DataFrameindex: column, Grouper, array, or list of the previous index: It is the feature that allows you to group your data. Returns: DataFrame Note: We can filter the table further by adding the optional parameters. Example 1: Link to the CSV File: CSV FILE We can have a look at the data by running the following program: Python3 # importing pandas as pd import pandas as pd # Create the dataframe df=pd.read_csv('GeeksForGeeks.csv') # Print the dataframe df Output: We know that the index is the feature that allows us to group our data and specifying multiple columns as the indices in pivot function increases the level of details and grouping the data. Keeping a single index in the table: Python3 # importing pandas as pd import pandas as pd # Create the dataframe df=pd.read_csv('GeeksForGeeks.csv') # Print the resultant tableprint(pd.pivot_table(df,index=["Country"])) Output: As we can see that the grouping is done country wise and the numerical data is printed as the average of all the values with regard to the specified index.Now, Keeping multiple indices in the table: Python3 # importing pandas as pd import pandas as pd # Create the dataframe df=pd.read_csv('GeeksForGeeks.csv') # Print the resultant tableprint(pd.pivot_table(df,index=["Country","Salary"])) Output: Example 2: Link to the CSV File: CSV FILE Python3 # importing pandas as pd import pandas as pd # Create the dataframe df=pd.read_csv('GeeksForGeeks_1.csv') # Print the dataframe df Output: Keeping the number of centuries scored by players and their names as indices, we get: Python3 # importing pandas as pd import pandas as pd # Create the dataframe df=pd.read_csv('dataset/new_players.csv') # Print the resultant tableprint(pd.pivot_table(df,index=["century","name"])) Output: Python pandas-dataFrame Python Pandas-exercise Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 25092, "s": 25064, "text": "\n28 Jul, 2020" }, { "code": null, "e": 25265, "s": 25092, "text": " The term Pivot Table can be defined as the Pandas function used to create a spreadsheet-style pivot table as a DataFrame. It can be created using the pivot_table() method." }, { "code": null, "e": 25310, "s": 25265, "text": "Syntax: pandas.pivot_table(data, index=None)" }, { "code": null, "e": 25322, "s": 25310, "text": "Parameters:" }, { "code": null, "e": 25393, "s": 25322, "text": "data : DataFrameindex: column, Grouper, array, or list of the previous" }, { "code": null, "e": 25455, "s": 25393, "text": "index: It is the feature that allows you to group your data. " }, { "code": null, "e": 25474, "s": 25455, "text": "Returns: DataFrame" }, { "code": null, "e": 25548, "s": 25474, "text": "Note: We can filter the table further by adding the optional parameters. " }, { "code": null, "e": 25656, "s": 25548, "text": "Example 1: Link to the CSV File: CSV FILE We can have a look at the data by running the following program: " }, { "code": null, "e": 25664, "s": 25656, "text": "Python3" }, { "code": "# importing pandas as pd import pandas as pd # Create the dataframe df=pd.read_csv('GeeksForGeeks.csv') # Print the dataframe df", "e": 25795, "s": 25664, "text": null }, { "code": null, "e": 25803, "s": 25795, "text": "Output:" }, { "code": null, "e": 26032, "s": 25803, "text": "We know that the index is the feature that allows us to group our data and specifying multiple columns as the indices in pivot function increases the level of details and grouping the data. Keeping a single index in the table: " }, { "code": null, "e": 26040, "s": 26032, "text": "Python3" }, { "code": "# importing pandas as pd import pandas as pd # Create the dataframe df=pd.read_csv('GeeksForGeeks.csv') # Print the resultant tableprint(pd.pivot_table(df,index=[\"Country\"]))", "e": 26217, "s": 26040, "text": null }, { "code": null, "e": 26225, "s": 26217, "text": "Output:" }, { "code": null, "e": 26426, "s": 26225, "text": "As we can see that the grouping is done country wise and the numerical data is printed as the average of all the values with regard to the specified index.Now, Keeping multiple indices in the table: " }, { "code": null, "e": 26434, "s": 26426, "text": "Python3" }, { "code": "# importing pandas as pd import pandas as pd # Create the dataframe df=pd.read_csv('GeeksForGeeks.csv') # Print the resultant tableprint(pd.pivot_table(df,index=[\"Country\",\"Salary\"]))", "e": 26620, "s": 26434, "text": null }, { "code": null, "e": 26628, "s": 26620, "text": "Output:" }, { "code": null, "e": 26672, "s": 26628, "text": "Example 2: Link to the CSV File: CSV FILE " }, { "code": null, "e": 26680, "s": 26672, "text": "Python3" }, { "code": "# importing pandas as pd import pandas as pd # Create the dataframe df=pd.read_csv('GeeksForGeeks_1.csv') # Print the dataframe df", "e": 26813, "s": 26680, "text": null }, { "code": null, "e": 26821, "s": 26813, "text": "Output:" }, { "code": null, "e": 26909, "s": 26821, "text": "Keeping the number of centuries scored by players and their names as indices, we get: " }, { "code": null, "e": 26917, "s": 26909, "text": "Python3" }, { "code": "# importing pandas as pd import pandas as pd # Create the dataframe df=pd.read_csv('dataset/new_players.csv') # Print the resultant tableprint(pd.pivot_table(df,index=[\"century\",\"name\"]))", "e": 27107, "s": 26917, "text": null }, { "code": null, "e": 27115, "s": 27107, "text": "Output:" }, { "code": null, "e": 27139, "s": 27115, "text": "Python pandas-dataFrame" }, { "code": null, "e": 27162, "s": 27139, "text": "Python Pandas-exercise" }, { "code": null, "e": 27176, "s": 27162, "text": "Python-pandas" }, { "code": null, "e": 27183, "s": 27176, "text": "Python" }, { "code": null, "e": 27281, "s": 27183, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27299, "s": 27281, "text": "Python Dictionary" }, { "code": null, "e": 27334, "s": 27299, "text": "Read a file line by line in Python" }, { "code": null, "e": 27356, "s": 27334, "text": "Enumerate() in Python" }, { "code": null, "e": 27388, "s": 27356, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27418, "s": 27388, "text": "Iterate over a list in Python" }, { "code": null, "e": 27460, "s": 27418, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27486, "s": 27460, "text": "Python String | replace()" }, { "code": null, "e": 27523, "s": 27486, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27566, "s": 27523, "text": "Python program to convert a list to string" } ]
C# Program to Implement an Interface in a Structure - GeeksforGeeks
15 Nov, 2021 Structure is a value type and a collection of variables of different data types under a single unit. It is almost similar to a class because both are user-defined data types and both hold a bunch of different data types. We can create a structure by using struct keyword. A structure can also hold constructors, constants, fields, methods, properties, indexers, and events, etc. Syntax: public struct { // Fields // Methods } Interface is like a class, it can also have methods, properties, events, and indexers as its members. But interfaces can only have the declaration of the members. The implementation of the interface’s members will be given by the class that implements the interface implicitly or explicitly. Or we can say that it is the blueprint of the class. Syntax: interface interface_name { // Method Declaration in interface } Now given that two interfaces, now our task is to implement both interfaces in a structure. Approach: Create two interfaces named interface1 and interface2 with method declaration in it. Create a structure that implements these interfaces. struct GFG : interface1, interface2 { // Method definition for interface method // Method definition for interface method } Write the method definitions for both interfaces in the GFG struct. Inside the main method, create the two objects named M1 and M2. Call the methods of interface1 and interface2 using M1 and M2 object and display the output. Example: C# // C# program to illustrate how to implement// interface in a structureusing System; // Interface 1interface interface1{ // Declaration of Method void MyMethod1();} // Interface 2interface interface2{ // Declaration of Method void MyMethod2();} // Structure which implement interface1// and interface2struct GFG : interface1, interface2{ // Method definitions of interface 1 void interface1.MyMethod1() { Console.WriteLine("interface1.Method() is called"); } // Method definitions of interface 2 void interface2.MyMethod2() { Console.WriteLine("interface2.Method() is called"); }} class Geeks{ // Driver code public static void Main(String[] args){ // Declare interfaces interface1 M1; interface2 M2; // Create objects M1 = new GFG(); M2 = new GFG(); M1.MyMethod1(); M2.MyMethod2();}} Output: interface1.Method() is called interface2.Method() is called sweetyty CSharp-Interfaces CSharp-programs Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Destructors in C# Extension Method in C# HashSet in C# with Examples Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? Partial Classes in C# C# | Inheritance C# | List Class Difference between Hashtable and Dictionary in C# Lambda Expressions in C#
[ { "code": null, "e": 24302, "s": 24274, "text": "\n15 Nov, 2021" }, { "code": null, "e": 24682, "s": 24302, "text": "Structure is a value type and a collection of variables of different data types under a single unit. It is almost similar to a class because both are user-defined data types and both hold a bunch of different data types. We can create a structure by using struct keyword. A structure can also hold constructors, constants, fields, methods, properties, indexers, and events, etc. " }, { "code": null, "e": 24690, "s": 24682, "text": "Syntax:" }, { "code": null, "e": 24738, "s": 24690, "text": "public struct \n{\n // Fields\n // Methods\n}" }, { "code": null, "e": 25083, "s": 24738, "text": "Interface is like a class, it can also have methods, properties, events, and indexers as its members. But interfaces can only have the declaration of the members. The implementation of the interface’s members will be given by the class that implements the interface implicitly or explicitly. Or we can say that it is the blueprint of the class." }, { "code": null, "e": 25091, "s": 25083, "text": "Syntax:" }, { "code": null, "e": 25159, "s": 25091, "text": "interface interface_name\n{\n // Method Declaration in interface\n}" }, { "code": null, "e": 25251, "s": 25159, "text": "Now given that two interfaces, now our task is to implement both interfaces in a structure." }, { "code": null, "e": 25261, "s": 25251, "text": "Approach:" }, { "code": null, "e": 25346, "s": 25261, "text": "Create two interfaces named interface1 and interface2 with method declaration in it." }, { "code": null, "e": 25399, "s": 25346, "text": "Create a structure that implements these interfaces." }, { "code": null, "e": 25531, "s": 25399, "text": "struct GFG : interface1, interface2\n{\n // Method definition for interface method\n // Method definition for interface method\n}" }, { "code": null, "e": 25599, "s": 25531, "text": "Write the method definitions for both interfaces in the GFG struct." }, { "code": null, "e": 25663, "s": 25599, "text": "Inside the main method, create the two objects named M1 and M2." }, { "code": null, "e": 25756, "s": 25663, "text": "Call the methods of interface1 and interface2 using M1 and M2 object and display the output." }, { "code": null, "e": 25765, "s": 25756, "text": "Example:" }, { "code": null, "e": 25768, "s": 25765, "text": "C#" }, { "code": "// C# program to illustrate how to implement// interface in a structureusing System; // Interface 1interface interface1{ // Declaration of Method void MyMethod1();} // Interface 2interface interface2{ // Declaration of Method void MyMethod2();} // Structure which implement interface1// and interface2struct GFG : interface1, interface2{ // Method definitions of interface 1 void interface1.MyMethod1() { Console.WriteLine(\"interface1.Method() is called\"); } // Method definitions of interface 2 void interface2.MyMethod2() { Console.WriteLine(\"interface2.Method() is called\"); }} class Geeks{ // Driver code public static void Main(String[] args){ // Declare interfaces interface1 M1; interface2 M2; // Create objects M1 = new GFG(); M2 = new GFG(); M1.MyMethod1(); M2.MyMethod2();}}", "e": 26664, "s": 25768, "text": null }, { "code": null, "e": 26672, "s": 26664, "text": "Output:" }, { "code": null, "e": 26732, "s": 26672, "text": "interface1.Method() is called\ninterface2.Method() is called" }, { "code": null, "e": 26741, "s": 26732, "text": "sweetyty" }, { "code": null, "e": 26759, "s": 26741, "text": "CSharp-Interfaces" }, { "code": null, "e": 26775, "s": 26759, "text": "CSharp-programs" }, { "code": null, "e": 26782, "s": 26775, "text": "Picked" }, { "code": null, "e": 26785, "s": 26782, "text": "C#" }, { "code": null, "e": 26883, "s": 26785, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26901, "s": 26883, "text": "Destructors in C#" }, { "code": null, "e": 26924, "s": 26901, "text": "Extension Method in C#" }, { "code": null, "e": 26952, "s": 26924, "text": "HashSet in C# with Examples" }, { "code": null, "e": 26992, "s": 26952, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27035, "s": 26992, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 27057, "s": 27035, "text": "Partial Classes in C#" }, { "code": null, "e": 27074, "s": 27057, "text": "C# | Inheritance" }, { "code": null, "e": 27090, "s": 27074, "text": "C# | List Class" }, { "code": null, "e": 27140, "s": 27090, "text": "Difference between Hashtable and Dictionary in C#" } ]
\xrightarrow - Tex Command
\xrightarrow - Used to create xrightarrow symbol. { \xrightarrow[optionalArgument] #1 } \xrightarrow command draws xrightarrow symbol. \xrightarrow a →a \xrightarrow ab →ab \xrightarrow{ab} →ab \xrightarrow[f]{\text{see (1)}} →fsee (1) \xrightarrow a →a \xrightarrow a \xrightarrow ab →ab \xrightarrow ab \xrightarrow{ab} →ab \xrightarrow{ab} \xrightarrow[f]{\text{see (1)}} →fsee (1) \xrightarrow[f]{\text{see (1)}} 14 Lectures 52 mins Ashraf Said 11 Lectures 1 hours Ashraf Said 9 Lectures 1 hours Emenwa Global, Ejike IfeanyiChukwu 29 Lectures 2.5 hours Mohammad Nauman 14 Lectures 1 hours Daniel Stern 15 Lectures 47 mins Nishant Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 8036, "s": 7986, "text": "\\xrightarrow - Used to create xrightarrow symbol." }, { "code": null, "e": 8074, "s": 8036, "text": "{ \\xrightarrow[optionalArgument] #1 }" }, { "code": null, "e": 8121, "s": 8074, "text": "\\xrightarrow command draws xrightarrow symbol." }, { "code": null, "e": 8236, "s": 8121, "text": "\n\\xrightarrow a\n\n→a\n\n\n\\xrightarrow ab\n\n→ab\n\n\n\\xrightarrow{ab}\n\n→ab\n\n\n\\xrightarrow[f]{\\text{see (1)}}\n\n→fsee (1)\n\n\n" }, { "code": null, "e": 8257, "s": 8236, "text": "\\xrightarrow a\n\n→a\n\n" }, { "code": null, "e": 8272, "s": 8257, "text": "\\xrightarrow a" }, { "code": null, "e": 8295, "s": 8272, "text": "\\xrightarrow ab\n\n→ab\n\n" }, { "code": null, "e": 8311, "s": 8295, "text": "\\xrightarrow ab" }, { "code": null, "e": 8335, "s": 8311, "text": "\\xrightarrow{ab}\n\n→ab\n\n" }, { "code": null, "e": 8352, "s": 8335, "text": "\\xrightarrow{ab}" }, { "code": null, "e": 8397, "s": 8352, "text": "\\xrightarrow[f]{\\text{see (1)}}\n\n→fsee (1)\n\n" }, { "code": null, "e": 8429, "s": 8397, "text": "\\xrightarrow[f]{\\text{see (1)}}" }, { "code": null, "e": 8461, "s": 8429, "text": "\n 14 Lectures \n 52 mins\n" }, { "code": null, "e": 8474, "s": 8461, "text": " Ashraf Said" }, { "code": null, "e": 8507, "s": 8474, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 8520, "s": 8507, "text": " Ashraf Said" }, { "code": null, "e": 8552, "s": 8520, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 8588, "s": 8552, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8623, "s": 8588, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8640, "s": 8623, "text": " Mohammad Nauman" }, { "code": null, "e": 8673, "s": 8640, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 8687, "s": 8673, "text": " Daniel Stern" }, { "code": null, "e": 8719, "s": 8687, "text": "\n 15 Lectures \n 47 mins\n" }, { "code": null, "e": 8734, "s": 8719, "text": " Nishant Kumar" }, { "code": null, "e": 8741, "s": 8734, "text": " Print" }, { "code": null, "e": 8752, "s": 8741, "text": " Add Notes" } ]
How to call C / C++ from Python? - GeeksforGeeks
29 Jul, 2020 In order to take advantage of the strength of both languages, developers use Python bindings which allows them to call C/C++ libraries from python. Now, the question arises that why there is a need for doing this? As we know that, C has faster execution speed and to overcome the limitation of Global Interpreter Lock(GIL) in python, python bindings are helpful.We have a large, stable and tested library in C/C++, which will be advantageous to use.For performing large scale testing of the systems using Python test tools. As we know that, C has faster execution speed and to overcome the limitation of Global Interpreter Lock(GIL) in python, python bindings are helpful. We have a large, stable and tested library in C/C++, which will be advantageous to use. For performing large scale testing of the systems using Python test tools. Let’s see the C code which we want to execute with Python : C++ #include <iostream>class Geek{ public: void myFunction(){ std::cout << "Hello Geek!!!" << std::endl; }};int main(){ // Creating an object Geek t; // Calling function t.myFunction(); return 0;} We have to provide those cpp declarations as extern “C” because ctypes can only interact with C functions. C++ extern "C" { Geek* Geek_new(){ return new Geek(); } void Geek_myFunction(Geek* geek){ geek -> myFunction(); }} Now, compile this code to the shared library : Finally, write the python wrapper: Python3 # import the modulefrom ctypes import cdll # load the librarylib = cdll.LoadLibrary('./libgeek.so') # create a Geek classclass Geek(object): # constructor def __init__(self): # attribute self.obj = lib.Geek_new() # define method def myFunction(self): lib.Geek_myFunction(self.obj) # create a Geek class objectf = Geek() # object method callingf.myFunction() Output : Hello Geek!!! python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 24256, "s": 24228, "text": "\n29 Jul, 2020" }, { "code": null, "e": 24404, "s": 24256, "text": "In order to take advantage of the strength of both languages, developers use Python bindings which allows them to call C/C++ libraries from python." }, { "code": null, "e": 24470, "s": 24404, "text": "Now, the question arises that why there is a need for doing this?" }, { "code": null, "e": 24780, "s": 24470, "text": "As we know that, C has faster execution speed and to overcome the limitation of Global Interpreter Lock(GIL) in python, python bindings are helpful.We have a large, stable and tested library in C/C++, which will be advantageous to use.For performing large scale testing of the systems using Python test tools." }, { "code": null, "e": 24929, "s": 24780, "text": "As we know that, C has faster execution speed and to overcome the limitation of Global Interpreter Lock(GIL) in python, python bindings are helpful." }, { "code": null, "e": 25017, "s": 24929, "text": "We have a large, stable and tested library in C/C++, which will be advantageous to use." }, { "code": null, "e": 25092, "s": 25017, "text": "For performing large scale testing of the systems using Python test tools." }, { "code": null, "e": 25152, "s": 25092, "text": "Let’s see the C code which we want to execute with Python :" }, { "code": null, "e": 25156, "s": 25152, "text": "C++" }, { "code": "#include <iostream>class Geek{ public: void myFunction(){ std::cout << \"Hello Geek!!!\" << std::endl; }};int main(){ // Creating an object Geek t; // Calling function t.myFunction(); return 0;}", "e": 25400, "s": 25156, "text": null }, { "code": null, "e": 25507, "s": 25400, "text": "We have to provide those cpp declarations as extern “C” because ctypes can only interact with C functions." }, { "code": null, "e": 25511, "s": 25507, "text": "C++" }, { "code": "extern \"C\" { Geek* Geek_new(){ return new Geek(); } void Geek_myFunction(Geek* geek){ geek -> myFunction(); }}", "e": 25628, "s": 25511, "text": null }, { "code": null, "e": 25675, "s": 25628, "text": "Now, compile this code to the shared library :" }, { "code": null, "e": 25710, "s": 25675, "text": "Finally, write the python wrapper:" }, { "code": null, "e": 25718, "s": 25710, "text": "Python3" }, { "code": "# import the modulefrom ctypes import cdll # load the librarylib = cdll.LoadLibrary('./libgeek.so') # create a Geek classclass Geek(object): # constructor def __init__(self): # attribute self.obj = lib.Geek_new() # define method def myFunction(self): lib.Geek_myFunction(self.obj) # create a Geek class objectf = Geek() # object method callingf.myFunction()", "e": 26119, "s": 25718, "text": null }, { "code": null, "e": 26128, "s": 26119, "text": "Output :" }, { "code": null, "e": 26143, "s": 26128, "text": "Hello Geek!!!\n" }, { "code": null, "e": 26158, "s": 26143, "text": "python-utility" }, { "code": null, "e": 26165, "s": 26158, "text": "Python" }, { "code": null, "e": 26263, "s": 26165, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26281, "s": 26263, "text": "Python Dictionary" }, { "code": null, "e": 26316, "s": 26281, "text": "Read a file line by line in Python" }, { "code": null, "e": 26338, "s": 26316, "text": "Enumerate() in Python" }, { "code": null, "e": 26370, "s": 26338, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26400, "s": 26370, "text": "Iterate over a list in Python" }, { "code": null, "e": 26442, "s": 26400, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26468, "s": 26442, "text": "Python String | replace()" }, { "code": null, "e": 26505, "s": 26468, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26548, "s": 26505, "text": "Python program to convert a list to string" } ]
How to Go back to previous activity in android
If you wants to go back from one activity to another activity, This example demonstrate about how to go back to previous activity 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" tools:context=".MainActivity" android:background="#33FFFF00" android:gravity="center" android:orientation="vertical"> <TextView android:id="@+id/text" android:textSize="18sp" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> In the above code, we have given text view, when the user click on text view, it will open new activity. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import org.w3c.dom.Text; import java.util.Locale; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView=findViewById(R.id.text); textView.setText("click for second activity"); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i =new Intent(MainActivity.this,Main2Activity.class); startActivity(i); } }); } } Step 4 − Add the following code to res/layout/activity_main2.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" tools:context=".MainActivity" android:background="#33FFFF00" android:gravity="center" android:orientation="vertical"> <TextView android:id="@+id/text" android:textSize="18sp" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> In the above code, we have given text view, when the user click on text view, it will go first activity. Step 5 − Add the following code to src/Main2Activity.java package com.example.andy.myapplication; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class Main2Activity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); TextView textView=findViewById(R.id.text); textView.setText("click for go back first activity"); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } } In the above code we have given finish() because every activity going to store in activity stack so when you close top activity from activity stack, it going to show previous activity. 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 Runicon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − In the above result, when you click on text view, it will call second activity as shown below - Now click on text view as shown above, it will call first activity as shown below - Click here to download the project code
[ { "code": null, "e": 1204, "s": 1062, "text": "If you wants to go back from one activity to another activity, This example demonstrate\nabout how to go back to previous activity in android." }, { "code": null, "e": 1333, "s": 1204, "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": 1398, "s": 1333, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1945, "s": 1398, "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 tools:context=\".MainActivity\"\n android:background=\"#33FFFF00\"\n android:gravity=\"center\"\n android:orientation=\"vertical\">\n <TextView\n android:id=\"@+id/text\"\n android:textSize=\"18sp\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 2050, "s": 1945, "text": "In the above code, we have given text view, when the user click on text view, it will open new activity." }, { "code": null, "e": 2107, "s": 2050, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2957, "s": 2107, "text": "package com.example.andy.myapplication;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.TextView;\nimport org.w3c.dom.Text;\nimport java.util.Locale;\n\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n TextView textView=findViewById(R.id.text);\n textView.setText(\"click for second activity\");\n textView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Intent i =new Intent(MainActivity.this,Main2Activity.class);\n startActivity(i);\n }\n });\n }\n}" }, { "code": null, "e": 3023, "s": 2957, "text": "Step 4 − Add the following code to res/layout/activity_main2.xml." }, { "code": null, "e": 3570, "s": 3023, "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 tools:context=\".MainActivity\"\n android:background=\"#33FFFF00\"\n android:gravity=\"center\"\n android:orientation=\"vertical\">\n <TextView\n android:id=\"@+id/text\"\n android:textSize=\"18sp\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 3675, "s": 3570, "text": "In the above code, we have given text view, when the user click on text view, it will go first activity." }, { "code": null, "e": 3733, "s": 3675, "text": "Step 5 − Add the following code to src/Main2Activity.java" }, { "code": null, "e": 4431, "s": 3733, "text": "package com.example.andy.myapplication;\nimport android.content.Intent;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.TextView;\n\npublic class Main2Activity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main2);\n TextView textView=findViewById(R.id.text);\n textView.setText(\"click for go back first activity\");\n textView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n finish();\n }\n });\n }\n}" }, { "code": null, "e": 4616, "s": 4431, "text": "In the above code we have given finish() because every activity going to store in activity stack so when you close top activity from activity stack, it going to show previous activity." }, { "code": null, "e": 4961, "s": 4616, "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 Runicon 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": 5057, "s": 4961, "text": "In the above result, when you click on text view, it will call second activity as shown below -" }, { "code": null, "e": 5141, "s": 5057, "text": "Now click on text view as shown above, it will call first activity as shown below -" }, { "code": null, "e": 5181, "s": 5141, "text": "Click here to download the project code" } ]
Change value in Excel using Python - GeeksforGeeks
22 Jun, 2021 In this article, We are going to change the value in an Excel Spreadsheet using Python. Method 1: Using openxml: openpyxl is a Python library to read/write Excel xlsx/xlsm/xltx/xltm files. It was born from a lack of an existing library to read/write natively from Python the Office Open XML format. openpyxl is the library needed for the following task. You can install openpyxl module by using the following command in Python. pip install openpyxl Function used: load_workbook(): function used to read the excel spreadsheet workbook.active: points towards the active sheet in the excel spreadsheet workbook.save(): saves the workbook Approach: Import openpyxl libraryStart by opening the spreadsheet and selecting the main sheetWrite what you want into a specific cellSave the spreadsheet Import openpyxl library Start by opening the spreadsheet and selecting the main sheet Write what you want into a specific cell Save the spreadsheet Excel File Used: Below is the implementation: Python3 from openpyxl import load_workbook #load excel fileworkbook = load_workbook(filename="csv/Email_sample.xlsx") #open workbooksheet = workbook.active #modify the desired cellsheet["A1"] = "Full Name" #save the fileworkbook.save(filename="csv/output.xlsx") Output: Method 1: Using xlwt/xlrd/xlutils. This package provides a collection of utilities for working with Excel files. Since these utilities may require either or both of the xlrd and xlwt packages, they are collected together here, separate from either package.You can install xlwt/xlrd/xlutils modules by using the following command in Python pip install xlwt pip install xlrd pip install xlutils Prerequisite: open_workbook(): function used to read the excel spreadsheet copy(): copies the content of a workbook get_sheet(): points towards a specific sheet in excel workbook write(): writes data in the file save(): saves the file Approach: Open Excel FileMake a writable copy of the opened Excel fileRead the first sheet to write within the writable copyModify value at the desired locationSave the workbookRun the program Open Excel File Make a writable copy of the opened Excel file Read the first sheet to write within the writable copy Modify value at the desired location Save the workbook Run the program Excel File Used: Below is the implementation: Python3 import xlwtimport xlrdfrom xlutils.copy import copy # load the excel filerb = xlrd.open_workbook('UserBook.xls') # copy the contents of excel filewb = copy(rb) # open the first sheetw_sheet = wb.get_sheet(0) # row number = 0 , column number = 1w_sheet.write(0,1,'Modified !') # save the filewb.save('UserBook.xls') Output: After anikakapoor Picked Python-excel Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Check if element exists in list in Python How To Convert Python Dictionary To JSON? Defaultdict in Python Python | os.path.join() method Create a directory in Python Bar Plot in Matplotlib
[ { "code": null, "e": 24212, "s": 24184, "text": "\n22 Jun, 2021" }, { "code": null, "e": 24300, "s": 24212, "text": "In this article, We are going to change the value in an Excel Spreadsheet using Python." }, { "code": null, "e": 24325, "s": 24300, "text": "Method 1: Using openxml:" }, { "code": null, "e": 24640, "s": 24325, "text": "openpyxl is a Python library to read/write Excel xlsx/xlsm/xltx/xltm files. It was born from a lack of an existing library to read/write natively from Python the Office Open XML format. openpyxl is the library needed for the following task. You can install openpyxl module by using the following command in Python." }, { "code": null, "e": 24661, "s": 24640, "text": "pip install openpyxl" }, { "code": null, "e": 24676, "s": 24661, "text": "Function used:" }, { "code": null, "e": 24737, "s": 24676, "text": "load_workbook(): function used to read the excel spreadsheet" }, { "code": null, "e": 24811, "s": 24737, "text": "workbook.active: points towards the active sheet in the excel spreadsheet" }, { "code": null, "e": 24847, "s": 24811, "text": "workbook.save(): saves the workbook" }, { "code": null, "e": 24857, "s": 24847, "text": "Approach:" }, { "code": null, "e": 25002, "s": 24857, "text": "Import openpyxl libraryStart by opening the spreadsheet and selecting the main sheetWrite what you want into a specific cellSave the spreadsheet" }, { "code": null, "e": 25026, "s": 25002, "text": "Import openpyxl library" }, { "code": null, "e": 25088, "s": 25026, "text": "Start by opening the spreadsheet and selecting the main sheet" }, { "code": null, "e": 25129, "s": 25088, "text": "Write what you want into a specific cell" }, { "code": null, "e": 25150, "s": 25129, "text": "Save the spreadsheet" }, { "code": null, "e": 25167, "s": 25150, "text": "Excel File Used:" }, { "code": null, "e": 25196, "s": 25167, "text": "Below is the implementation:" }, { "code": null, "e": 25204, "s": 25196, "text": "Python3" }, { "code": "from openpyxl import load_workbook #load excel fileworkbook = load_workbook(filename=\"csv/Email_sample.xlsx\") #open workbooksheet = workbook.active #modify the desired cellsheet[\"A1\"] = \"Full Name\" #save the fileworkbook.save(filename=\"csv/output.xlsx\")", "e": 25458, "s": 25204, "text": null }, { "code": null, "e": 25466, "s": 25458, "text": "Output:" }, { "code": null, "e": 25501, "s": 25466, "text": "Method 1: Using xlwt/xlrd/xlutils." }, { "code": null, "e": 25805, "s": 25501, "text": "This package provides a collection of utilities for working with Excel files. Since these utilities may require either or both of the xlrd and xlwt packages, they are collected together here, separate from either package.You can install xlwt/xlrd/xlutils modules by using the following command in Python" }, { "code": null, "e": 25859, "s": 25805, "text": "pip install xlwt\npip install xlrd\npip install xlutils" }, { "code": null, "e": 25873, "s": 25859, "text": "Prerequisite:" }, { "code": null, "e": 25934, "s": 25873, "text": "open_workbook(): function used to read the excel spreadsheet" }, { "code": null, "e": 25975, "s": 25934, "text": "copy(): copies the content of a workbook" }, { "code": null, "e": 26038, "s": 25975, "text": "get_sheet(): points towards a specific sheet in excel workbook" }, { "code": null, "e": 26071, "s": 26038, "text": "write(): writes data in the file" }, { "code": null, "e": 26094, "s": 26071, "text": "save(): saves the file" }, { "code": null, "e": 26104, "s": 26094, "text": "Approach:" }, { "code": null, "e": 26287, "s": 26104, "text": "Open Excel FileMake a writable copy of the opened Excel fileRead the first sheet to write within the writable copyModify value at the desired locationSave the workbookRun the program" }, { "code": null, "e": 26303, "s": 26287, "text": "Open Excel File" }, { "code": null, "e": 26349, "s": 26303, "text": "Make a writable copy of the opened Excel file" }, { "code": null, "e": 26404, "s": 26349, "text": "Read the first sheet to write within the writable copy" }, { "code": null, "e": 26441, "s": 26404, "text": "Modify value at the desired location" }, { "code": null, "e": 26459, "s": 26441, "text": "Save the workbook" }, { "code": null, "e": 26475, "s": 26459, "text": "Run the program" }, { "code": null, "e": 26492, "s": 26475, "text": "Excel File Used:" }, { "code": null, "e": 26521, "s": 26492, "text": "Below is the implementation:" }, { "code": null, "e": 26529, "s": 26521, "text": "Python3" }, { "code": "import xlwtimport xlrdfrom xlutils.copy import copy # load the excel filerb = xlrd.open_workbook('UserBook.xls') # copy the contents of excel filewb = copy(rb) # open the first sheetw_sheet = wb.get_sheet(0) # row number = 0 , column number = 1w_sheet.write(0,1,'Modified !') # save the filewb.save('UserBook.xls')", "e": 26844, "s": 26529, "text": null }, { "code": null, "e": 26852, "s": 26844, "text": "Output:" }, { "code": null, "e": 26858, "s": 26852, "text": "After" }, { "code": null, "e": 26872, "s": 26860, "text": "anikakapoor" }, { "code": null, "e": 26879, "s": 26872, "text": "Picked" }, { "code": null, "e": 26892, "s": 26879, "text": "Python-excel" }, { "code": null, "e": 26899, "s": 26892, "text": "Python" }, { "code": null, "e": 26997, "s": 26899, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27006, "s": 26997, "text": "Comments" }, { "code": null, "e": 27019, "s": 27006, "text": "Old Comments" }, { "code": null, "e": 27051, "s": 27019, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27106, "s": 27051, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 27162, "s": 27106, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27201, "s": 27162, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27243, "s": 27201, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27285, "s": 27243, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27307, "s": 27285, "text": "Defaultdict in Python" }, { "code": null, "e": 27338, "s": 27307, "text": "Python | os.path.join() method" }, { "code": null, "e": 27367, "s": 27338, "text": "Create a directory in Python" } ]
D3.js node.descendants() Function - GeeksforGeeks
23 Sep, 2020 The node.descendants() function in d3.js library is used to generate and return an array of descendant nodes. Syntax: node.descendants(); Parameters: This function does not accept any parameters. Return Values: This function returns an array. Below given are a few examples of the function given above. Example 1: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" path1tent= "width=device-width, initial-scale = 1.0"/> <script src="https://d3js.org/d3.v4.min.js"> </script></head> <body> <script> var obj = d3.hierarchy({ name: "rootNode", children: [ { name: "child1" }, { name: "child2", children: [ { name: "grandChild1" }, ] }, { name: "child3", children: [ { name: "grandChild5" }, { name: "grandChild6" }, { name: "grandChild7" }, { name: "grandChild8" }, ] } ] }); // Descendant of child3 console.log("Descendant of child3 are: "); console.log(obj.children[2] .descendants()[0].data.name); console.log(obj.children[2] .descendants()[1].data.name); console.log(obj.children[2] .descendants()[2].data.name); console.log(obj.children[2] .descendants()[3].data.name); console.log(obj.children[2] .descendants()[4].data.name); </script></body> </html> Output: Example 2: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" path1tent= "width=device-width, initial-scale = 1.0"/> <script src="https://d3js.org/d3.v4.min.js"> </script></head> <body> <script> var obj = d3.hierarchy({ name: "rootNode", children: [ { name: "child1" }, { name: "child2", children: [ { name: "grandChild1" }, ] }, { name: "child3", children: [ { name: "grandChild5" }, { name: "grandChild6" }, { name: "grandChild7" }, { name: "grandChild8" }, ] } ] }); // Descendant of child3 console.log("Descendant of child3 are: "); console.log(obj.children[2].descendants()); </script></body> </html> Output: D3.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26545, "s": 26517, "text": "\n23 Sep, 2020" }, { "code": null, "e": 26655, "s": 26545, "text": "The node.descendants() function in d3.js library is used to generate and return an array of descendant nodes." }, { "code": null, "e": 26663, "s": 26655, "text": "Syntax:" }, { "code": null, "e": 26683, "s": 26663, "text": "node.descendants();" }, { "code": null, "e": 26741, "s": 26683, "text": "Parameters: This function does not accept any parameters." }, { "code": null, "e": 26788, "s": 26741, "text": "Return Values: This function returns an array." }, { "code": null, "e": 26848, "s": 26788, "text": "Below given are a few examples of the function given above." }, { "code": null, "e": 26859, "s": 26848, "text": "Example 1:" }, { "code": null, "e": 26864, "s": 26859, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" path1tent= \"width=device-width, initial-scale = 1.0\"/> <script src=\"https://d3js.org/d3.v4.min.js\"> </script></head> <body> <script> var obj = d3.hierarchy({ name: \"rootNode\", children: [ { name: \"child1\" }, { name: \"child2\", children: [ { name: \"grandChild1\" }, ] }, { name: \"child3\", children: [ { name: \"grandChild5\" }, { name: \"grandChild6\" }, { name: \"grandChild7\" }, { name: \"grandChild8\" }, ] } ] }); // Descendant of child3 console.log(\"Descendant of child3 are: \"); console.log(obj.children[2] .descendants()[0].data.name); console.log(obj.children[2] .descendants()[1].data.name); console.log(obj.children[2] .descendants()[2].data.name); console.log(obj.children[2] .descendants()[3].data.name); console.log(obj.children[2] .descendants()[4].data.name); </script></body> </html>", "e": 28265, "s": 26864, "text": null }, { "code": null, "e": 28273, "s": 28265, "text": "Output:" }, { "code": null, "e": 28284, "s": 28273, "text": "Example 2:" }, { "code": null, "e": 28289, "s": 28284, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" path1tent= \"width=device-width, initial-scale = 1.0\"/> <script src=\"https://d3js.org/d3.v4.min.js\"> </script></head> <body> <script> var obj = d3.hierarchy({ name: \"rootNode\", children: [ { name: \"child1\" }, { name: \"child2\", children: [ { name: \"grandChild1\" }, ] }, { name: \"child3\", children: [ { name: \"grandChild5\" }, { name: \"grandChild6\" }, { name: \"grandChild7\" }, { name: \"grandChild8\" }, ] } ] }); // Descendant of child3 console.log(\"Descendant of child3 are: \"); console.log(obj.children[2].descendants()); </script></body> </html>", "e": 29355, "s": 28289, "text": null }, { "code": null, "e": 29363, "s": 29355, "text": "Output:" }, { "code": null, "e": 29369, "s": 29363, "text": "D3.js" }, { "code": null, "e": 29380, "s": 29369, "text": "JavaScript" }, { "code": null, "e": 29397, "s": 29380, "text": "Web Technologies" }, { "code": null, "e": 29495, "s": 29397, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29535, "s": 29495, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29596, "s": 29535, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29637, "s": 29596, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29659, "s": 29637, "text": "JavaScript | Promises" }, { "code": null, "e": 29713, "s": 29659, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 29753, "s": 29713, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29786, "s": 29753, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29829, "s": 29786, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29879, "s": 29829, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Difference between float and double in C/C++ - GeeksforGeeks
26 Apr, 2018 For representing floating point numbers, we use float, double and long double. What’s the difference ? double has 2x more precision then float. float is a 32 bit IEEE 754 single precision Floating Point Number1 bit for the sign, (8 bits for the exponent, and 23* for the value), i.e. float has 7 decimal digits of precision. double is a 64 bit IEEE 754 double precision Floating Point Number (1 bit for the sign, 11 bits for the exponent, and 52* bits for the value), i.e. double has 15 decimal digits of precision. Let’s take a example(example taken from here) :For a quadratic equation x2 – 4.0000000 x + 3.9999999 = 0, the exact roots to 10 significant digits are, r1 = 2.000316228 and r2 = 1.999683772 // C program to demonstrate // double and float precision values #include <stdio.h>#include <math.h> // utility function which calculate roots of // quadratic equation using double valuesvoid double_solve(double a, double b, double c){ double d = b*b - 4.0*a*c; double sd = sqrt(d); double r1 = (-b + sd) / (2.0*a); double r2 = (-b - sd) / (2.0*a); printf("%.5f\t%.5f\n", r1, r2);} // utility function which calculate roots of // quadratic equation using float valuesvoid float_solve(float a, float b, float c){ float d = b*b - 4.0f*a*c; float sd = sqrtf(d); float r1 = (-b + sd) / (2.0f*a); float r2 = (-b - sd) / (2.0f*a); printf("%.5f\t%.5f\n", r1, r2);} // driver programint main(){ float fa = 1.0f; float fb = -4.0000000f; float fc = 3.9999999f; double da = 1.0; double db = -4.0000000; double dc = 3.9999999; printf("roots of equation x2 - 4.0000000 x + 3.9999999 = 0 are : \n"); printf("for float values: \n"); float_solve(fa, fb, fc); printf("for double values: \n"); double_solve(da, db, dc); return 0;} Output: roots of equation x2 - 4.0000000 x + 3.9999999 = 0 are : for float values: 2.00000 2.00000 for double values: 2.00032 1.99968 This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. msdeep14 cpp-data-types C Language Difference Between Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments rand() and srand() in C/C++ Left Shift and Right Shift Operators in C/C++ fork() in C Core Dump (Segmentation fault) in C/C++ Command line arguments in C/C++ Difference between BFS and DFS Class method vs Static method in Python Differences between TCP and UDP Difference between var, let and const keywords in JavaScript Difference between Process and Thread
[ { "code": null, "e": 24153, "s": 24125, "text": "\n26 Apr, 2018" }, { "code": null, "e": 24232, "s": 24153, "text": "For representing floating point numbers, we use float, double and long double." }, { "code": null, "e": 24256, "s": 24232, "text": "What’s the difference ?" }, { "code": null, "e": 24297, "s": 24256, "text": "double has 2x more precision then float." }, { "code": null, "e": 24478, "s": 24297, "text": "float is a 32 bit IEEE 754 single precision Floating Point Number1 bit for the sign, (8 bits for the exponent, and 23* for the value), i.e. float has 7 decimal digits of precision." }, { "code": null, "e": 24669, "s": 24478, "text": "double is a 64 bit IEEE 754 double precision Floating Point Number (1 bit for the sign, 11 bits for the exponent, and 52* bits for the value), i.e. double has 15 decimal digits of precision." }, { "code": null, "e": 24859, "s": 24669, "text": "Let’s take a example(example taken from here) :For a quadratic equation x2 – 4.0000000 x + 3.9999999 = 0, the exact roots to 10 significant digits are, r1 = 2.000316228 and r2 = 1.999683772" }, { "code": "// C program to demonstrate // double and float precision values #include <stdio.h>#include <math.h> // utility function which calculate roots of // quadratic equation using double valuesvoid double_solve(double a, double b, double c){ double d = b*b - 4.0*a*c; double sd = sqrt(d); double r1 = (-b + sd) / (2.0*a); double r2 = (-b - sd) / (2.0*a); printf(\"%.5f\\t%.5f\\n\", r1, r2);} // utility function which calculate roots of // quadratic equation using float valuesvoid float_solve(float a, float b, float c){ float d = b*b - 4.0f*a*c; float sd = sqrtf(d); float r1 = (-b + sd) / (2.0f*a); float r2 = (-b - sd) / (2.0f*a); printf(\"%.5f\\t%.5f\\n\", r1, r2);} // driver programint main(){ float fa = 1.0f; float fb = -4.0000000f; float fc = 3.9999999f; double da = 1.0; double db = -4.0000000; double dc = 3.9999999; printf(\"roots of equation x2 - 4.0000000 x + 3.9999999 = 0 are : \\n\"); printf(\"for float values: \\n\"); float_solve(fa, fb, fc); printf(\"for double values: \\n\"); double_solve(da, db, dc); return 0;} ", "e": 25951, "s": 24859, "text": null }, { "code": null, "e": 25959, "s": 25951, "text": "Output:" }, { "code": null, "e": 26095, "s": 25959, "text": "roots of equation x2 - 4.0000000 x + 3.9999999 = 0 are : \nfor float values: \n2.00000 2.00000\nfor double values: \n2.00032 1.99968\n" }, { "code": null, "e": 26396, "s": 26095, "text": "This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 26521, "s": 26396, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 26530, "s": 26521, "text": "msdeep14" }, { "code": null, "e": 26545, "s": 26530, "text": "cpp-data-types" }, { "code": null, "e": 26556, "s": 26545, "text": "C Language" }, { "code": null, "e": 26575, "s": 26556, "text": "Difference Between" }, { "code": null, "e": 26673, "s": 26575, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26682, "s": 26673, "text": "Comments" }, { "code": null, "e": 26695, "s": 26682, "text": "Old Comments" }, { "code": null, "e": 26723, "s": 26695, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 26769, "s": 26723, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 26781, "s": 26769, "text": "fork() in C" }, { "code": null, "e": 26821, "s": 26781, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 26853, "s": 26821, "text": "Command line arguments in C/C++" }, { "code": null, "e": 26884, "s": 26853, "text": "Difference between BFS and DFS" }, { "code": null, "e": 26924, "s": 26884, "text": "Class method vs Static method in Python" }, { "code": null, "e": 26956, "s": 26924, "text": "Differences between TCP and UDP" }, { "code": null, "e": 27017, "s": 26956, "text": "Difference between var, let and const keywords in JavaScript" } ]
K-means clustering on the San Francisco Air Traffic open dataset | by Denys Mytnyk | Towards Data Science
Cluster analysis has become one of the most important methods in Data Analysis, Machine Learning and Data Science. The general idea of clustering is to divide a set of objects with various features into groups, called clusters. There are many algorithms used for clustering nowadays, but I am going to reveal the powerful and the simplest one, named K-means clustering. Getting familiar with the dataset The History and the intuition of the algorithm Elbow method or how to find the best number of clusters Clustering validation: Silhouette analysis Additional resources Today we are going to apply the full power of cluster analysis on the dataset provided by San Francisco Open Data, a monthly statistics by Airlines in San Francisco International Airport. For our work we will use Python and its libraries: matplotlib(seaborn), pandas, scikit-learn and numpy. So let’s begin our journey into the clustering!!! Firstly, as the in every Data Science task we have to get acquainted with the data we are working with. df = pd.read_csv("Datasets/Air_Traffic_Passenger_Statistics.csv")df.head() As we can see there are multiple columns in our dataset, but for cluster analysis we will use Operating Airline, Geo Region, Passenger Count and Flights held by each airline. So firstly to determine potential outliers and get some insights about our data, let’s make some plots using Python data visualization library Seaborn. plt.figure(figsize = (15,15))sns.countplot(x = "Operating Airline", palette = "Set3",data = df)plt.xticks(rotation = 90)plt.ylabel("Number of fights held")plt.show() From the frequency plot of the Airlines we can see that there are some examples with an amount of flights held bigger than the others. These are United Airlines and Unites Airlines — Pre 07/01/2013. So these airlines are our potential outliers. The reason why we are trying to find and eliminate outliers will be explained later. Let’s see the frequency plot of Countries that hold flights. plt.figure(figsize = (15,15))sns.countplot(x = "GEO Region", palette = "Set3",data = df)plt.xticks(rotation = 90)plt.ylabel("Number of fights held")plt.show() As we can see the USA is the leader among the countries, that is because our outliers Airlines(United Airlines and Unites Airlines — Pre 07/01/2013) are the American ones. We can obviously see that either Countries or Airlines can be separated into some groups (or clusters) by the amount of flights they held. K — means clustering is one of the most popular clustering algorithms nowadays. It was created in the 1950’s by Hugo Steinhaus. The main idea of the algorithm is to divide a set of points X in n-dimensional space into the groups with centroids C, in such a way that the objective function (the MSE of the points and corresponding centroids) is minimized. Let’s see how it can be achieved by looking at the algorithm: Firstly the centroids are initialized randomly. The second step is to repeat until convergence (the centroids haven’t changed from the previous iteration) two steps: To find for each point in the X the closest centroid and to add this point to a cluster To calculate the new centroids for each cluster, taking the mean in values in every dimension So as this algorithms is working with distances it is very sensitive to outliers, that’s why before doing cluster analysis we have to identify outliers and remove them from the dataset. In order to find outliers more accurately, we will build the scatter plot. airline_count = df["Operating Airline"].value_counts()airline_count.sort_index(inplace=True)passenger_count = df.groupby("Operating Airline").sum()["Passenger Count"]passenger_count.sort_index(inplace=True)from sklearn.preprocessing import scalex = airline_count.valuesy = passenger_count.valuesplt.figure(figsize = (10,10))plt.scatter(x, y)plt.xlabel("Flights held")plt.ylabel("Passengers")for i, txt in enumerate(airline_count.index.values): a = plt.gca() plt.annotate(txt, (x[i], y[i]))plt.show() We can see that most of the airlines are grouped together in the bottom left part of the plot, some are above them, and our 2 outliers United Airlines and Unites Airlines — Pre 07/01/2013. So let’s get rid of them. df_1 = airline_count + passenger_countdf_1.sort_values(ascending = False, inplace = True)outliers = df_1.head(2).index.valuesairline_count = airline_count.drop(outliers)airline_count.sort_index(inplace=True)passenger_count = passenger_count.drop(outliers)passenger_count.sort_index(inplace = True)x = airline_count.valuesy = passenger_count.values We have prepared our dataset for clustering. However the question is how to determine the “best” number of clusters to use. In order to figure this out we will apply the “Elbow method”. As we have already discussed, we are trying to minimize the objective function. It is clear that the more centroids we have the less is the value of the objective function.Moreover, it will become 0 — global minimum, when all points are centroids for themselves, but such variant is not for us, we will try to have some trade-off between number of clusters and the value of the objective function.In order to do this, let’s make plot of dependence of objective function value based on the number of clusters. from sklearn.cluster import KMeansX = np.array(list(zip(x,y)))inertias = []for k in range(2, 10): kmeans = KMeans(n_clusters=k) kmeans.fit(X) inertias.append(kmeans.inertia_)plt.plot(range(2,10), inertias, "o-g")plt.xlabel("Number of clusters")plt.ylabel("Inertia")plt.show() Our task is to find such number of clusters after which the objective function is decreasing not so fast or in analogy with human arm: if we imagine the plot as the human’s arm then the optimal number of clusters will be the point of the elbow. In out case the optimal number of clusters is 6. So now we are ready to do cluster analysis on our dataset. kmeans = KMeans(n_clusters=6)kmeans.fit(X)y_kmeans = kmeans.predict(X)plt.figure(figsize = (15,15))plt.xlabel("Flights held")plt.ylabel("Passengers")plt.scatter(X[:, 0], X[:, 1], c=y_kmeans, s=300, cmap='Set1')for i, txt in enumerate(airline_count.index.values): plt.annotate(txt, (X[i,0], X[i,1]), size = 7)plt.show() Now we have done the clustering of our data and we have make some assumptions and predictions based on the results. We can see that American Airlines and SkyWest airlines hold many flights and transport many people, so we can infer that maybe this airlines have planes with bigger capacity or people use these airlines more than other. Cluster analysis allows you to get many insights about your data. Now it’s important for us to validate the results of our clustering (to see how good the partition is), for this we will use Silhouette analysis. In order to understand the main feature of such a type of validation we have to find out what a silhouette coefficient is. For each point in our dataset we can calculate a silhouette coefficient using the formula above but there are some unclear things about what a(i) and b(i) is. So let’s understand the meaning of a(i) parameter. For each point we can calculate a(i) - the average of distances between current point i and i’s cluster neighbors point denoted as j (either i or j should correspond to the same cluster). Now, let’s understand what b(i) parameter means. For each point we can calculate b(i) - a minimum values of distances between current point i and points j that are not from the same cluster as i. Using parameters described above we can calculate the silhouette coefficient for each point in the dataset. Silhouette score takes values in range [-1;1]. When the value of coefficient is 1 this means that this point is really close to it’s cluster and not to the other,analogically -1 is the worst case. It’s always useful to make a silhouette plot. Let’s figure out what does it look like. In silhouette plot we draw a silhouette coefficient for every point grouped into clusters and sorted inside them. Looking at the plot we can tell how good is our classification: if the width of all “bars” if the same and every point inside a cluster has the silhouette coefficient bigger than the global average, such classification can be called good, otherwise we can’t tell that it’s absolutely perfect, but we can make some trade-offs due to the data we are working with. So now let’s make silhouette plot for our clustering (code is based on the example from scikit-learn documentation on Silhouette analysis). from sklearn.metrics import silhouette_samples, silhouette_scoreimport matplotlib.cm as cmn_clusters = 6plt.figure(figsize = (10,10))plt.gca().set_xlim([-0.1,1])plt.gca().set_ylim([0, len(X) + (n_clusters + 1) * 10])clusterer = KMeans(n_clusters=n_clusters, random_state=10)labels = clusterer.fit_predict(X)print("The average silhouette_score is :{}".format(silhouette_score(X, labels)))sample_silhouette_values = silhouette_samples(X, labels)y_lower = 10for i in range(n_clusters): ith_cluster_silhouette_values = \ sample_silhouette_values[labels == i] ith_cluster_silhouette_values.sort() size_cluster_i = ith_cluster_silhouette_values.shape[0] y_upper = y_lower + size_cluster_i color = cm.nipy_spectral(float(i) / n_clusters) plt.gca().fill_betweenx(np.arange(y_lower, y_upper), 0, ith_cluster_silhouette_values, facecolor=color, edgecolor=color, alpha=0.7) plt.gca().text(-0.05, y_lower + 0.5 * size_cluster_i, str(i)) y_lower = y_upper + 10plt.gca().axvline(x=silhouette_score(X, labels), color="red", linestyle="--", label = "Avg silhouette score")plt.title("The silhouette plot")plt.xlabel("The silhouette coefficient values")plt.ylabel("Cluster label")plt.legend()plt.show() As we can see clusters are not of the same size and not all clusters are made of points that have a silhouette coefficient bigger than the global average, but looking at our data, that is distributed in a bit strange way (see the scatter plot) we can conclude that this clustering has shown good results. Thanks you a lot for reading, hope you enjoyed the great power of cluster analysis!!! Rousseeuw, P.J.: Silhouettes: A Graphical Aid to the Interpretation and Validation of Cluster Analysis Application of k Means Clustering algorithm for prediction of Students Academic Performance Image Segmentation Using K -means Clustering Algorithm and Subtractive Clustering Algorithm
[ { "code": null, "e": 542, "s": 172, "text": "Cluster analysis has become one of the most important methods in Data Analysis, Machine Learning and Data Science. The general idea of clustering is to divide a set of objects with various features into groups, called clusters. There are many algorithms used for clustering nowadays, but I am going to reveal the powerful and the simplest one, named K-means clustering." }, { "code": null, "e": 576, "s": 542, "text": "Getting familiar with the dataset" }, { "code": null, "e": 623, "s": 576, "text": "The History and the intuition of the algorithm" }, { "code": null, "e": 679, "s": 623, "text": "Elbow method or how to find the best number of clusters" }, { "code": null, "e": 722, "s": 679, "text": "Clustering validation: Silhouette analysis" }, { "code": null, "e": 743, "s": 722, "text": "Additional resources" }, { "code": null, "e": 1085, "s": 743, "text": "Today we are going to apply the full power of cluster analysis on the dataset provided by San Francisco Open Data, a monthly statistics by Airlines in San Francisco International Airport. For our work we will use Python and its libraries: matplotlib(seaborn), pandas, scikit-learn and numpy. So let’s begin our journey into the clustering!!!" }, { "code": null, "e": 1189, "s": 1085, "text": "Firstly, as the in every Data Science task we have to get acquainted with the data we are working with." }, { "code": null, "e": 1264, "s": 1189, "text": "df = pd.read_csv(\"Datasets/Air_Traffic_Passenger_Statistics.csv\")df.head()" }, { "code": null, "e": 1591, "s": 1264, "text": "As we can see there are multiple columns in our dataset, but for cluster analysis we will use Operating Airline, Geo Region, Passenger Count and Flights held by each airline. So firstly to determine potential outliers and get some insights about our data, let’s make some plots using Python data visualization library Seaborn." }, { "code": null, "e": 1757, "s": 1591, "text": "plt.figure(figsize = (15,15))sns.countplot(x = \"Operating Airline\", palette = \"Set3\",data = df)plt.xticks(rotation = 90)plt.ylabel(\"Number of fights held\")plt.show()" }, { "code": null, "e": 2148, "s": 1757, "text": "From the frequency plot of the Airlines we can see that there are some examples with an amount of flights held bigger than the others. These are United Airlines and Unites Airlines — Pre 07/01/2013. So these airlines are our potential outliers. The reason why we are trying to find and eliminate outliers will be explained later. Let’s see the frequency plot of Countries that hold flights." }, { "code": null, "e": 2307, "s": 2148, "text": "plt.figure(figsize = (15,15))sns.countplot(x = \"GEO Region\", palette = \"Set3\",data = df)plt.xticks(rotation = 90)plt.ylabel(\"Number of fights held\")plt.show()" }, { "code": null, "e": 2618, "s": 2307, "text": "As we can see the USA is the leader among the countries, that is because our outliers Airlines(United Airlines and Unites Airlines — Pre 07/01/2013) are the American ones. We can obviously see that either Countries or Airlines can be separated into some groups (or clusters) by the amount of flights they held." }, { "code": null, "e": 2973, "s": 2618, "text": "K — means clustering is one of the most popular clustering algorithms nowadays. It was created in the 1950’s by Hugo Steinhaus. The main idea of the algorithm is to divide a set of points X in n-dimensional space into the groups with centroids C, in such a way that the objective function (the MSE of the points and corresponding centroids) is minimized." }, { "code": null, "e": 3035, "s": 2973, "text": "Let’s see how it can be achieved by looking at the algorithm:" }, { "code": null, "e": 3201, "s": 3035, "text": "Firstly the centroids are initialized randomly. The second step is to repeat until convergence (the centroids haven’t changed from the previous iteration) two steps:" }, { "code": null, "e": 3289, "s": 3201, "text": "To find for each point in the X the closest centroid and to add this point to a cluster" }, { "code": null, "e": 3383, "s": 3289, "text": "To calculate the new centroids for each cluster, taking the mean in values in every dimension" }, { "code": null, "e": 3644, "s": 3383, "text": "So as this algorithms is working with distances it is very sensitive to outliers, that’s why before doing cluster analysis we have to identify outliers and remove them from the dataset. In order to find outliers more accurately, we will build the scatter plot." }, { "code": null, "e": 4150, "s": 3644, "text": "airline_count = df[\"Operating Airline\"].value_counts()airline_count.sort_index(inplace=True)passenger_count = df.groupby(\"Operating Airline\").sum()[\"Passenger Count\"]passenger_count.sort_index(inplace=True)from sklearn.preprocessing import scalex = airline_count.valuesy = passenger_count.valuesplt.figure(figsize = (10,10))plt.scatter(x, y)plt.xlabel(\"Flights held\")plt.ylabel(\"Passengers\")for i, txt in enumerate(airline_count.index.values): a = plt.gca() plt.annotate(txt, (x[i], y[i]))plt.show()" }, { "code": null, "e": 4365, "s": 4150, "text": "We can see that most of the airlines are grouped together in the bottom left part of the plot, some are above them, and our 2 outliers United Airlines and Unites Airlines — Pre 07/01/2013. So let’s get rid of them." }, { "code": null, "e": 4713, "s": 4365, "text": "df_1 = airline_count + passenger_countdf_1.sort_values(ascending = False, inplace = True)outliers = df_1.head(2).index.valuesairline_count = airline_count.drop(outliers)airline_count.sort_index(inplace=True)passenger_count = passenger_count.drop(outliers)passenger_count.sort_index(inplace = True)x = airline_count.valuesy = passenger_count.values" }, { "code": null, "e": 4899, "s": 4713, "text": "We have prepared our dataset for clustering. However the question is how to determine the “best” number of clusters to use. In order to figure this out we will apply the “Elbow method”." }, { "code": null, "e": 5408, "s": 4899, "text": "As we have already discussed, we are trying to minimize the objective function. It is clear that the more centroids we have the less is the value of the objective function.Moreover, it will become 0 — global minimum, when all points are centroids for themselves, but such variant is not for us, we will try to have some trade-off between number of clusters and the value of the objective function.In order to do this, let’s make plot of dependence of objective function value based on the number of clusters." }, { "code": null, "e": 5693, "s": 5408, "text": "from sklearn.cluster import KMeansX = np.array(list(zip(x,y)))inertias = []for k in range(2, 10): kmeans = KMeans(n_clusters=k) kmeans.fit(X) inertias.append(kmeans.inertia_)plt.plot(range(2,10), inertias, \"o-g\")plt.xlabel(\"Number of clusters\")plt.ylabel(\"Inertia\")plt.show()" }, { "code": null, "e": 6046, "s": 5693, "text": "Our task is to find such number of clusters after which the objective function is decreasing not so fast or in analogy with human arm: if we imagine the plot as the human’s arm then the optimal number of clusters will be the point of the elbow. In out case the optimal number of clusters is 6. So now we are ready to do cluster analysis on our dataset." }, { "code": null, "e": 6368, "s": 6046, "text": "kmeans = KMeans(n_clusters=6)kmeans.fit(X)y_kmeans = kmeans.predict(X)plt.figure(figsize = (15,15))plt.xlabel(\"Flights held\")plt.ylabel(\"Passengers\")plt.scatter(X[:, 0], X[:, 1], c=y_kmeans, s=300, cmap='Set1')for i, txt in enumerate(airline_count.index.values): plt.annotate(txt, (X[i,0], X[i,1]), size = 7)plt.show()" }, { "code": null, "e": 6916, "s": 6368, "text": "Now we have done the clustering of our data and we have make some assumptions and predictions based on the results. We can see that American Airlines and SkyWest airlines hold many flights and transport many people, so we can infer that maybe this airlines have planes with bigger capacity or people use these airlines more than other. Cluster analysis allows you to get many insights about your data. Now it’s important for us to validate the results of our clustering (to see how good the partition is), for this we will use Silhouette analysis." }, { "code": null, "e": 7039, "s": 6916, "text": "In order to understand the main feature of such a type of validation we have to find out what a silhouette coefficient is." }, { "code": null, "e": 7249, "s": 7039, "text": "For each point in our dataset we can calculate a silhouette coefficient using the formula above but there are some unclear things about what a(i) and b(i) is. So let’s understand the meaning of a(i) parameter." }, { "code": null, "e": 7486, "s": 7249, "text": "For each point we can calculate a(i) - the average of distances between current point i and i’s cluster neighbors point denoted as j (either i or j should correspond to the same cluster). Now, let’s understand what b(i) parameter means." }, { "code": null, "e": 8641, "s": 7486, "text": "For each point we can calculate b(i) - a minimum values of distances between current point i and points j that are not from the same cluster as i. Using parameters described above we can calculate the silhouette coefficient for each point in the dataset. Silhouette score takes values in range [-1;1]. When the value of coefficient is 1 this means that this point is really close to it’s cluster and not to the other,analogically -1 is the worst case. It’s always useful to make a silhouette plot. Let’s figure out what does it look like. In silhouette plot we draw a silhouette coefficient for every point grouped into clusters and sorted inside them. Looking at the plot we can tell how good is our classification: if the width of all “bars” if the same and every point inside a cluster has the silhouette coefficient bigger than the global average, such classification can be called good, otherwise we can’t tell that it’s absolutely perfect, but we can make some trade-offs due to the data we are working with. So now let’s make silhouette plot for our clustering (code is based on the example from scikit-learn documentation on Silhouette analysis)." }, { "code": null, "e": 9903, "s": 8641, "text": "from sklearn.metrics import silhouette_samples, silhouette_scoreimport matplotlib.cm as cmn_clusters = 6plt.figure(figsize = (10,10))plt.gca().set_xlim([-0.1,1])plt.gca().set_ylim([0, len(X) + (n_clusters + 1) * 10])clusterer = KMeans(n_clusters=n_clusters, random_state=10)labels = clusterer.fit_predict(X)print(\"The average silhouette_score is :{}\".format(silhouette_score(X, labels)))sample_silhouette_values = silhouette_samples(X, labels)y_lower = 10for i in range(n_clusters): ith_cluster_silhouette_values = \\ sample_silhouette_values[labels == i] ith_cluster_silhouette_values.sort() size_cluster_i = ith_cluster_silhouette_values.shape[0] y_upper = y_lower + size_cluster_i color = cm.nipy_spectral(float(i) / n_clusters) plt.gca().fill_betweenx(np.arange(y_lower, y_upper), 0, ith_cluster_silhouette_values, facecolor=color, edgecolor=color, alpha=0.7) plt.gca().text(-0.05, y_lower + 0.5 * size_cluster_i, str(i)) y_lower = y_upper + 10plt.gca().axvline(x=silhouette_score(X, labels), color=\"red\", linestyle=\"--\", label = \"Avg silhouette score\")plt.title(\"The silhouette plot\")plt.xlabel(\"The silhouette coefficient values\")plt.ylabel(\"Cluster label\")plt.legend()plt.show()" }, { "code": null, "e": 10208, "s": 9903, "text": "As we can see clusters are not of the same size and not all clusters are made of points that have a silhouette coefficient bigger than the global average, but looking at our data, that is distributed in a bit strange way (see the scatter plot) we can conclude that this clustering has shown good results." }, { "code": null, "e": 10294, "s": 10208, "text": "Thanks you a lot for reading, hope you enjoyed the great power of cluster analysis!!!" }, { "code": null, "e": 10397, "s": 10294, "text": "Rousseeuw, P.J.: Silhouettes: A Graphical Aid to the Interpretation and Validation of Cluster Analysis" }, { "code": null, "e": 10489, "s": 10397, "text": "Application of k Means Clustering algorithm for prediction of Students Academic Performance" } ]
Java.Lang.Double class in Java - GeeksforGeeks
03 Aug, 2021 Double class is a wrapper class for the primitive type double which contains several methods to effectively deal with a double value like converting it to a string representation, and vice-versa. An object of Double class can hold a single double value. There are mainly two constructors to initialize a Double object- Double(double b): Creates a Double object initialized with the value provided. Syntax : public Double(Double d) Parameters : d : value with which to initialize Double(String s): Creates a Double object initialized with the parsed double value provided by string representation. Default radix is taken to be 10. Syntax : public Double(String s) throws NumberFormatException Parameters : s : string representation of the byte value Throws : NumberFormatException : If the string provided does not represent any double value. Methods: 1. toString(): Returns the string corresponding to the double value. Syntax : public String toString(double b) Parameters : b : double value for which string representation required. 2. valueOf(): returns the Double object initialized with the value provided. Syntax : public static Double valueOf(double b) Parameters : b : a double value Another overloaded function valueOf(String val) which provides function similar to new Double(Double.parseDouble(val,10)) Syntax : public static Double valueOf(String s) throws NumberFormatException Parameters : s : a String object to be parsed as double Throws : NumberFormatException : if String cannot be parsed to a double value in given radix. 3. parseDouble(): returns double value by parsing the string. Differs from valueOf() as it returns a primitive double value and valueOf() return Double object. Syntax : public static double parseDouble(String val) throws NumberFormatException Parameters : val : String representation of double Throws : NumberFormatException : if String cannot be parsed to a double value in given radix. 4. byteValue(): returns a byte value corresponding to this Double Object. Syntax : public byte byteValue() 5. shortValue(): returns a short value corresponding to this Double Object. Syntax : public short shortValue() 6. intValue(): returns a int value corresponding to this Double Object. Syntax : public int intValue() 7. longValue(): returns a long value corresponding to this Double Object. Syntax : public long longValue() 8. doubleValue(): returns a double value corresponding to this Double Object. Syntax : public double doubleValue() 9. floatValue(): returns a float value corresponding to this Double Object. Syntax : public float floatValue() 10. hashCode(): returns the hashcode corresponding to this Double Object. Syntax : public int hashCode() 11. isNaN(): returns true if the double object in consideration is not a number, otherwise false. Syntax : public boolean isNaN() Another static method isNaN(double val) can be used if we don’t need any object of double to be created. It provides similar functionality as the above version. Syntax : public static boolean isNaN(double val) Parameters : val : double value to check for 12. isInfinite(): returns true if the double object in consideration is very large, otherwise false. Specifically, any number beyond 0x7ff0000000000000L on the positive side and below 0xfff0000000000000L on negative side is the infinity values. Syntax : public boolean isInfinite() Another static method isInfinite(double val) can be used if we dont need any object of double to be created. It provides similar functionality as the above version. Syntax : public static boolean isInfinte(double val) Parameters : val : double value to check for 13. toHexString(): Returns the hexadecimal representation of the argument double value. Syntax : public static String toHexString(double val) Parameters : val : double value to be represented as hex string 14. doubleToLongBits(): returns the IEEE 754 floating-point “double format” bit layout of the given double argument. Syntax : public static long doubleToLongBits(double val) Parameters : val : double value to convert 15. doubleToRawLongBits(): returns the IEEE 754 floating-point “double format” bit layout of the given double argument. It differs from the previous method as it preserves the Nan values. Syntax : public static long doubleToRawLongBits(double val) Parameters : val : double value to convert 16. LongBitsToDouble(): Returns the double value corresponding to the long bit pattern of the argument. It does reverse work of the previous two methods. Syntax : public static double LongBitsToDouble(long b) Parameters : b : long bit pattern 17. equals(): Used to compare the equality of two Double objects. This method returns true if both the objects contain same double value. Should be used only if checking for equality. In all other cases, compareTo method should be preferred. Syntax : public boolean equals(Object obj) Parameters : obj : object to compare with 18. compareTo(): Used to compare two Double objects for numerical equality. This should be used when comparing two Double values for numerical equality as it would differentiate between less and greater values. Returns a value less than 0,0,value greater than 0 for less than,equal to and greater than. Syntax : public int compareTo(Double b) Parameters : b : Double object to compare with 19. compare(): Used to compare two primitive double values for numerical equality. As it is a static method therefore it can be used without creating any object of Double. Syntax : public static int compare(double x,double y) Parameters : x : double value y : another double value Java // Java program to illustrate// various Double class methods// of java.lang classpublic class Double_test{ public static void main(String[] args) { double b = 55.05; String bb = "45"; // Construct two Double objects Double x = new Double(b); Double y = new Double(bb); // toString() System.out.println("toString(b) = " + Double.toString(b)); // valueOf() // return Double object Double z = Double.valueOf(b); System.out.println("valueOf(b) = " + z); z = Double.valueOf(bb); System.out.println("ValueOf(bb) = " + z); // parseDouble() // return primitive double value double zz = Double.parseDouble(bb); System.out.println("parseDouble(bb) = " + zz); System.out.println("bytevalue(x) = " + x.byteValue()); System.out.println("shortvalue(x) = " + x.shortValue()); System.out.println("intvalue(x) = " + x.intValue()); System.out.println("longvalue(x) = " + x.longValue()); System.out.println("doublevalue(x) = " + x.doubleValue()); System.out.println("floatvalue(x) = " + x.floatValue()); int hash = x.hashCode(); System.out.println("hashcode(x) = " + hash); boolean eq = x.equals(y); System.out.println("x.equals(y) = " + eq); int e = Double.compare(x, y); System.out.println("compare(x,y) = " + e); int f = x.compareTo(y); System.out.println("x.compareTo(y) = " + f); Double d = Double.valueOf("1010.54789654123654"); System.out.println("isNaN(d) = " + d.isNaN()); System.out.println("Double.isNaN(45.12452) = " + Double.isNaN(45.12452)); // Double.POSITIVE_INFINITY stores // the positive infinite value d = Double.valueOf(Double.POSITIVE_INFINITY + 1); System.out.println("Double.isInfinite(d) = " + Double.isInfinite(d.doubleValue())); double dd = 10245.21452; System.out.println("Double.toString(dd) = " + Double.toHexString(dd)); long double_to_long = Double.doubleToLongBits(dd); System.out.println("Double.doubleToLongBits(dd) = " + double_to_long); double long_to_double = Double.longBitsToDouble(double_to_long); System.out.println("Double.LongBitsToDouble(double_to_long) = " + long_to_double); } } Output : toString(b) = 55.05 valueOf(b) = 55.05 ValueOf(bb) = 45.0 parseDouble(bb) = 45.0 bytevalue(x) = 55 shortvalue(x) = 55 intvalue(x) = 55 longvalue(x) = 55 doublevalue(x) = 55.05 floatvalue(x) = 55.05 hashcode(x) = 640540672 x.equals(y) = false compare(x,y) = 1 x.compareTo(y) = 1 isNaN(d) = false Double.isNaN(45.12452) = false Double.isInfinite(d) = true Double.toString(dd) = 0x1.4029b7564302bp13 Double.doubleToLongBits(dd) = 4666857980575363115 Double.LongBitsToDouble(double_to_long) = 10245.21452 References: Official Java Documentation This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. rajeev0719singh abhishek0719kadiyan sagar0719kumar Java-lang package java-wrapper-class Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples How to iterate any Map in Java Interfaces in Java Initialize an ArrayList in Java
[ { "code": null, "e": 22648, "s": 22620, "text": "\n03 Aug, 2021" }, { "code": null, "e": 22968, "s": 22648, "text": "Double class is a wrapper class for the primitive type double which contains several methods to effectively deal with a double value like converting it to a string representation, and vice-versa. An object of Double class can hold a single double value. There are mainly two constructors to initialize a Double object- " }, { "code": null, "e": 23048, "s": 22968, "text": "Double(double b): Creates a Double object initialized with the value provided. " }, { "code": null, "e": 23129, "s": 23048, "text": "Syntax : public Double(Double d)\nParameters :\nd : value with which to initialize" }, { "code": null, "e": 23281, "s": 23129, "text": "Double(String s): Creates a Double object initialized with the parsed double value provided by string representation. Default radix is taken to be 10. " }, { "code": null, "e": 23515, "s": 23281, "text": "Syntax : public Double(String s) \n throws NumberFormatException\nParameters :\ns : string representation of the byte value \nThrows :\nNumberFormatException : If the string provided does not represent any double value." }, { "code": null, "e": 23526, "s": 23515, "text": "Methods: " }, { "code": null, "e": 23596, "s": 23526, "text": "1. toString(): Returns the string corresponding to the double value. " }, { "code": null, "e": 23710, "s": 23596, "text": "Syntax : public String toString(double b)\nParameters :\nb : double value for which string representation required." }, { "code": null, "e": 23788, "s": 23710, "text": "2. valueOf(): returns the Double object initialized with the value provided. " }, { "code": null, "e": 23868, "s": 23788, "text": "Syntax : public static Double valueOf(double b)\nParameters :\nb : a double value" }, { "code": null, "e": 23991, "s": 23868, "text": "Another overloaded function valueOf(String val) which provides function similar to new Double(Double.parseDouble(val,10)) " }, { "code": null, "e": 24229, "s": 23991, "text": "Syntax : public static Double valueOf(String s)\n throws NumberFormatException\nParameters :\ns : a String object to be parsed as double\nThrows :\nNumberFormatException : if String cannot be parsed to a double value in given radix." }, { "code": null, "e": 24390, "s": 24229, "text": "3. parseDouble(): returns double value by parsing the string. Differs from valueOf() as it returns a primitive double value and valueOf() return Double object. " }, { "code": null, "e": 24632, "s": 24390, "text": "Syntax : public static double parseDouble(String val)\n throws NumberFormatException\nParameters :\nval : String representation of double \nThrows :\nNumberFormatException : if String cannot be parsed to a double value in given radix." }, { "code": null, "e": 24707, "s": 24632, "text": "4. byteValue(): returns a byte value corresponding to this Double Object. " }, { "code": null, "e": 24740, "s": 24707, "text": "Syntax : public byte byteValue()" }, { "code": null, "e": 24817, "s": 24740, "text": "5. shortValue(): returns a short value corresponding to this Double Object. " }, { "code": null, "e": 24852, "s": 24817, "text": "Syntax : public short shortValue()" }, { "code": null, "e": 24925, "s": 24852, "text": "6. intValue(): returns a int value corresponding to this Double Object. " }, { "code": null, "e": 24956, "s": 24925, "text": "Syntax : public int intValue()" }, { "code": null, "e": 25031, "s": 24956, "text": "7. longValue(): returns a long value corresponding to this Double Object. " }, { "code": null, "e": 25064, "s": 25031, "text": "Syntax : public long longValue()" }, { "code": null, "e": 25143, "s": 25064, "text": "8. doubleValue(): returns a double value corresponding to this Double Object. " }, { "code": null, "e": 25180, "s": 25143, "text": "Syntax : public double doubleValue()" }, { "code": null, "e": 25257, "s": 25180, "text": "9. floatValue(): returns a float value corresponding to this Double Object. " }, { "code": null, "e": 25292, "s": 25257, "text": "Syntax : public float floatValue()" }, { "code": null, "e": 25367, "s": 25292, "text": "10. hashCode(): returns the hashcode corresponding to this Double Object. " }, { "code": null, "e": 25398, "s": 25367, "text": "Syntax : public int hashCode()" }, { "code": null, "e": 25497, "s": 25398, "text": "11. isNaN(): returns true if the double object in consideration is not a number, otherwise false. " }, { "code": null, "e": 25529, "s": 25497, "text": "Syntax : public boolean isNaN()" }, { "code": null, "e": 25691, "s": 25529, "text": "Another static method isNaN(double val) can be used if we don’t need any object of double to be created. It provides similar functionality as the above version. " }, { "code": null, "e": 25785, "s": 25691, "text": "Syntax : public static boolean isNaN(double val)\nParameters :\nval : double value to check for" }, { "code": null, "e": 26031, "s": 25785, "text": "12. isInfinite(): returns true if the double object in consideration is very large, otherwise false. Specifically, any number beyond 0x7ff0000000000000L on the positive side and below 0xfff0000000000000L on negative side is the infinity values. " }, { "code": null, "e": 26068, "s": 26031, "text": "Syntax : public boolean isInfinite()" }, { "code": null, "e": 26234, "s": 26068, "text": "Another static method isInfinite(double val) can be used if we dont need any object of double to be created. It provides similar functionality as the above version. " }, { "code": null, "e": 26332, "s": 26234, "text": "Syntax : public static boolean isInfinte(double val)\nParameters :\nval : double value to check for" }, { "code": null, "e": 26421, "s": 26332, "text": "13. toHexString(): Returns the hexadecimal representation of the argument double value. " }, { "code": null, "e": 26540, "s": 26421, "text": "Syntax : public static String toHexString(double val)\nParameters : \nval : double value to be represented as hex string" }, { "code": null, "e": 26658, "s": 26540, "text": "14. doubleToLongBits(): returns the IEEE 754 floating-point “double format” bit layout of the given double argument. " }, { "code": null, "e": 26758, "s": 26658, "text": "Syntax : public static long doubleToLongBits(double val)\nParameters :\nval : double value to convert" }, { "code": null, "e": 26947, "s": 26758, "text": "15. doubleToRawLongBits(): returns the IEEE 754 floating-point “double format” bit layout of the given double argument. It differs from the previous method as it preserves the Nan values. " }, { "code": null, "e": 27050, "s": 26947, "text": "Syntax : public static long doubleToRawLongBits(double val)\nParameters :\nval : double value to convert" }, { "code": null, "e": 27205, "s": 27050, "text": "16. LongBitsToDouble(): Returns the double value corresponding to the long bit pattern of the argument. It does reverse work of the previous two methods. " }, { "code": null, "e": 27294, "s": 27205, "text": "Syntax : public static double LongBitsToDouble(long b)\nParameters :\nb : long bit pattern" }, { "code": null, "e": 27537, "s": 27294, "text": "17. equals(): Used to compare the equality of two Double objects. This method returns true if both the objects contain same double value. Should be used only if checking for equality. In all other cases, compareTo method should be preferred. " }, { "code": null, "e": 27622, "s": 27537, "text": "Syntax : public boolean equals(Object obj)\nParameters :\nobj : object to compare with" }, { "code": null, "e": 27926, "s": 27622, "text": "18. compareTo(): Used to compare two Double objects for numerical equality. This should be used when comparing two Double values for numerical equality as it would differentiate between less and greater values. Returns a value less than 0,0,value greater than 0 for less than,equal to and greater than. " }, { "code": null, "e": 28013, "s": 27926, "text": "Syntax : public int compareTo(Double b)\nParameters :\nb : Double object to compare with" }, { "code": null, "e": 28186, "s": 28013, "text": "19. compare(): Used to compare two primitive double values for numerical equality. As it is a static method therefore it can be used without creating any object of Double. " }, { "code": null, "e": 28295, "s": 28186, "text": "Syntax : public static int compare(double x,double y)\nParameters :\nx : double value\ny : another double value" }, { "code": null, "e": 28300, "s": 28295, "text": "Java" }, { "code": "// Java program to illustrate// various Double class methods// of java.lang classpublic class Double_test{ public static void main(String[] args) { double b = 55.05; String bb = \"45\"; // Construct two Double objects Double x = new Double(b); Double y = new Double(bb); // toString() System.out.println(\"toString(b) = \" + Double.toString(b)); // valueOf() // return Double object Double z = Double.valueOf(b); System.out.println(\"valueOf(b) = \" + z); z = Double.valueOf(bb); System.out.println(\"ValueOf(bb) = \" + z); // parseDouble() // return primitive double value double zz = Double.parseDouble(bb); System.out.println(\"parseDouble(bb) = \" + zz); System.out.println(\"bytevalue(x) = \" + x.byteValue()); System.out.println(\"shortvalue(x) = \" + x.shortValue()); System.out.println(\"intvalue(x) = \" + x.intValue()); System.out.println(\"longvalue(x) = \" + x.longValue()); System.out.println(\"doublevalue(x) = \" + x.doubleValue()); System.out.println(\"floatvalue(x) = \" + x.floatValue()); int hash = x.hashCode(); System.out.println(\"hashcode(x) = \" + hash); boolean eq = x.equals(y); System.out.println(\"x.equals(y) = \" + eq); int e = Double.compare(x, y); System.out.println(\"compare(x,y) = \" + e); int f = x.compareTo(y); System.out.println(\"x.compareTo(y) = \" + f); Double d = Double.valueOf(\"1010.54789654123654\"); System.out.println(\"isNaN(d) = \" + d.isNaN()); System.out.println(\"Double.isNaN(45.12452) = \" + Double.isNaN(45.12452)); // Double.POSITIVE_INFINITY stores // the positive infinite value d = Double.valueOf(Double.POSITIVE_INFINITY + 1); System.out.println(\"Double.isInfinite(d) = \" + Double.isInfinite(d.doubleValue())); double dd = 10245.21452; System.out.println(\"Double.toString(dd) = \" + Double.toHexString(dd)); long double_to_long = Double.doubleToLongBits(dd); System.out.println(\"Double.doubleToLongBits(dd) = \" + double_to_long); double long_to_double = Double.longBitsToDouble(double_to_long); System.out.println(\"Double.LongBitsToDouble(double_to_long) = \" + long_to_double); } }", "e": 30719, "s": 28300, "text": null }, { "code": null, "e": 30729, "s": 30719, "text": "Output : " }, { "code": null, "e": 31230, "s": 30729, "text": "toString(b) = 55.05\nvalueOf(b) = 55.05\nValueOf(bb) = 45.0\nparseDouble(bb) = 45.0\nbytevalue(x) = 55\nshortvalue(x) = 55\nintvalue(x) = 55\nlongvalue(x) = 55\ndoublevalue(x) = 55.05\nfloatvalue(x) = 55.05\nhashcode(x) = 640540672\nx.equals(y) = false\ncompare(x,y) = 1\nx.compareTo(y) = 1\nisNaN(d) = false\nDouble.isNaN(45.12452) = false\nDouble.isInfinite(d) = true\nDouble.toString(dd) = 0x1.4029b7564302bp13\nDouble.doubleToLongBits(dd) = 4666857980575363115\nDouble.LongBitsToDouble(double_to_long) = 10245.21452" }, { "code": null, "e": 31271, "s": 31230, "text": "References: Official Java Documentation " }, { "code": null, "e": 31695, "s": 31271, "text": "This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 31711, "s": 31695, "text": "rajeev0719singh" }, { "code": null, "e": 31731, "s": 31711, "text": "abhishek0719kadiyan" }, { "code": null, "e": 31746, "s": 31731, "text": "sagar0719kumar" }, { "code": null, "e": 31764, "s": 31746, "text": "Java-lang package" }, { "code": null, "e": 31783, "s": 31764, "text": "java-wrapper-class" }, { "code": null, "e": 31788, "s": 31783, "text": "Java" }, { "code": null, "e": 31793, "s": 31788, "text": "Java" }, { "code": null, "e": 31891, "s": 31793, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31900, "s": 31891, "text": "Comments" }, { "code": null, "e": 31913, "s": 31900, "text": "Old Comments" }, { "code": null, "e": 31928, "s": 31913, "text": "Arrays in Java" }, { "code": null, "e": 31972, "s": 31928, "text": "Split() String method in Java with examples" }, { "code": null, "e": 31994, "s": 31972, "text": "For-each loop in Java" }, { "code": null, "e": 32019, "s": 31994, "text": "Reverse a string in Java" }, { "code": null, "e": 32055, "s": 32019, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 32106, "s": 32055, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 32136, "s": 32106, "text": "HashMap in Java with Examples" }, { "code": null, "e": 32167, "s": 32136, "text": "How to iterate any Map in Java" }, { "code": null, "e": 32186, "s": 32167, "text": "Interfaces in Java" } ]
Tryit Editor v3.7
Tryit: HTML title attribute
[]
R - Object Oriented Programming - GeeksforGeeks
10 Aug, 2021 In this article, we will discuss Object-Oriented Programming (OOPs) in R Programming Language. We will discuss the S3 and S4 classes, inheritance in these classes, and the methods provided by these classes. In R programming, OOPs provide classes and objects as its key tools to reduce and manage the complexity of the program. R is a functional language that uses concepts of OOPs. We can think of a class as a sketch of a car. It contains all the details about the model_name, model_no, engine, etc. Based on these descriptions we select a car. Car is the object. Each car object has its own characteristics and features. An object is also called an instance of a class and the process of creating this object is called instantiation. In R S3 and S4 classes are the two most important classes for object-oriented programming. But before going discussing these classes let’s see a brief about classes and objects. Class is the blueprint or a prototype from which objects are made by encapsulating data members and functions. An object is a data structure that contains some methods that act upon its attributes. S3 class does not have a predefined definition and is able to dispatch. In this class, the generic function makes a call to the method. Easy implementation of S3 is possible because it differs from the traditional programming language Java, C++, and C# which implements Object Oriented message passing. To create an object of this class we will create a list that will contain all the class members. Then this list is passed to the class() method as an argument. Syntax: variable_name <- list(attribute1, attribute2, attribute3....attributeN) Example: In the following code, a Student class is defined. An appropriate class name is given having attributes student’s name and roll number. Then the object of the student class is created and invoked. R # List creation with its attributes name# and roll no.a < - list(name="Adam", Roll_No=15) # Defining a class "Student"class(a) < - "Student" # Creation of objecta Output: $name [1] "Adam" $Roll_No [1] 15 attr(, "class") [1] "Student" The generic functions are a good example of polymorphism. To understand the concept of generic functions consider the print() function. The print() function is a collection of various print functions that are created for different data types and data structures in the R Programming Language. It calls the appropriate function depending upon the type of object passed as an argument. We can see the various implementation of print functions using the methods() function. Example: Seeing different types of print function R methods(print) Output: Now let’s create a generic function of our own. We will create the print function for our class that will print all the members in our specified format. But before creating a print function let’s create what the print function does to our class. Example: R # List creation with its attributes name# and roll no.a = list(name="Adam", Roll_No=15) # Defining a class "Student"class(a) = "Student" # Creation of objectprint(a) Output: $name [1] "Adam" $Roll_No [1] 15 attr(,"class") [1] "Student" Now let’s print all the members in our specified format. Consider the below example – Example: R print.Student <- function(obj){ cat("name: " ,obj$name, "\n") cat("Roll No: ", obj$Roll_No, "\n")} print(a) Output: name: Adam Roll No: 15 Attributes of an object do not affect the value of an object, but they are a piece of extra information that is used to handle the objects. The function attributes() can be used to view the attributes of an object. Examples: An S3 object is created and its attributes are displayed. R attributes(a) Output: $names 'name''Roll_No' $class 'Student' Also, you can add attributes to an object by using attr. R attr(a, "age")<-c(18)attributes(a) Output: $names 'name''Roll_No' $class 'Student' $age 18 Inheritance is an important concept in OOP(object-oriented programming) which allows one class to derive the features and functionalities of another class. This feature facilitates code-reusability. S3 class in R programming language has no formal and fixed definition. In an S3 object, a list with its class attribute is set to a class name. S3 class objects inherit only methods from their base class. Example: In the following code, inheritance is done using S3 class, firstly the object is created of the class student. R # student function with argument# name(n) and roll_no(r)student < - function(n, r) { value < - list(name=n, Roll=r) attr(value, "class") < - "student" value} Then, the method is defined to print the details of the student. R # 'print.student' method createdprint.student < - function(obj) { # 'cat' function is used to concatenate # strings cat("Name:", obj$name, "\n") cat("Roll", obj$roll, "\n")} Now, inheritance is done while creating another class by doing class(obj) <- c(child, parent). R s < - list(name="Kesha", Roll=21, country="India") # child class 'Student' inherits# parent class 'student'class(s) < - c("Student", "student")s Output: Name: Kesha Roll: 21 The following code overwrites the method for class student. R # 'Student' class object is passed# in the function of class 'student' print.student < - function(obj) { cat(obj$name, "is from", obj$country, "\n")}s Output: Kesha is from India S4 class has a predefined definition. It contains functions for defining methods and generics. It makes multiple dispatches easy. This class contains auxiliary functions for defining methods and generics. setClass() command is used to create S4 class. Following is the syntax for setclass command which denotes myclass with slots containing name and rollno. Syntax: setClass(“myclass”, slots=list(name=”character”, Roll_No=”numeric”)) The new() function is used to create an object of the S4 class. In this function, we will pass the class name as well as the value for the slots. Example: R # Function setClass() command used# to create S4 class containing list of slots.setClass("Student", slots=list(name="character", Roll_No="numeric")) # 'new' keyword used to create object of# class 'Student'a <- new("Student", name="Adam", Roll_No=20) # Calling objecta Output: Slot "name": [1] "Adam" Slot "Roll_No": [1] 20 setClass() returns a generator function which helps in creating objects and it acts as a constructor. Example: R stud <- setClass("Student", slots=list(name="character", Roll_No="numeric")) # Calling objectstud Output: new(“classGeneratorFunction”, .Data = function (...) new(“Student”, ...), className = structure(“Student”, package = “.GlobalEnv”), package = “.GlobalEnv”) Now the above-created stud function will act as the constructor for the Student class. It will behave as the new() function. Example: R stud(name="Adam", Roll_No=15) Output: An object of class "Student" Slot "name": [1] "Adam" Slot "Roll_No": [1] 15 S4 class in R programming have proper definition and derived classes will be able to inherit both attributes and methods from its base class. For this, we will first create a base class with appropriate slots and will create a generic function for that class. Then we will create a derived class that will inherit using the contains parameter. The derived class will inherit the members as well as functions from the base class. Example: R # Define S4 classsetClass("student", slots=list(name="character", age="numeric", rno="numeric") ) # Defining a function to display object detailssetMethod("show", "student", function(obj){ cat(obj@name, "\n") cat(obj@age, "\n") cat(obj@rno, "\n") } ) # Inherit from studentsetClass("InternationalStudent", slots=list(country="character"), contains="student" ) # Rest of the attributes will be inherited from students < - new("InternationalStudent", name="Adam", age=22, rno=15, country="India")show(s) Output: Adam 22 15 The reasons for defining both S3 and S4 class are as follows: S4 class alone will not be seen if the S3 generic function is called directly. This will be the case, for example, if some function calls unique() from a package that does not make that function an S4 generic. However, primitive functions and operators are exceptions: The internal C code will look for S4 methods if and only if the object is an S4 object. S4 method dispatch would be used to dispatch any binary operator calls where either of the operands was an S4 object. S3 class alone will not be called if there is any eligible non-default S4 method. So if a package defined an S3 method for unique for an S4 class but another package defined an S4 method for a superclass of that class, the superclass method would be chosen, probably not what was intended. Picked R-OOPs R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change column name of a given DataFrame in R How to Replace specific values in column in R DataFrame ? Loops in R (for, while, repeat) Adding elements in a vector in R programming - append() method Filter data by multiple conditions in R using Dplyr How to change Row Names of DataFrame in R ? Change Color of Bars in Barchart using ggplot2 in R Convert Factor to Numeric and Numeric to Factor in R Programming Remove rows with NA in one column of R DataFrame Group by function in R using Dplyr
[ { "code": null, "e": 28990, "s": 28962, "text": "\n10 Aug, 2021" }, { "code": null, "e": 29197, "s": 28990, "text": "In this article, we will discuss Object-Oriented Programming (OOPs) in R Programming Language. We will discuss the S3 and S4 classes, inheritance in these classes, and the methods provided by these classes." }, { "code": null, "e": 29904, "s": 29197, "text": "In R programming, OOPs provide classes and objects as its key tools to reduce and manage the complexity of the program. R is a functional language that uses concepts of OOPs. We can think of a class as a sketch of a car. It contains all the details about the model_name, model_no, engine, etc. Based on these descriptions we select a car. Car is the object. Each car object has its own characteristics and features. An object is also called an instance of a class and the process of creating this object is called instantiation. In R S3 and S4 classes are the two most important classes for object-oriented programming. But before going discussing these classes let’s see a brief about classes and objects." }, { "code": null, "e": 30103, "s": 29904, "text": "Class is the blueprint or a prototype from which objects are made by encapsulating data members and functions. An object is a data structure that contains some methods that act upon its attributes. " }, { "code": null, "e": 30406, "s": 30103, "text": "S3 class does not have a predefined definition and is able to dispatch. In this class, the generic function makes a call to the method. Easy implementation of S3 is possible because it differs from the traditional programming language Java, C++, and C# which implements Object Oriented message passing." }, { "code": null, "e": 30566, "s": 30406, "text": "To create an object of this class we will create a list that will contain all the class members. Then this list is passed to the class() method as an argument." }, { "code": null, "e": 30575, "s": 30566, "text": "Syntax: " }, { "code": null, "e": 30647, "s": 30575, "text": "variable_name <- list(attribute1, attribute2, attribute3....attributeN)" }, { "code": null, "e": 30657, "s": 30647, "text": "Example: " }, { "code": null, "e": 30855, "s": 30657, "text": "In the following code, a Student class is defined. An appropriate class name is given having attributes student’s name and roll number. Then the object of the student class is created and invoked. " }, { "code": null, "e": 30857, "s": 30855, "text": "R" }, { "code": "# List creation with its attributes name# and roll no.a < - list(name=\"Adam\", Roll_No=15) # Defining a class \"Student\"class(a) < - \"Student\" # Creation of objecta", "e": 31020, "s": 30857, "text": null }, { "code": null, "e": 31028, "s": 31020, "text": "Output:" }, { "code": null, "e": 31093, "s": 31028, "text": "$name\n[1] \"Adam\"\n\n$Roll_No\n[1] 15\n\nattr(, \"class\")\n[1] \"Student\"" }, { "code": null, "e": 31564, "s": 31093, "text": "The generic functions are a good example of polymorphism. To understand the concept of generic functions consider the print() function. The print() function is a collection of various print functions that are created for different data types and data structures in the R Programming Language. It calls the appropriate function depending upon the type of object passed as an argument. We can see the various implementation of print functions using the methods() function." }, { "code": null, "e": 31614, "s": 31564, "text": "Example: Seeing different types of print function" }, { "code": null, "e": 31616, "s": 31614, "text": "R" }, { "code": "methods(print)", "e": 31631, "s": 31616, "text": null }, { "code": null, "e": 31639, "s": 31631, "text": "Output:" }, { "code": null, "e": 31885, "s": 31639, "text": "Now let’s create a generic function of our own. We will create the print function for our class that will print all the members in our specified format. But before creating a print function let’s create what the print function does to our class." }, { "code": null, "e": 31895, "s": 31885, "text": " Example:" }, { "code": null, "e": 31897, "s": 31895, "text": "R" }, { "code": "# List creation with its attributes name# and roll no.a = list(name=\"Adam\", Roll_No=15) # Defining a class \"Student\"class(a) = \"Student\" # Creation of objectprint(a)", "e": 32063, "s": 31897, "text": null }, { "code": null, "e": 32071, "s": 32063, "text": "Output:" }, { "code": null, "e": 32135, "s": 32071, "text": "$name\n[1] \"Adam\"\n\n$Roll_No\n[1] 15\n\nattr(,\"class\")\n[1] \"Student\"" }, { "code": null, "e": 32221, "s": 32135, "text": "Now let’s print all the members in our specified format. Consider the below example –" }, { "code": null, "e": 32230, "s": 32221, "text": "Example:" }, { "code": null, "e": 32232, "s": 32230, "text": "R" }, { "code": "print.Student <- function(obj){ cat(\"name: \" ,obj$name, \"\\n\") cat(\"Roll No: \", obj$Roll_No, \"\\n\")} print(a)", "e": 32342, "s": 32232, "text": null }, { "code": null, "e": 32350, "s": 32342, "text": "Output:" }, { "code": null, "e": 32377, "s": 32350, "text": "name: Adam \nRoll No: 15 " }, { "code": null, "e": 32592, "s": 32377, "text": "Attributes of an object do not affect the value of an object, but they are a piece of extra information that is used to handle the objects. The function attributes() can be used to view the attributes of an object." }, { "code": null, "e": 32660, "s": 32592, "text": "Examples: An S3 object is created and its attributes are displayed." }, { "code": null, "e": 32662, "s": 32660, "text": "R" }, { "code": "attributes(a)", "e": 32676, "s": 32662, "text": null }, { "code": null, "e": 32684, "s": 32676, "text": "Output:" }, { "code": null, "e": 32724, "s": 32684, "text": "$names\n'name''Roll_No'\n$class\n'Student'" }, { "code": null, "e": 32782, "s": 32724, "text": "Also, you can add attributes to an object by using attr. " }, { "code": null, "e": 32784, "s": 32782, "text": "R" }, { "code": "attr(a, \"age\")<-c(18)attributes(a)", "e": 32819, "s": 32784, "text": null }, { "code": null, "e": 32827, "s": 32819, "text": "Output:" }, { "code": null, "e": 32875, "s": 32827, "text": "$names\n'name''Roll_No'\n$class\n'Student'\n$age\n18" }, { "code": null, "e": 33074, "s": 32875, "text": "Inheritance is an important concept in OOP(object-oriented programming) which allows one class to derive the features and functionalities of another class. This feature facilitates code-reusability." }, { "code": null, "e": 33279, "s": 33074, "text": "S3 class in R programming language has no formal and fixed definition. In an S3 object, a list with its class attribute is set to a class name. S3 class objects inherit only methods from their base class." }, { "code": null, "e": 33289, "s": 33279, "text": "Example: " }, { "code": null, "e": 33400, "s": 33289, "text": "In the following code, inheritance is done using S3 class, firstly the object is created of the class student." }, { "code": null, "e": 33402, "s": 33400, "text": "R" }, { "code": "# student function with argument# name(n) and roll_no(r)student < - function(n, r) { value < - list(name=n, Roll=r) attr(value, \"class\") < - \"student\" value}", "e": 33569, "s": 33402, "text": null }, { "code": null, "e": 33635, "s": 33569, "text": "Then, the method is defined to print the details of the student. " }, { "code": null, "e": 33637, "s": 33635, "text": "R" }, { "code": "# 'print.student' method createdprint.student < - function(obj) { # 'cat' function is used to concatenate # strings cat(\"Name:\", obj$name, \"\\n\") cat(\"Roll\", obj$roll, \"\\n\")}", "e": 33824, "s": 33637, "text": null }, { "code": null, "e": 33919, "s": 33824, "text": "Now, inheritance is done while creating another class by doing class(obj) <- c(child, parent)." }, { "code": null, "e": 33921, "s": 33919, "text": "R" }, { "code": "s < - list(name=\"Kesha\", Roll=21, country=\"India\") # child class 'Student' inherits# parent class 'student'class(s) < - c(\"Student\", \"student\")s", "e": 34066, "s": 33921, "text": null }, { "code": null, "e": 34075, "s": 34066, "text": "Output: " }, { "code": null, "e": 34098, "s": 34075, "text": "Name: Kesha \nRoll: 21 " }, { "code": null, "e": 34158, "s": 34098, "text": "The following code overwrites the method for class student." }, { "code": null, "e": 34160, "s": 34158, "text": "R" }, { "code": "# 'Student' class object is passed# in the function of class 'student' print.student < - function(obj) { cat(obj$name, \"is from\", obj$country, \"\\n\")}s", "e": 34314, "s": 34160, "text": null }, { "code": null, "e": 34322, "s": 34314, "text": "Output:" }, { "code": null, "e": 34342, "s": 34322, "text": "Kesha is from India" }, { "code": null, "e": 34547, "s": 34342, "text": "S4 class has a predefined definition. It contains functions for defining methods and generics. It makes multiple dispatches easy. This class contains auxiliary functions for defining methods and generics." }, { "code": null, "e": 34700, "s": 34547, "text": "setClass() command is used to create S4 class. Following is the syntax for setclass command which denotes myclass with slots containing name and rollno." }, { "code": null, "e": 34709, "s": 34700, "text": "Syntax: " }, { "code": null, "e": 34781, "s": 34709, "text": " setClass(“myclass”, slots=list(name=”character”, Roll_No=”numeric”)) " }, { "code": null, "e": 34927, "s": 34781, "text": "The new() function is used to create an object of the S4 class. In this function, we will pass the class name as well as the value for the slots." }, { "code": null, "e": 34937, "s": 34927, "text": "Example: " }, { "code": null, "e": 34939, "s": 34937, "text": "R" }, { "code": "# Function setClass() command used# to create S4 class containing list of slots.setClass(\"Student\", slots=list(name=\"character\", Roll_No=\"numeric\")) # 'new' keyword used to create object of# class 'Student'a <- new(\"Student\", name=\"Adam\", Roll_No=20) # Calling objecta", "e": 35238, "s": 34939, "text": null }, { "code": null, "e": 35247, "s": 35238, "text": "Output: " }, { "code": null, "e": 35295, "s": 35247, "text": "Slot \"name\":\n[1] \"Adam\"\n\nSlot \"Roll_No\":\n[1] 20" }, { "code": null, "e": 35397, "s": 35295, "text": "setClass() returns a generator function which helps in creating objects and it acts as a constructor." }, { "code": null, "e": 35406, "s": 35397, "text": "Example:" }, { "code": null, "e": 35408, "s": 35406, "text": "R" }, { "code": "stud <- setClass(\"Student\", slots=list(name=\"character\", Roll_No=\"numeric\")) # Calling objectstud", "e": 35536, "s": 35408, "text": null }, { "code": null, "e": 35544, "s": 35536, "text": "Output:" }, { "code": null, "e": 35597, "s": 35544, "text": "new(“classGeneratorFunction”, .Data = function (...)" }, { "code": null, "e": 35676, "s": 35597, "text": "new(“Student”, ...), className = structure(“Student”, package = “.GlobalEnv”)," }, { "code": null, "e": 35703, "s": 35676, "text": " package = “.GlobalEnv”)" }, { "code": null, "e": 35828, "s": 35703, "text": "Now the above-created stud function will act as the constructor for the Student class. It will behave as the new() function." }, { "code": null, "e": 35837, "s": 35828, "text": "Example:" }, { "code": null, "e": 35839, "s": 35837, "text": "R" }, { "code": "stud(name=\"Adam\", Roll_No=15)", "e": 35869, "s": 35839, "text": null }, { "code": null, "e": 35877, "s": 35869, "text": "Output:" }, { "code": null, "e": 35954, "s": 35877, "text": "An object of class \"Student\"\nSlot \"name\":\n[1] \"Adam\"\n\nSlot \"Roll_No\":\n[1] 15" }, { "code": null, "e": 36383, "s": 35954, "text": "S4 class in R programming have proper definition and derived classes will be able to inherit both attributes and methods from its base class. For this, we will first create a base class with appropriate slots and will create a generic function for that class. Then we will create a derived class that will inherit using the contains parameter. The derived class will inherit the members as well as functions from the base class." }, { "code": null, "e": 36392, "s": 36383, "text": "Example:" }, { "code": null, "e": 36394, "s": 36392, "text": "R" }, { "code": "# Define S4 classsetClass(\"student\", slots=list(name=\"character\", age=\"numeric\", rno=\"numeric\") ) # Defining a function to display object detailssetMethod(\"show\", \"student\", function(obj){ cat(obj@name, \"\\n\") cat(obj@age, \"\\n\") cat(obj@rno, \"\\n\") } ) # Inherit from studentsetClass(\"InternationalStudent\", slots=list(country=\"character\"), contains=\"student\" ) # Rest of the attributes will be inherited from students < - new(\"InternationalStudent\", name=\"Adam\", age=22, rno=15, country=\"India\")show(s)", "e": 37030, "s": 36394, "text": null }, { "code": null, "e": 37038, "s": 37030, "text": "Output:" }, { "code": null, "e": 37051, "s": 37038, "text": "Adam \n22 \n15" }, { "code": null, "e": 37114, "s": 37051, "text": "The reasons for defining both S3 and S4 class are as follows: " }, { "code": null, "e": 37324, "s": 37114, "text": "S4 class alone will not be seen if the S3 generic function is called directly. This will be the case, for example, if some function calls unique() from a package that does not make that function an S4 generic." }, { "code": null, "e": 37589, "s": 37324, "text": "However, primitive functions and operators are exceptions: The internal C code will look for S4 methods if and only if the object is an S4 object. S4 method dispatch would be used to dispatch any binary operator calls where either of the operands was an S4 object." }, { "code": null, "e": 37671, "s": 37589, "text": "S3 class alone will not be called if there is any eligible non-default S4 method." }, { "code": null, "e": 37879, "s": 37671, "text": "So if a package defined an S3 method for unique for an S4 class but another package defined an S4 method for a superclass of that class, the superclass method would be chosen, probably not what was intended." }, { "code": null, "e": 37886, "s": 37879, "text": "Picked" }, { "code": null, "e": 37893, "s": 37886, "text": "R-OOPs" }, { "code": null, "e": 37904, "s": 37893, "text": "R Language" }, { "code": null, "e": 38002, "s": 37904, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38011, "s": 38002, "text": "Comments" }, { "code": null, "e": 38024, "s": 38011, "text": "Old Comments" }, { "code": null, "e": 38069, "s": 38024, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 38127, "s": 38069, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 38159, "s": 38127, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 38222, "s": 38159, "text": "Adding elements in a vector in R programming - append() method" }, { "code": null, "e": 38274, "s": 38222, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 38318, "s": 38274, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 38370, "s": 38318, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 38435, "s": 38370, "text": "Convert Factor to Numeric and Numeric to Factor in R Programming" }, { "code": null, "e": 38484, "s": 38435, "text": "Remove rows with NA in one column of R DataFrame" } ]
C program to compare if the two matrices are equal or not
The user has to enter the order of two matrices and elements of two matrices. Then, these two matrix are compared. If both matrix elements and size are equal, then it displays that the two matrices are equal. If size of matrix is equal but the elements are not equal, then it displays that the matrix can be compared but is not equal. If the size and elements are not matched, then it displays that the matrices cannot be compared. Following is the C program to compare if the two matrices are equal or not − #include <stdio.h> #include <conio.h> main(){ int A[10][10], B[10][10]; int i, j, R1, C1, R2, C2, flag =1; printf("Enter the order of the matrix A\n"); scanf("%d %d", &R1, &C1); printf("Enter the order of the matrix B\n"); scanf("%d %d", &R2,&C2); printf("Enter the elements of matrix A\n"); for(i=0; i<R1; i++){ for(j=0; j<C1; j++){ scanf("%d",&A[i][j]); } } printf("Enter the elements of matrix B\n"); for(i=0; i<R2; i++){ for(j=0; j<C2; j++){ scanf("%d",&B[i][j]); } } printf("MATRIX A is\n"); for(i=0; i<R1; i++){ for(j=0; j<C1; j++){ printf("%3d",A[i][j]); } printf("\n"); } printf("MATRIX B is\n"); for(i=0; i<R2; i++){ for(j=0; j<C2; j++){ printf("%3d",B[i][j]); } printf("\n"); } /* Comparing two matrices for equality */ if(R1 == R2 && C1 == C2){ printf("Matrices can be compared\n"); for(i=0; i<R1; i++){ for(j=0; j<C2; j++){ if(A[i][j] != B[i][j]){ flag = 0; break; } } } } else{ printf(" Cannot be compared\n"); exit(1); } if(flag == 1 ) printf("Two matrices are equal\n"); else printf("But,two matrices are not equal\n"); } When the above program is executed, it produces the following result − Run 1: Enter the order of the matrix A 2 2 Enter the order of the matrix B 2 2 Enter the elements of matrix A 1 2 3 4 Enter the elements of matrix B 1 2 3 4 MATRIX A is 1 2 3 4 MATRIX B is 1 2 3 4 Matrices can be compared Two matrices are equal Run 2: Enter the order of the matrix A 2 2 Enter the order of the matrix B 2 2 Enter the elements of matrix A 1 2 3 4 Enter the elements of matrix B 5 6 7 8 MATRIX A is 1 2 3 4 MATRIX B is 5 6 7 8 Matrices can be compared But,two matrices are not equal
[ { "code": null, "e": 1177, "s": 1062, "text": "The user has to enter the order of two matrices and elements of two matrices. Then, these two matrix are compared." }, { "code": null, "e": 1271, "s": 1177, "text": "If both matrix elements and size are equal, then it displays that the two matrices are equal." }, { "code": null, "e": 1397, "s": 1271, "text": "If size of matrix is equal but the elements are not equal, then it displays that the matrix can be compared but is not equal." }, { "code": null, "e": 1494, "s": 1397, "text": "If the size and elements are not matched, then it displays that the matrices cannot be compared." }, { "code": null, "e": 1571, "s": 1494, "text": "Following is the C program to compare if the two matrices are equal or not −" }, { "code": null, "e": 2890, "s": 1571, "text": "#include <stdio.h>\n#include <conio.h>\nmain(){\n int A[10][10], B[10][10];\n int i, j, R1, C1, R2, C2, flag =1;\n printf(\"Enter the order of the matrix A\\n\");\n scanf(\"%d %d\", &R1, &C1);\n printf(\"Enter the order of the matrix B\\n\");\n scanf(\"%d %d\", &R2,&C2);\n printf(\"Enter the elements of matrix A\\n\");\n for(i=0; i<R1; i++){\n for(j=0; j<C1; j++){\n scanf(\"%d\",&A[i][j]);\n }\n }\n printf(\"Enter the elements of matrix B\\n\");\n for(i=0; i<R2; i++){\n for(j=0; j<C2; j++){\n scanf(\"%d\",&B[i][j]);\n }\n }\n printf(\"MATRIX A is\\n\");\n for(i=0; i<R1; i++){\n for(j=0; j<C1; j++){\n printf(\"%3d\",A[i][j]);\n }\n printf(\"\\n\");\n }\n printf(\"MATRIX B is\\n\");\n for(i=0; i<R2; i++){\n for(j=0; j<C2; j++){\n printf(\"%3d\",B[i][j]);\n }\n printf(\"\\n\");\n }\n /* Comparing two matrices for equality */\n if(R1 == R2 && C1 == C2){\n printf(\"Matrices can be compared\\n\");\n for(i=0; i<R1; i++){\n for(j=0; j<C2; j++){\n if(A[i][j] != B[i][j]){\n flag = 0;\n break;\n }\n }\n }\n }\n else{\n printf(\" Cannot be compared\\n\");\n exit(1);\n }\n if(flag == 1 )\n printf(\"Two matrices are equal\\n\");\n else\n printf(\"But,two matrices are not equal\\n\");\n}" }, { "code": null, "e": 2961, "s": 2890, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 3484, "s": 2961, "text": "Run 1:\nEnter the order of the matrix A\n2 2\nEnter the order of the matrix B\n2 2\nEnter the elements of matrix A\n1\n2\n3\n4\nEnter the elements of matrix B\n1\n2\n3\n4\nMATRIX A is\n 1 2\n 3 4\nMATRIX B is\n 1 2\n 3 4\nMatrices can be compared\nTwo matrices are equal\n\nRun 2:\nEnter the order of the matrix A\n2 2\nEnter the order of the matrix B\n2 2\nEnter the elements of matrix A\n1\n2\n3\n4\nEnter the elements of matrix B\n5\n6\n7\n8\nMATRIX A is\n 1 2\n 3 4\nMATRIX B is\n 5 6\n 7 8\nMatrices can be compared\nBut,two matrices are not equal" } ]
Sum of Middle Elements of two sorted arrays | Practice | GeeksforGeeks
Given 2 sorted arrays Ar1 and Ar2 of size N each. Merge the given arrays and find the sum of the two middle elements of the merged array. Example 1: Input: N = 5 Ar1[] = {1, 2, 4, 6, 10} Ar2[] = {4, 5, 6, 9, 12} Output: 11 Explanation: The merged array looks like {1,2,4,4,5,6,6,9,10,12}. Sum of middle elements is 11 (5 + 6). Example 2: Input: N = 5 Ar1[] = {1, 12, 15, 26, 38} Ar2[] = {2, 13, 17, 30, 45} Output: 32 Explanation: The merged array looks like {1, 2, 12, 13, 15, 17, 26, 30, 38, 45} sum of middle elements is 32 (15 + 17). Your Task: You don't need to read input or print anything. Your task is to complete the function findMidSum() which takes ar1, ar2 and n as input parameters and returns the sum of middle elements. Expected Time Complexity: O(log N) Expected Auxiliary Space: O(1) Constraints: 1 <= N <= 103 1 <= Ar1[i] <= 106 1 <= Ar2[i] <= 106 0 suprithsk200116 hours ago //simple c++ soln vector<int> ans; for(int i=0;i<n;i++){ ans.push_back(ar1[i]); } for(int i=0;i<n;i++){ ans.push_back(ar2[i]); } sort(ans.begin(),ans.end()); int mid=ans.size()/2; return ans[mid]+ans[mid-1]; 0 tupesanket199919 hours ago Expected Time Complexity: O(log N) Expected Auxiliary Space: O(1) int findMidSum(int ar1[], int ar2[], int n) { int low = 0,high=n; while(low <= high){ int cut1 = (low + high)>>1 ; int cut2 = n - cut1; int left1 = (cut1==0) ? INT_MIN:ar1[cut1-1]; int left2 = (cut2==0) ? INT_MIN:ar2[cut2-1]; int right1 = (cut1==n) ? INT_MAX:ar1[cut1]; int right2 = (cut2==n) ? INT_MAX:ar2[cut2]; if(left1<= right2 && left2 <=right1){ return max(left1,left2) + min(right1,right2); }else if(left1 > right2){ high = cut1-1; }else{ low = cut1+1; } } return -1; } 0 sambhavjsj20001 week ago PYTHON TIME TAKEN - 0.21 class Solution:def findMidSum(self, ar1, ar2, n): li=ar1+ar2 mid=len(li)//2 middle=[] sum=0 li=sorted(li) if len(li)%2!=0: middle.append(li[mid]) else: middle.append(li[mid-1]) middle.append(li[mid]) for i in middle: sum+=i return sum 0 mayank180919991 week ago int findMidSum(int ar1[], int ar2[], int n) { // code here vector<int>ans; for(int i=0;i<n;i++){ ans.push_back(ar1[i]); ans.push_back(ar2[i]); } sort(ans.begin(),ans.end()); return ans[n]+ans[n-1]; } 0 mayank18091999 This comment was deleted. 0 shaikhmohammedammar1 week ago int findMidSum(int ar1[], int ar2[], int n) { vector<int> arr; /* /// trying for pointers, but can't help. int pt1 = 0, pt2 = 0; for(int i=0; i<n-1; i++){ if(ar1[pt1]<ar2[pt2] and pt1<n) pt1++; else pt2++; } return (ar1[pt1]+ar2[pt2]); */ for(int i=0; i<n; i++){ arr.push_back(ar1[i]); arr.push_back(ar2[i]); } n = arr.size(); sort(arr.begin(), arr.end()); return (arr[n>>1]+arr[(n>>1)-1]); } +1 aloksinghbais021 week ago C++ solution having time complexity as O(2*2*log(N)*log(N)) and space complexity as O(1) is as follows :- Execution Time :- 0.21 / 1.91 sec int helper(int ar1[],int ar2[],int n,int ele){ int s = 0; int e = n-1; while(s <= e){ int mid = (s+e)/2; int lb = lower_bound(ar2,ar2+n,ar1[mid]) - ar2; int ub = upper_bound(ar2,ar2+n,ar1[mid]) - ar2; int lbne = lb + mid; int ubne = ub + mid; if(ele >= lbne && ele <= ubne){ return (ar1[mid]); } else if(ele < lbne){ e = mid - 1; } else{ s = mid + 1; } } s = 0; e = n-1; while(s <= e){ int mid = (s+e)/2; int lb = lower_bound(ar1,ar1+n,ar2[mid]) - ar1; int ub = upper_bound(ar1,ar1+n,ar2[mid]) - ar1; int lbne = lb + mid; int ubne = ub + mid; if(ele >= lbne && ele <= ubne){ return (ar2[mid]); } else if(ele < lbne){ e = mid - 1; } else{ s = mid + 1; } } return (-1); } int findMidSum(int ar1[], int ar2[], int n) { int a = helper(ar1,ar2,n,n-1); int b = helper(ar1,ar2,n,n); return (a+b); } 0 imabhishek021 week ago easy solution c++: int findMidSum(int ar1[], int ar2[], int n) { vector<int >ans; for(int i=0;i<n;i++) { ans.push_back(ar1[i]); ans.push_back(ar2[i]); } sort(ans.begin(),ans.end()); int x=ans.size(); return ans[x/2]+ans[(x/2)-1]; } }; 0 kiranbari12 weeks ago int findMidSum(int ar1[], int ar2[], int n){ int i=0,j=0,c=0; int n1,n2; while(c<=n){ if(j==n ||(i<n && j<n && ar1[i]<=ar2[j])){ if(c==n-1) n1=ar1[i]; else if(c==n){ n2=ar1[i]; } i++; }else if(i==n ||(i<n && j<n && ar1[i]>ar2[j])){ if(c==n-1) n1=ar2[j]; else if(c==n){ n2=ar2[j]; } j++; } c++; } return n1+n2; } +1 aashaykaurav2 weeks ago python - def findMidSum(self, ar1, ar2, n): # code here Arr = [] i ,j = 0, 0 while i < n and j < n: if ar1[i] <= ar2[j]: Arr.append(ar1[i]) i += 1 else: Arr.append(ar2[j]) j += 1 if i == n: while j < n: Arr.append(ar2[j]) j += 1 if j == n: while i < n: Arr.append(ar1[i]) i += 1 k = len(Arr)//2 s = Arr[k] + Arr[k-1] return s 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": 364, "s": 226, "text": "Given 2 sorted arrays Ar1 and Ar2 of size N each. Merge the given arrays and find the sum of the two middle elements of the merged array." }, { "code": null, "e": 377, "s": 366, "text": "Example 1:" }, { "code": null, "e": 556, "s": 377, "text": "Input:\nN = 5\nAr1[] = {1, 2, 4, 6, 10}\nAr2[] = {4, 5, 6, 9, 12}\nOutput: 11\nExplanation: The merged array looks like\n{1,2,4,4,5,6,6,9,10,12}. Sum of middle\nelements is 11 (5 + 6).\n" }, { "code": null, "e": 569, "s": 558, "text": "Example 2:" }, { "code": null, "e": 770, "s": 569, "text": "Input:\nN = 5\nAr1[] = {1, 12, 15, 26, 38}\nAr2[] = {2, 13, 17, 30, 45}\nOutput: 32\nExplanation: The merged array looks like\n{1, 2, 12, 13, 15, 17, 26, 30, 38, 45} \nsum of middle elements is 32 (15 + 17)." }, { "code": null, "e": 971, "s": 772, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function findMidSum() which takes ar1, ar2 and n as input parameters and returns the sum of middle elements. " }, { "code": null, "e": 1039, "s": 973, "text": "Expected Time Complexity: O(log N)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1106, "s": 1041, "text": "Constraints:\n1 <= N <= 103\n1 <= Ar1[i] <= 106\n1 <= Ar2[i] <= 106" }, { "code": null, "e": 1108, "s": 1106, "text": "0" }, { "code": null, "e": 1134, "s": 1108, "text": "suprithsk200116 hours ago" }, { "code": null, "e": 1152, "s": 1134, "text": "//simple c++ soln" }, { "code": null, "e": 1440, "s": 1152, "text": "vector<int> ans; for(int i=0;i<n;i++){ ans.push_back(ar1[i]); } for(int i=0;i<n;i++){ ans.push_back(ar2[i]); } sort(ans.begin(),ans.end()); int mid=ans.size()/2; return ans[mid]+ans[mid-1];" }, { "code": null, "e": 1442, "s": 1440, "text": "0" }, { "code": null, "e": 1469, "s": 1442, "text": "tupesanket199919 hours ago" }, { "code": null, "e": 1504, "s": 1469, "text": "Expected Time Complexity: O(log N)" }, { "code": null, "e": 1535, "s": 1504, "text": "Expected Auxiliary Space: O(1)" }, { "code": null, "e": 2222, "s": 1535, "text": " int findMidSum(int ar1[], int ar2[], int n) {\n int low = 0,high=n;\n while(low <= high){\n int cut1 = (low + high)>>1 ;\n int cut2 = n - cut1;\n int left1 = (cut1==0) ? INT_MIN:ar1[cut1-1];\n int left2 = (cut2==0) ? INT_MIN:ar2[cut2-1];\n int right1 = (cut1==n) ? INT_MAX:ar1[cut1];\n int right2 = (cut2==n) ? INT_MAX:ar2[cut2];\n if(left1<= right2 && left2 <=right1){\n return max(left1,left2) + min(right1,right2);\n }else if(left1 > right2){\n high = cut1-1;\n }else{\n low = cut1+1;\n }\n }\n return -1;\n }" }, { "code": null, "e": 2224, "s": 2222, "text": "0" }, { "code": null, "e": 2249, "s": 2224, "text": "sambhavjsj20001 week ago" }, { "code": null, "e": 2256, "s": 2249, "text": "PYTHON" }, { "code": null, "e": 2274, "s": 2256, "text": "TIME TAKEN - 0.21" }, { "code": null, "e": 2598, "s": 2274, "text": "class Solution:def findMidSum(self, ar1, ar2, n): li=ar1+ar2 mid=len(li)//2 middle=[] sum=0 li=sorted(li) if len(li)%2!=0: middle.append(li[mid]) else: middle.append(li[mid-1]) middle.append(li[mid]) for i in middle: sum+=i return sum" }, { "code": null, "e": 2600, "s": 2598, "text": "0" }, { "code": null, "e": 2625, "s": 2600, "text": "mayank180919991 week ago" }, { "code": null, "e": 2934, "s": 2625, "text": " int findMidSum(int ar1[], int ar2[], int n) {\n // code here\n vector<int>ans;\n for(int i=0;i<n;i++){\n ans.push_back(ar1[i]);\n ans.push_back(ar2[i]);\n }\n sort(ans.begin(),ans.end());\n return ans[n]+ans[n-1];\n }" }, { "code": null, "e": 2936, "s": 2934, "text": "0" }, { "code": null, "e": 2951, "s": 2936, "text": "mayank18091999" }, { "code": null, "e": 2977, "s": 2951, "text": "This comment was deleted." }, { "code": null, "e": 2979, "s": 2977, "text": "0" }, { "code": null, "e": 3009, "s": 2979, "text": "shaikhmohammedammar1 week ago" }, { "code": null, "e": 3615, "s": 3009, "text": "int findMidSum(int ar1[], int ar2[], int n) {\n vector<int> arr;\n /* /// trying for pointers, but can't help.\n int pt1 = 0, pt2 = 0;\n for(int i=0; i<n-1; i++){\n if(ar1[pt1]<ar2[pt2] and pt1<n) pt1++;\n else pt2++;\n }\n return (ar1[pt1]+ar2[pt2]);\n */\n for(int i=0; i<n; i++){\n arr.push_back(ar1[i]);\n arr.push_back(ar2[i]);\n }\n n = arr.size();\n sort(arr.begin(), arr.end());\n return (arr[n>>1]+arr[(n>>1)-1]);\n }" }, { "code": null, "e": 3618, "s": 3615, "text": "+1" }, { "code": null, "e": 3644, "s": 3618, "text": "aloksinghbais021 week ago" }, { "code": null, "e": 3751, "s": 3644, "text": "C++ solution having time complexity as O(2*2*log(N)*log(N)) and space complexity as O(1) is as follows :- " }, { "code": null, "e": 3787, "s": 3753, "text": "Execution Time :- 0.21 / 1.91 sec" }, { "code": null, "e": 5002, "s": 3789, "text": "int helper(int ar1[],int ar2[],int n,int ele){ int s = 0; int e = n-1; while(s <= e){ int mid = (s+e)/2; int lb = lower_bound(ar2,ar2+n,ar1[mid]) - ar2; int ub = upper_bound(ar2,ar2+n,ar1[mid]) - ar2; int lbne = lb + mid; int ubne = ub + mid; if(ele >= lbne && ele <= ubne){ return (ar1[mid]); } else if(ele < lbne){ e = mid - 1; } else{ s = mid + 1; } } s = 0; e = n-1; while(s <= e){ int mid = (s+e)/2; int lb = lower_bound(ar1,ar1+n,ar2[mid]) - ar1; int ub = upper_bound(ar1,ar1+n,ar2[mid]) - ar1; int lbne = lb + mid; int ubne = ub + mid; if(ele >= lbne && ele <= ubne){ return (ar2[mid]); } else if(ele < lbne){ e = mid - 1; } else{ s = mid + 1; } } return (-1); } int findMidSum(int ar1[], int ar2[], int n) { int a = helper(ar1,ar2,n,n-1); int b = helper(ar1,ar2,n,n); return (a+b); }" }, { "code": null, "e": 5004, "s": 5002, "text": "0" }, { "code": null, "e": 5027, "s": 5004, "text": "imabhishek021 week ago" }, { "code": null, "e": 5046, "s": 5027, "text": "easy solution c++:" }, { "code": null, "e": 5377, "s": 5046, "text": "int findMidSum(int ar1[], int ar2[], int n) {\n \n vector<int >ans;\n \n for(int i=0;i<n;i++)\n {\n ans.push_back(ar1[i]);\n ans.push_back(ar2[i]);\n }\n sort(ans.begin(),ans.end());\n \n int x=ans.size();\n return ans[x/2]+ans[(x/2)-1];\n \n \n }\n};" }, { "code": null, "e": 5379, "s": 5377, "text": "0" }, { "code": null, "e": 5401, "s": 5379, "text": "kiranbari12 weeks ago" }, { "code": null, "e": 5991, "s": 5401, "text": "int findMidSum(int ar1[], int ar2[], int n){\n int i=0,j=0,c=0;\n int n1,n2;\n while(c<=n){\n if(j==n ||(i<n && j<n && ar1[i]<=ar2[j])){\n if(c==n-1)\n n1=ar1[i];\n else if(c==n){\n n2=ar1[i];\n }\n i++;\n }else if(i==n ||(i<n && j<n && ar1[i]>ar2[j])){\n if(c==n-1)\n n1=ar2[j];\n else if(c==n){\n n2=ar2[j];\n }\n j++;\n }\n c++;\n }\n return n1+n2;\n }" }, { "code": null, "e": 5994, "s": 5991, "text": "+1" }, { "code": null, "e": 6018, "s": 5994, "text": "aashaykaurav2 weeks ago" }, { "code": null, "e": 6027, "s": 6018, "text": "python -" }, { "code": null, "e": 6456, "s": 6027, "text": "def findMidSum(self, ar1, ar2, n): # code here Arr = [] i ,j = 0, 0 while i < n and j < n: if ar1[i] <= ar2[j]: Arr.append(ar1[i]) i += 1 else: Arr.append(ar2[j]) j += 1 if i == n: while j < n: Arr.append(ar2[j]) j += 1 if j == n: while i < n: Arr.append(ar1[i]) i += 1 k = len(Arr)//2 s = Arr[k] + Arr[k-1] return s" }, { "code": null, "e": 6602, "s": 6456, "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": 6638, "s": 6602, "text": " Login to access your submissions. " }, { "code": null, "e": 6648, "s": 6638, "text": "\nProblem\n" }, { "code": null, "e": 6658, "s": 6648, "text": "\nContest\n" }, { "code": null, "e": 6721, "s": 6658, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6869, "s": 6721, "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": 7077, "s": 6869, "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": 7183, "s": 7077, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to count number of characters in EditText while typing in android?
This example demonstrates how do I count number of characters in editText while typing 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="4dp" tools:context=".MainActivity"> <EditText android:id="@+id/editText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:ems="10" android:hint="EditText"/> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/editText" android:layout_marginBottom="20dp" android:layout_centerInParent="true" android:textSize="24sp" android:textStyle="bold" android:text="Count Display Here"/> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView textView; EditText editText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); editText = findViewById(R.id.editText); editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { int length = editText.length(); String convert = String.valueOf(length); textView.setText(convert); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { } }); } } 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 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": 1161, "s": 1062, "text": "This example demonstrates how do I count number of characters in editText while typing in android." }, { "code": null, "e": 1290, "s": 1161, "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": 1355, "s": 1290, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2268, "s": 1355, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n 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=\"4dp\"\n tools:context=\".MainActivity\">\n <EditText\n android:id=\"@+id/editText\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:ems=\"10\"\n android:hint=\"EditText\"/>\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_above=\"@+id/editText\"\n android:layout_marginBottom=\"20dp\"\n android:layout_centerInParent=\"true\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\"\n android:text=\"Count Display Here\"/>\n</RelativeLayout>" }, { "code": null, "e": 2325, "s": 2268, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3395, "s": 2325, "text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.text.Editable;\nimport android.text.TextWatcher;\nimport android.widget.EditText;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n EditText editText;\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 editText = findViewById(R.id.editText);\n editText.addTextChangedListener(new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) {\n int length = editText.length();\n String convert = String.valueOf(length);\n textView.setText(convert);\n }\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) {\n }\n @Override\n public void afterTextChanged(Editable s) { }\n });\n }\n}" }, { "code": null, "e": 3450, "s": 3395, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4156, "s": 3450, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action\n android:name=\"android.intent.action.MAIN\" />\n <category\n android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4503, "s": 4156, "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 −" } ]
Check if two lists are identical in Python
In python data analysis, we may come across situation when we need to compare two lists and find out if they are identical meaning having same elements or not. Live Demo listA = ['Mon','Tue','Wed','Thu'] listB = ['Mon','Wed','Tue','Thu'] # Given lists print("Given listA: ",listA) print("Given listB: ",listB) # Sort the lists listA.sort() listB.sort() # Check for equality if listA == listB: print("Lists are identical") else: print("Lists are not identical") Running the above code gives us the following result − Given listA: ['Mon', 'Tue', 'Wed', 'Thu'] Given listB: ['Mon', 'Wed', 'Tue', 'Thu'] Lists are identical The Counter function from collections module can help us in finding the number of occurrences of each item in the list. In the below example we also take two duplicate elements. If the frequency of each element is equal in both the lists, we consider the lists to be identical. Live Demo import collections listA = ['Mon','Tue','Wed','Tue'] listB = ['Mon','Wed','Tue','Tue'] # Given lists print("Given listA: ",listA) print("Given listB: ",listB) # Check for equality if collections.Counter(listA) == collections.Counter(listB): print("Lists are identical") else: print("Lists are not identical") # Checking again listB = ['Mon','Wed','Wed','Tue'] print("Given listB: ",listB) # Check for equality if collections.Counter(listA) == collections.Counter(listB): print("Lists are identical") else: print("Lists are not identical") Running the above code gives us the following result − Given listA: ['Mon', 'Tue', 'Wed', 'Tue'] Given listB: ['Mon', 'Wed', 'Tue', 'Tue'] Lists are identical Given listB: ['Mon', 'Wed', 'Wed', 'Tue'] Lists are not identical
[ { "code": null, "e": 1222, "s": 1062, "text": "In python data analysis, we may come across situation when we need to compare two lists and find out if they are identical meaning having same elements or not." }, { "code": null, "e": 1233, "s": 1222, "text": " Live Demo" }, { "code": null, "e": 1531, "s": 1233, "text": "listA = ['Mon','Tue','Wed','Thu']\nlistB = ['Mon','Wed','Tue','Thu']\n# Given lists\nprint(\"Given listA: \",listA)\nprint(\"Given listB: \",listB)\n# Sort the lists\nlistA.sort()\nlistB.sort()\n\n# Check for equality\nif listA == listB:\n print(\"Lists are identical\")\nelse:\n print(\"Lists are not identical\")" }, { "code": null, "e": 1586, "s": 1531, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1690, "s": 1586, "text": "Given listA: ['Mon', 'Tue', 'Wed', 'Thu']\nGiven listB: ['Mon', 'Wed', 'Tue', 'Thu']\nLists are identical" }, { "code": null, "e": 1968, "s": 1690, "text": "The Counter function from collections module can help us in finding the number of occurrences of each item in the list. In the below example we also take two duplicate elements. If the frequency of each element is equal in both the lists, we consider the lists to be identical." }, { "code": null, "e": 1979, "s": 1968, "text": " Live Demo" }, { "code": null, "e": 2532, "s": 1979, "text": "import collections\nlistA = ['Mon','Tue','Wed','Tue']\nlistB = ['Mon','Wed','Tue','Tue']\n# Given lists\nprint(\"Given listA: \",listA)\nprint(\"Given listB: \",listB)\n# Check for equality\nif collections.Counter(listA) == collections.Counter(listB):\n print(\"Lists are identical\")\nelse:\n print(\"Lists are not identical\")\n\n# Checking again\nlistB = ['Mon','Wed','Wed','Tue']\nprint(\"Given listB: \",listB)\n\n# Check for equality\nif collections.Counter(listA) == collections.Counter(listB):\n print(\"Lists are identical\")\nelse:\n print(\"Lists are not identical\")" }, { "code": null, "e": 2587, "s": 2532, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2757, "s": 2587, "text": "Given listA: ['Mon', 'Tue', 'Wed', 'Tue']\nGiven listB: ['Mon', 'Wed', 'Tue', 'Tue']\nLists are identical\nGiven listB: ['Mon', 'Wed', 'Wed', 'Tue']\nLists are not identical" } ]
Format date as Year/Quarter in R - GeeksforGeeks
23 May, 2021 A date can be represented in multiple formats as per requirement. Some requirements only want information regarding year and quarter and other parts of a date seem unnecessary in such scenarios. In such cases, the date can be formatted to display only year and quarter. In this article we, will be looking at the different approaches to format date as year/quarter in R language. paste() function is used to Concatenate vectors after converting to character. Syntax: paste (..., sep = ” “, collapse = NULL) format() function helps to format an R object for pretty printing. Syntax: format(x, ...) sprintf() function basically returns a character vector containing a formatted combination of text and variable values. Syntax: sprintf(fmt, ...) as.POSIXLt() function is used to manipulate objects of classes representing calendar dates and times. Syntax: as.POSIXlt(x, tz = “”, ...) Example: R gfg_date=as.Date(c("2021-05-13","2000-07-12", "2020-10-08","2001-09-04")) gfg_date gfg_quarters <- paste( format(gfg_date, "%Y"), sprintf("%02i", (as.POSIXlt(gfg_date)$mon) %/% 3L + 1L), sep = "/") gfg_quarters Output: In this approach to format given dates as quarter user needs to call paste0() function and quarter() function of the lubridate package and pass the required parameters into it. Then this approach will be converting the given date as year/quarters in R programming language. paste0() function is used to concatenate vectors after converting to character. Syntax: paste0(..., collapse = NULL) quarter() function is used to divide the year into fourths. Syntax: quarter(x, with_year = FALSE, fiscal_start = 1) Parameters: x:-a date-time object of class POSIXct, POSIXlt, Date, chron, yearmon, yearqtr, zoo, zooreg, timeDate, xts, its, ti, jul, timeSeries, fts or anything else that can be converted with as.POSIXlt with_year:-logical indicating whether or not to include the quarter’s year. fiscal_start:-numeric indicating the starting month of a fiscal year Example: R library("lubridate") gfg_date=as.Date(c("2021-05-13","2000-07-12", "2020-10-08","2001-09-04"))gfg_date gfg_quarters <- paste0(year(gfg_date),"/0",quarter(gfg_date))gfg_quarters Output: Under this approach to format given dates as year/quarter users need to first install and load the zoo package. Then call the as.yearqtr() function with the required parameters into it, with this user will be getting a formatted date as year/quarter in return. as.yearqtr() function is used for representing quarterly data. Syntax: as.yearqtr(x, format, ...) Parameter: x:-for yearqtr a numeric (interpreted as being “in years”). For as.yearqtr another date class object. format:-character string specifying format. For coercing to “yearqtr” from character: “%Y” and “%q” have to be specified. ...:-arguments passed ot other methods. Example: R library("zoo") gfg_date=as.Date(c("2021-05-13","2000-07-12", "2020-10-08","2001-09-04"))gfg_date gfg_quarters <-as.yearqtr(gfg_date,format = "%Y-%m-%d")gfg_quarters Output: Picked R-DateTime R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Control Statements in R Programming Change Color of Bars in Barchart using ggplot2 in R Data Visualization in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? Logistic Regression in R Programming Linear Discriminant Analysis in R Programming How to filter R DataFrame by values in a column? How to change Colors in ggplot2 Line Plot in R ? How to import an Excel File into R ?
[ { "code": null, "e": 24851, "s": 24823, "text": "\n23 May, 2021" }, { "code": null, "e": 25231, "s": 24851, "text": "A date can be represented in multiple formats as per requirement. Some requirements only want information regarding year and quarter and other parts of a date seem unnecessary in such scenarios. In such cases, the date can be formatted to display only year and quarter. In this article we, will be looking at the different approaches to format date as year/quarter in R language." }, { "code": null, "e": 25310, "s": 25231, "text": "paste() function is used to Concatenate vectors after converting to character." }, { "code": null, "e": 25358, "s": 25310, "text": "Syntax: paste (..., sep = ” “, collapse = NULL)" }, { "code": null, "e": 25425, "s": 25358, "text": "format() function helps to format an R object for pretty printing." }, { "code": null, "e": 25448, "s": 25425, "text": "Syntax: format(x, ...)" }, { "code": null, "e": 25568, "s": 25448, "text": "sprintf() function basically returns a character vector containing a formatted combination of text and variable values." }, { "code": null, "e": 25594, "s": 25568, "text": "Syntax: sprintf(fmt, ...)" }, { "code": null, "e": 25696, "s": 25594, "text": "as.POSIXLt() function is used to manipulate objects of classes representing calendar dates and times." }, { "code": null, "e": 25732, "s": 25696, "text": "Syntax: as.POSIXlt(x, tz = “”, ...)" }, { "code": null, "e": 25741, "s": 25732, "text": "Example:" }, { "code": null, "e": 25743, "s": 25741, "text": "R" }, { "code": "gfg_date=as.Date(c(\"2021-05-13\",\"2000-07-12\", \"2020-10-08\",\"2001-09-04\")) gfg_date gfg_quarters <- paste( format(gfg_date, \"%Y\"), sprintf(\"%02i\", (as.POSIXlt(gfg_date)$mon) %/% 3L + 1L), sep = \"/\") gfg_quarters", "e": 25979, "s": 25743, "text": null }, { "code": null, "e": 25987, "s": 25979, "text": "Output:" }, { "code": null, "e": 26261, "s": 25987, "text": "In this approach to format given dates as quarter user needs to call paste0() function and quarter() function of the lubridate package and pass the required parameters into it. Then this approach will be converting the given date as year/quarters in R programming language." }, { "code": null, "e": 26341, "s": 26261, "text": "paste0() function is used to concatenate vectors after converting to character." }, { "code": null, "e": 26378, "s": 26341, "text": "Syntax: paste0(..., collapse = NULL)" }, { "code": null, "e": 26438, "s": 26378, "text": "quarter() function is used to divide the year into fourths." }, { "code": null, "e": 26446, "s": 26438, "text": "Syntax:" }, { "code": null, "e": 26494, "s": 26446, "text": "quarter(x, with_year = FALSE, fiscal_start = 1)" }, { "code": null, "e": 26506, "s": 26494, "text": "Parameters:" }, { "code": null, "e": 26699, "s": 26506, "text": "x:-a date-time object of class POSIXct, POSIXlt, Date, chron, yearmon, yearqtr, zoo, zooreg, timeDate, xts, its, ti, jul, timeSeries, fts or anything else that can be converted with as.POSIXlt" }, { "code": null, "e": 26775, "s": 26699, "text": "with_year:-logical indicating whether or not to include the quarter’s year." }, { "code": null, "e": 26844, "s": 26775, "text": "fiscal_start:-numeric indicating the starting month of a fiscal year" }, { "code": null, "e": 26853, "s": 26844, "text": "Example:" }, { "code": null, "e": 26855, "s": 26853, "text": "R" }, { "code": "library(\"lubridate\") gfg_date=as.Date(c(\"2021-05-13\",\"2000-07-12\", \"2020-10-08\",\"2001-09-04\"))gfg_date gfg_quarters <- paste0(year(gfg_date),\"/0\",quarter(gfg_date))gfg_quarters", "e": 27052, "s": 26855, "text": null }, { "code": null, "e": 27060, "s": 27052, "text": "Output:" }, { "code": null, "e": 27321, "s": 27060, "text": "Under this approach to format given dates as year/quarter users need to first install and load the zoo package. Then call the as.yearqtr() function with the required parameters into it, with this user will be getting a formatted date as year/quarter in return." }, { "code": null, "e": 27384, "s": 27321, "text": "as.yearqtr() function is used for representing quarterly data." }, { "code": null, "e": 27419, "s": 27384, "text": "Syntax: as.yearqtr(x, format, ...)" }, { "code": null, "e": 27430, "s": 27419, "text": "Parameter:" }, { "code": null, "e": 27532, "s": 27430, "text": "x:-for yearqtr a numeric (interpreted as being “in years”). For as.yearqtr another date class object." }, { "code": null, "e": 27654, "s": 27532, "text": "format:-character string specifying format. For coercing to “yearqtr” from character: “%Y” and “%q” have to be specified." }, { "code": null, "e": 27694, "s": 27654, "text": "...:-arguments passed ot other methods." }, { "code": null, "e": 27703, "s": 27694, "text": "Example:" }, { "code": null, "e": 27705, "s": 27703, "text": "R" }, { "code": "library(\"zoo\") gfg_date=as.Date(c(\"2021-05-13\",\"2000-07-12\", \"2020-10-08\",\"2001-09-04\"))gfg_date gfg_quarters <-as.yearqtr(gfg_date,format = \"%Y-%m-%d\")gfg_quarters", "e": 27890, "s": 27705, "text": null }, { "code": null, "e": 27898, "s": 27890, "text": "Output:" }, { "code": null, "e": 27905, "s": 27898, "text": "Picked" }, { "code": null, "e": 27916, "s": 27905, "text": "R-DateTime" }, { "code": null, "e": 27927, "s": 27916, "text": "R Language" }, { "code": null, "e": 28025, "s": 27927, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28034, "s": 28025, "text": "Comments" }, { "code": null, "e": 28047, "s": 28034, "text": "Old Comments" }, { "code": null, "e": 28083, "s": 28047, "text": "Control Statements in R Programming" }, { "code": null, "e": 28135, "s": 28083, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28159, "s": 28135, "text": "Data Visualization in R" }, { "code": null, "e": 28194, "s": 28159, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28232, "s": 28194, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 28269, "s": 28232, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 28315, "s": 28269, "text": "Linear Discriminant Analysis in R Programming" }, { "code": null, "e": 28364, "s": 28315, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28413, "s": 28364, "text": "How to change Colors in ggplot2 Line Plot in R ?" } ]
Cordova - Camera
This plugin is used for taking photos or using files from the image gallery. Run the following code in the command prompt window to install this plugin. C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugincamera Now, we will create the button for calling the camera and img where the image will be displayed once taken. This will be added to index.html inside the div class = "app" element. <button id = "cameraTakePicture">TAKE PICTURE</button> <img id = "myImage"></img> The event listener is added inside the onDeviceReady function to ensure that Cordova is loaded before we start using it. document.getElementById("cameraTakePicture").addEventListener ("click", cameraTakePicture); We will create the cameraTakePicture function that is passed as a callback to our event listener. It will be fired when the button is tapped. Inside this function, we will call the navigator.camera global object provided by the plugin API. If taking picture is successful, the data will be sent to the onSuccess callback function, if not, the alert with error message will be shown. We will place this code at the bottom of index.js. function cameraTakePicture() { navigator.camera.getPicture(onSuccess, onFail, { quality: 50, destinationType: Camera.DestinationType.DATA_URL }); function onSuccess(imageData) { var image = document.getElementById('myImage'); image.src = "data:image/jpeg;base64," + imageData; } function onFail(message) { alert('Failed because: ' + message); } } When we run the app and press the button, native camera will be triggered. When we take and save picture, it will be displayed on screen. The same procedure can be used for getting image from the local file system. The only difference is the function created in the last step. You can see that the sourceType optional parameter has been added. C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugincamera <button id = "cameraGetPicture">GET PICTURE</button> document.getElementById("cameraGetPicture").addEventListener("click", cameraGetPicture); function cameraGetPicture() { navigator.camera.getPicture(onSuccess, onFail, { quality: 50, destinationType: Camera.DestinationType.DATA_URL, sourceType: Camera.PictureSourceType.PHOTOLIBRARY }); function onSuccess(imageURL) { var image = document.getElementById('myImage'); image.src = imageURL; } function onFail(message) { alert('Failed because: ' + message); } } When we press the second button, the file system will open instead of the camera so we can choose the image that is to be displayed. This plugin offers lots of optional parameters for customization. quality Quality of the image in the range of 0-100. Default is 50. destinationType DATA_URL or 0 Returns base64 encoded string. FILE_URI or 1 Returns image file URI. NATIVE_URI or 2 Returns image native URI. sourceType PHOTOLIBRARY or 0 Opens photo library. CAMERA or 1 Opens native camera. SAVEDPHOTOALBUM or 2 Opens saved photo album. allowEdit Allows image editing. encodingType JPEG or 0 Returns JPEG encoded image. PNG or 1 Returns PNG encoded image. targetWidth Image scaling width in pixels. targetHeight Image scaling height in pixels. mediaType PICTURE or 0 Allows only picture selection. VIDEO or 1 Allows only video selection. ALLMEDIA or 2 Allows all media type selection. correctOrientation Used for correcting orientation of the image. saveToPhotoAlbum Used to save the image to the photo album. popoverOptions Used for setting popover location on IOS. cameraDirection FRONT or 0 Front camera. BACK or 1 Back camera. ALLMEDIA 45 Lectures 2 hours Skillbakerystudios 16 Lectures 1 hours Nilay Mehta Print Add Notes Bookmark this page
[ { "code": null, "e": 2257, "s": 2180, "text": "This plugin is used for taking photos or using files from the image gallery." }, { "code": null, "e": 2333, "s": 2257, "text": "Run the following code in the command prompt window to install this plugin." }, { "code": null, "e": 2415, "s": 2333, "text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova plugin add cordova-plugincamera\n" }, { "code": null, "e": 2594, "s": 2415, "text": "Now, we will create the button for calling the camera and img where the image will be displayed once taken. This will be added to index.html inside the div class = \"app\" element." }, { "code": null, "e": 2676, "s": 2594, "text": "<button id = \"cameraTakePicture\">TAKE PICTURE</button>\n<img id = \"myImage\"></img>" }, { "code": null, "e": 2797, "s": 2676, "text": "The event listener is added inside the onDeviceReady function to ensure that Cordova is loaded before we start using it." }, { "code": null, "e": 2894, "s": 2797, "text": "document.getElementById(\"cameraTakePicture\").addEventListener \n (\"click\", cameraTakePicture); " }, { "code": null, "e": 3328, "s": 2894, "text": "We will create the cameraTakePicture function that is passed as a callback to our event listener. It will be fired when the button is tapped. Inside this function, we will call the navigator.camera global object provided by the plugin API. If taking picture is successful, the data will be sent to the onSuccess callback function, if not, the alert with error message will be shown. We will place this code at the bottom of index.js." }, { "code": null, "e": 3746, "s": 3328, "text": "function cameraTakePicture() { \n navigator.camera.getPicture(onSuccess, onFail, { \n quality: 50, \n destinationType: Camera.DestinationType.DATA_URL \n }); \n \n function onSuccess(imageData) { \n var image = document.getElementById('myImage'); \n image.src = \"data:image/jpeg;base64,\" + imageData; \n } \n \n function onFail(message) { \n alert('Failed because: ' + message); \n } \n}" }, { "code": null, "e": 3821, "s": 3746, "text": "When we run the app and press the button, native camera will be triggered." }, { "code": null, "e": 3884, "s": 3821, "text": "When we take and save picture, it will be displayed on screen." }, { "code": null, "e": 4090, "s": 3884, "text": "The same procedure can be used for getting image from the local file system. The only difference is the function created in the last step. You can see that the sourceType optional parameter has been added." }, { "code": null, "e": 4172, "s": 4090, "text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova plugin add cordova-plugincamera\n" }, { "code": null, "e": 4225, "s": 4172, "text": "<button id = \"cameraGetPicture\">GET PICTURE</button>" }, { "code": null, "e": 4316, "s": 4225, "text": "document.getElementById(\"cameraGetPicture\").addEventListener(\"click\", cameraGetPicture); \n" }, { "code": null, "e": 4734, "s": 4316, "text": "function cameraGetPicture() {\n navigator.camera.getPicture(onSuccess, onFail, { quality: 50,\n destinationType: Camera.DestinationType.DATA_URL,\n sourceType: Camera.PictureSourceType.PHOTOLIBRARY\n });\n\n function onSuccess(imageURL) {\n var image = document.getElementById('myImage');\n image.src = imageURL;\n }\n\n function onFail(message) {\n alert('Failed because: ' + message);\n }\n\n}" }, { "code": null, "e": 4867, "s": 4734, "text": "When we press the second button, the file system will open instead of the camera so we can choose the image that is to be displayed." }, { "code": null, "e": 4933, "s": 4867, "text": "This plugin offers lots of optional parameters for customization." }, { "code": null, "e": 4941, "s": 4933, "text": "quality" }, { "code": null, "e": 5000, "s": 4941, "text": "Quality of the image in the range of 0-100. Default is 50." }, { "code": null, "e": 5016, "s": 5000, "text": "destinationType" }, { "code": null, "e": 5061, "s": 5016, "text": "DATA_URL or 0 Returns base64 encoded string." }, { "code": null, "e": 5099, "s": 5061, "text": "FILE_URI or 1 Returns image file URI." }, { "code": null, "e": 5141, "s": 5099, "text": "NATIVE_URI or 2 Returns image native URI." }, { "code": null, "e": 5152, "s": 5141, "text": "sourceType" }, { "code": null, "e": 5191, "s": 5152, "text": "PHOTOLIBRARY or 0 Opens photo library." }, { "code": null, "e": 5224, "s": 5191, "text": "CAMERA or 1 Opens native camera." }, { "code": null, "e": 5270, "s": 5224, "text": "SAVEDPHOTOALBUM or 2 Opens saved photo album." }, { "code": null, "e": 5280, "s": 5270, "text": "allowEdit" }, { "code": null, "e": 5302, "s": 5280, "text": "Allows image editing." }, { "code": null, "e": 5315, "s": 5302, "text": "encodingType" }, { "code": null, "e": 5353, "s": 5315, "text": "JPEG or 0 Returns JPEG encoded image." }, { "code": null, "e": 5389, "s": 5353, "text": "PNG or 1 Returns PNG encoded image." }, { "code": null, "e": 5401, "s": 5389, "text": "targetWidth" }, { "code": null, "e": 5432, "s": 5401, "text": "Image scaling width in pixels." }, { "code": null, "e": 5445, "s": 5432, "text": "targetHeight" }, { "code": null, "e": 5477, "s": 5445, "text": "Image scaling height in pixels." }, { "code": null, "e": 5487, "s": 5477, "text": "mediaType" }, { "code": null, "e": 5531, "s": 5487, "text": "PICTURE or 0 Allows only picture selection." }, { "code": null, "e": 5571, "s": 5531, "text": "VIDEO or 1 Allows only video selection." }, { "code": null, "e": 5618, "s": 5571, "text": "ALLMEDIA or 2 Allows all media type selection." }, { "code": null, "e": 5637, "s": 5618, "text": "correctOrientation" }, { "code": null, "e": 5683, "s": 5637, "text": "Used for correcting orientation of the image." }, { "code": null, "e": 5700, "s": 5683, "text": "saveToPhotoAlbum" }, { "code": null, "e": 5743, "s": 5700, "text": "Used to save the image to the photo album." }, { "code": null, "e": 5758, "s": 5743, "text": "popoverOptions" }, { "code": null, "e": 5800, "s": 5758, "text": "Used for setting popover location on IOS." }, { "code": null, "e": 5816, "s": 5800, "text": "cameraDirection" }, { "code": null, "e": 5841, "s": 5816, "text": "FRONT or 0 Front camera." }, { "code": null, "e": 5864, "s": 5841, "text": "BACK or 1 Back camera." }, { "code": null, "e": 5873, "s": 5864, "text": "ALLMEDIA" }, { "code": null, "e": 5906, "s": 5873, "text": "\n 45 Lectures \n 2 hours \n" }, { "code": null, "e": 5926, "s": 5906, "text": " Skillbakerystudios" }, { "code": null, "e": 5959, "s": 5926, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 5972, "s": 5959, "text": " Nilay Mehta" }, { "code": null, "e": 5979, "s": 5972, "text": " Print" }, { "code": null, "e": 5990, "s": 5979, "text": " Add Notes" } ]
BBAug: A Package for Bounding Box Augmentation in PyTorch | by Harpal Sahota | Towards Data Science
Links: Paper Tensorflow Policies BBAug Object detection models like many neural network models work best when trained on large amounts of data. It is often the case that there is limited data available and many researchers around the world are looking into augmentations strategies to increase the amount of data available. One such piece of research was conducted by Google’s Brain Team and published in a paper called: Learning Data Augmentation Strategies for Object Detection. In this paper, the authors determine a set of augmentations called policies which perform well for object detection problems. The policies were obtained by searching for augmentations which improves general model performance. The authors define an augmentation policy as a set of sub-policies. As the model is training, one of these sub-policies is randomly selected and used to augment the image. Within each sub-policy are the augmentations to be applied to the image one after the other. Each transformation also has two hyperparameters: probability and magnitude. The probability states how likely this augmentation will be applied and the magnitude represents the degree of the augmentation. The code snapshot below shows the policy used in the paper: policy = [ [('TranslateX_BBox', 0.6, 4), ('Equalize', 0.8, 10)], [('TranslateY_Only_BBoxes', 0.2, 2), ('Cutout', 0.8, 8)], [('Sharpness', 0.0, 8), ('ShearX_BBox', 0.4, 0)], [('ShearY_BBox', 1.0, 2), ('TranslateY_Only_BBoxes', 0.6, 6)], [('Rotate_BBox', 0.6, 10), ('Color', 1.0, 6)],] There are 5 sub-policies within this policy and if we take the first sub-policy it contains the TranslateX_BBox and the Equalize augmentations. The TranslateX_BBox operation translates the image on the x-axis by a magnitude 4. The magnitude does not directly translate to pixels in this instance but is scaled to a pixel value dependent on the magnitude. This augmentation also has a probability of 0.6 implying that if this augmentation is selected there is a 60% chance of the augmentation being applied. With each augmentation having an associated probability a notion of stochasticity is introduced adding a degree of randomness to training. In total, the Brain Team have come up with a total of 4 policies: v0, v1, v2 and v3. The v0 policy is shown in the paper, the other three policies contain many more sub-policies with several different transformations. Overall the augmentations fall into three categories which the authors define as: Colour Operations: Distort colour channels, without impacting the locations of the bounding boxes Geometric Operations: Geometrically distort the image, which correspondingly alters the location and size of the bounding boxes. Bounding Box Operations: Only distort the pixel content contained within the bounding box annotations So where does BBAug come into this? BBAug is a python package which implements all the policies derived by the Google Brain Team. The package is a wrapper to make use of these policies much easier. The actual augmentations are done by the excellent imgaug package. The policy shown above is applied to an example image and shown below. Each row is a different sub-policy and each column is a different run of the said sub-policy. As you can see, there is a degree of variation between runs of a sub-policy therefore, adding a degree of randomness to training. This is just one of the 4 policies implemented in BBAug. For a full visualisation of all 4 policies check out the GitHub page of the package. The package also comes with several useful features such as the possibility of custom policies, and bounding boxes that fall outside of the image are automatically removed or clipped if they are partially outside the image. For example, in the image below a translation augmentation is applied pushing the bounding box partially outside of the image. You can see the new bounding box has shrunk to accommodate for this. It is also possible to create augmentations which only affect the bounding box region. In the image below a Solarize augmentation is applied only to the bounding box areas: If you would like to know more the package comes with a custom augmentation notebook. How easy is it to augment a single image with a random policy? It’s as easy as this: You first need to import the policies module from the BBAug package. Within this module are the 4 different policies available to you. In the above example policy set v0 was selected because this is the one used in the paper. The module also comes with a container class which will hold our chosen policy, select a random policy and apply the randomly chosen policy to an image. Line 7 instantiates the policy container with our selected augmentation policy. The next piece of code selects a random augmentation. Finally, we apply an augmentation to the image. With just 5 lines of code, we can apply an augmentation to an image. This is rather a simple example and how can it be expanded to training a model? Luckily, the package comes with a notebook illustrating how to incorporate BBAug into a PyTorch training pipeline. This package implements the augmentation policies derived by the Google Brain Team. Currently, all 4 policies are implemented and the package comes with accompanying notebooks to help users integrate the policies into their PyTorch training pipelines. I highly recommend checking out the package’s GitHub page for a better understanding and examples of all the policies.
[ { "code": null, "e": 179, "s": 172, "text": "Links:" }, { "code": null, "e": 185, "s": 179, "text": "Paper" }, { "code": null, "e": 205, "s": 185, "text": "Tensorflow Policies" }, { "code": null, "e": 211, "s": 205, "text": "BBAug" }, { "code": null, "e": 879, "s": 211, "text": "Object detection models like many neural network models work best when trained on large amounts of data. It is often the case that there is limited data available and many researchers around the world are looking into augmentations strategies to increase the amount of data available. One such piece of research was conducted by Google’s Brain Team and published in a paper called: Learning Data Augmentation Strategies for Object Detection. In this paper, the authors determine a set of augmentations called policies which perform well for object detection problems. The policies were obtained by searching for augmentations which improves general model performance." }, { "code": null, "e": 1410, "s": 879, "text": "The authors define an augmentation policy as a set of sub-policies. As the model is training, one of these sub-policies is randomly selected and used to augment the image. Within each sub-policy are the augmentations to be applied to the image one after the other. Each transformation also has two hyperparameters: probability and magnitude. The probability states how likely this augmentation will be applied and the magnitude represents the degree of the augmentation. The code snapshot below shows the policy used in the paper:" }, { "code": null, "e": 1725, "s": 1410, "text": "policy = [ [('TranslateX_BBox', 0.6, 4), ('Equalize', 0.8, 10)], [('TranslateY_Only_BBoxes', 0.2, 2), ('Cutout', 0.8, 8)], [('Sharpness', 0.0, 8), ('ShearX_BBox', 0.4, 0)], [('ShearY_BBox', 1.0, 2), ('TranslateY_Only_BBoxes', 0.6, 6)], [('Rotate_BBox', 0.6, 10), ('Color', 1.0, 6)],]" }, { "code": null, "e": 2671, "s": 1725, "text": "There are 5 sub-policies within this policy and if we take the first sub-policy it contains the TranslateX_BBox and the Equalize augmentations. The TranslateX_BBox operation translates the image on the x-axis by a magnitude 4. The magnitude does not directly translate to pixels in this instance but is scaled to a pixel value dependent on the magnitude. This augmentation also has a probability of 0.6 implying that if this augmentation is selected there is a 60% chance of the augmentation being applied. With each augmentation having an associated probability a notion of stochasticity is introduced adding a degree of randomness to training. In total, the Brain Team have come up with a total of 4 policies: v0, v1, v2 and v3. The v0 policy is shown in the paper, the other three policies contain many more sub-policies with several different transformations. Overall the augmentations fall into three categories which the authors define as:" }, { "code": null, "e": 2769, "s": 2671, "text": "Colour Operations: Distort colour channels, without impacting the locations of the bounding boxes" }, { "code": null, "e": 2898, "s": 2769, "text": "Geometric Operations: Geometrically distort the image, which correspondingly alters the location and size of the bounding boxes." }, { "code": null, "e": 3000, "s": 2898, "text": "Bounding Box Operations: Only distort the pixel content contained within the bounding box annotations" }, { "code": null, "e": 3265, "s": 3000, "text": "So where does BBAug come into this? BBAug is a python package which implements all the policies derived by the Google Brain Team. The package is a wrapper to make use of these policies much easier. The actual augmentations are done by the excellent imgaug package." }, { "code": null, "e": 3430, "s": 3265, "text": "The policy shown above is applied to an example image and shown below. Each row is a different sub-policy and each column is a different run of the said sub-policy." }, { "code": null, "e": 4122, "s": 3430, "text": "As you can see, there is a degree of variation between runs of a sub-policy therefore, adding a degree of randomness to training. This is just one of the 4 policies implemented in BBAug. For a full visualisation of all 4 policies check out the GitHub page of the package. The package also comes with several useful features such as the possibility of custom policies, and bounding boxes that fall outside of the image are automatically removed or clipped if they are partially outside the image. For example, in the image below a translation augmentation is applied pushing the bounding box partially outside of the image. You can see the new bounding box has shrunk to accommodate for this." }, { "code": null, "e": 4295, "s": 4122, "text": "It is also possible to create augmentations which only affect the bounding box region. In the image below a Solarize augmentation is applied only to the bounding box areas:" }, { "code": null, "e": 4381, "s": 4295, "text": "If you would like to know more the package comes with a custom augmentation notebook." }, { "code": null, "e": 4466, "s": 4381, "text": "How easy is it to augment a single image with a random policy? It’s as easy as this:" }, { "code": null, "e": 5291, "s": 4466, "text": "You first need to import the policies module from the BBAug package. Within this module are the 4 different policies available to you. In the above example policy set v0 was selected because this is the one used in the paper. The module also comes with a container class which will hold our chosen policy, select a random policy and apply the randomly chosen policy to an image. Line 7 instantiates the policy container with our selected augmentation policy. The next piece of code selects a random augmentation. Finally, we apply an augmentation to the image. With just 5 lines of code, we can apply an augmentation to an image. This is rather a simple example and how can it be expanded to training a model? Luckily, the package comes with a notebook illustrating how to incorporate BBAug into a PyTorch training pipeline." } ]
How can we print multiple blank lines in python?
We can print multiple blank lines in python by using the \n character the number of times we need a blank line. For example, If you need 5 blank lines, you can use − Python 2.x: print "\n\n\n\n\n" Python 3.x: print("\n\n\n\n\n") You can use features like repetition operator in python to make this easier. For example, Python 2.x: print "\n" * 5 Python 3.x: print("\n" * 5) All of these commands will print 5 blank lines on the STDOUT.
[ { "code": null, "e": 1228, "s": 1062, "text": "We can print multiple blank lines in python by using the \\n character the number of times we need a blank line. For example, If you need 5 blank lines, you can use −" }, { "code": null, "e": 1292, "s": 1228, "text": "Python 2.x:\nprint \"\\n\\n\\n\\n\\n\"\n\nPython 3.x:\nprint(\"\\n\\n\\n\\n\\n\")" }, { "code": null, "e": 1382, "s": 1292, "text": "You can use features like repetition operator in python to make this easier. For example," }, { "code": null, "e": 1438, "s": 1382, "text": "Python 2.x:\nprint \"\\n\" * 5\n\nPython 3.x:\nprint(\"\\n\" * 5)" }, { "code": null, "e": 1500, "s": 1438, "text": "All of these commands will print 5 blank lines on the STDOUT." } ]
C++ Program to Store and Display Information Using Structure
A structure is a collection of items of different data types. It is very useful in creating complex data structures with different data type records. A structure is defined with the struct keyword. An example of a structure is as follows − struct employee { int empID; char name[50]; float salary; }; A program that stores and displays information using structure is given as follows. Live Demo #include <iostream> using namespace std; struct employee { int empID; char name[50]; int salary; char department[50]; }; int main() { struct employee emp[3] = { { 1 , "Harry" , 20000 , "Finance" } , { 2 , "Sally" , 50000 , "HR" } , { 3 , "John" , 15000 , "Technical" } }; cout<<"The employee information is given as follows:"<<endl; cout<<endl; for(int i=0; i<3;i++) { cout<<"Employee ID: "<<emp[i].empID<<endl; cout<<"Name: "<<emp[i].name<<endl; cout<<"Salary: "<<emp[i].salary<<endl; cout<<"Department: "<<emp[i].department<<endl; cout<<endl; } return 0; } The employee information is given as follows: Employee ID: 1 Name: Harry Salary: 20000 Department: Finance Employee ID: 2 Name: Sally Salary: 50000 Department: HR Employee ID: 3 Name: John Salary: 15000 Department: Technical In the above program, the structure is defined before the main() function. The structure contains the employee ID, name, salary and department of an employee. This is demonstrated in the following code snippet. struct employee { int empID; char name[50]; int salary; char department[50]; }; In the main() function, an object array of type struct employee is defined. This contains the employee ID, name, salary and department values. This is shown as follows. struct employee emp[3] = { { 1 , "Harry" , 20000 , "Finance" } , { 2 , "Sally" , 50000 , "HR" } , { 3 , "John" , 15000 , "Technical" } }; The structure values are displayed using a for loop. This is shown in the following manner. cout<<"The employee information is given as follows:"<<endl; cout<<endl; for(int i=0; i<3;i++) { cout<<"Employee ID: "<<emp[i].empID<<endl; cout<<"Name: "<<emp[i].name<<endl; cout<<"Salary: "<<emp[i].salary<<endl; cout<<"Department: "<<emp[i].department<<endl; cout<<endl; }
[ { "code": null, "e": 1260, "s": 1062, "text": "A structure is a collection of items of different data types. It is very useful in creating complex data structures with different data type records. A structure is defined with the struct keyword." }, { "code": null, "e": 1302, "s": 1260, "text": "An example of a structure is as follows −" }, { "code": null, "e": 1372, "s": 1302, "text": "struct employee {\n int empID;\n char name[50];\n float salary;\n};" }, { "code": null, "e": 1456, "s": 1372, "text": "A program that stores and displays information using structure is given as follows." }, { "code": null, "e": 1467, "s": 1456, "text": " Live Demo" }, { "code": null, "e": 2089, "s": 1467, "text": "#include <iostream>\nusing namespace std;\nstruct employee {\n int empID;\n char name[50];\n int salary;\n char department[50];\n};\nint main() {\n struct employee emp[3] = { { 1 , \"Harry\" , 20000 , \"Finance\" } , { 2 , \"Sally\" , 50000 , \"HR\" } , { 3 , \"John\" , 15000 , \"Technical\" } };\n cout<<\"The employee information is given as follows:\"<<endl;\n cout<<endl;\n for(int i=0; i<3;i++) {\n cout<<\"Employee ID: \"<<emp[i].empID<<endl;\n cout<<\"Name: \"<<emp[i].name<<endl;\n cout<<\"Salary: \"<<emp[i].salary<<endl;\n cout<<\"Department: \"<<emp[i].department<<endl;\n cout<<endl;\n }\n return 0;\n}" }, { "code": null, "e": 2316, "s": 2089, "text": "The employee information is given as follows:\nEmployee ID: 1\nName: Harry\nSalary: 20000\nDepartment: Finance\n\nEmployee ID: 2\nName: Sally\nSalary: 50000\nDepartment: HR\n\nEmployee ID: 3\nName: John\nSalary: 15000\nDepartment: Technical" }, { "code": null, "e": 2527, "s": 2316, "text": "In the above program, the structure is defined before the main() function. The structure contains the employee ID, name, salary and department of an employee. This is demonstrated in the following code snippet." }, { "code": null, "e": 2619, "s": 2527, "text": "struct employee {\n int empID;\n char name[50];\n int salary;\n char department[50];\n};" }, { "code": null, "e": 2788, "s": 2619, "text": "In the main() function, an object array of type struct employee is defined. This contains the employee ID, name, salary and department values. This is shown as follows." }, { "code": null, "e": 2926, "s": 2788, "text": "struct employee emp[3] = { { 1 , \"Harry\" , 20000 , \"Finance\" } , { 2 , \"Sally\" , 50000 , \"HR\" } , { 3 , \"John\" , 15000 , \"Technical\" } };" }, { "code": null, "e": 3018, "s": 2926, "text": "The structure values are displayed using a for loop. This is shown in the following manner." }, { "code": null, "e": 3308, "s": 3018, "text": "cout<<\"The employee information is given as follows:\"<<endl;\ncout<<endl;\nfor(int i=0; i<3;i++) {\n cout<<\"Employee ID: \"<<emp[i].empID<<endl;\n cout<<\"Name: \"<<emp[i].name<<endl;\n cout<<\"Salary: \"<<emp[i].salary<<endl;\n cout<<\"Department: \"<<emp[i].department<<endl;\n cout<<endl;\n}" } ]
Consecutive elements sum array in JavaScript
We are required to write a JavaScript function that takes in an array of Numbers and returns a new array with elements as the sum of two consecutive elements from the original array. For example, if the input array is − const arr1 = [1, 1, 2, 7, 4, 5, 6, 7, 8, 9]; Then the output should be − const output = [2, 9, 9, 13, 17] The code for this will be − const arr11 = [1, 1, 2, 7, 4, 5, 6, 7, 8, 9]; const consecutiveSum = arr => { const res = []; for(let i = 0; i < arr.length; i += 2){ res.push(arr[i] + (arr[i+1] || 0)); }; return res; }; console.log(conseutiveSum(arr1)); The output in the console − [ 2, 9, 9, 13, 17 ]
[ { "code": null, "e": 1245, "s": 1062, "text": "We are required to write a JavaScript function that takes in an array of Numbers and returns a\nnew array with elements as the sum of two consecutive elements from the original array." }, { "code": null, "e": 1282, "s": 1245, "text": "For example, if the input array is −" }, { "code": null, "e": 1327, "s": 1282, "text": "const arr1 = [1, 1, 2, 7, 4, 5, 6, 7, 8, 9];" }, { "code": null, "e": 1355, "s": 1327, "text": "Then the output should be −" }, { "code": null, "e": 1388, "s": 1355, "text": "const output = [2, 9, 9, 13, 17]" }, { "code": null, "e": 1416, "s": 1388, "text": "The code for this will be −" }, { "code": null, "e": 1656, "s": 1416, "text": "const arr11 = [1, 1, 2, 7, 4, 5, 6, 7, 8, 9];\nconst consecutiveSum = arr => {\n const res = [];\n for(let i = 0; i < arr.length; i += 2){\n res.push(arr[i] + (arr[i+1] || 0));\n };\n return res;\n};\nconsole.log(conseutiveSum(arr1));" }, { "code": null, "e": 1684, "s": 1656, "text": "The output in the console −" }, { "code": null, "e": 1704, "s": 1684, "text": "[ 2, 9, 9, 13, 17 ]" } ]
Python Data Access - Quick Guide
The Python standard for database interfaces is the Python DB-API. Most Python database interfaces adhere to this standard. You can choose the right database for your application. Python Database API supports a wide range of database servers such as − GadFly mSQL MySQL PostgreSQL Microsoft SQL Server 2000 Informix Interbase Oracle Sybase Here is the list of available Python database interfaces: Python Database Interfaces and APIs. You must download a separate DB API module for each database you need to access. For example, if you need to access an Oracle database as well as a MySQL database, you must download both the Oracle and the MySQL database modules. MySQL Python/Connector is an interface for connecting to a MySQL database server from Python. It implements the Python Database API and is built on top of the MySQL. First of all, you need to make sure you have already installed python in your machine. To do so, open command prompt and type python in it and press Enter. If python is already installed in your system, this command will display its version as shown below − C:\Users\Tutorialspoint>python Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> Now press ctrl+z and then Enter to get out of the python shell and create a folder (in which you intended to install Python-MySQL connector) named Python_MySQL as − >>> ^Z C:\Users\Tutorialspoint>d: D:\>mkdir Python_MySQL PIP is a package manager in python using which you can install various modules/packages in Python. Therefore, to install Mysql-python mysql-connector-python you need to make sure that you have PIP installed in your computer and have its location added to path. You can do so, by executing the pip command. If you didn’t have PIP in your system or, if you haven’t added its location in the Path environment variable, you will get an error message as − D:\Python_MySQL>pip 'pip' is not recognized as an internal or external command, operable program or batch file. To install PIP, download the get-pip.py to the above created folder and, from command navigate it and install pip as follows − D:\>cd Python_MySQL D:\Python_MySQL>python get-pip.py Collecting pip Downloading https://files.pythonhosted.org/packages/8d/07/f7d7ced2f97ca3098c16565efbe6b15fafcba53e8d9bdb431e09140514b0/pip-19.2.2-py2.py3-none-any.whl (1.4MB) |████████████████████████████████| 1.4MB 1.3MB/s Collecting wheel Downloading https://files.pythonhosted.org/packages/00/83/b4a77d044e78ad1a45610eb88f745be2fd2c6d658f9798a15e384b7d57c9/wheel-0.33.6-py2.py3-none-any.whl Installing collected packages: pip, wheel Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. Successfully installed pip-19.2.2 wheel-0.33.6 Once you have Python and PIP installed, open command prompt and upgrade pip (optional) as shown below − C:\Users\Tutorialspoint>python -m pip install --upgrade pip Collecting pip Using cached https://files.pythonhosted.org/packages/8d/07/f7d7ced2f97ca3098c16565efbe6b15fafcba53e8d9bdb431e09140514b0/pip-19.2.2-py2.py3-none-any.whl Python Data Access 4 Installing collected packages: pip Found existing installation: pip 19.0.3 Uninstalling pip-19.0.3: Successfully uninstalled pip-19.0.3 Successfully installed pip-19.2.2 Then open command prompt in admin mode and install python MySQL connect as − C:\WINDOWS\system32>pip install mysql-connector-python Collecting mysql-connector-python Using cached https://files.pythonhosted.org/packages/99/74/f41182e6b7aadc62b038b6939dce784b7f9ec4f89e2ae14f9ba8190dc9ab/mysql_connector_python-8.0.17-py2.py3-none-any.whl Collecting protobuf>=3.0.0 (from mysql-connector-python) Using cached https://files.pythonhosted.org/packages/09/0e/614766ea191e649216b87d331a4179338c623e08c0cca291bcf8638730ce/protobuf-3.9.1-cp37-cp37m-win32.whl Collecting six>=1.9 (from protobuf>=3.0.0->mysql-connector-python) Using cached https://files.pythonhosted.org/packages/73/fb/00a976f728d0d1fecfe898238ce23f502a721c0ac0ecfedb80e0d88c64e9/six-1.12.0-py2.py3-none-any.whl Requirement already satisfied: setuptools in c:\program files (x86)\python37-32\lib\site-packages (from protobuf>=3.0.0->mysql-connector-python) (40.8.0) Installing collected packages: six, protobuf, mysql-connector-python Successfully installed mysql-connector-python-8.0.17 protobuf-3.9.1 six-1.12.0 To verify the installation of the create a sample python script with the following line in it. import mysql.connector If the installation is successful, when you execute it, you should not get any errors − D:\Python_MySQL>python test.py D:\Python_MySQL> Simply, if you need to install Python from scratch. Visit the Python Home Page. Click on the Downloads button, you will be redirected to the downloads page which provides links for latest version of python for various platforms choose one and download it. For instance, we have downloaded python-3.7.4.exe (for windows). Start the installation process by double-clicking the downloaded .exe file. Check the Add Python 3.7 to Path option and proceed with the installation. After completion of this process, python will be installed in your system. To connect with MySQL, (one way is to) open the MySQL command prompt in your system as shown below − It asks for password here; you need to type the password you have set to the default user (root) at the time of installation. Then a connection is established with MySQL displaying the following message − Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 4 Server version: 5.7.12-log MySQL Community Server (GPL) Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. You can disconnect from the MySQL database any time using the exit command at mysql> prompt. mysql> exit Bye Before establishing connection to MySQL database using python, assume − That we have created a database with name mydb. That we have created a database with name mydb. We have created a table EMPLOYEE with columns FIRST_NAME, LAST_NAME, AGE, SEX and INCOME. We have created a table EMPLOYEE with columns FIRST_NAME, LAST_NAME, AGE, SEX and INCOME. The credentials we are using to connect with MySQL are username: root, password: password. The credentials we are using to connect with MySQL are username: root, password: password. You can establish a connection using the connect() constructor. This accepts username, password, host and, name of the database you need to connect with (optional) and, returns an object of the MySQLConnection class. Following is the example of connecting with MySQL database "mydb". import mysql.connector #establishing the connection conn = mysql.connector.connect(user='root', password='password', host='127.0.0.1', database='mydb') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Executing an MYSQL function using the execute() method cursor.execute("SELECT DATABASE()") # Fetch a single row using fetchone() method. data = cursor.fetchone() print("Connection established to: ",data) #Closing the connection conn.close() On executing, this script produces the following output − D:\Python_MySQL>python EstablishCon.py Connection established to: ('mydb',) You can also establish connection to MySQL by passing credentials (user name, password, hostname, and database name) to connection.MySQLConnection() as shown below − from mysql.connector import (connection) #establishing the connection conn = connection.MySQLConnection(user='root', password='password', host='127.0.0.1', database='mydb') #Closing the connection conn.close() You can create a database in MYSQL using the CREATE DATABASE query. Following is the syntax of the CREATE DATABASE query − CREATE DATABASE name_of_the_database Following statement creates a database with name mydb in MySQL − mysql> CREATE DATABASE mydb; Query OK, 1 row affected (0.04 sec) If you observe the list of databases using the SHOW DATABASES statement, you can observe the newly created database in it as shown below − mysql> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | information_schema | | logging | | mydatabase | | mydb | | performance_schema | | students | | sys | +--------------------+ 26 rows in set (0.15 sec) After establishing connection with MySQL, to manipulate data in it you need to connect to a database. You can connect to an existing database or, create your own. You would need special privileges to create or to delete a MySQL database. So if you have access to the root user, you can create any database. Following example establishes connection with MYSQL and creates a database in it. import mysql.connector #establishing the connection conn = mysql.connector.connect(user='root', password='password', host='127.0.0.1') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Doping database MYDATABASE if already exists. cursor.execute("DROP database IF EXISTS MyDatabase") #Preparing query to create a database sql = "CREATE database MYDATABASE"; #Creating a database cursor.execute(sql) #Retrieving the list of databases print("List of databases: ") cursor.execute("SHOW DATABASES") print(cursor.fetchall()) #Closing the connection conn.close() List of databases: [('information_schema',), ('dbbug61332',), ('details',), ('exampledatabase',), ('mydatabase',), ('mydb',), ('mysql',), ('performance_schema',)] The CREATE TABLE statement is used to create tables in MYSQL database. Here, you need to specify the name of the table and, definition (name and datatype) of each column. Following is the syntax to create a table in MySQL − CREATE TABLE table_name( column1 datatype, column2 datatype, column3 datatype, ..... columnN datatype, ); Following query creates a table named EMPLOYEE in MySQL with five columns namely, FIRST_NAME, LAST_NAME, AGE, SEX and, INCOME. mysql> CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT ); Query OK, 0 rows affected (0.42 sec) The DESC statement gives you the description of the specified table. Using this you can verify if the table has been created or not as shown below − mysql> Desc Employee; +------------+----------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +------------+----------+------+-----+---------+-------+ | FIRST_NAME | char(20) | NO | | NULL | | | LAST_NAME | char(20) | YES | | NULL | | | AGE | int(11) | YES | | NULL | | | SEX | char(1) | YES | | NULL | | | INCOME | float | YES | | NULL | | +------------+----------+------+-----+---------+-------+ 5 rows in set (0.07 sec) The method named execute() (invoked on the cursor object) accepts two variables − A String value representing the query to be executed. A String value representing the query to be executed. An optional args parameter which can be a tuple or, list or, dictionary, representing the parameters of the query (values of the place holders). An optional args parameter which can be a tuple or, list or, dictionary, representing the parameters of the query (values of the place holders). It returns an integer value representing the number of rows effected by the query. Once a database connection is established, you can create tables by passing the CREATE TABLE query to the execute() method. In short, to create a table using python 7minus; Import mysql.connector package. Import mysql.connector package. Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it. Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it. Create a cursor object by invoking the cursor() method on the connection object created above. Create a cursor object by invoking the cursor() method on the connection object created above. Then, execute the CREATE TABLE statement by passing it as a parameter to the execute() method. Then, execute the CREATE TABLE statement by passing it as a parameter to the execute() method. Following example creates a table named Employee in the database mydb. import mysql.connector #establishing the connection conn = mysql.connector.connect( user='root', password='password', host='127.0.0.1', database='mydb' ) #Creating a cursor object using the cursor() method cursor = conn.cursor() #Dropping EMPLOYEE table if already exists. cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") #Creating table as per requirement sql ='''CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )''' cursor.execute(sql) #Closing the connection conn.close() You can add new rows to an existing table of MySQL using the INSERT INTO statement. In this, you need to specify the name of the table, column names, and values (in the same order as column names). Following is the syntax of the INSERT INTO statement of MySQL. INSERT INTO TABLE_NAME (column1, column2,column3,...columnN) VALUES (value1, value2, value3,...valueN); Following query inserts a record into the table named EMPLOYEE. INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES (' Mac', 'Mohan', 20, 'M', 2000 ); You can verify the records of the table after insert operation using the SELECT statement as − mysql> select * from Employee; +------------+-----------+------+------+--------+ | FIRST_NAME | LAST_NAME | AGE | SEX | INCOME | +------------+-----------+------+------+--------+ | Mac | Mohan | 20 | M | 2000 | +------------+-----------+------+------+--------+ 1 row in set (0.00 sec) It is not mandatory to specify the names of the columns always, if you pass values of a record in the same order of the columns of the table you can execute the SELECT statement without the column names as follows − INSERT INTO EMPLOYEE VALUES ('Mac', 'Mohan', 20, 'M', 2000); The execute() method (invoked on the cursor object) accepts a query as parameter and executes the given query. To insert data, you need to pass the MySQL INSERT statement as a parameter to it. cursor.execute("""INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Mac', 'Mohan', 20, 'M', 2000)""") To insert data into a table in MySQL using python − import mysql.connector package. import mysql.connector package. Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it. Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it. Create a cursor object by invoking the cursor() method on the connection object created above Create a cursor object by invoking the cursor() method on the connection object created above Then, execute the INSERT statement by passing it as a parameter to the execute() method. Then, execute the INSERT statement by passing it as a parameter to the execute() method. The following example executes SQL INSERT statement to insert a record into the EMPLOYEE table − import mysql.connector #establishing the connection conn = mysql.connector.connect( user='root', password='password', host='127.0.0.1', database='mydb') #Creating a cursor object using the cursor() method cursor = conn.cursor() # Preparing SQL query to INSERT a record into the database. sql = """INSERT INTO EMPLOYEE( FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Mac', 'Mohan', 20, 'M', 2000)""" try: # Executing the SQL command cursor.execute(sql) # Commit your changes in the database conn.commit() except: # Rolling back in case of error conn.rollback() # Closing the connection conn.close() You can also use “%s” instead of values in the INSERT query of MySQL and pass values to them as lists as shown below − cursor.execute("""INSERT INTO EMPLOYEE VALUES ('Mac', 'Mohan', 20, 'M', 2000)""", ('Ramya', 'Ramapriya', 25, 'F', 5000)) Following example inserts a record into the Employee table dynamically. import mysql.connector #establishing the connection conn = mysql.connector.connect( user='root', password='password', host='127.0.0.1', database='mydb') #Creating a cursor object using the cursor() method cursor = conn.cursor() # Preparing SQL query to INSERT a record into the database. insert_stmt = ( "INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME)" "VALUES (%s, %s, %s, %s, %s)" ) data = ('Ramya', 'Ramapriya', 25, 'F', 5000) try: # Executing the SQL command cursor.execute(insert_stmt, data) # Commit your changes in the database conn.commit() except: # Rolling back in case of error conn.rollback() print("Data inserted") # Closing the connection conn.close() Data inserted You can retrieve/fetch data from a table in MySQL using the SELECT query. This query/statement returns contents of the specified table in tabular form and it is called as result-set. Following is the syntax of the SELECT query − SELECT column1, column2, columnN FROM table_name; Assume we have created a table in MySQL with name cricketers_data as − CREATE TABLE cricketers_data( First_Name VARCHAR(255), Last_Name VARCHAR(255), Date_Of_Birth date, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); And if we have inserted 5 records in to it using INSERT statements as − 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 query retrieves the FIRST_NAME and Country values from the table. mysql> select FIRST_NAME, Country from cricketers_data; +------------+-------------+ | FIRST_NAME | Country | +------------+-------------+ | Shikhar | India | | Jonathan | SouthAfrica | | Kumara | Srilanka | | Virat | India | | Rohit | India | +------------+-------------+ 5 rows in set (0.00 sec) You can also retrieve all the values of each record using * instated of the name of the columns as − mysql> SELECT * from cricketers_data; +------------+------------+---------------+----------------+-------------+ | First_Name | Last_Name | Date_Of_Birth | Place_Of_Birth | Country | +------------+------------+---------------+----------------+-------------+ | Shikhar | Dhawan | 1981-12-05 | Delhi | India | | Jonathan | Trott | 1981-04-22 | CapeTown | SouthAfrica | | Kumara | Sangakkara | 1977-10-27 | Matale | Srilanka | | Virat | Kohli | 1988-11-05 | Delhi | India | | Rohit | Sharma | 1987-04-30 | Nagpur | India | +------------+------------+---------------+----------------+-------------+ 5 rows in set (0.00 sec) READ Operation on any database means to fetch some useful information from the database. You can fetch data from MYSQL using the fetch() method provided by the mysql-connector-python. The cursor.MySQLCursor class provides three methods namely fetchall(), fetchmany() and, fetchone() where, The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows it returns the remaining ones). The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows it returns the remaining ones). The fetchone() method fetches the next row in the result of a query and returns it as a tuple. The fetchone() method fetches the next row in the result of a query and returns it as a tuple. The fetchmany() method is similar to the fetchone() but, it retrieves the next set of rows in the result set of a query, instead of a single row. The fetchmany() method is similar to the fetchone() but, it retrieves the next set of rows in the result set of a query, instead of a single row. Note − A result set is an object that is returned when a cursor object is used to query a table. rowcount − This is a read-only attribute and returns the number of rows that were affected by an execute() method. Following example fetches all the rows of the EMPLOYEE table using the SELECT query and from the obtained result set initially, we are retrieving the first row using the fetchone() method and then fetching the remaining rows using the fetchall() method. import mysql.connector #establishing the connection conn = mysql.connector.connect( user='root', password='password', host='127.0.0.1', database='mydb') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Retrieving single row sql = '''SELECT * from EMPLOYEE''' #Executing the query cursor.execute(sql) #Fetching 1st row from the table result = cursor.fetchone(); print(result) #Fetching 1st row from the table result = cursor.fetchall(); print(result) #Closing the connection conn.close() ('Krishna', 'Sharma', 19, 'M', 2000.0) [('Raj', 'Kandukuri', 20, 'M', 7000.0), ('Ramya', 'Ramapriya', 25, 'M', 5000.0)] Following example retrieves first two rows of the EMPLOYEE table using the fetchmany() method. import mysql.connector #establishing the connection conn = mysql.connector.connect( user='root', password='password', host='127.0.0.1', database='mydb') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Retrieving single row sql = '''SELECT * from EMPLOYEE''' #Executing the query cursor.execute(sql) #Fetching 1st row from the table result = cursor.fetchmany(size =2); print(result) #Closing the connection conn.close() [('Krishna', 'Sharma', 19, 'M', 2000.0), ('Raj', 'Kandukuri', 20, 'M', 7000.0)] If you want to fetch, delete or, update particular rows of a table in MySQL, you need to use the where clause to specify condition to filter the rows of the table for the operation. For example, if you have a SELECT statement with where clause, only the rows which satisfies the specified condition will be retrieved. Following is the syntax of the WHERE clause − SELECT column1, column2, columnN FROM table_name WHERE [condition] Assume we have created a table in MySQL with name EMPLOYEES as − mysql> CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT ); Query OK, 0 rows affected (0.36 sec) And if we have inserted 4 records in to it using INSERT statements as − mysql> INSERT INTO EMPLOYEE VALUES ('Krishna', 'Sharma', 19, 'M', 2000), ('Raj', 'Kandukuri', 20, 'M', 7000), ('Ramya', 'Ramapriya', 25, 'F', 5000), ('Mac', 'Mohan', 26, 'M', 2000); Following MySQL statement retrieves the records of the employees whose income is greater than 4000. mysql> SELECT * FROM EMPLOYEE WHERE INCOME > 4000; +------------+-----------+------+------+--------+ | FIRST_NAME | LAST_NAME | AGE | SEX | INCOME | +------------+-----------+------+------+--------+ | Raj | Kandukuri | 20 | M | 7000 | | Ramya | Ramapriya | 25 | F | 5000 | +------------+-----------+------+------+--------+ 2 rows in set (0.00 sec) To fetch specific records from a table using the python program − import mysql.connector package. import mysql.connector package. Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it. Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it. Create a cursor object by invoking the cursor() method on the connection object created above. Create a cursor object by invoking the cursor() method on the connection object created above. Then, execute the SELECT statement with WHERE clause, by passing it as a parameter to the execute() method. Then, execute the SELECT statement with WHERE clause, by passing it as a parameter to the execute() method. Following example creates a table named Employee and populates it. Then using the where clause it retrieves the records with age value less than 23. import mysql.connector #establishing the connection conn = mysql.connector.connect( user='root', password='password', host='127.0.0.1', database='mydb') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Doping EMPLOYEE table if already exists. cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") sql = '''CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )''' cursor.execute(sql) #Populating the table insert_stmt = "INSERT INTO EMPLOYEE (FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES (%s, %s, %s, %s, %s)" data = [('Krishna', 'Sharma', 19, 'M', 2000), ('Raj', 'Kandukuri', 20, 'M', 7000), ('Ramya', 'Ramapriya', 25, 'F', 5000),('Mac', 'Mohan', 26, 'M', 2000)] cursor.executemany(insert_stmt, data) conn.commit() #Retrieving specific records using the where clause cursor.execute("SELECT * from EMPLOYEE WHERE AGE <23") print(cursor.fetchall()) #Closing the connection conn.close() [('Krishna', 'Sharma', 19, 'M', 2000.0), ('Raj', 'Kandukuri', 20, 'M', 7000.0)] While fetching data using SELECT query, you can sort the results in desired order (ascending or descending) using the OrderBy clause. By default, this clause sorts results in ascending order, if you need to arrange them in descending order you need to use “DESC” explicitly. Following is the syntax SELECT column-list FROM table_name [WHERE condition] [ORDER BY column1, column2,.. columnN] [ASC | DESC]; of the ORDER BY clause: Assume we have created a table in MySQL with name EMPLOYEES as − mysql> CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT ); Query OK, 0 rows affected (0.36 sec) And if we have inserted 4 records in to it using INSERT statements as − mysql> INSERT INTO EMPLOYEE VALUES ('Krishna', 'Sharma', 19, 'M', 2000), ('Raj', 'Kandukuri', 20, 'M', 7000), ('Ramya', 'Ramapriya', 25, 'F', 5000), ('Mac', 'Mohan', 26, 'M', 2000); Following statement retrieves the contents of the EMPLOYEE table in ascending order of the age. mysql> SELECT * FROM EMPLOYEE ORDER BY AGE; +------------+-----------+------+------+--------+ | FIRST_NAME | LAST_NAME | AGE | SEX | INCOME | +------------+-----------+------+------+--------+ | Krishna | Sharma | 19 | M | 2000 | | Raj | Kandukuri | 20 | M | 7000 | | Ramya | Ramapriya | 25 | F | 5000 | | Mac | Mohan | 26 | M | 2000 | +------------+-----------+------+------+--------+ 4 rows in set (0.04 sec) You can also retrieve data in descending order using DESC as − mysql> SELECT * FROM EMPLOYEE ORDER BY FIRST_NAME, INCOME DESC; +------------+-----------+------+------+--------+ | FIRST_NAME | LAST_NAME | AGE | SEX | INCOME | +------------+-----------+------+------+--------+ | Krishna | Sharma | 19 | M | 2000 | | Mac | Mohan | 26 | M | 2000 | | Raj | Kandukuri | 20 | M | 7000 | | Ramya | Ramapriya | 25 | F | 5000 | +------------+-----------+------+------+--------+ 4 rows in set (0.00 sec) To retrieve contents of a table in specific order, invoke the execute() method on the cursor object and, pass the SELECT statement along with ORDER BY clause, as a parameter to it. In the following example we are creating a table with name and Employee, populating it, and retrieving its records back in the (ascending) order of their age, using the ORDER BY clause. import mysql.connector #establishing the connection conn = mysql.connector.connect( user='root', password='password', host='127.0.0.1', database='mydb') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Doping EMPLOYEE table if already exists. cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") sql = '''CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )''' cursor.execute(sql) #Populating the table insert_stmt = "INSERT INTO EMPLOYEE (FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES (%s, %s, %s, %s, %s)" data = [('Krishna', 'Sharma', 26, 'M', 2000), ('Raj', 'Kandukuri', 20, 'M', 7000), ('Ramya', 'Ramapriya', 29, 'F', 5000), ('Mac', 'Mohan', 26, 'M', 2000)] cursor.executemany(insert_stmt, data) conn.commit() #Retrieving specific records using the ORDER BY clause cursor.execute("SELECT * from EMPLOYEE ORDER BY AGE") print(cursor.fetchall()) #Closing the connection conn.close() [('Raj', 'Kandukuri', 20, 'M', 7000.0), ('Krishna', 'Sharma', 26, 'M', 2000.0), ('Mac', 'Mohan', 26, 'M', 2000.0), ('Ramya', 'Ramapriya', 29, 'F', 5000.0) ] In the same way you can retrieve data from a table in descending order using the ORDER BY clause. import mysql.connector #establishing the connection conn = mysql.connector.connect( user='root', password='password', host='127.0.0.1', database='mydb') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Retrieving specific records using the ORDERBY clause cursor.execute("SELECT * from EMPLOYEE ORDER BY INCOME DESC") print(cursor.fetchall()) #Closing the connection conn.close() [('Raj', 'Kandukuri', 20, 'M', 7000.0), ('Ramya', 'Ramapriya', 29, 'F', 5000.0), ('Krishna', 'Sharma', 26, 'M', 2000.0), ('Mac', 'Mohan', 26, 'M', 2000.0) ] UPDATE Operation on any database updates one or more records, which are already available in the database. You can update the values of existing records in MySQL using the UPDATE statement. To update specific rows, you need to use the WHERE clause along with it. Following is the syntax of the UPDATE statement in MySQL − UPDATE table_name SET column1 = value1, column2 = value2...., columnN = valueN WHERE [condition]; You can combine N number of conditions using the AND or the OR operators. Assume we have created a table in MySQL with name EMPLOYEES as − mysql> CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT ); Query OK, 0 rows affected (0.36 sec) And if we have inserted 4 records in to it using INSERT statements as − mysql> INSERT INTO EMPLOYEE VALUES ('Krishna', 'Sharma', 19, 'M', 2000), ('Raj', 'Kandukuri', 20, 'M', 7000), ('Ramya', 'Ramapriya', 25, 'F', 5000), ('Mac', 'Mohan', 26, 'M', 2000); Following MySQL statement increases the age of all male employees by one year − mysql> UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = 'M'; Query OK, 3 rows affected (0.06 sec) Rows matched: 3 Changed: 3 Warnings: 0 If you retrieve the contents of the table, you can see the updated values as − mysql> select * from EMPLOYEE; +------------+-----------+------+------+--------+ | FIRST_NAME | LAST_NAME | AGE | SEX | INCOME | +------------+-----------+------+------+--------+ | Krishna | Sharma | 20 | M | 2000 | | Raj | Kandukuri | 21 | M | 7000 | | Ramya | Ramapriya | 25 | F | 5000 | | Mac | Mohan | 27 | M | 2000 | +------------+-----------+------+------+--------+ 4 rows in set (0.00 sec) To update the records in a table in MySQL using python − import mysql.connector package. import mysql.connector package. Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it. Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it. Create a cursor object by invoking the cursor() method on the connection object created above. Create a cursor object by invoking the cursor() method on the connection object created above. Then, execute the UPDATE statement by passing it as a parameter to the execute() method. Then, execute the UPDATE statement by passing it as a parameter to the execute() method. The following example increases age of all the males by one year. import mysql.connector #establishing the connection conn = mysql.connector.connect( user='root', password='password', host='127.0.0.1', database='mydb') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Preparing the query to update the records sql = '''UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = 'M' ''' try: # Execute the SQL command cursor.execute(sql) # Commit your changes in the database conn.commit() except: # Rollback in case there is any error conn.rollback() #Retrieving data sql = '''SELECT * from EMPLOYEE''' #Executing the query cursor.execute(sql) #Displaying the result print(cursor.fetchall()) #Closing the connection conn.close() [('Krishna', 'Sharma', 22, 'M', 2000.0), ('Raj', 'Kandukuri', 23, 'M', 7000.0), ('Ramya', 'Ramapriya', 26, 'F', 5000.0) ] To delete records from a MySQL table, you need to use the DELETE FROM statement. To remove specific records, you need to use WHERE clause along with it. Following is the syntax of the DELETE query in MYSQL − DELETE FROM table_name [WHERE Clause] Assume we have created a table in MySQL with name EMPLOYEES as − mysql> CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT ); Query OK, 0 rows affected (0.36 sec) And if we have inserted 4 records in to it using INSERT statements as − mysql> INSERT INTO EMPLOYEE VALUES ('Krishna', 'Sharma', 19, 'M', 2000), ('Raj', 'Kandukuri', 20, 'M', 7000), ('Ramya', 'Ramapriya', 25, 'F', 5000), ('Mac', 'Mohan', 26, 'M', 2000); Following MySQL statement deletes the record of the employee with FIRST_NAME ”Mac”. mysql> DELETE FROM EMPLOYEE WHERE FIRST_NAME = 'Mac'; Query OK, 1 row affected (0.12 sec) If you retrieve the contents of the table, you can see only 3 records since we have deleted one. mysql> select * from EMPLOYEE; +------------+-----------+------+------+--------+ | FIRST_NAME | LAST_NAME | AGE | SEX | INCOME | +------------+-----------+------+------+--------+ | Krishna | Sharma | 20 | M | 2000 | | Raj | Kandukuri | 21 | M | 7000 | | Ramya | Ramapriya | 25 | F | 5000 | +------------+-----------+------+------+--------+ 3 rows in set (0.00 sec) If you execute the DELETE statement without the WHERE clause all the records from the specified table will be deleted. mysql> DELETE FROM EMPLOYEE; Query OK, 3 rows affected (0.09 sec) If you retrieve the contents of the table, you will get an empty set as shown below − mysql> select * from EMPLOYEE; Empty set (0.00 sec) DELETE operation is required when you want to delete some records from your database. To delete the records in a table − import mysql.connector package. import mysql.connector package. Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it. Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it. Create a cursor object by invoking the cursor() method on the connection object created above. Create a cursor object by invoking the cursor() method on the connection object created above. Then, execute the DELETE statement by passing it as a parameter to the execute() method. Then, execute the DELETE statement by passing it as a parameter to the execute() method. Following program deletes all the records from EMPLOYEE whose AGE is more than 20 − import mysql.connector #establishing the connection conn = mysql.connector.connect( user='root', password='password', host='127.0.0.1', database='mydb') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Retrieving single row print("Contents of the table: ") cursor.execute("SELECT * from EMPLOYEE") print(cursor.fetchall()) #Preparing the query to delete records sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (25) try: # Execute the SQL command cursor.execute(sql) # Commit your changes in the database conn.commit() except: # Roll back in case there is any error conn.rollback() #Retrieving data print("Contents of the table after delete operation ") cursor.execute("SELECT * from EMPLOYEE") print(cursor.fetchall()) #Closing the connection conn.close() Contents of the table: [('Krishna', 'Sharma', 22, 'M', 2000.0), ('Raj', 'Kandukuri', 23, 'M', 7000.0), ('Ramya', 'Ramapriya', 26, 'F', 5000.0), ('Mac', 'Mohan', 20, 'M', 2000.0), ('Ramya', 'Rama priya', 27, 'F', 9000.0)] Contents of the table after delete operation: [('Krishna', 'Sharma', 22, 'M', 2000.0), ('Raj', 'Kandukuri', 23, 'M', 7000.0), ('Mac', 'Mohan', 20, 'M', 2000.0)] You can remove an entire table using the DROP TABLE statement. You just need to specify the name of the table you need to delete. Following is the syntax of the DROP TABLE statement in MySQL − DROP TABLE table_name; Before deleting a table get the list of tables using the SHOW TABLES statement as follows − mysql> SHOW TABLES; +-----------------+ | Tables_in_mydb | +-----------------+ | contact | | cricketers_data | | employee | | sample | | tutorials | +-----------------+ 5 rows in set (0.00 sec) Following statement removes the table named sample from the database completely − mysql> DROP TABLE sample; Query OK, 0 rows affected (0.29 sec) Since we have deleted the table named sample from MySQL, if you get the list of tables again you will not find the table name sample in it. mysql> SHOW TABLES; +-----------------+ | Tables_in_mydb | +-----------------+ | contact | | cricketers_data | | employee | | tutorials | +-----------------+ 4 rows in set (0.00 sec) You can drop a table whenever you need to, using the DROP statement of MYSQL, but you need to be very careful while deleting any existing table because the data lost will not be recovered after deleting a table. To drop a table from a MYSQL database using python invoke the execute() method on the cursor object and pass the drop statement as a parameter to it. Following table drops a table named EMPLOYEE from the database. import mysql.connector #establishing the connection conn = mysql.connector.connect( user='root', password='password', host='127.0.0.1', database='mydb' ) #Creating a cursor object using the cursor() method cursor = conn.cursor() #Retrieving the list of tables print("List of tables in the database: ") cursor.execute("SHOW Tables") print(cursor.fetchall()) #Doping EMPLOYEE table if already exists cursor.execute ("DROP TABLE EMPLOYEE") print("Table dropped... ") #Retrieving the list of tables print( "List of tables after dropping the EMPLOYEE table: ") cursor.execute("SHOW Tables") print(cursor.fetchall()) #Closing the connection conn.close() List of tables in the database: [('employee',), ('employeedata',), ('sample',), ('tutorials',)] Table dropped... List of tables after dropping the EMPLOYEE table: [('employeedata',), ('sample',), ('tutorials',)] If you try to drop a table which does not exist in the database, an error occurs as − mysql.connector.errors.ProgrammingError: 1051 (42S02): Unknown table 'mydb.employee' You can prevent this error by verifying whether the table exists before deleting, by adding the IF EXISTS to the DELETE statement. import mysql.connector #establishing the connection conn = mysql.connector.connect( user='root', password='password', host='127.0.0.1', database='mydb') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Retrieving the list of tables print("List of tables in the database: ") cursor.execute("SHOW Tables") print(cursor.fetchall()) #Doping EMPLOYEE table if already exists cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") print("Table dropped... ") #Retrieving the list of tables print("List of tables after dropping the EMPLOYEE table: ") cursor.execute("SHOW Tables") print(cursor.fetchall()) #Closing the connection conn.close() List of tables in the database: [('employeedata',), ('sample',), ('tutorials',)] Table dropped... List of tables after dropping the EMPLOYEE table: [('employeedata',), ('sample',), ('tutorials',)] While fetching records if you want to limit them by a particular number, you can do so, using the LIMIT clause of MYSQL. Assume we have created a table in MySQL with name EMPLOYEES as − mysql> CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT ); Query OK, 0 rows affected (0.36 sec) And if we have inserted 4 records in to it using INSERT statements as − mysql> INSERT INTO EMPLOYEE VALUES ('Krishna', 'Sharma', 19, 'M', 2000), ('Raj', 'Kandukuri', 20, 'M', 7000), ('Ramya', 'Ramapriya', 25, 'F', 5000), ('Mac', 'Mohan', 26, 'M', 2000); Following SQL statement retrieves first two records of the Employee table using the LIMIT clause. SELECT * FROM EMPLOYEE LIMIT 2; +------------+-----------+------+------+--------+ | FIRST_NAME | LAST_NAME | AGE | SEX | INCOME | +------------+-----------+------+------+--------+ | Krishna | Sharma | 19 | M | 2000 | | Raj | Kandukuri | 20 | M | 7000 | +------------+-----------+------+------+--------+ 2 rows in set (0.00 sec) If you invoke the execute() method on the cursor object by passing the SELECT query along with the LIMIT clause, you can retrieve required number of records. To drop a table from a MYSQL database using python invoke the execute() method on the cursor object and pass the drop statement as a parameter to it. Following python example creates and populates a table with name EMPLOYEE and, using the LIMIT clause it fetches the first two records of it. import mysql.connector #establishing the connection conn = mysql.connector.connect( user='root', password='password', host='127.0.0.1', database='mydb') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Retrieving single row sql = '''SELECT * from EMPLOYEE LIMIT 2''' #Executing the query cursor.execute(sql) #Fetching the data result = cursor.fetchall(); print(result) #Closing the connection conn.close() [('Krishna', 'Sharma', 26, 'M', 2000.0), ('Raj', 'Kandukuri', 20, 'M', 7000.0)] If you need to limit the records starting from nth record (not 1st), you can do so, using OFFSET along with LIMIT. import mysql.connector #establishing the connection conn = mysql.connector.connect( user='root', password='password', host='127.0.0.1', database='mydb') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Retrieving single row sql = '''SELECT * from EMPLOYEE LIMIT 2 OFFSET 2''' #Executing the query cursor.execute(sql) #Fetching the data result = cursor.fetchall(); print(result) #Closing the connection conn.close() [('Ramya', 'Ramapriya', 29, 'F', 5000.0), ('Mac', 'Mohan', 26, 'M', 2000.0)] When you have divided the data in two tables you can fetch combined records from these two tables using Joins. Suppose we have created a table with name EMPLOYEE and populated data into it as shown below − mysql> CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT, CONTACT INT ); Query OK, 0 rows affected (0.36 sec) INSERT INTO Employee VALUES ('Ramya', 'Rama Priya', 27, 'F', 9000, 101), ('Vinay', 'Bhattacharya', 20, 'M', 6000, 102), ('Sharukh', 'Sheik', 25, 'M', 8300, 103), ('Sarmista', 'Sharma', 26, 'F', 10000, 104), ('Trupthi', 'Mishra', 24, 'F', 6000, 105); Query OK, 5 rows affected (0.08 sec) Records: 5 Duplicates: 0 Warnings: 0 Then, if we have created another table and populated it as − CREATE TABLE CONTACT( ID INT NOT NULL, EMAIL CHAR(20) NOT NULL, PHONE LONG, CITY CHAR(20) ); Query OK, 0 rows affected (0.49 sec) INSERT INTO CONTACT (ID, EMAIL, CITY) VALUES (101, '[email protected]', 'Hyderabad'), (102, '[email protected]', 'Vishakhapatnam'), (103, '[email protected]', 'Pune'), (104, '[email protected]', 'Mumbai'); Query OK, 4 rows affected (0.10 sec) Records: 4 Duplicates: 0 Warnings: 0 Following statement retrieves data combining the values in these two tables − mysql> SELECT * from EMPLOYEE INNER JOIN CONTACT ON EMPLOYEE.CONTACT = CONTACT.ID; +------------+--------------+------+------+--------+---------+-----+--------------------+-------+----------------+ | FIRST_NAME | LAST_NAME | AGE | SEX | INCOME | CONTACT | ID | EMAIL | PHONE | CITY | +------------+--------------+------+------+--------+---------+-----+--------------------+-------+----------------+ | Ramya | Rama Priya | 27 | F | 9000 | 101 | 101 | [email protected] | NULL | Hyderabad | | Vinay | Bhattacharya | 20 | M | 6000 | 102 | 102 | [email protected] | NULL | Vishakhapatnam | | Sharukh | Sheik | 25 | M | 8300 | 103 | 103 | [email protected] | NULL | Pune | | Sarmista | Sharma | 26 | F | 10000 | 104 | 104 | [email protected] | NULL | Mumbai | +------------+--------------+------+------+--------+---------+-----+--------------------+-------+----------------+ 4 rows in set (0.00 sec) Following example retrieves data from the above two tables combined by contact column of the EMPLOYEE table and ID column of the CONTACT table. import mysql.connector #establishing the connection conn = mysql.connector.connect( user='root', password='password', host='127.0.0.1', database='mydb' ) #Creating a cursor object using the cursor() method cursor = conn.cursor() #Retrieving single row sql = '''SELECT * from EMPLOYEE INNER JOIN CONTACT ON EMPLOYEE.CONTACT = CONTACT.ID''' #Executing the query cursor.execute(sql) #Fetching 1st row from the table result = cursor.fetchall(); print(result) #Closing the connection conn.close() [('Krishna', 'Sharma', 26, 'M', 2000, 101, 101, '[email protected]', 9848022338, 'Hyderabad'), ('Raj', 'Kandukuri', 20, 'M', 7000, 102, 102, '[email protected]', 9848022339, 'Vishakhapatnam'), ('Ramya', 'Ramapriya', 29, 'F', 5000, 103, 103, '[email protected]', 9848022337, 'Pune'), ('Mac', 'Mohan', 26, 'M', 2000, 104, 104, '[email protected]', 9848022330, 'Mumbai')] The MySQLCursor of mysql-connector-python (and similar libraries) is used to execute statements to communicate with the MySQL database. Using the methods of it you can execute SQL statements, fetch data from the result sets, call procedures. You can create Cursor object using the cursor() method of the Connection object/class. import mysql.connector #establishing the connection conn = mysql.connector.connect( user='root', password='password', host='127.0.0.1', database='mydb' ) #Creating a cursor object using the cursor() method cursor = conn.cursor() Following are the various methods provided by the Cursor class/object. callproc() This method is used to call existing procedures MySQL database. close() This method is used to close the current cursor object. Info() This method gives information about the last query. executemany() This method accepts a list series of parameters list. Prepares an MySQL query and executes it with all the parameters. execute() This method accepts a MySQL query as a parameter and executes the given query. fetchall() This method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows it returns the remaining ones) fetchone() This method fetches the next row in the result of a query and returns it as a tuple. fetchmany() This method is similar to the fetchone() but, it retrieves the next set of rows in the result set of a query, instead of a single row. etchwarnings() This method returns the warnings generated by the last executed query. Following are the properties of the Cursor class − column_names This is a read only property which returns the list containing the column names of a result-set. description This is a read only property which returns the list containing the description of columns in a result-set. lastrowid This is a read only property, if there are any auto-incremented columns in the table, this returns the value generated for that column in the last INSERT or, UPDATE operation. rowcount This returns the number of rows returned/updated in case of SELECT and UPDATE operations. statement This property returns the last executed statement. PostgreSQL is a powerful, open source object-relational database system. It has more than 15 years of active development phase and a proven architecture that has earned it a strong reputation for reliability, data integrity, and correctness. To communicate with PostgreSQL using Python you need to install psycopg, an adapter provided for python programming, the current version of this is psycog2. psycopg2 was written with the aim of being very small and fast, and stable as a rock. It is available under PIP (package manager of python) First of all, make sure python and PIP is installed in your system properly and, PIP is up-to-date. To upgrade PIP, open command prompt and execute the following command − C:\Users\Tutorialspoint>python -m pip install --upgrade pip Collecting pip Using cached https://files.pythonhosted.org/packages/8d/07/f7d7ced2f97ca3098c16565efbe6b15fafcba53e8d9bdb431e09140514b0/pip-19.2.2-py2.py3-none-any.whl Installing collected packages: pip Found existing installation: pip 19.0.3 Uninstalling pip-19.0.3: Successfully uninstalled pip-19.0.3 Successfully installed pip-19.2.2 Then, open command prompt in admin mode and execute the pip install psycopg2-binary command as shown below − C:\WINDOWS\system32>pip install psycopg2-binary Collecting psycopg2-binary Using cached https://files.pythonhosted.org/packages/80/79/d0d13ce4c2f1addf4786f4a2ded802c2df66ddf3c1b1a982ed8d4cb9fc6d/psycopg2_binary-2.8.3-cp37-cp37m-win32.whl Installing collected packages: psycopg2-binary Successfully installed psycopg2-binary-2.8.3 To verify the installation, create a sample python script with the following line in it. import mysql.connector If the installation is successful, when you execute it, you should not get any errors − D:\Python_PostgreSQL>import psycopg2 D:\Python_PostgreSQL> PostgreSQL provides its own shell to execute queries. To establish connection with the PostgreSQL database, make sure that you have installed it properly in your system. Open the PostgreSQL shell prompt and pass details like Server, Database, username, and password. If all the details you have given are appropriate, a connection is established with PostgreSQL database. While passing the details you can go with the default server, database, port and, user name suggested by the shell. The connection class of the psycopg2 represents/handles an instance of a connection. You can create new connections using the connect() function. This accepts the basic connection parameters such as dbname, user, password, host, port and returns a connection object. Using this function, you can establish a connection with the PostgreSQL. The following Python code shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned. The name of the default database of PostgreSQL is postrgre. Therefore, we are supplying it as the database name. import psycopg2 #establishing the connection conn = psycopg2.connect( database="postgres", user='postgres', password='password', host='127.0.0.1', port= '5432' ) #Creating a cursor object using the cursor() method cursor = conn.cursor() #Executing an MYSQL function using the execute() method cursor.execute("select version()") # Fetch a single row using fetchone() method. data = cursor.fetchone() print("Connection established to: ",data) #Closing the connection conn.close() Connection established to: ( 'PostgreSQL 11.5, compiled by Visual C++ build 1914, 64-bit', ) Connection established to: ( 'PostgreSQL 11.5, compiled by Visual C++ build 1914, 64-bit', ) You can create a database in PostgreSQL using the CREATE DATABASE statement. You can execute this statement in PostgreSQL shell prompt by specifying the name of the database to be created after the command. Following is the syntax of the CREATE DATABASE statement. CREATE DATABASE dbname; Following statement creates a database named testdb in PostgreSQL. postgres=# CREATE DATABASE testdb; CREATE DATABASE You can list out the database in PostgreSQL using the \l command. If you verify the list of databases, you can find the newly created database as follows − postgres=# \l List of databases Name | Owner | Encoding | Collate | Ctype | -----------+----------+----------+----------------------------+-------------+ mydb | postgres | UTF8 | English_United States.1252 | ........... | postgres | postgres | UTF8 | English_United States.1252 | ........... | template0 | postgres | UTF8 | English_United States.1252 | ........... | template1 | postgres | UTF8 | English_United States.1252 | ........... | testdb | postgres | UTF8 | English_United States.1252 | ........... | (5 rows) You can also create a database in PostgreSQL from command prompt using the command createdb, a wrapper around the SQL statement CREATE DATABASE. C:\Program Files\PostgreSQL\11\bin> createdb -h localhost -p 5432 -U postgres sampledb Password: The cursor class of psycopg2 provides various methods execute various PostgreSQL commands, fetch records and copy data. You can create a cursor object using the cursor() method of the Connection class. The execute() method of this class accepts a PostgreSQL query as a parameter and executes it. Therefore, to create a database in PostgreSQL, execute the CREATE DATABASE query using this method. Following python example creates a database named mydb in PostgreSQL database. import psycopg2 #establishing the connection conn = psycopg2.connect( database="postgres", user='postgres', password='password', host='127.0.0.1', port= '5432' ) conn.autocommit = True #Creating a cursor object using the cursor() method cursor = conn.cursor() #Preparing query to create a database sql = '''CREATE database mydb'''; #Creating a database cursor.execute(sql) print("Database created successfully........") #Closing the connection conn.close() Database created successfully........ You can create a new table in a database in PostgreSQL using the CREATE TABLE statement. While executing this you need to specify the name of the table, column names and their data types. Following is the syntax of the CREATE TABLE statement in PostgreSQL. CREATE TABLE table_name( column1 datatype, column2 datatype, column3 datatype, ..... columnN datatype, ); Following example creates a table with name CRICKETERS in PostgreSQL. postgres=# CREATE TABLE CRICKETERS ( First_Name VARCHAR(255), Last_Name VARCHAR(255), Age INT, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); CREATE TABLE postgres=# You can get the list of tables in a database in PostgreSQL using the \dt command. After creating a table, if you can verify the list of tables you can observe the newly created table in it as follows − postgres=# \dt List of relations Schema | Name | Type | Owner --------+------------+-------+---------- public | cricketers | table | postgres (1 row) postgres=# In the same way, you can get the description of the created table using \d as shown below − postgres=# \d cricketers Table "public.cricketers" Column | Type | Collation | Nullable | Default ----------------+------------------------+-----------+----------+--------- first_name | character varying(255) | | | last_name | character varying(255) | | | age | integer | | | place_of_birth | character varying(255) | | | country | character varying(255) | | | postgres=# To create a table using python you need to execute the CREATE TABLE statement using the execute() method of the Cursor of pyscopg2. The following Python example creates a table with name employee. import psycopg2 #Establishing the connection conn = psycopg2.connect( database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432' ) #Creating a cursor object using the cursor() method cursor = conn.cursor() #Doping EMPLOYEE table if already exists. cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") #Creating table as per requirement sql ='''CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )''' cursor.execute(sql) print("Table created successfully........") conn.commit() #Closing the connection conn.close() Table created successfully........ You can insert record into an existing table in PostgreSQL using the INSERT INTO statement. While executing this, you need to specify the name of the table, and values for the columns in it. Following is the recommended syntax of the INSERT statement − INSERT INTO TABLE_NAME (column1, column2, column3,...columnN) VALUES (value1, value2, value3,...valueN); Where, column1, column2, column3,.. are the names of the columns of a table, and value1, value2, value3,... are the values you need to insert into the table. Assume we have created a table with name CRICKETERS using the CREATE TABLE statement as shown below − postgres=# CREATE TABLE CRICKETERS ( First_Name VARCHAR(255), Last_Name VARCHAR(255), Age INT, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); CREATE TABLE postgres=# Following PostgreSQL statement inserts a row in the above created table − postgres=# insert into CRICKETERS ( First_Name, Last_Name, Age, Place_Of_Birth, Country) values('Shikhar', 'Dhawan', 33, 'Delhi', 'India'); INSERT 0 1 postgres=# While inserting records using the INSERT INTO statement, if you skip any columns names Record will be inserted leaving empty spaces at columns which you have skipped. postgres=# insert into CRICKETERS (First_Name, Last_Name, Country) values('Jonathan', 'Trott', 'SouthAfrica'); INSERT 0 1 You can also insert records into a table without specifying the column names, if the order of values you pass is same as their respective column names in the table. postgres=# insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka'); INSERT 0 1 postgres=# insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India'); INSERT 0 1 postgres=# insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India'); INSERT 0 1 postgres=# After inserting the records into a table you can verify its contents using the SELECT statement as shown below − postgres=# SELECT * from CRICKETERS; first_name | last_name | age | place_of_birth | country ------------+------------+-----+----------------+------------- Shikhar | Dhawan | 33 | Delhi | India Jonathan | Trott | | | SouthAfrica Kumara | Sangakkara | 41 | Matale | Srilanka Virat | Kohli | 30 | Delhi | India Rohit | Sharma | 32 | Nagpur | India (5 rows) The cursor class of psycopg2 provides a method with name execute() method. This method accepts the query as a parameter and executes it. Therefore, to insert data into a table in PostgreSQL using python − Import psycopg2 package. Import psycopg2 package. Create a connection object using the connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it. Create a connection object using the connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it. Turn off the auto-commit mode by setting false as value to the attribute autocommit. Turn off the auto-commit mode by setting false as value to the attribute autocommit. The cursor() method of the Connection class of the psycopg2 library returns a cursor object. Create a cursor object using this method. The cursor() method of the Connection class of the psycopg2 library returns a cursor object. Create a cursor object using this method. Then, execute the INSERT statement(s) by passing it/them as a parameter to the execute() method. Then, execute the INSERT statement(s) by passing it/them as a parameter to the execute() method. Following Python program creates a table with name EMPLOYEE in PostgreSQL database and inserts records into it using the execute() method − import psycopg2 #Establishing the connection conn = psycopg2.connect( database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432' ) #Setting auto commit false conn.autocommit = True #Creating a cursor object using the cursor() method cursor = conn.cursor() # Preparing SQL queries to INSERT a record into the database. cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Ramya', 'Rama priya', 27, 'F', 9000)''') cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Vinay', 'Battacharya', 20, 'M', 6000)''') cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Sharukh', 'Sheik', 25, 'M', 8300)''') cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Sarmista', 'Sharma', 26, 'F', 10000)''') cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Tripthi', 'Mishra', 24, 'F', 6000)''') # Commit your changes in the database conn.commit() print("Records inserted........") # Closing the connection conn.close() Records inserted........ You can retrieve the contents of an existing table in PostgreSQL using the SELECT statement. At this statement, you need to specify the name of the table and, it returns its contents in tabular format which is known as result set. Following is the syntax of the SELECT statement in PostgreSQL − SELECT column1, column2, columnN FROM table_name; Assume we have created a table with name CRICKETERS using the following query − postgres=# CREATE TABLE CRICKETERS ( First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); CREATE TABLE postgres=# And if we have inserted 5 records in to it using INSERT statements as − postgres=# insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India'); INSERT 0 1 postgres=# insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica'); INSERT 0 1 postgres=# insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka'); INSERT 0 1 postgres=# insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India'); INSERT 0 1 postgres=# insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India'); INSERT 0 1 Following SELECT query retrieves the values of the columns FIRST_NAME, LAST_NAME and, COUNTRY from the CRICKETERS table. postgres=# SELECT FIRST_NAME, LAST_NAME, COUNTRY FROM CRICKETERS; first_name | last_name | country ------------+------------+------------- Shikhar | Dhawan | India Jonathan | Trott | SouthAfrica Kumara | Sangakkara | Srilanka Virat | Kohli | India Rohit | Sharma | India (5 rows) If you want to retrieve all the columns of each record you need to replace the names of the columns with "*" as shown below − postgres=# SELECT * FROM CRICKETERS; first_name | last_name | age | place_of_birth | country ------------+------------+-----+----------------+------------- Shikhar | Dhawan | 33 | Delhi | India Jonathan | Trott | 38 | CapeTown | SouthAfrica Kumara | Sangakkara | 41 | Matale | Srilanka Virat | Kohli | 30 | Delhi | India Rohit | Sharma | 32 | Nagpur | India (5 rows) postgres=# READ Operation on any database means to fetch some useful information from the database. You can fetch data from PostgreSQL using the fetch() method provided by the psycopg2. The Cursor class provides three methods namely fetchall(), fetchmany() and, fetchone() where, The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows, it returns the remaining ones). The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows, it returns the remaining ones). The fetchone() method fetches the next row in the result of a query and returns it as a tuple. The fetchone() method fetches the next row in the result of a query and returns it as a tuple. The fetchmany() method is similar to the fetchone() but, it retrieves the next set of rows in the result set of a query, instead of a single row. The fetchmany() method is similar to the fetchone() but, it retrieves the next set of rows in the result set of a query, instead of a single row. Note − A result set is an object that is returned when a cursor object is used to query a table. The following Python program connects to a database named mydb of PostgreSQL and retrieves all the records from a table named EMPLOYEE. import psycopg2 #establishing the connection conn = psycopg2.connect( database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432' ) #Setting auto commit false conn.autocommit = True #Creating a cursor object using the cursor() method cursor = conn.cursor() #Retrieving data cursor.execute('''SELECT * from EMPLOYEE''') #Fetching 1st row from the table result = cursor.fetchone(); print(result) #Fetching 1st row from the table result = cursor.fetchall(); print(result) #Commit your changes in the database conn.commit() #Closing the connection conn.close() ('Ramya', 'Rama priya', 27, 'F', 9000.0) [('Vinay', 'Battacharya', 20, 'M', 6000.0), ('Sharukh', 'Sheik', 25, 'M', 8300.0), ('Sarmista', 'Sharma', 26, 'F', 10000.0), ('Tripthi', 'Mishra', 24, 'F', 6000.0)] While performing SELECT, UPDATE or, DELETE operations, you can specify condition to filter the records using the WHERE clause. The operation will be performed on the records which satisfies the given condition. Following is the syntax of the WHERE clause in PostgreSQL − SELECT column1, column2, columnN FROM table_name WHERE [search_condition] You can specify a search_condition using comparison or logical operators. like >, <, =, LIKE, NOT, etc. The following examples would make this concept clear. Assume we have created a table with name CRICKETERS using the following query − postgres=# CREATE TABLE CRICKETERS ( First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); CREATE TABLE postgres=# And if we have inserted 5 records in to it using INSERT statements as − postgres=# insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India'); INSERT 0 1 postgres=# insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica'); INSERT 0 1 postgres=# insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka'); INSERT 0 1 postgres=# insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India'); INSERT 0 1 postgres=# insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India'); INSERT 0 1 Following SELECT statement retrieves the records whose age is greater than 35 − postgres=# SELECT * FROM CRICKETERS WHERE AGE > 35; first_name | last_name | age | place_of_birth | country ------------+------------+-----+----------------+------------- Jonathan | Trott | 38 | CapeTown | SouthAfrica Kumara | Sangakkara | 41 | Matale | Srilanka (2 rows) postgres=# To fetch specific records from a table using the python program execute the SELECT statement with WHERE clause, by passing it as a parameter to the execute() method. Following python example demonstrates the usage of WHERE command using python. import psycopg2 #establishing the connection conn = psycopg2.connect( database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432' ) #Setting auto commit false conn.autocommit = True #Creating a cursor object using the cursor() method cursor = conn.cursor() #Doping EMPLOYEE table if already exists. cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") sql = '''CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )''' cursor.execute(sql) #Populating the table insert_stmt = "INSERT INTO EMPLOYEE (FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES (%s, %s, %s, %s, %s)" data = [('Krishna', 'Sharma', 19, 'M', 2000), ('Raj', 'Kandukuri', 20, 'M', 7000), ('Ramya', 'Ramapriya', 25, 'M', 5000), ('Mac', 'Mohan', 26, 'M', 2000)] cursor.executemany(insert_stmt, data) #Retrieving specific records using the where clause cursor.execute("SELECT * from EMPLOYEE WHERE AGE <23") print(cursor.fetchall()) #Commit your changes in the database conn.commit() #Closing the connection conn.close() [('Krishna', 'Sharma', 19, 'M', 2000.0), ('Raj', 'Kandukuri', 20, 'M', 7000.0)] Usually if you try to retrieve data from a table, you will get the records in the same order in which you have inserted them. Using the ORDER BY clause, while retrieving the records of a table you can sort the resultant records in ascending or descending order based on the desired column. Following is the syntax of the ORDER BY clause in PostgreSQL. SELECT column-list FROM table_name [WHERE condition] [ORDER BY column1, column2, .. columnN] [ASC | DESC]; Assume we have created a table with name CRICKETERS using the following query − postgres=# CREATE TABLE CRICKETERS ( First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); CREATE TABLE postgres=# And if we have inserted 5 records in to it using INSERT statements as − postgres=# insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India'); INSERT 0 1 postgres=# insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica'); INSERT 0 1 postgres=# insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka'); INSERT 0 1 postgres=# insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India'); INSERT 0 1 postgres=# insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India'); INSERT 0 1 Following SELECT statement retrieves the rows of the CRICKETERS table in the ascending order of their age − postgres=# SELECT * FROM CRICKETERS ORDER BY AGE; first_name | last_name | age | place_of_birth | country ------------+------------+-----+----------------+------------- Virat | Kohli | 30 | Delhi | India Rohit | Sharma | 32 | Nagpur | India Shikhar | Dhawan | 33 | Delhi | India Jonathan | Trott | 38 | CapeTown | SouthAfrica Kumara | Sangakkara | 41 | Matale | Srilanka (5 rows)es: You can use more than one column to sort the records of a table. Following SELECT statements sort the records of the CRICKETERS table based on the columns age and FIRST_NAME. postgres=# SELECT * FROM CRICKETERS ORDER BY AGE, FIRST_NAME; first_name | last_name | age | place_of_birth | country ------------+------------+-----+----------------+------------- Virat | Kohli | 30 | Delhi | India Rohit | Sharma | 32 | Nagpur | India Shikhar | Dhawan | 33 | Delhi | India Jonathan | Trott | 38 | CapeTown | SouthAfrica Kumara | Sangakkara | 41 | Matale | Srilanka (5 rows) By default, the ORDER BY clause sorts the records of a table in ascending order. You can arrange the results in descending order using DESC as − postgres=# SELECT * FROM CRICKETERS ORDER BY AGE DESC; first_name | last_name | age | place_of_birth | country ------------+------------+-----+----------------+------------- Kumara | Sangakkara | 41 | Matale | Srilanka Jonathan | Trott | 38 | CapeTown | SouthAfrica Shikhar | Dhawan | 33 | Delhi | India Rohit | Sharma | 32 | Nagpur | India Virat | Kohli | 30 | Delhi | India (5 rows) To retrieve contents of a table in specific order, invoke the execute() method on the cursor object and, pass the SELECT statement along with ORDER BY clause, as a parameter to it. In the following example, we are creating a table with name and Employee, populating it, and retrieving its records back in the (ascending) order of their age, using the ORDER BY clause. import psycopg2 #establishing the connection conn = psycopg2.connect( database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432' ) #Setting auto commit false conn.autocommit = True #Creating a cursor object using the cursor() method cursor = conn.cursor() #Doping EMPLOYEE table if already exists. cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") #Creating a table sql = '''CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME INT, CONTACT INT )''' cursor.execute(sql) #Populating the table insert_stmt = "INSERT INTO EMPLOYEE ( FIRST_NAME, LAST_NAME, AGE, SEX, INCOME, CONTACT) VALUES (%s, %s, %s, %s, %s, %s)" data = [('Krishna', 'Sharma', 26, 'M', 2000, 101), ('Raj', 'Kandukuri', 20, 'M', 7000, 102), ('Ramya', 'Ramapriya', 29, 'F', 5000, 103), ('Mac', 'Mohan', 26, 'M', 2000, 104)] cursor.executemany(insert_stmt, data) conn.commit() #Retrieving specific records using the ORDER BY clause cursor.execute("SELECT * from EMPLOYEE ORDER BY AGE") print(cursor.fetchall()) #Commit your changes in the database conn.commit() #Closing the connection conn.close() [('Sharukh', 'Sheik', 25, 'M', 8300.0), ('Sarmista', 'Sharma', 26, 'F', 10000.0)] You can modify the contents of existing records of a table in PostgreSQL using the UPDATE statement. To update specific rows, you need to use the WHERE clause along with it. Following is the syntax of the UPDATE statement in PostgreSQL − UPDATE table_name SET column1 = value1, column2 = value2...., columnN = valueN WHERE [condition]; Assume we have created a table with name CRICKETERS using the following query − postgres=# CREATE TABLE CRICKETERS ( First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); CREATE TABLE postgres=# And if we have inserted 5 records in to it using INSERT statements as − postgres=# insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India'); INSERT 0 1 postgres=# insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica'); INSERT 0 1 postgres=# insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka'); INSERT 0 1 postgres=# insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India'); INSERT 0 1 postgres=# insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India'); INSERT 0 1 Following statement modifies the age of the cricketer, whose first name is Shikhar − postgres=# UPDATE CRICKETERS SET AGE = 45 WHERE FIRST_NAME = 'Shikhar' ; UPDATE 1 postgres=# If you retrieve the record whose FIRST_NAME is Shikhar you observe that the age value has been changed to 45 − postgres=# SELECT * FROM CRICKETERS WHERE FIRST_NAME = 'Shikhar'; first_name | last_name | age | place_of_birth | country ------------+-----------+-----+----------------+--------- Shikhar | Dhawan | 45 | Delhi | India (1 row) postgres=# If you haven’t used the WHERE clause, values of all the records will be updated. Following UPDATE statement increases the age of all the records in the CRICKETERS table by 1 − postgres=# UPDATE CRICKETERS SET AGE = AGE+1; UPDATE 5 If you retrieve the contents of the table using SELECT command, you can see the updated values as − postgres=# SELECT * FROM CRICKETERS; first_name | last_name | age | place_of_birth | country ------------+------------+-----+----------------+------------- Jonathan | Trott | 39 | CapeTown | SouthAfrica Kumara | Sangakkara | 42 | Matale | Srilanka Virat | Kohli | 31 | Delhi | India Rohit | Sharma | 33 | Nagpur | India Shikhar | Dhawan | 46 | Delhi | India (5 rows) The cursor class of psycopg2 provides a method with name execute() method. This method accepts the query as a parameter and executes it. Therefore, to insert data into a table in PostgreSQL using python − Import psycopg2 package. Import psycopg2 package. Create a connection object using the connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it. Create a connection object using the connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it. Turn off the auto-commit mode by setting false as value to the attribute autocommit. Turn off the auto-commit mode by setting false as value to the attribute autocommit. The cursor() method of the Connection class of the psycopg2 library returns a cursor object. Create a cursor object using this method. The cursor() method of the Connection class of the psycopg2 library returns a cursor object. Create a cursor object using this method. Then, execute the UPDATE statement by passing it as a parameter to the execute() method. Then, execute the UPDATE statement by passing it as a parameter to the execute() method. Following Python code updates the contents of the Employee table and retrieves the results − import psycopg2 #establishing the connection conn = psycopg2.connect( database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432' ) #Setting auto commit false conn.autocommit = True #Creating a cursor object using the cursor() method cursor = conn.cursor() #Fetching all the rows before the update print("Contents of the Employee table: ") sql = '''SELECT * from EMPLOYEE''' cursor.execute(sql) print(cursor.fetchall()) #Updating the records sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = 'M'" cursor.execute(sql) print("Table updated...... ") #Fetching all the rows after the update print("Contents of the Employee table after the update operation: ") sql = '''SELECT * from EMPLOYEE''' cursor.execute(sql) print(cursor.fetchall()) #Commit your changes in the database conn.commit() #Closing the connection conn.close() Contents of the Employee table: [('Ramya', 'Rama priya', 27, 'F', 9000.0), ('Vinay', 'Battacharya', 20, 'M', 6000.0), ('Sharukh', 'Sheik', 25, 'M', 8300.0), ('Sarmista', 'Sharma', 26, 'F', 10000.0), ('Tripthi', 'Mishra', 24, 'F', 6000.0)] Table updated...... Contents of the Employee table after the update operation: [('Ramya', 'Rama priya', 27, 'F', 9000.0), ('Sarmista', 'Sharma', 26, 'F', 10000.0), ('Tripthi', 'Mishra', 24, 'F', 6000.0), ('Vinay', 'Battacharya', 21, 'M', 6000.0), ('Sharukh', 'Sheik', 26, 'M', 8300.0)] You can delete the records in an existing table using the DELETE FROM statement of PostgreSQL database. To remove specific records, you need to use WHERE clause along with it. Following is the syntax of the DELETE query in PostgreSQL − DELETE FROM table_name [WHERE Clause] Assume we have created a table with name CRICKETERS using the following query − postgres=# CREATE TABLE CRICKETERS ( First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); CREATE TABLE postgres=# And if we have inserted 5 records in to it using INSERT statements as − postgres=# insert into CRICKETERS values ('Shikhar', 'Dhawan', 33, 'Delhi', 'India'); INSERT 0 1 postgres=# insert into CRICKETERS values ('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica'); INSERT 0 1 postgres=# insert into CRICKETERS values ('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka'); INSERT 0 1 postgres=# insert into CRICKETERS values ('Virat', 'Kohli', 30, 'Delhi', 'India'); INSERT 0 1 postgres=# insert into CRICKETERS values ('Rohit', 'Sharma', 32, 'Nagpur', 'India'); INSERT 0 1 Following statement deletes the record of the cricketer whose last name is 'Sangakkara'. − postgres=# DELETE FROM CRICKETERS WHERE LAST_NAME = 'Sangakkara'; DELETE 1 If you retrieve the contents of the table using the SELECT statement, you can see only 4 records since we have deleted one. postgres=# SELECT * FROM CRICKETERS; first_name | last_name | age | place_of_birth | country ------------+-----------+-----+----------------+------------- Jonathan | Trott | 39 | CapeTown | SouthAfrica Virat | Kohli | 31 | Delhi | India Rohit | Sharma | 33 | Nagpur | India Shikhar | Dhawan | 46 | Delhi | India (4 rows) If you execute the DELETE FROM statement without the WHERE clause all the records from the specified table will be deleted. postgres=# DELETE FROM CRICKETERS; DELETE 4 Since you have deleted all the records, if you try to retrieve the contents of the CRICKETERS table, using SELECT statement you will get an empty result set as shown below − postgres=# SELECT * FROM CRICKETERS; first_name | last_name | age | place_of_birth | country ------------+-----------+-----+----------------+--------- (0 rows) The cursor class of psycopg2 provides a method with name execute() method. This method accepts the query as a parameter and executes it. Therefore, to insert data into a table in PostgreSQL using python − Import psycopg2 package. Import psycopg2 package. Create a connection object using the connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it. Create a connection object using the connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it. Turn off the auto-commit mode by setting false as value to the attribute autocommit. Turn off the auto-commit mode by setting false as value to the attribute autocommit. The cursor() method of the Connection class of the psycopg2 library returns a cursor object. Create a cursor object using this method. The cursor() method of the Connection class of the psycopg2 library returns a cursor object. Create a cursor object using this method. Then, execute the UPDATE statement by passing it as a parameter to the execute() method. Then, execute the UPDATE statement by passing it as a parameter to the execute() method. Following Python code deletes records of the EMPLOYEE table with age values greater than 25 − import psycopg2 #establishing the connection conn = psycopg2.connect( database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432' ) #Setting auto commit false conn.autocommit = True #Creating a cursor object using the cursor() method cursor = conn.cursor() #Retrieving contents of the table print("Contents of the table: ") cursor.execute('''SELECT * from EMPLOYEE''') print(cursor.fetchall()) #Deleting records cursor.execute('''DELETE FROM EMPLOYEE WHERE AGE > 25''') #Retrieving data after delete print("Contents of the table after delete operation ") cursor.execute("SELECT * from EMPLOYEE") print(cursor.fetchall()) #Commit your changes in the database conn.commit() #Closing the connection conn.close() Contents of the table: [('Ramya', 'Rama priya', 27, 'F', 9000.0), ('Sarmista', 'Sharma', 26, 'F', 10000.0), ('Tripthi', 'Mishra', 24, 'F', 6000.0), ('Vinay', 'Battacharya', 21, 'M', 6000.0), ('Sharukh', 'Sheik', 26, 'M', 8300.0)] Contents of the table after delete operation: [('Tripthi', 'Mishra', 24, 'F', 6000.0), ('Vinay', 'Battacharya', 21, 'M', 6000.0)] You can drop a table from PostgreSQL database using the DROP TABLE statement. Following is the syntax of the DROP TABLE statement in PostgreSQL − DROP TABLE table_name; Assume we have created two tables with name CRICKETERS and EMPLOYEES using the following queries − postgres=# CREATE TABLE CRICKETERS ( First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); CREATE TABLE postgres=# postgres=# CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT ); CREATE TABLE postgres=# Now if you verify the list of tables using the “\dt” command, you can see the above created tables as − postgres=# \dt; List of relations Schema | Name | Type | Owner --------+------------+-------+---------- public | cricketers | table | postgres public | employee | table | postgres (2 rows) postgres=# Following statement deletes the table named Employee from the database − postgres=# DROP table employee; DROP TABLE Since you have deleted the Employee table, if you retrieve the list of tables again, you can observe only one table in it. postgres=# \dt; List of relations Schema | Name | Type | Owner --------+------------+-------+---------- public | cricketers | table | postgres (1 row) postgres=# If you try to delete the Employee table again, since you have already deleted it, you will get an error saying “table does not exist” as shown below − postgres=# DROP table employee; ERROR: table "employee" does not exist postgres=# To resolve this, you can use the IF EXISTS clause along with the DELTE statement. This removes the table if it exists else skips the DLETE operation. postgres=# DROP table IF EXISTS employee; NOTICE: table "employee" does not exist, skipping DROP TABLE postgres=# You can drop a table whenever you need to, using the DROP statement. But you need to be very careful while deleting any existing table because the data lost will not be recovered after deleting a table. import psycopg2 #establishing the connection conn = psycopg2.connect( database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432' ) #Setting auto commit false conn.autocommit = True #Creating a cursor object using the cursor() method cursor = conn.cursor() #Doping EMPLOYEE table if already exists cursor.execute("DROP TABLE emp") print("Table dropped... ") #Commit your changes in the database conn.commit() #Closing the connection conn.close() #Table dropped... While executing a PostgreSQL SELECT statement you can limit the number of records in its result using the LIMIT clause. Following is the syntax of the LMIT clause in PostgreSQL − SELECT column1, column2, columnN FROM table_name LIMIT [no of rows] Assume we have created a table with name CRICKETERS using the following query − postgres=# CREATE TABLE CRICKETERS ( First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); CREATE TABLE postgres=# And if we have inserted 5 records in to it using INSERT statements as − postgres=# insert into CRICKETERS values ('Shikhar', 'Dhawan', 33, 'Delhi', 'India'); INSERT 0 1 postgres=# insert into CRICKETERS values ('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica'); INSERT 0 1 postgres=# insert into CRICKETERS values ('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka'); INSERT 0 1 postgres=# insert into CRICKETERS values ('Virat', 'Kohli', 30, 'Delhi', 'India'); INSERT 0 1 postgres=# insert into CRICKETERS values ('Rohit', 'Sharma', 32, 'Nagpur', 'India'); INSERT 0 1 Following statement retrieves the first 3 records of the Cricketers table using the LIMIT clause − postgres=# SELECT * FROM CRICKETERS LIMIT 3; first_name | last_name | age | place_of_birth | country ------------+------------+-----+----------------+------------- Shikhar | Dhawan | 33 | Delhi | India Jonathan | Trott | 38 | CapeTown | SouthAfrica Kumara | Sangakkara | 41 | Matale | Srilanka (3 rows) If you want to get records starting from a particular record (offset) you can do so, using the OFFSET clause along with LIMIT. postgres=# SELECT * FROM CRICKETERS LIMIT 3 OFFSET 2; first_name | last_name | age | place_of_birth | country ------------+------------+-----+----------------+---------- Kumara | Sangakkara | 41 | Matale | Srilanka Virat | Kohli | 30 | Delhi | India Rohit | Sharma | 32 | Nagpur | India (3 rows) postgres=# Following python example retrieves the contents of a table named EMPLOYEE, limiting the number of records in the result to 2 − import psycopg2 #establishing the connection conn = psycopg2.connect( database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432' ) #Setting auto commit false conn.autocommit = True #Creating a cursor object using the cursor() method cursor = conn.cursor() #Retrieving single row sql = '''SELECT * from EMPLOYEE LIMIT 2 OFFSET 2''' #Executing the query cursor.execute(sql) #Fetching the data result = cursor.fetchall(); print(result) #Commit your changes in the database conn.commit() #Closing the connection conn.close() [('Sharukh', 'Sheik', 25, 'M', 8300.0), ('Sarmista', 'Sharma', 26, 'F', 10000.0)] When you have divided the data in two tables you can fetch combined records from these two tables using Joins. Assume we have created a table with name CRICKETERS and inserted 5 records into it as shown below − postgres=# CREATE TABLE CRICKETERS ( First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); postgres=# insert into CRICKETERS values ( 'Shikhar', 'Dhawan', 33, 'Delhi', 'India' ); postgres=# insert into CRICKETERS values ( 'Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica' ); postgres=# insert into CRICKETERS values ( 'Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka' ); postgres=# insert into CRICKETERS values ( 'Virat', 'Kohli', 30, 'Delhi', 'India' ); postgres=# insert into CRICKETERS values ( 'Rohit', 'Sharma', 32, 'Nagpur', 'India' ); And, if we have created another table with name OdiStats and inserted 5 records into it as − postgres=# CREATE TABLE ODIStats ( First_Name VARCHAR(255), Matches INT, Runs INT, AVG FLOAT, Centuries INT, HalfCenturies INT ); postgres=# insert into OdiStats values ('Shikhar', 133, 5518, 44.5, 17, 27); postgres=# insert into OdiStats values ('Jonathan', 68, 2819, 51.25, 4, 22); postgres=# insert into OdiStats values ('Kumara', 404, 14234, 41.99, 25, 93); postgres=# insert into OdiStats values ('Virat', 239, 11520, 60.31, 43, 54); postgres=# insert into OdiStats values ('Rohit', 218, 8686, 48.53, 24, 42); Following statement retrieves data combining the values in these two tables − postgres=# SELECT Cricketers.First_Name, Cricketers.Last_Name, Cricketers.Country, OdiStats.matches, OdiStats.runs, OdiStats.centuries, OdiStats.halfcenturies from Cricketers INNER JOIN OdiStats ON Cricketers.First_Name = OdiStats.First_Name; first_name | last_name | country | matches | runs | centuries | halfcenturies ------------+------------+-------------+---------+-------+-----------+--------------- Shikhar | Dhawan | India | 133 | 5518 | 17 | 27 Jonathan | Trott | SouthAfrica | 68 | 2819 | 4 | 22 Kumara | Sangakkara | Srilanka | 404 | 14234 | 25 | 93 Virat | Kohli | India | 239 | 11520 | 43 | 54 Rohit | Sharma | India | 218 | 8686 | 24 | 42 (5 rows) postgres=# When you have divided the data in two tables you can fetch combined records from these two tables using Joins. Following python program demonstrates the usage of the JOIN clause − import psycopg2 #establishing the connection conn = psycopg2.connect( database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432' ) #Setting auto commit false conn.autocommit = True #Creating a cursor object using the cursor() method cursor = conn.cursor() #Retrieving single row sql = '''SELECT * from EMP INNER JOIN CONTACT ON EMP.CONTACT = CONTACT.ID''' #Executing the query cursor.execute(sql) #Fetching 1st row from the table result = cursor.fetchall(); print(result) #Commit your changes in the database conn.commit() #Closing the connection conn.close() [('Ramya', 'Rama priya', 27, 'F', 9000.0, 101, 101, '[email protected]', 'Hyderabad'), ('Vinay', 'Battacharya', 20, 'M', 6000.0, 102, 102, '[email protected]', 'Vishakhapatnam'), ('Sharukh', 'Sheik', 25, 'M', 8300.0, 103, 103, '[email protected] ', 'Pune'), ('Sarmista', 'Sharma', 26, 'F', 10000.0, 104, 104, '[email protected]', 'Mumbai')] The Cursor class of the psycopg library provide methods to execute the PostgreSQL commands in the database using python code. Using the methods of it you can execute SQL statements, fetch data from the result sets, call procedures. You can create Cursor object using the cursor() method of the Connection object/class. import psycopg2 #establishing the connection conn = psycopg2.connect( database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432' ) #Setting auto commit false conn.autocommit = True #Creating a cursor object using the cursor() method cursor = conn.cursor() Following are the various methods provided by the Cursor class/object. callproc() This method is used to call existing procedures PostgreSQL database. close() This method is used to close the current cursor object. executemany() This method accepts a list series of parameters list. Prepares an MySQL query and executes it with all the parameters. execute() This method accepts a MySQL query as a parameter and executes the given query. fetchall() This method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows it returns the remaining ones) fetchone() This method fetches the next row in the result of a query and returns it as a tuple. fetchmany() This method is similar to the fetchone() but, it retrieves the next set of rows in the result set of a query, instead of a single row. Following are the properties of the Cursor class − description This is a read only property which returns the list containing the description of columns in a result-set. astrowid This is a read only property, if there are any auto-incremented columns in the table, this returns the value generated for that column in the last INSERT or, UPDATE operation. rowcount This returns the number of rows returned/updated in case of SELECT and UPDATE operations. closed This property specifies whether a cursor is closed or not, if so it returns true, else false. connection This returns a reference to the connection object using which this cursor was created. name This property returns the name of the cursor. scrollable This property specifies whether a particular cursor is scrollable. SQLite3 can be integrated with Python using sqlite3 module, which was written by Gerhard Haring. It provides an SQL interface compliant with the DB-API 2.0 specification described by PEP 249. You do not need to install this module separately because it is shipped by default along with Python version 2.5.x onwards. To use sqlite3 module, you must first create a connection object that represents the database and then optionally you can create a cursor object, which will help you in executing all the SQL statements. Following are important sqlite3 module routines, which can suffice your requirement to work with SQLite database from your Python program. If you are looking for a more sophisticated application, then you can look into Python sqlite3 module's official documentation. sqlite3.connect(database [,timeout ,other optional arguments]) This API opens a connection to the SQLite database file. You can use ":memory:" to open a database connection to a database that resides in RAM instead of on disk. If database is opened successfully, it returns a connection object. connection.cursor([cursorClass]) This routine creates a cursor which will be used throughout your database programming with Python. This method accepts a single optional parameter cursorClass. If supplied, this must be a custom cursor class that extends sqlite3.Cursor. cursor.execute(sql [, optional parameters]) This routine executes an SQL statement. The SQL statement may be parameterized (i. e. placeholders instead of SQL literals). The sqlite3 module supports two kinds of placeholders: question marks and named placeholders (named style). For example − cursor.execute("insert into people values (?, ?)", (who, age)) connection.execute(sql [, optional parameters]) This routine is a shortcut of the above execute method provided by the cursor object and it creates an intermediate cursor object by calling the cursor method, then calls the cursor's execute method with the parameters given. cursor.executemany(sql, seq_of_parameters) This routine executes an SQL command against all parameter sequences or mappings found in the sequence sql. connection.executemany(sql[, parameters]) This routine is a shortcut that creates an intermediate cursor object by calling the cursor method, then calls the cursor.s executemany method with the parameters given. cursor.executescript(sql_script) This routine executes multiple SQL statements at once provided in the form of script. It issues a COMMIT statement first, then executes the SQL script it gets as a parameter. All the SQL statements should be separated by a semi colon (;). connection.executescript(sql_script) This routine is a shortcut that creates an intermediate cursor object by calling the cursor method, then calls the cursor's executescript method with the parameters given. connection.total_changes() This routine returns the total number of database rows that have been modified, inserted, or deleted since the database connection was opened. connection.commit() This method commits the current transaction. If you don't call this method, anything you did since the last call to commit() is not visible from other database connections. connection.rollback() This method rolls back any changes to the database since the last call to commit(). connection.close() This method closes the database connection. Note that this does not automatically call commit(). If you just close your database connection without calling commit() first, your changes will be lost! cursor.fetchone() This method fetches the next row of a query result set, returning a single sequence, or None when no more data is available. cursor.fetchmany([size = cursor.arraysize]) This routine fetches the next set of rows of a query result, returning a list. An empty list is returned when no more rows are available. The method tries to fetch as many rows as indicated by the size parameter. cursor.fetchall() This routine fetches all (remaining) rows of a query result, returning a list. An empty list is returned when no rows are available. To establish connection with SQLite Open command prompt, browse through the location of where you have installed SQLite and just execute the command sqlite3 as shown below − You can communicate with SQLite2 database using the SQLite3 python module. To do so, first of all you need to establish a connection (create a connection object). To establish a connection with SQLite3 database using python you need to − Import the sqlite3 module using the import statement. Import the sqlite3 module using the import statement. The connect() method accepts the name of the database you need to connect with as a parameter and, returns a Connection object. The connect() method accepts the name of the database you need to connect with as a parameter and, returns a Connection object. import sqlite3 conn = sqlite3.connect('example.db') print("Connection established ..........") Using the SQLite CREATE TABLE statement you can create a table in a database. Following is the syntax to create a table in SQLite database − CREATE TABLE database_name.table_name( column1 datatype PRIMARY KEY(one or more columns), column2 datatype, column3 datatype, ..... columnN datatype ); Following SQLite query/statement creates a table with name CRICKETERS in SQLite database − sqlite> CREATE TABLE CRICKETERS ( First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); sqlite> Let us create one more table OdiStats describing the One-day cricket statistics of each player in CRICKETERS table. sqlite> CREATE TABLE ODIStats ( First_Name VARCHAR(255), Matches INT, Runs INT, AVG FLOAT, Centuries INT, HalfCenturies INT ); sqlite You can get the list of tables in a database in SQLite database using the .tables command. After creating a table, if you can verify the list of tables you can observe the newly created table in it as − sqlite> . tables CRICKETERS ODIStats sqlite> The Cursor object contains all the methods to execute quires and fetch data etc. The cursor method of the connection class returns a cursor object. Therefore, to create a table in SQLite database using python − Establish connection with a database using the connect() method. Establish connection with a database using the connect() method. Create a cursor object by invoking the cursor() method on the above created connection object. Create a cursor object by invoking the cursor() method on the above created connection object. Now execute the CREATE TABLE statement using the execute() method of the Cursor class. Now execute the CREATE TABLE statement using the execute() method of the Cursor class. Following Python program creates a table named Employee in SQLite3 − import sqlite3 #Connecting to sqlite conn = sqlite3.connect('example.db') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Doping EMPLOYEE table if already exists. cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") #Creating table as per requirement sql ='''CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )''' cursor.execute(sql) print("Table created successfully........") # Commit your changes in the database conn.commit() #Closing the connection conn.close() Table created successfully........ You can add new rows to an existing table of SQLite using the INSERT INTO statement. In this, you need to specify the name of the table, column names, and values (in the same order as column names). Following is the recommended syntax of the INSERT statement − INSERT INTO TABLE_NAME (column1, column2, column3,...columnN) VALUES (value1, value2, value3,...valueN); Where, column1, column2, column3,.. are the names of the columns of a table and value1, value2, value3,... are the values you need to insert into the table. Assume we have created a table with name CRICKETERS using the CREATE TABLE statement as shown below − sqlite> CREATE TABLE CRICKETERS ( First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); sqlite> Following PostgreSQL statement inserts a row in the above created table. sqlite> insert into CRICKETERS (First_Name, Last_Name, Age, Place_Of_Birth, Country) values ('Shikhar', 'Dhawan', 33, 'Delhi', 'India'); sqlite> While inserting records using the INSERT INTO statement, if you skip any columns names, this record will be inserted leaving empty spaces at columns which you have skipped. sqlite> insert into CRICKETERS (First_Name, Last_Name, Country) values ('Jonathan', 'Trott', 'SouthAfrica'); sqlite> You can also insert records into a table without specifying the column names, if the order of values you pass is same as their respective column names in the table. sqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka'); sqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India'); sqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India'); sqlite> After inserting the records into a table you can verify its contents using the SELECT statement as shown below − sqlite> select * from cricketers; Shikhar | Dhawan | 33 | Delhi | India Jonathan | Trott | | | SouthAfrica Kumara | Sangakkara | 41 | Matale | Srilanka Virat | Kohli | 30 | Delhi | India Rohit | Sharma | 32 | Nagpur | India sqlite> To add records to an existing table in SQLite database − Import sqlite3 package. Import sqlite3 package. Create a connection object using the connect() method by passing the name of the database as a parameter to it. Create a connection object using the connect() method by passing the name of the database as a parameter to it. The cursor() method returns a cursor object using which you can communicate with SQLite3. Create a cursor object by invoking the cursor() object on the (above created) Connection object. The cursor() method returns a cursor object using which you can communicate with SQLite3. Create a cursor object by invoking the cursor() object on the (above created) Connection object. Then, invoke the execute() method on the cursor object, by passing an INSERT statement as a parameter to it. Then, invoke the execute() method on the cursor object, by passing an INSERT statement as a parameter to it. Following python example inserts records into to a table named EMPLOYEE − import sqlite3 #Connecting to sqlite conn = sqlite3.connect('example.db') #Creating a cursor object using the cursor() method cursor = conn.cursor() # Preparing SQL queries to INSERT a record into the database. cursor.execute('''INSERT INTO EMPLOYEE( FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Ramya', 'Rama Priya', 27, 'F', 9000)''') cursor.execute('''INSERT INTO EMPLOYEE( FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Vinay', 'Battacharya', 20, 'M', 6000)''') cursor.execute('''INSERT INTO EMPLOYEE( FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Sharukh', 'Sheik', 25, 'M', 8300)''') cursor.execute('''INSERT INTO EMPLOYEE( FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Sarmista', 'Sharma', 26, 'F', 10000)''') cursor.execute('''INSERT INTO EMPLOYEE( FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Tripthi', 'Mishra', 24, 'F', 6000)''') # Commit your changes in the database conn.commit() print("Records inserted........") # Closing the connection conn.close() Records inserted........ You can retrieve data from an SQLite table using the SELCT query. This query/statement returns contents of the specified relation (table) in tabular form and it is called as result-set. Following is the syntax of the SELECT statement in SQLite − SELECT column1, column2, columnN FROM table_name; Assume we have created a table with name CRICKETERS using the following query − sqlite> CREATE TABLE CRICKETERS ( First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); sqlite> And if we have inserted 5 records in to it using INSERT statements as − sqlite> insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India'); sqlite> insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica'); sqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka'); sqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India'); sqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India'); sqlite> Following SELECT query retrieves the values of the columns FIRST_NAME, LAST_NAME and, COUNTRY from the CRICKETERS table. sqlite> SELECT FIRST_NAME, LAST_NAME, COUNTRY FROM CRICKETERS; Shikhar |Dhawan |India Jonathan |Trott |SouthAfrica Kumara |Sangakkara |Srilanka Virat |Kohli |India Rohit |Sharma |India sqlite> As you observe, the SELECT statement of the SQLite database just returns the records of the specified tables. To get a formatted output you need to set the header, and mode using the respective commands before the SELECT statement as shown below − sqlite> .header on sqlite> .mode column sqlite> SELECT FIRST_NAME, LAST_NAME, COUNTRY FROM CRICKETERS; First_Name Last_Name Country ---------- -------------------- ---------- Shikhar Dhawan India Jonathan Trott SouthAfric Kumara Sangakkara Srilanka Virat Kohli India Rohit Sharma India sqlite> If you want to retrieve all the columns of each record, you need to replace the names of the columns with "*" as shown below − sqlite> .header on sqlite> .mode column sqlite> SELECT * FROM CRICKETERS; First_Name Last_Name Age Place_Of_Birth Country ---------- ---------- ---------- -------------- ---------- Shikhar Dhawan 33 Delhi India Jonathan Trott 38 CapeTown SouthAfric Kumara Sangakkara 41 Matale Srilanka Virat Kohli 30 Delhi India Rohit Sharma 32 Nagpur India sqlite> In SQLite by default the width of the columns is 10 values beyond this width are chopped (observe the country column of 2nd row in above table). You can set the width of each column to required value using the .width command, before retrieving the contents of a table as shown below − sqlite> .width 10, 10, 4, 10, 13 sqlite> SELECT * FROM CRICKETERS; First_Name Last_Name Age Place_Of_B Country ---------- ---------- ---- ---------- ------------- Shikhar Dhawan 33 Delhi India Jonathan Trott 38 CapeTown SouthAfrica Kumara Sangakkara 41 Matale Srilanka Virat Kohli 30 Delhi India Rohit Sharma 32 Nagpur India sqlite> READ Operation on any database means to fetch some useful information from the database. You can fetch data from MYSQL using the fetch() method provided by the sqlite python module. The sqlite3.Cursor class provides three methods namely fetchall(), fetchmany() and, fetchone() where, The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows it returns the remaining ones). The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows it returns the remaining ones). The fetchone() method fetches the next row in the result of a query and returns it as a tuple. The fetchone() method fetches the next row in the result of a query and returns it as a tuple. The fetchmany() method is similar to the fetchone() but, it retrieves the next set of rows in the result set of a query, instead of a single row. The fetchmany() method is similar to the fetchone() but, it retrieves the next set of rows in the result set of a query, instead of a single row. Note − A result set is an object that is returned when a cursor object is used to query a table. Following example fetches all the rows of the EMPLOYEE table using the SELECT query and from the obtained result set initially, we are retrieving the first row using the fetchone() method and then fetching the remaining rows using the fetchall() method. Following Python program shows how to fetch and display records from the COMPANY table created in the above example. import sqlite3 #Connecting to sqlite conn = sqlite3.connect('example.db') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Retrieving data cursor.execute('''SELECT * from EMPLOYEE''') #Fetching 1st row from the table result = cursor.fetchone(); print(result) #Fetching 1st row from the table result = cursor.fetchall(); print(result) #Commit your changes in the database conn.commit() #Closing the connection conn.close() ('Ramya', 'Rama priya', 27, 'F', 9000.0) [('Vinay', 'Battacharya', 20, 'M', 6000.0), ('Sharukh', 'Sheik', 25, 'M', 8300.0), ('Sarmista', 'Sharma', 26, 'F', 10000.0), ('Tripthi', 'Mishra', 24, 'F', 6000.0) ] If you want to fetch, delete or, update particular rows of a table in SQLite, you need to use the where clause to specify condition to filter the rows of the table for the operation. For example, if you have a SELECT statement with where clause, only the rows which satisfies the specified condition will be retrieved. Following is the syntax of the WHERE clause in SQLite − SELECT column1, column2, columnN FROM table_name WHERE [search_condition] You can specify a search_condition using comparison or logical operators. like >, <, =, LIKE, NOT, etc. The following examples would make this concept clear. Assume we have created a table with name CRICKETERS using the following query − sqlite> CREATE TABLE CRICKETERS ( First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); sqlite> And if we have inserted 5 records in to it using INSERT statements as − sqlite> insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India'); sqlite> insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica'); sqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka'); sqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India'); sqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India'); sqlite> Following SELECT statement retrieves the records whose age is greater than 35 − sqlite> SELECT * FROM CRICKETERS WHERE AGE > 35; First_Name Last_Name Age Place_Of_B Country ---------- ---------- ---- ---------- ------------- Jonathan Trott 38 CapeTown SouthAfrica Kumara Sangakkara 41 Matale Srilanka sqlite> The Cursor object/class contains all the methods to execute queries and fetch data, etc. The cursor method of the connection class returns a cursor object. Therefore, to create a table in SQLite database using python − Establish connection with a database using the connect() method. Establish connection with a database using the connect() method. Create a cursor object by invoking the cursor() method on the above created connection object. Create a cursor object by invoking the cursor() method on the above created connection object. Now execute the CREATE TABLE statement using the execute() method of the Cursor class. Now execute the CREATE TABLE statement using the execute() method of the Cursor class. Following example creates a table named Employee and populates it. Then using the where clause it retrieves the records with age value less than 23. import sqlite3 #Connecting to sqlite conn = sqlite3.connect('example.db') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Doping EMPLOYEE table if already exists. cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") sql = '''CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )''' cursor.execute(sql) #Populating the table cursor.execute('''INSERT INTO EMPLOYEE( FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Ramya', 'Rama priya', 27, 'F', 9000)''') cursor.execute('''INSERT INTO EMPLOYEE (FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Vinay', 'Battacharya', 20, 'M', 6000)''') cursor.execute('''INSERT INTO EMPLOYEE( FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Sharukh', 'Sheik', 25, 'M', 8300)''') cursor.execute('''INSERT INTO EMPLOYEE( FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Sarmista', 'Sharma', 26, 'F', 10000)''') cursor.execute('''INSERT INTO EMPLOYEE( FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Tripthi', 'Mishra', 24, 'F', 6000)''') #Retrieving specific records using the where clause cursor.execute("SELECT * from EMPLOYEE WHERE AGE <23") print(cursor.fetchall()) #Commit your changes in the database conn.commit() #Closing the connection conn.close() [('Vinay', 'Battacharya', 20, 'M', 6000.0)] While fetching data using SELECT query, you will get the records in the same order in which you have inserted them. You can sort the results in desired order (ascending or descending) using the Order By clause. By default, this clause sorts results in ascending order, if you need to arrange them in descending order you need to use “DESC” explicitly. Following is the syntax of the ORDER BY clause in SQLite. SELECT column-list FROM table_name [WHERE condition] [ORDER BY column1, column2, .. columnN] [ASC | DESC]; Assume we have created a table with name CRICKETERS using the following query − sqlite> CREATE TABLE CRICKETERS ( First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); sqlite> And if we have inserted 5 records in to it using INSERT statements as − sqlite> insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India'); sqlite> insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica'); sqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka'); sqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India'); sqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India'); sqlite> Following SELECT statement retrieves the rows of the CRICKETERS table in the ascending order of their age − sqlite> SELECT * FROM CRICKETERS ORDER BY AGE; First_Name Last_Name Age Place_Of_B Country ---------- ---------- ---- ---------- ------------- Virat Kohli 30 Delhi India Rohit Sharma 32 Nagpur India Shikhar Dhawan 33 Delhi India Jonathan Trott 38 CapeTown SouthAfrica Kumara Sangakkara 41 Matale Srilanka sqlite> You can use more than one column to sort the records of a table. Following SELECT statements sorts the records of the CRICKETERS table based on the columns AGE and FIRST_NAME. sqlite> SELECT * FROM CRICKETERS ORDER BY AGE, FIRST_NAME; First_Name Last_Name Age Place_Of_B Country ---------- ---------- ---- ---------- ------------- Virat Kohli 30 Delhi India Rohit Sharma 32 Nagpur India Shikhar Dhawan 33 Delhi India Jonathan Trott 38 CapeTown SouthAfrica Kumara Sangakkara 41 Matale Srilanka sqlite> By default, the ORDER BY clause sorts the records of a table in ascending order you can arrange the results in descending order using DESC as − sqlite> SELECT * FROM CRICKETERS ORDER BY AGE DESC; First_Name Last_Name Age Place_Of_B Country ---------- ---------- ---- ---------- ------------- Kumara Sangakkara 41 Matale Srilanka Jonathan Trott 38 CapeTown SouthAfrica Shikhar Dhawan 33 Delhi India Rohit Sharma 32 Nagpur India Virat Kohli 30 Delhi India sqlite> To retrieve contents of a table in specific order, invoke the execute() method on the cursor object and, pass the SELECT statement along with ORDER BY clause, as a parameter to it. In the following example we are creating a table with name and Employee, populating it, and retrieving its records back in the (ascending) order of their age, using the ORDER BY clause. import psycopg2 #establishing the connection conn = psycopg2.connect( database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432' ) #Setting auto commit false conn.autocommit = True #Creating a cursor object using the cursor() method cursor = conn.cursor() #Doping EMPLOYEE table if already exists. cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") #Creating a table sql = '''CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME INT, CONTACT INT )''' cursor.execute(sql) #Populating the table #Populating the table cursor.execute('''INSERT INTO EMPLOYEE (FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Ramya', 'Rama priya', 27, 'F', 9000), ('Vinay', 'Battacharya', 20, 'M', 6000), ('Sharukh', 'Sheik', 25, 'M', 8300), ('Sarmista', 'Sharma', 26, 'F', 10000), ('Tripthi', 'Mishra', 24, 'F', 6000)''') conn.commit() #Retrieving specific records using the ORDER BY clause cursor.execute("SELECT * from EMPLOYEE ORDER BY AGE") print(cursor.fetchall()) #Commit your changes in the database conn.commit() #Closing the connection conn.close() [('Vinay', 'Battacharya', 20, 'M', 6000, None), ('Tripthi', 'Mishra', 24, 'F', 6000, None), ('Sharukh', 'Sheik', 25, 'M', 8300, None), ('Sarmista', 'Sharma', 26, 'F', 10000, None), ('Ramya', 'Rama priya', 27, 'F', 9000, None)] UPDATE Operation on any database implies modifying the values of one or more records of a table, which are already available in the database. You can update the values of existing records in SQLite using the UPDATE statement. To update specific rows, you need to use the WHERE clause along with it. Following is the syntax of the UPDATE statement in SQLite − UPDATE table_name SET column1 = value1, column2 = value2...., columnN = valueN WHERE [condition]; Assume we have created a table with name CRICKETERS using the following query − sqlite> CREATE TABLE CRICKETERS ( First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); sqlite> And if we have inserted 5 records in to it using INSERT statements as − sqlite> insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India'); sqlite> insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica'); sqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka'); sqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India'); sqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India'); sqlite> Following Statement modifies the age of the cricketer, whose first name is Shikhar − sqlite> UPDATE CRICKETERS SET AGE = 45 WHERE FIRST_NAME = 'Shikhar' ; sqlite> If you retrieve the record whose FIRST_NAME is Shikhar you observe that the age value has been changed to 45 − sqlite> SELECT * FROM CRICKETERS WHERE FIRST_NAME = 'Shikhar'; First_Name Last_Name Age Place_Of_B Country ---------- ---------- ---- ---------- ------------- Shikhar Dhawan 45 Delhi India sqlite> If you haven’t used the WHERE clause values of all the records will be updated. Following UPDATE statement increases the age of all the records in the CRICKETERS table by 1 − sqlite> UPDATE CRICKETERS SET AGE = AGE+1; sqlite> If you retrieve the contents of the table using SELECT command, you can see the updated values as − sqlite> SELECT * FROM CRICKETERS; First_Name Last_Name Age Place_Of_B Country ---------- ---------- ---- ---------- ------------- Shikhar Dhawan 46 Delhi India Jonathan Trott 39 CapeTown SouthAfrica Kumara Sangakkara 42 Matale Srilanka Virat Kohli 31 Delhi India Rohit Sharma 33 Nagpur India sqlite> To add records to an existing table in SQLite database − Import sqlite3 package. Import sqlite3 package. Create a connection object using the connect() method by passing the name of the database as a parameter to it. Create a connection object using the connect() method by passing the name of the database as a parameter to it. The cursor() method returns a cursor object using which you can communicate with SQLite3 . Create a cursor object by invoking the cursor() object on the (above created) Connection object. The cursor() method returns a cursor object using which you can communicate with SQLite3 . Create a cursor object by invoking the cursor() object on the (above created) Connection object. Then, invoke the execute() method on the cursor object, by passing an UPDATE statement as a parameter to it. Then, invoke the execute() method on the cursor object, by passing an UPDATE statement as a parameter to it. Following Python example, creates a table with name EMPLOYEE, inserts 5 records into it and, increases the age of all the male employees by 1 − import sqlite3 #Connecting to sqlite conn = sqlite3.connect('example.db') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Doping EMPLOYEE table if already exists. cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") #Creating table as per requirement sql ='''CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )''' cursor.execute(sql) #Inserting data cursor.execute('''INSERT INTO EMPLOYEE (FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Ramya', 'Rama priya', 27, 'F', 9000), ('Vinay', 'Battacharya', 20, 'M', 6000), ('Sharukh', 'Sheik', 25, 'M', 8300), ('Sarmista', 'Sharma', 26, 'F', 10000), ('Tripthi', 'Mishra', 24, 'F', 6000)''') conn.commit() #Fetching all the rows before the update print("Contents of the Employee table: ") cursor.execute('''SELECT * from EMPLOYEE''') print(cursor.fetchall()) #Updating the records sql = '''UPDATE EMPLOYEE SET AGE=AGE+1 WHERE SEX = 'M' ''' cursor.execute(sql) print("Table updated...... ") #Fetching all the rows after the update print("Contents of the Employee table after the update operation: ") cursor.execute('''SELECT * from EMPLOYEE''') print(cursor.fetchall()) #Commit your changes in the database conn.commit() #Closing the connection conn.close() Contents of the Employee table: [('Ramya', 'Rama priya', 27, 'F', 9000.0), ('Vinay', 'Battacharya', 20, 'M', 6000.0), ('Sharukh', 'Sheik', 25, 'M', 8300.0), ('Sarmista', 'Sharma', 26, 'F', 10000.0), ('Tripthi', 'Mishra', 24, 'F', 6000.0)] Table updated...... Contents of the Employee table after the update operation: [('Ramya', 'Rama priya', 27, 'F', 9000.0), ('Vinay', 'Battacharya', 21, 'M', 6000.0), ('Sharukh', 'Sheik', 26, 'M', 8300.0), ('Sarmista', 'Sharma', 26, 'F', 10000.0), ('Tripthi', 'Mishra', 24, 'F', 6000.0)] To delete records from a SQLite table, you need to use the DELETE FROM statement. To remove specific records, you need to use WHERE clause along with it. To update specific rows, you need to use the WHERE clause along with it. Following is the syntax of the DELETE query in SQLite − DELETE FROM table_name [WHERE Clause] Assume we have created a table with name CRICKETERS using the following query − sqlite> CREATE TABLE CRICKETERS ( First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); sqlite> And if we have inserted 5 records in to it using INSERT statements as − sqlite> insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India'); sqlite> insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica'); sqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka'); sqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India'); sqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India'); sqlite> Following statement deletes the record of the cricketer whose last name is 'Sangakkara'. sqlite> DELETE FROM CRICKETERS WHERE LAST_NAME = 'Sangakkara'; sqlite> If you retrieve the contents of the table using the SELECT statement, you can see only 4 records since we have deleted one. sqlite> SELECT * FROM CRICKETERS; First_Name Last_Name Age Place_Of_B Country ---------- ---------- ---- ---------- ------------- Shikhar Dhawan 46 Delhi India Jonathan Trott 39 CapeTown SouthAfrica Virat Kohli 31 Delhi India Rohit Sharma 33 Nagpur India sqlite> If you execute the DELETE FROM statement without the WHERE clause, all the records from the specified table will be deleted. sqlite> DELETE FROM CRICKETERS; sqlite> Since you have deleted all the records, if you try to retrieve the contents of the CRICKETERS table, using SELECT statement you will get an empty result set as shown below − sqlite> SELECT * FROM CRICKETERS; sqlite> To add records to an existing table in SQLite database − Import sqlite3 package. Import sqlite3 package. Create a connection object using the connect() method by passing the name of the database as a parameter to it. Create a connection object using the connect() method by passing the name of the database as a parameter to it. The cursor() method returns a cursor object using which you can communicate with SQLite3 . Create a cursor object by invoking the cursor() object on the (above created) Connection object. The cursor() method returns a cursor object using which you can communicate with SQLite3 . Create a cursor object by invoking the cursor() object on the (above created) Connection object. Then, invoke the execute() method on the cursor object, by passing an DELETE statement as a parameter to it. Then, invoke the execute() method on the cursor object, by passing an DELETE statement as a parameter to it. Following python example deletes the records from EMPLOYEE table with age value greater than 25. import sqlite3 #Connecting to sqlite conn = sqlite3.connect('example.db') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Retrieving contents of the table print("Contents of the table: ") cursor.execute('''SELECT * from EMPLOYEE''') print(cursor.fetchall()) #Deleting records cursor.execute('''DELETE FROM EMPLOYEE WHERE AGE > 25''') #Retrieving data after delete print("Contents of the table after delete operation ") cursor.execute("SELECT * from EMPLOYEE") print(cursor.fetchall()) #Commit your changes in the database conn.commit() #Closing the connection conn.close() Contents of the table: [('Ramya', 'Rama priya', 27, 'F', 9000.0), ('Vinay', 'Battacharya', 21, 'M', 6000.0), ('Sharukh', 'Sheik', 26, 'M', 8300.0), ('Sarmista', 'Sharma', 26, 'F', 10000.0), ('Tripthi', 'Mishra', 24, 'F', 6000.0)] Contents of the table after delete operation [('Vinay', 'Battacharya', 21, 'M', 6000.0), ('Tripthi', 'Mishra', 24, 'F', 6000.0)] You can remove an entire table using the DROP TABLE statement. You just need to specify the name of the table you need to delete. Following is the syntax of the DROP TABLE statement in PostgreSQL − DROP TABLE table_name; Assume we have created two tables with name CRICKETERS and EMPLOYEES using the following queries − sqlite> CREATE TABLE CRICKETERS ( First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); sqlite> CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT ); sqlite> Now if you verify the list of tables using the .tables command, you can see the above created tables in it ( list) as − sqlite> .tables CRICKETERS EMPLOYEE sqlite> Following statement deletes the table named Employee from the database − sqlite> DROP table employee; sqlite> Since you have deleted the Employee table, if you retrieve the list of tables again, you can observe only one table in it. sqlite> .tables CRICKETERS sqlite> If you try to delete the Employee table again, since you have already deleted it you will get an error saying “no such table” as shown below − sqlite> DROP table employee; Error: no such table: employee sqlite> To resolve this, you can use the IF EXISTS clause along with the DELTE statement. This removes the table if it exists else skips the DLETE operation. sqlite> DROP table IF EXISTS employee; sqlite> You can drop a table whenever you need to, using the DROP statement of MYSQL, but you need to be very careful while deleting any existing table because the data lost will not be recovered after deleting a table. To drop a table from a SQLite3 database using python invoke the execute() method on the cursor object and pass the drop statement as a parameter to it. import sqlite3 #Connecting to sqlite conn = sqlite3.connect('example.db') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Doping EMPLOYEE table if already exists cursor.execute("DROP TABLE emp") print("Table dropped... ") #Commit your changes in the database conn.commit() #Closing the connection conn.close() Table dropped... While fetching records if you want to limit them by a particular number, you can do so, using the LIMIT clause of SQLite. Following is the syntax of the LIMIT clause in SQLite − SELECT column1, column2, columnN FROM table_name LIMIT [no of rows] Assume we have created a table with name CRICKETERS using the following query − sqlite> CREATE TABLE CRICKETERS ( First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); sqlite> And if we have inserted 5 records in to it using INSERT statements as − sqlite> insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India'); sqlite> insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica'); sqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka'); sqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India'); sqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India'); sqlite> Following statement retrieves the first 3 records of the Cricketers table using the LIMIT clause − sqlite> SELECT * FROM CRICKETERS LIMIT 3; First_Name Last_Name Age Place_Of_B Country ---------- ---------- ---- ---------- ------------- Shikhar Dhawan 33 Delhi India Jonathan Trott 38 CapeTown SouthAfrica Kumara Sangakkara 41 Matale Srilanka sqlite> If you need to limit the records starting from nth record (not 1st), you can do so, using OFFSET along with LIMIT. sqlite> SELECT * FROM CRICKETERS LIMIT 3 OFFSET 2; First_Name Last_Name Age Place_Of_B Country ---------- ---------- ---- ---------- ------------- Kumara Sangakkara 41 Matale Srilanka Virat Kohli 30 Delhi India Rohit Sharma 32 Nagpur India sqlite> If you Invoke the execute() method on the cursor object by passing the SELECT query along with the LIMIT clause, you can retrieve required number of records. Following python example retrieves the first two records of the EMPLOYEE table using the LIMIT clause. import sqlite3 #Connecting to sqlite conn = sqlite3.connect('example.db') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Retrieving single row sql = '''SELECT * from EMPLOYEE LIMIT 3''' #Executing the query cursor.execute(sql) #Fetching the data result = cursor.fetchall(); print(result) #Commit your changes in the database conn.commit() #Closing the connection conn.close() [('Ramya', 'Rama priya', 27, 'F', 9000.0), ('Vinay', 'Battacharya', 20, 'M', 6000.0), ('Sharukh', 'Sheik', 25, 'M', 8300.0)] When you have divided the data in two tables you can fetch combined records from these two tables using Joins. Assume we have created a table with name CRICKETERS using the following query − sqlite> CREATE TABLE CRICKETERS ( First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); sqlite> Let us create one more table OdiStats describing the One-day cricket statistics of each player in CRICKETERS table. sqlite> CREATE TABLE ODIStats ( First_Name VARCHAR(255), Matches INT, Runs INT, AVG FLOAT, Centuries INT, HalfCenturies INT ); sqlite> Following statement retrieves data combining the values in these two tables − sqlite> SELECT Cricketers.First_Name, Cricketers.Last_Name, Cricketers.Country, OdiStats.matches, OdiStats.runs, OdiStats.centuries, OdiStats.halfcenturies from Cricketers INNER JOIN OdiStats ON Cricketers.First_Name = OdiStats.First_Name; First_Name Last_Name Country Matches Runs Centuries HalfCenturies ---------- ---------- ------- ---------- ------------- ---------- ---------- Shikhar Dhawan Indi 133 5518 17 27 Jonathan Trott Sout 68 2819 4 22 Kumara Sangakkara Sril 404 14234 25 93 Virat Kohli Indi 239 11520 43 54 Rohit Sharma Indi 218 8686 24 42 sqlite> Following SQLite example, demonstrates the JOIN clause using python − import sqlite3 #Connecting to sqlite conn = sqlite3.connect('example.db') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Retrieving data sql = '''SELECT * from EMP INNER JOIN CONTACT ON EMP.CONTACT = CONTACT.ID''' #Executing the query cursor.execute(sql) #Fetching 1st row from the table result = cursor.fetchall(); print(result) #Commit your changes in the database conn.commit() #Closing the connection conn.close() [('Ramya', 'Rama priya', 27, 'F', 9000.0, 101, 101, '[email protected]', 'Hyderabad'), ('Vinay', 'Battacharya', 20, 'M', 6000.0, 102, 102,'[email protected]', 'Vishakhapatnam'), ('Sharukh', 'Sheik', 25, 'M', 8300.0, 103, 103, '[email protected]', 'Pune'), ('Sarmista', 'Sharma', 26, 'F', 10000.0, 104, 104, '[email protected]', 'Mumbai')] The sqlite3.Cursor class is an instance using which you can invoke methods that execute SQLite statements, fetch data from the result sets of the queries. You can create Cursor object using the cursor() method of the Connection object/class. import sqlite3 #Connecting to sqlite conn = sqlite3.connect('example.db') #Creating a cursor object using the cursor() method cursor = conn.cursor() Following are the various methods provided by the Cursor class/object. execute() This routine executes an SQL statement. The SQL statement may be parameterized (i.e., placeholders instead of SQL literals). The psycopg2 module supports placeholder using %s sign For example:cursor.execute("insert into people values (%s, %s)", (who, age)) executemany() This routine executes an SQL command against all parameter sequences or mappings found in the sequence sql. fetchone() This method fetches the next row of a query result set, returning a single sequence, or None when no more data is available. fetchmany() This routine fetches the next set of rows of a query result, returning a list. An empty list is returned when no more rows are available. The method tries to fetch as many rows as indicated by the size parameter. fetchall() This routine fetches all (remaining) rows of a query result, returning a list. An empty list is returned when no rows are available. Following are the properties of the Cursor class − arraySize This is a read/write property you can set the number of rows returned by the fetchmany() method. description This is a read only property which returns the list containing the description of columns in a result-set. lastrowid This is a read only property, if there are any auto-incremented columns in the table, this returns the value generated for that column in the last INSERT or, UPDATE operation. rowcount This returns the number of rows returned/updated in case of SELECT and UPDATE operations. connection This read-only attribute provides the SQLite database Connection used by the Cursor object. Pymongo is a python distribution which provides tools to work with MongoDB, it is the most preferred way to communicate with MongoDB database from python. To install pymongo first of all make sure you have installed python3 (along with PIP) and MongoDB properly. Then execute the following command. C:\WINDOWS\system32>pip install pymongo Collecting pymongo Using cached https://files.pythonhosted.org/packages/cb/a6/b0ae3781b0ad75825e00e29dc5489b53512625e02328d73556e1ecdf12f8/pymongo-3.9.0-cp37-cp37m-win32.whl Installing collected packages: pymongo Successfully installed pymongo-3.9.0 Once you have installed pymongo, open a new text document, paste the following line in it and, save it as test.py. import pymongo If you have installed pymongo properly, if you execute the test.py as shown below, you should not get any issues. D:\Python_MongoDB>test.py D:\Python_MongoDB> Unlike other databases, MongoDB does not provide separate command to create a database. In general, the use command is used to select/switch to the specific database. This command initially verifies whether the database we specify exists, if so, it connects to it. If the database, we specify with the use command doesn’t exist a new database will be created. Therefore, you can create a database in MongoDB using the Use command. Basic syntax of use DATABASE statement is as follows − use DATABASE_NAME Following command creates a database named in mydb. >use mydb switched to db mydb You can verify your creation by using the db command, this displays the current database. >db mydb To connect to MongoDB using pymongo, you need to import and create a MongoClient, then you can directly access the database you need to create in attribute passion. Following example creates a database in MangoDB. from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['mydb'] print("Database created........") #Verification print("List of databases after creating new one") print(client.list_database_names()) Database created........ List of databases after creating new one: ['admin', 'config', 'local', 'mydb'] You can also specify the port and host names while creating a MongoClient and can access the databases in dictionary style. from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['mydb'] print("Database created........") Database created........ A collection in MongoDB holds a set of documents, it is analogous to a table in relational databases. You can create a collection using the createCollection() method. This method accepts a String value representing the name of the collection to be created and an options (optional) parameter. Using this you can specify the following − The size of the collection. The max number of documents allowed in the capped collection. Whether the collection we create should be capped collection (fixed size collection). Whether the collection we create should be auto-indexed. Following is the syntax to create a collection in MongoDB. db.createCollection("CollectionName") Following method creates a collection named ExampleCollection. > use mydb switched to db mydb > db.createCollection("ExampleCollection") { "ok" : 1 } > Similarly, following is a query that creates a collection using the options of the createCollection() method. >db.createCollection("mycol", { capped : true, autoIndexId : true, size : 6142800, max : 10000 } ) { "ok" : 1 } > Following python example connects to a database in MongoDB (mydb) and, creates a collection in it. from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['mydb'] #Creating a collection collection = db['example'] print("Collection created........") Collection created........ You can store documents into MongoDB using the insert() method. This method accepts a JSON document as a parameter. Following is the syntax of the insert method. >db.COLLECTION_NAME.insert(DOCUMENT_NAME) > use mydb switched to db mydb > db.createCollection("sample") { "ok" : 1 } > doc1 = {"name": "Ram", "age": "26", "city": "Hyderabad"} { "name" : "Ram", "age" : "26", "city" : "Hyderabad" } > db.sample.insert(doc1) WriteResult({ "nInserted" : 1 }) > Similarly, you can also insert multiple documents using the insert() method. > use testDB switched to db testDB > db.createCollection("sample") { "ok" : 1 } > data = [ { "_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad" }, { "_id": "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" }, { "_id": "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" } ] [ { "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" }, { "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" }, { "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" } ] > db.sample.insert(data) BulkWriteResult ({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 3, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] }) > Pymongo provides a method named insert_one() to insert a document in MangoDB. To this method, we need to pass the document in dictionary format. Following example inserts a document in the collection named example. from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['mydb'] #Creating a collection coll = db['example'] #Inserting document into a collection doc1 = {"name": "Ram", "age": "26", "city": "Hyderabad"} coll.insert_one(doc1) print(coll.find_one()) { '_id': ObjectId('5d63ad6ce043e2a93885858b'), 'name': 'Ram', 'age': '26', 'city': 'Hyderabad' } To insert multiple documents into MongoDB using pymongo, you need to invoke the insert_many() method. from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['mydb'] #Creating a collection coll = db['example'] #Inserting document into a collection data = [ { "_id": "101", "name": "Ram", "age": "26", "city": "Hyderabad" }, { "_id": "102", "name": "Rahim", "age": "27", "city": "Bangalore" }, { "_id": "103", "name": "Robert", "age": "28", "city": "Mumbai" } ] res = coll.insert_many(data) print("Data inserted ......") print(res.inserted_ids) Data inserted ...... ['101', '102', '103'] You can read/retrieve stored documents from MongoDB using the find() method. This method retrieves and displays all the documents in MongoDB in a non-structured way. Following is the syntax of the find() method. >db.CollectionName.find() Assume we have inserted 3 documents into a database named testDB in a collection named sample using the following queries − > use testDB > db.createCollection("sample") > data = [ {"_id": "1001", "name" : "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" }, {"_id": "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" } ] > db.sample.insert(data) You can retrieve the inserted documents using the find() method as − > use testDB switched to db testDB > db.sample.find() { "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" } { "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" } { "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" } > You can also retrieve first document in the collection using the findOne() method as − > db.sample.findOne() { "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" } The find_One() method of pymongo is used to retrieve a single document based on your query, in case of no matches this method returns nothing and if you doesn’t use any query it returns the first document of the collection. This method comes handy whenever you need to retrieve only one document of a result or, if you are sure that your query returns only one document. Following python example retrieve first document of a collection − from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['mydatabase'] #Creating a collection coll = db['example'] #Inserting document into a collection data = [ {"_id": "101", "name": "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "102", "name": "Rahim", "age": "27", "city": "Bangalore"}, {"_id": "103", "name": "Robert", "age": "28", "city": "Mumbai"} ] res = coll.insert_many(data) print("Data inserted ......") print(res.inserted_ids) #Retrieving the first record using the find_one() method print("First record of the collection: ") print(coll.find_one()) #Retrieving a record with is 103 using the find_one() method print("Record whose id is 103: ") print(coll.find_one({"_id": "103"})) Data inserted ...... ['101', '102', '103'] First record of the collection: {'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'} Record whose id is 103: {'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'} To get multiple documents in a single query (single call od find method), you can use the find() method of the pymongo. If haven’t passed any query, this returns all the documents of a collection and, if you have passed a query to this method, it returns all the matched documents. #Getting the database instance db = client['myDB'] #Creating a collection coll = db['example'] #Inserting document into a collection data = [ {"_id": "101", "name": "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "102", "name": "Rahim", "age": "27", "city": "Bangalore"}, {"_id": "103", "name": "Robert", "age": "28", "city": "Mumbai"} ] res = coll.insert_many(data) print("Data inserted ......") #Retrieving all the records using the find() method print("Records of the collection: ") for doc1 in coll.find(): print(doc1) #Retrieving records with age greater than 26 using the find() method print("Record whose age is more than 26: ") for doc2 in coll.find({"age":{"$gt":"26"}}): print(doc2) Data inserted ...... Records of the collection: {'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'} {'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'} {'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'} Record whose age is more than 26: {'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'} {'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'} While retrieving using find() method, you can filter the documents using the query object. You can pass the query specifying the condition for the required documents as a parameter to this method. Following is the list of operators used in the queries in MongoDB. Following example retrieves the document in a collection whose name is sarmista. from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['sdsegf'] #Creating a collection coll = db['example'] #Inserting document into a collection data = [ {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"}, {"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"}, {"_id": "1004", "name": "Romeo", "age": "25", "city": "Pune"}, {"_id": "1005", "name": "Sarmista", "age": "23", "city": "Delhi"}, {"_id": "1006", "name": "Rasajna", "age": "26", "city": "Chennai"} ] res = coll.insert_many(data) print("Data inserted ......") #Retrieving data print("Documents in the collection: ") for doc1 in coll.find({"name":"Sarmista"}): print(doc1) Data inserted ...... Documents in the collection: {'_id': '1005', 'name': 'Sarmista', 'age': '23', 'city': 'Delhi'} Following example retrieves the document in a collection whose age value is greater than 26. from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['ghhj'] #Creating a collection coll = db['example'] #Inserting document into a collection data = [ {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"}, {"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"}, {"_id": "1004", "name": "Romeo", "age": "25", "city": "Pune"}, {"_id": "1005", "name": "Sarmista", "age": "23", "city": "Delhi"}, {"_id": "1006", "name": "Rasajna", "age": "26", "city": "Chennai"} ] res = coll.insert_many(data) print("Data inserted ......") #Retrieving data print("Documents in the collection: ") for doc in coll.find({"age":{"$gt":"26"}}): print(doc) Data inserted ...... Documents in the collection: {'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'} {'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'} While retrieving the contents of a collection, you can sort and arrange them in ascending or descending orders using the sort() method. To this method, you can pass the field(s) and the sorting order which is 1 or -1. Where, 1 is for ascending order and -1 is descending order. Following is the syntax of the sort() method. >db.COLLECTION_NAME.find().sort({KEY:1}) Assume we have created a collection and inserted 5 documents into it as shown below − > use testDB switched to db testDB > db.createCollection("myColl") { "ok" : 1 } > data = [ ... {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"}, ... {"_id": "1002", "name": "Rahim", "age": 27, "city": "Bangalore"}, ... {"_id": "1003", "name": "Robert", "age": 28, "city": "Mumbai"}, ... {"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"}, ... {"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"}, ... {"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"} ] > db.sample.insert(data) BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 6, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] }) Following line retrieves all the documents of the collection which are sorted in ascending order based on age. > db.sample.find().sort({age:1}) { "_id" : "1005", "name" : "Sarmista", "age" : 23, "city" : "Delhi" } { "_id" : "1004", "name" : "Romeo", "age" : 25, "city" : "Pune" } { "_id" : "1006", "name" : "Rasajna", "age" : 26, "city" : "Chennai" } { "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" } { "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" } { "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" } To sort the results of a query in ascending or, descending order pymongo provides the sort() method. To this method, pass a number value representing the number of documents you need in the result. By default, this method sorts the documents in ascending order based on the specified field. If you need to sort in descending order pass -1 along with the field name − coll.find().sort("age",-1) Following example retrieves all the documents of a collection arranged according to the age values in ascending order − from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['b_mydb'] #Creating a collection coll = db['myColl'] #Inserting document into a collection data = [ {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"}, {"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"}, {"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"}, {"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"}, {"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"} ] res = coll.insert_many(data) print("Data inserted ......") #Retrieving first 3 documents using the find() and limit() methods print("List of documents (sorted in ascending order based on age): ") for doc1 in coll.find().sort("age"): print(doc1) Data inserted ...... List of documents (sorted in ascending order based on age): {'_id': '1005', 'name': 'Sarmista', 'age': 23, 'city': 'Delhi'} {'_id': '1004', 'name': 'Romeo', 'age': 25, 'city': 'Pune'} {'_id': '1006', 'name': 'Rasajna', 'age': 26, 'city': 'Chennai'} {'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'} {'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'} {'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'} You can delete documents in a collection using the remove() method of MongoDB. This method accepts two optional parameters − deletion criteria specifying the condition to delete documents. deletion criteria specifying the condition to delete documents. just one, if you pass true or 1 as second parameter, then only one document will be deleted. just one, if you pass true or 1 as second parameter, then only one document will be deleted. Following is the syntax of the remove() method − >db.COLLECTION_NAME.remove(DELLETION_CRITTERIA) Assume we have created a collection and inserted 5 documents into it as shown below − > use testDB switched to db testDB > db.createCollection("myColl") { "ok" : 1 } > data = [ ... {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"}, ... {"_id": "1002", "name": "Rahim", "age": 27, "city": "Bangalore"}, ... {"_id": "1003", "name": "Robert", "age": 28, "city": "Mumbai"}, ... {"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"}, ... {"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"}, ... {"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"} ] > db.sample.insert(data) BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 6, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] }) Following query deletes the document(s) of the collection which have name value as Sarmista. > db.sample.remove({"name": "Sarmista"}) WriteResult({ "nRemoved" : 1 }) > db.sample.find() { "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" } { "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" } { "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" } { "_id" : "1004", "name" : "Romeo", "age" : 25, "city" : "Pune" } { "_id" : "1006", "name" : "Rasajna", "age" : 26, "city" : "Chennai" } If you invoke remove() method without passing deletion criteria, all the documents in the collection will be deleted. > db.sample.remove({}) WriteResult({ "nRemoved" : 5 }) > db.sample.find() To delete documents from a collection of MangoDB, you can delete documents from a collections using the methods delete_one() and delete_many() methods. These methods accept a query object specifying the condition for deleting documents. The detele_one() method deletes a single document, in case of a match. If no query is specified this method deletes the first document in the collection. Following python example deletes the document in the collection which has id value as 1006. from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['lpaksgf'] #Creating a collection coll = db['example'] #Inserting document into a collection data = [ {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"}, {"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"}, {"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"}, {"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"}, {"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"} ] res = coll.insert_many(data) print("Data inserted ......") #Deleting one document coll.delete_one({"_id" : "1006"}) #Retrieving all the records using the find() method print("Documents in the collection after update operation: ") for doc2 in coll.find(): print(doc2) Data inserted ...... Documents in the collection after update operation: {'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'} {'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'} {'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'} {'_id': '1004', 'name': 'Romeo', 'age': 25, 'city': 'Pune'} {'_id': '1005', 'name': 'Sarmista', 'age': 23, 'city': 'Delhi'} Similarly, the delete_many() method of pymongo deletes all the documents that satisfies the specified condition. Following example deletes all the documents in the collection whose age value is greater than 26 − from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['sampleDB'] #Creating a collection coll = db['example'] #Inserting document into a collection data = [ {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"}, {"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"}, {"_id": "1004", "name": "Romeo", "age": "25", "city": "Pune"}, {"_id": "1005", "name": "Sarmista", "age": "23", "city": "Delhi"}, {"_id": "1006", "name": "Rasajna", "age": "26", "city": "Chennai"} ] res = coll.insert_many(data) print("Data inserted ......") #Deleting multiple documents coll.delete_many({"age":{"$gt":"26"}}) #Retrieving all the records using the find() method print("Documents in the collection after update operation: ") for doc2 in coll.find(): print(doc2) Data inserted ...... Documents in the collection after update operation: {'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'} {'_id': '1004', 'name': 'Romeo', 'age': '25', 'city': 'Pune'} {'_id': '1005', 'name': 'Sarmista', 'age': '23', 'city': 'Delhi'} {'_id': '1006', 'name': 'Rasajna', 'age': '26', 'city': 'Chennai'} If you invoke the delete_many() method without passing any query, this method deletes all the documents in the collection. coll.delete_many({}) You can delete collections using drop() method of MongoDB. Following is the syntax of drop() method − db.COLLECTION_NAME.drop() Following example drops collection with name sample − > show collections myColl sample > db.sample.drop() true > show collections myColl You can drop/delete a collection from the current database by invoking drop() method. from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['example2'] #Creating a collection col1 = db['collection'] col1.insert_one({"name": "Ram", "age": "26", "city": "Hyderabad"}) col2 = db['coll'] col2.insert_one({"name": "Rahim", "age": "27", "city": "Bangalore"}) col3 = db['myColl'] col3.insert_one({"name": "Robert", "age": "28", "city": "Mumbai"}) col4 = db['data'] col4.insert_one({"name": "Romeo", "age": "25", "city": "Pune"}) #List of collections print("List of collections:") collections = db.list_collection_names() for coll in collections: print(coll) #Dropping a collection col1.drop() col4.drop() print("List of collections after dropping two of them: ") #List of collections collections = db.list_collection_names() for coll in collections: print(coll) List of collections: coll data collection myColl List of collections after dropping two of them: coll myColl You can update the contents of an existing documents using the update() method or save() method. The update method modifies the existing document whereas the save method replaces the existing document with the new one. Following is the syntax of the update() and save() methods of MangoDB − >db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA) Or, db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA}) Assume we have created a collection in a database and inserted 3 records in it as shown below − > use testdatabase switched to db testdatabase > data = [ ... {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"}, ... {"_id": "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" }, ... {"_id": "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" } ] [ { "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" }, { "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" }, { "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" } ] > db.createCollection("sample") { "ok" : 1 } > db.sample.insert(data) Following method updates the city value of the document with id 1002. > db.sample.update({"_id":"1002"},{"$set":{"city":"Visakhapatnam"}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.sample.find() { "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" } { "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Visakhapatnam" } { "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" } Similarly you can replace the document with new data by saving it with same id using the save() method. > db.sample.save( { "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Vijayawada" } ) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.sample.find() { "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Vijayawada" } { "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Visakhapatnam" } { "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" } Similar to find_one() method which retrieves single document, the update_one() method of pymongo updates a single document. This method accepts a query specifying which document to update and the update operation. Following python example updates the location value of a document in a collection. from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['myDB'] #Creating a collection coll = db['example'] #Inserting document into a collection data = [ {"_id": "101", "name": "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "102", "name": "Rahim", "age": "27", "city": "Bangalore"}, {"_id": "103", "name": "Robert", "age": "28", "city": "Mumbai"} ] res = coll.insert_many(data) print("Data inserted ......") #Retrieving all the records using the find() method print("Documents in the collection: ") for doc1 in coll.find(): print(doc1) coll.update_one({"_id":"102"},{"$set":{"city":"Visakhapatnam"}}) #Retrieving all the records using the find() method print("Documents in the collection after update operation: ") for doc2 in coll.find(): print(doc2) Data inserted ...... Documents in the collection: {'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'} {'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'} {'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'} Documents in the collection after update operation: {'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'} {'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Visakhapatnam'} {'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'} Similarly, the update_many() method of pymongo updates all the documents that satisfies the specified condition. Following example updates the location value in all the documents in a collection (empty condition) − from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['myDB'] #Creating a collection coll = db['example'] #Inserting document into a collection data = [ {"_id": "101", "name": "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "102", "name": "Rahim", "age": "27", "city": "Bangalore"}, {"_id": "103", "name": "Robert", "age": "28", "city": "Mumbai"} ] res = coll.insert_many(data) print("Data inserted ......") #Retrieving all the records using the find() method print("Documents in the collection: ") for doc1 in coll.find(): print(doc1) coll.update_many({},{"$set":{"city":"Visakhapatnam"}}) #Retrieving all the records using the find() method print("Documents in the collection after update operation: ") for doc2 in coll.find(): print(doc2) Data inserted ...... Documents in the collection: {'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'} {'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'} {'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'} Documents in the collection after update operation: {'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Visakhapatnam'} {'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Visakhapatnam'} {'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Visakhapatnam'} While retrieving the contents of a collection you can limit the number of documents in the result using the limit() method. This method accepts a number value representing the number of documents you want in the result. Following is the syntax of the limit() method − >db.COLLECTION_NAME.find().limit(NUMBER) Assume we have created a collection and inserted 5 documents into it as shown below − > use testDB switched to db testDB > db.createCollection("sample") { "ok" : 1 } > data = [ ... {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"}, ... {"_id": "1002", "name": "Rahim", "age": 27, "city": "Bangalore"}, ... {"_id": "1003", "name": "Robert", "age": 28, "city": "Mumbai"}, ... {"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"}, ... {"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"}, ... {"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"} ] > db.sample.insert(data) BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 6, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] }) Following line retrieves the first 3 documents of the collection. > db.sample.find().limit(3) { "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" } { "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" } { "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" } To restrict the results of a query to a particular number of documents pymongo provides the limit() method. To this method pass a number value representing the number of documents you need in the result. Following example retrieves first three documents in a collection. from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['l'] #Creating a collection coll = db['myColl'] #Inserting document into a collection data = [ {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"}, {"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"}, {"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"}, {"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"}, {"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"} ] res = coll.insert_many(data) print("Data inserted ......") #Retrieving first 3 documents using the find() and limit() methods print("First 3 documents in the collection: ") for doc1 in coll.find().limit(3): print(doc1) Data inserted ...... First 3 documents in the collection: {'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'} {'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'} {'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'} 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 3328, "s": 3205, "text": "The Python standard for database interfaces is the Python DB-API. Most Python database interfaces adhere to this standard." }, { "code": null, "e": 3456, "s": 3328, "text": "You can choose the right database for your application. Python Database API supports a wide range of database servers such as −" }, { "code": null, "e": 3463, "s": 3456, "text": "GadFly" }, { "code": null, "e": 3468, "s": 3463, "text": "mSQL" }, { "code": null, "e": 3474, "s": 3468, "text": "MySQL" }, { "code": null, "e": 3485, "s": 3474, "text": "PostgreSQL" }, { "code": null, "e": 3511, "s": 3485, "text": "Microsoft SQL Server 2000" }, { "code": null, "e": 3520, "s": 3511, "text": "Informix" }, { "code": null, "e": 3530, "s": 3520, "text": "Interbase" }, { "code": null, "e": 3537, "s": 3530, "text": "Oracle" }, { "code": null, "e": 3544, "s": 3537, "text": "Sybase" }, { "code": null, "e": 3869, "s": 3544, "text": "Here is the list of available Python database interfaces: Python Database Interfaces and APIs. You must download a separate DB API module for each database you need to access. For example, if you need to access an Oracle database as well as a MySQL database, you must download both the Oracle and the MySQL database modules." }, { "code": null, "e": 4035, "s": 3869, "text": "MySQL Python/Connector is an interface for connecting to a MySQL database server from Python. It implements the Python Database API and is built on top of the MySQL." }, { "code": null, "e": 4293, "s": 4035, "text": "First of all, you need to make sure you have already installed python in your machine. To do so, open command prompt and type python in it and press Enter. If python is already installed in your system, this command will display its version as shown below −" }, { "code": null, "e": 4493, "s": 4293, "text": "C:\\Users\\Tutorialspoint>python\nPython 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>>\n" }, { "code": null, "e": 4658, "s": 4493, "text": "Now press ctrl+z and then Enter to get out of the python shell and create a folder (in which you intended to install Python-MySQL connector) named Python_MySQL as −" }, { "code": null, "e": 4716, "s": 4658, "text": ">>> ^Z\nC:\\Users\\Tutorialspoint>d:\nD:\\>mkdir Python_MySQL\n" }, { "code": null, "e": 4977, "s": 4716, "text": "PIP is a package manager in python using which you can install various modules/packages in Python. Therefore, to install Mysql-python mysql-connector-python you need to make sure that you have PIP installed in your computer and have its location added to path." }, { "code": null, "e": 5167, "s": 4977, "text": "You can do so, by executing the pip command. If you didn’t have PIP in your system or, if you haven’t added its location in the Path environment variable, you will get an error message as −" }, { "code": null, "e": 5280, "s": 5167, "text": "D:\\Python_MySQL>pip\n'pip' is not recognized as an internal or external command,\noperable program or batch file.\n" }, { "code": null, "e": 5407, "s": 5280, "text": "To install PIP, download the get-pip.py to the above created folder and, from command navigate it and install pip as follows −" }, { "code": null, "e": 6058, "s": 5407, "text": "D:\\>cd Python_MySQL\nD:\\Python_MySQL>python get-pip.py\nCollecting pip\nDownloading https://files.pythonhosted.org/packages/8d/07/f7d7ced2f97ca3098c16565efbe6b15fafcba53e8d9bdb431e09140514b0/pip-19.2.2-py2.py3-none-any.whl (1.4MB)\n|████████████████████████████████| 1.4MB 1.3MB/s\nCollecting wheel\nDownloading https://files.pythonhosted.org/packages/00/83/b4a77d044e78ad1a45610eb88f745be2fd2c6d658f9798a15e384b7d57c9/wheel-0.33.6-py2.py3-none-any.whl\nInstalling collected packages: pip, wheel\nConsider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.\nSuccessfully installed pip-19.2.2 wheel-0.33.6\n" }, { "code": null, "e": 6162, "s": 6058, "text": "Once you have Python and PIP installed, open command prompt and upgrade pip (optional) as shown below −" }, { "code": null, "e": 6581, "s": 6162, "text": "C:\\Users\\Tutorialspoint>python -m pip install --upgrade pip\nCollecting pip\nUsing cached https://files.pythonhosted.org/packages/8d/07/f7d7ced2f97ca3098c16565efbe6b15fafcba53e8d9bdb431e09140514b0/pip-19.2.2-py2.py3-none-any.whl\nPython Data Access\n4\nInstalling collected packages: pip\nFound existing installation: pip 19.0.3\nUninstalling pip-19.0.3:\nSuccessfully uninstalled pip-19.0.3\nSuccessfully installed pip-19.2.2\n" }, { "code": null, "e": 6658, "s": 6581, "text": "Then open command prompt in admin mode and install python MySQL connect as −" }, { "code": null, "e": 7653, "s": 6658, "text": "C:\\WINDOWS\\system32>pip install mysql-connector-python\nCollecting mysql-connector-python\nUsing cached https://files.pythonhosted.org/packages/99/74/f41182e6b7aadc62b038b6939dce784b7f9ec4f89e2ae14f9ba8190dc9ab/mysql_connector_python-8.0.17-py2.py3-none-any.whl\nCollecting protobuf>=3.0.0 (from mysql-connector-python)\nUsing cached https://files.pythonhosted.org/packages/09/0e/614766ea191e649216b87d331a4179338c623e08c0cca291bcf8638730ce/protobuf-3.9.1-cp37-cp37m-win32.whl\nCollecting six>=1.9 (from protobuf>=3.0.0->mysql-connector-python)\nUsing cached https://files.pythonhosted.org/packages/73/fb/00a976f728d0d1fecfe898238ce23f502a721c0ac0ecfedb80e0d88c64e9/six-1.12.0-py2.py3-none-any.whl\nRequirement already satisfied: setuptools in c:\\program files (x86)\\python37-32\\lib\\site-packages (from protobuf>=3.0.0->mysql-connector-python) (40.8.0)\nInstalling collected packages: six, protobuf, mysql-connector-python\nSuccessfully installed mysql-connector-python-8.0.17 protobuf-3.9.1 six-1.12.0\n" }, { "code": null, "e": 7748, "s": 7653, "text": "To verify the installation of the create a sample python script with the following line in it." }, { "code": null, "e": 7772, "s": 7748, "text": "import mysql.connector\n" }, { "code": null, "e": 7860, "s": 7772, "text": "If the installation is successful, when you execute it, you should not get any errors −" }, { "code": null, "e": 7909, "s": 7860, "text": "D:\\Python_MySQL>python test.py\nD:\\Python_MySQL>\n" }, { "code": null, "e": 7989, "s": 7909, "text": "Simply, if you need to install Python from scratch. Visit the Python Home Page." }, { "code": null, "e": 8165, "s": 7989, "text": "Click on the Downloads button, you will be redirected to the downloads page which provides links for latest version of python for various platforms choose one and download it." }, { "code": null, "e": 8306, "s": 8165, "text": "For instance, we have downloaded python-3.7.4.exe (for windows). Start the installation process by double-clicking the downloaded .exe file." }, { "code": null, "e": 8456, "s": 8306, "text": "Check the Add Python 3.7 to Path option and proceed with the installation. After completion of this process, python will be installed in your system." }, { "code": null, "e": 8557, "s": 8456, "text": "To connect with MySQL, (one way is to) open the MySQL command prompt in your system as shown below −" }, { "code": null, "e": 8683, "s": 8557, "text": "It asks for password here; you need to type the password you have set to the default user (root) at the time of installation." }, { "code": null, "e": 8762, "s": 8683, "text": "Then a connection is established with MySQL displaying the following message −" }, { "code": null, "e": 9201, "s": 8762, "text": "Welcome to the MySQL monitor. Commands end with ; or \\g.\nYour MySQL connection id is 4\nServer version: 5.7.12-log MySQL Community Server (GPL)\n\nCopyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.\n\nOracle is a registered trademark of Oracle Corporation and/or its\naffiliates. Other names may be trademarks of their respective\nowners.\n\nType 'help;' or '\\h' for help. Type '\\c' to clear the current input statement.\n" }, { "code": null, "e": 9294, "s": 9201, "text": "You can disconnect from the MySQL database any time using the exit command at mysql> prompt." }, { "code": null, "e": 9311, "s": 9294, "text": "mysql> exit\nBye\n" }, { "code": null, "e": 9383, "s": 9311, "text": "Before establishing connection to MySQL database using python, assume −" }, { "code": null, "e": 9431, "s": 9383, "text": "That we have created a database with name mydb." }, { "code": null, "e": 9479, "s": 9431, "text": "That we have created a database with name mydb." }, { "code": null, "e": 9569, "s": 9479, "text": "We have created a table EMPLOYEE with columns FIRST_NAME, LAST_NAME, AGE, SEX and INCOME." }, { "code": null, "e": 9659, "s": 9569, "text": "We have created a table EMPLOYEE with columns FIRST_NAME, LAST_NAME, AGE, SEX and INCOME." }, { "code": null, "e": 9750, "s": 9659, "text": "The credentials we are using to connect with MySQL are username: root, password: password." }, { "code": null, "e": 9841, "s": 9750, "text": "The credentials we are using to connect with MySQL are username: root, password: password." }, { "code": null, "e": 10058, "s": 9841, "text": "You can establish a connection using the connect() constructor. This accepts username, password, host and, name of the database you need to connect with (optional) and, returns an object of the MySQLConnection class." }, { "code": null, "e": 10125, "s": 10058, "text": "Following is the example of connecting with MySQL database \"mydb\"." }, { "code": null, "e": 10599, "s": 10125, "text": "import mysql.connector\n\n#establishing the connection\nconn = mysql.connector.connect(user='root', password='password', host='127.0.0.1', database='mydb')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Executing an MYSQL function using the execute() method\ncursor.execute(\"SELECT DATABASE()\")\n\n# Fetch a single row using fetchone() method.\ndata = cursor.fetchone()\nprint(\"Connection established to: \",data)\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 10657, "s": 10599, "text": "On executing, this script produces the following output −" }, { "code": null, "e": 10734, "s": 10657, "text": "D:\\Python_MySQL>python EstablishCon.py\nConnection established to: ('mydb',)\n" }, { "code": null, "e": 10900, "s": 10734, "text": "You can also establish connection to MySQL by passing credentials (user name, password, hostname, and database name) to connection.MySQLConnection() as shown below −" }, { "code": null, "e": 11113, "s": 10900, "text": "from mysql.connector import (connection)\n\n#establishing the connection\nconn = connection.MySQLConnection(user='root', password='password', host='127.0.0.1', database='mydb')\n\n#Closing the connection\nconn.close()\n" }, { "code": null, "e": 11181, "s": 11113, "text": "You can create a database in MYSQL using the CREATE DATABASE query." }, { "code": null, "e": 11236, "s": 11181, "text": "Following is the syntax of the CREATE DATABASE query −" }, { "code": null, "e": 11274, "s": 11236, "text": "CREATE DATABASE name_of_the_database\n" }, { "code": null, "e": 11339, "s": 11274, "text": "Following statement creates a database with name mydb in MySQL −" }, { "code": null, "e": 11405, "s": 11339, "text": "mysql> CREATE DATABASE mydb;\nQuery OK, 1 row affected (0.04 sec)\n" }, { "code": null, "e": 11544, "s": 11405, "text": "If you observe the list of databases using the SHOW DATABASES statement, you can observe the newly created database in it as shown below −" }, { "code": null, "e": 11847, "s": 11544, "text": "mysql> SHOW DATABASES;\n+--------------------+\n| Database |\n+--------------------+\n| information_schema |\n| logging |\n| mydatabase |\n| mydb |\n| performance_schema |\n| students |\n| sys |\n+--------------------+\n26 rows in set (0.15 sec)\n" }, { "code": null, "e": 12010, "s": 11847, "text": "After establishing connection with MySQL, to manipulate data in it you need to connect to a database. You can connect to an existing database or, create your own." }, { "code": null, "e": 12154, "s": 12010, "text": "You would need special privileges to create or to delete a MySQL database. So if you have access to the root user, you can create any database." }, { "code": null, "e": 12236, "s": 12154, "text": "Following example establishes connection with MYSQL and creates a database in it." }, { "code": null, "e": 12826, "s": 12236, "text": "import mysql.connector\n\n#establishing the connection\nconn = mysql.connector.connect(user='root', password='password', host='127.0.0.1')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Doping database MYDATABASE if already exists.\ncursor.execute(\"DROP database IF EXISTS MyDatabase\")\n\n#Preparing query to create a database\nsql = \"CREATE database MYDATABASE\";\n\n#Creating a database\ncursor.execute(sql)\n\n#Retrieving the list of databases\nprint(\"List of databases: \")\ncursor.execute(\"SHOW DATABASES\")\nprint(cursor.fetchall())\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 12989, "s": 12826, "text": "List of databases:\n[('information_schema',), ('dbbug61332',), ('details',), ('exampledatabase',), ('mydatabase',), ('mydb',), ('mysql',), ('performance_schema',)]" }, { "code": null, "e": 13160, "s": 12989, "text": "The CREATE TABLE statement is used to create tables in MYSQL database. Here, you need to specify the name of the table and, definition (name and datatype) of each column." }, { "code": null, "e": 13213, "s": 13160, "text": "Following is the syntax to create a table in MySQL −" }, { "code": null, "e": 13334, "s": 13213, "text": "CREATE TABLE table_name(\n column1 datatype,\n column2 datatype,\n column3 datatype,\n .....\n columnN datatype,\n);" }, { "code": null, "e": 13461, "s": 13334, "text": "Following query creates a table named EMPLOYEE in MySQL with five columns namely, FIRST_NAME, LAST_NAME, AGE, SEX and, INCOME." }, { "code": null, "e": 13631, "s": 13461, "text": "mysql> CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT,\n SEX CHAR(1),\n INCOME FLOAT\n);\nQuery OK, 0 rows affected (0.42 sec)" }, { "code": null, "e": 13780, "s": 13631, "text": "The DESC statement gives you the description of the specified table. Using this you can verify if the table has been created or not as shown below −" }, { "code": null, "e": 14341, "s": 13780, "text": "mysql> Desc Employee;\n+------------+----------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+------------+----------+------+-----+---------+-------+\n| FIRST_NAME | char(20) | NO | | NULL | |\n| LAST_NAME | char(20) | YES | | NULL | |\n| AGE | int(11) | YES | | NULL | |\n| SEX | char(1) | YES | | NULL | |\n| INCOME | float | YES | | NULL | |\n+------------+----------+------+-----+---------+-------+\n5 rows in set (0.07 sec)\n" }, { "code": null, "e": 14423, "s": 14341, "text": "The method named execute() (invoked on the cursor object) accepts two variables −" }, { "code": null, "e": 14477, "s": 14423, "text": "A String value representing the query to be executed." }, { "code": null, "e": 14531, "s": 14477, "text": "A String value representing the query to be executed." }, { "code": null, "e": 14676, "s": 14531, "text": "An optional args parameter which can be a tuple or, list or, dictionary, representing the parameters of the query (values of the place holders)." }, { "code": null, "e": 14821, "s": 14676, "text": "An optional args parameter which can be a tuple or, list or, dictionary, representing the parameters of the query (values of the place holders)." }, { "code": null, "e": 14904, "s": 14821, "text": "It returns an integer value representing the number of rows effected by the query." }, { "code": null, "e": 15028, "s": 14904, "text": "Once a database connection is established, you can create tables by passing the CREATE TABLE query to the execute() method." }, { "code": null, "e": 15077, "s": 15028, "text": "In short, to create a table using python 7minus;" }, { "code": null, "e": 15109, "s": 15077, "text": "Import mysql.connector package." }, { "code": null, "e": 15141, "s": 15109, "text": "Import mysql.connector package." }, { "code": null, "e": 15329, "s": 15141, "text": "Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it." }, { "code": null, "e": 15517, "s": 15329, "text": "Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it." }, { "code": null, "e": 15612, "s": 15517, "text": "Create a cursor object by invoking the cursor() method on the connection object created above." }, { "code": null, "e": 15707, "s": 15612, "text": "Create a cursor object by invoking the cursor() method on the connection object created above." }, { "code": null, "e": 15802, "s": 15707, "text": "Then, execute the CREATE TABLE statement by passing it as a parameter to the execute() method." }, { "code": null, "e": 15897, "s": 15802, "text": "Then, execute the CREATE TABLE statement by passing it as a parameter to the execute() method." }, { "code": null, "e": 15968, "s": 15897, "text": "Following example creates a table named Employee in the database mydb." }, { "code": null, "e": 16525, "s": 15968, "text": "import mysql.connector\n\n#establishing the connection\nconn = mysql.connector.connect(\n user='root', password='password', host='127.0.0.1', database='mydb'\n)\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Dropping EMPLOYEE table if already exists.\ncursor.execute(\"DROP TABLE IF EXISTS EMPLOYEE\")\n\n#Creating table as per requirement\nsql ='''CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT,\n SEX CHAR(1),\n INCOME FLOAT\n)'''\ncursor.execute(sql)\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 16723, "s": 16525, "text": "You can add new rows to an existing table of MySQL using the INSERT INTO statement. In this, you need to specify the name of the table, column names, and values (in the same order as column names)." }, { "code": null, "e": 16786, "s": 16723, "text": "Following is the syntax of the INSERT INTO statement of MySQL." }, { "code": null, "e": 16891, "s": 16786, "text": "INSERT INTO TABLE_NAME (column1, column2,column3,...columnN)\nVALUES (value1, value2, value3,...valueN);\n" }, { "code": null, "e": 16955, "s": 16891, "text": "Following query inserts a record into the table named EMPLOYEE." }, { "code": null, "e": 17063, "s": 16955, "text": "INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('\n Mac', 'Mohan', 20, 'M', 2000\n);\n" }, { "code": null, "e": 17158, "s": 17063, "text": "You can verify the records of the table after insert operation using the SELECT statement as −" }, { "code": null, "e": 17465, "s": 17158, "text": "mysql> select * from Employee;\n+------------+-----------+------+------+--------+\n| FIRST_NAME | LAST_NAME | AGE | SEX | INCOME |\n+------------+-----------+------+------+--------+\n| Mac | Mohan | 20 | M | 2000 | \n+------------+-----------+------+------+--------+\n1 row in set (0.00 sec)\n" }, { "code": null, "e": 17681, "s": 17465, "text": "It is not mandatory to specify the names of the columns always, if you pass values of a record in the same order of the columns of the table you can execute the SELECT statement without the column names as follows −" }, { "code": null, "e": 17743, "s": 17681, "text": "INSERT INTO EMPLOYEE VALUES ('Mac', 'Mohan', 20, 'M', 2000);\n" }, { "code": null, "e": 17936, "s": 17743, "text": "The execute() method (invoked on the cursor object) accepts a query as parameter and executes the given query. To insert data, you need to pass the MySQL INSERT statement as a parameter to it." }, { "code": null, "e": 18064, "s": 17936, "text": "cursor.execute(\"\"\"INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) \n VALUES ('Mac', 'Mohan', 20, 'M', 2000)\"\"\")\n" }, { "code": null, "e": 18116, "s": 18064, "text": "To insert data into a table in MySQL using python −" }, { "code": null, "e": 18148, "s": 18116, "text": "import mysql.connector package." }, { "code": null, "e": 18180, "s": 18148, "text": "import mysql.connector package." }, { "code": null, "e": 18368, "s": 18180, "text": "Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it." }, { "code": null, "e": 18556, "s": 18368, "text": "Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it." }, { "code": null, "e": 18650, "s": 18556, "text": "Create a cursor object by invoking the cursor() method on the connection object created above" }, { "code": null, "e": 18744, "s": 18650, "text": "Create a cursor object by invoking the cursor() method on the connection object created above" }, { "code": null, "e": 18833, "s": 18744, "text": "Then, execute the INSERT statement by passing it as a parameter to the execute() method." }, { "code": null, "e": 18922, "s": 18833, "text": "Then, execute the INSERT statement by passing it as a parameter to the execute() method." }, { "code": null, "e": 19019, "s": 18922, "text": "The following example executes SQL INSERT statement to insert a record into the EMPLOYEE table −" }, { "code": null, "e": 19654, "s": 19019, "text": "import mysql.connector\n\n#establishing the connection\nconn = mysql.connector.connect(\n user='root', password='password', host='127.0.0.1', database='mydb')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n# Preparing SQL query to INSERT a record into the database.\nsql = \"\"\"INSERT INTO EMPLOYEE(\n FIRST_NAME, LAST_NAME, AGE, SEX, INCOME)\n VALUES ('Mac', 'Mohan', 20, 'M', 2000)\"\"\"\n\ntry:\n # Executing the SQL command\n cursor.execute(sql)\n\n # Commit your changes in the database\n conn.commit()\n\nexcept:\n # Rolling back in case of error\n conn.rollback()\n\n# Closing the connection\nconn.close()" }, { "code": null, "e": 19773, "s": 19654, "text": "You can also use “%s” instead of values in the INSERT query of MySQL and pass values to them as lists as shown below −" }, { "code": null, "e": 19899, "s": 19773, "text": "cursor.execute(\"\"\"INSERT INTO EMPLOYEE VALUES ('Mac', 'Mohan', 20, 'M', 2000)\"\"\", \n ('Ramya', 'Ramapriya', 25, 'F', 5000))\n" }, { "code": null, "e": 19971, "s": 19899, "text": "Following example inserts a record into the Employee table dynamically." }, { "code": null, "e": 20690, "s": 19971, "text": "import mysql.connector\n\n#establishing the connection\nconn = mysql.connector.connect(\n user='root', password='password', host='127.0.0.1', database='mydb')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n# Preparing SQL query to INSERT a record into the database.\ninsert_stmt = (\n \"INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME)\"\n \"VALUES (%s, %s, %s, %s, %s)\"\n)\ndata = ('Ramya', 'Ramapriya', 25, 'F', 5000)\n\ntry:\n # Executing the SQL command\n cursor.execute(insert_stmt, data)\n \n # Commit your changes in the database\n conn.commit()\n\nexcept:\n # Rolling back in case of error\n conn.rollback()\n\nprint(\"Data inserted\")\n\n# Closing the connection\nconn.close()" }, { "code": null, "e": 20705, "s": 20690, "text": "Data inserted\n" }, { "code": null, "e": 20888, "s": 20705, "text": "You can retrieve/fetch data from a table in MySQL using the SELECT query. This query/statement returns contents of the specified table in tabular form and it is called as result-set." }, { "code": null, "e": 20934, "s": 20888, "text": "Following is the syntax of the SELECT query −" }, { "code": null, "e": 20985, "s": 20934, "text": "SELECT column1, column2, columnN FROM table_name;\n" }, { "code": null, "e": 21056, "s": 20985, "text": "Assume we have created a table in MySQL with name cricketers_data as −" }, { "code": null, "e": 21224, "s": 21056, "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);\n" }, { "code": null, "e": 21296, "s": 21224, "text": "And if we have inserted 5 records in to it using INSERT statements as −" }, { "code": null, "e": 21803, "s": 21296, "text": "insert into cricketers_data values(\n 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');\ninsert into cricketers_data values(\n 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');\ninsert into cricketers_data values(\n 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');\ninsert into cricketers_data values(\n 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');\ninsert into cricketers_data values(\n 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');" }, { "code": null, "e": 21879, "s": 21803, "text": "Following query retrieves the FIRST_NAME and Country values from the table." }, { "code": null, "e": 22222, "s": 21879, "text": "mysql> select FIRST_NAME, Country from cricketers_data;\n+------------+-------------+\n| FIRST_NAME | Country |\n+------------+-------------+\n| Shikhar | India |\n| Jonathan | SouthAfrica |\n| Kumara | Srilanka |\n| Virat | India |\n| Rohit | India |\n+------------+-------------+\n5 rows in set (0.00 sec)\n" }, { "code": null, "e": 22323, "s": 22222, "text": "You can also retrieve all the values of each record using * instated of the name of the columns as −" }, { "code": null, "e": 23062, "s": 22323, "text": "mysql> SELECT * from cricketers_data;\n+------------+------------+---------------+----------------+-------------+\n| First_Name | Last_Name | Date_Of_Birth | Place_Of_Birth | Country |\n+------------+------------+---------------+----------------+-------------+\n| Shikhar | Dhawan | 1981-12-05 | Delhi | India |\n| Jonathan | Trott | 1981-04-22 | CapeTown | SouthAfrica |\n| Kumara | Sangakkara | 1977-10-27 | Matale | Srilanka |\n| Virat | Kohli | 1988-11-05 | Delhi | India |\n| Rohit | Sharma | 1987-04-30 | Nagpur | India |\n+------------+------------+---------------+----------------+-------------+\n5 rows in set (0.00 sec)\n" }, { "code": null, "e": 23246, "s": 23062, "text": "READ Operation on any database means to fetch some useful information from the database. You can fetch data from MYSQL using the fetch() method provided by the mysql-connector-python." }, { "code": null, "e": 23352, "s": 23246, "text": "The cursor.MySQLCursor class provides three methods namely fetchall(), fetchmany() and, fetchone() where," }, { "code": null, "e": 23540, "s": 23352, "text": "The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows it returns the remaining ones)." }, { "code": null, "e": 23728, "s": 23540, "text": "The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows it returns the remaining ones)." }, { "code": null, "e": 23823, "s": 23728, "text": "The fetchone() method fetches the next row in the result of a query and returns it as a tuple." }, { "code": null, "e": 23918, "s": 23823, "text": "The fetchone() method fetches the next row in the result of a query and returns it as a tuple." }, { "code": null, "e": 24064, "s": 23918, "text": "The fetchmany() method is similar to the fetchone() but, it retrieves the next set of rows in the result set of a query, instead of a single row." }, { "code": null, "e": 24210, "s": 24064, "text": "The fetchmany() method is similar to the fetchone() but, it retrieves the next set of rows in the result set of a query, instead of a single row." }, { "code": null, "e": 24307, "s": 24210, "text": "Note − A result set is an object that is returned when a cursor object is used to query a table." }, { "code": null, "e": 24422, "s": 24307, "text": "rowcount − This is a read-only attribute and returns the number of rows that were affected by an execute() method." }, { "code": null, "e": 24676, "s": 24422, "text": "Following example fetches all the rows of the EMPLOYEE table using the SELECT query and from the obtained result set initially, we are retrieving the first row using the fetchone() method and then fetching the remaining rows using the fetchall() method." }, { "code": null, "e": 25200, "s": 24676, "text": "import mysql.connector\n\n#establishing the connection\nconn = mysql.connector.connect(\n user='root', password='password', host='127.0.0.1', database='mydb')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Retrieving single row\nsql = '''SELECT * from EMPLOYEE'''\n\n#Executing the query\ncursor.execute(sql)\n\n#Fetching 1st row from the table\nresult = cursor.fetchone();\nprint(result)\n\n#Fetching 1st row from the table\nresult = cursor.fetchall();\nprint(result)\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 25321, "s": 25200, "text": "('Krishna', 'Sharma', 19, 'M', 2000.0)\n[('Raj', 'Kandukuri', 20, 'M', 7000.0), ('Ramya', 'Ramapriya', 25, 'M', 5000.0)]\n" }, { "code": null, "e": 25416, "s": 25321, "text": "Following example retrieves first two rows of the EMPLOYEE table using the fetchmany() method." }, { "code": null, "e": 25872, "s": 25416, "text": "import mysql.connector\n\n#establishing the connection\nconn = mysql.connector.connect(\n user='root', password='password', host='127.0.0.1', database='mydb')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Retrieving single row\nsql = '''SELECT * from EMPLOYEE'''\n\n#Executing the query\ncursor.execute(sql)\n\n#Fetching 1st row from the table\nresult = cursor.fetchmany(size =2);\nprint(result)\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 25953, "s": 25872, "text": "[('Krishna', 'Sharma', 19, 'M', 2000.0), ('Raj', 'Kandukuri', 20, 'M', 7000.0)]\n" }, { "code": null, "e": 26135, "s": 25953, "text": "If you want to fetch, delete or, update particular rows of a table in MySQL, you need to use the where clause to specify condition to filter the rows of the table for the operation." }, { "code": null, "e": 26271, "s": 26135, "text": "For example, if you have a SELECT statement with where clause, only the rows which satisfies the specified condition will be retrieved." }, { "code": null, "e": 26317, "s": 26271, "text": "Following is the syntax of the WHERE clause −" }, { "code": null, "e": 26385, "s": 26317, "text": "SELECT column1, column2, columnN\nFROM table_name\nWHERE [condition]\n" }, { "code": null, "e": 26450, "s": 26385, "text": "Assume we have created a table in MySQL with name EMPLOYEES as −" }, { "code": null, "e": 26620, "s": 26450, "text": "mysql> CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT,\n SEX CHAR(1),\n INCOME FLOAT\n);\nQuery OK, 0 rows affected (0.36 sec)" }, { "code": null, "e": 26692, "s": 26620, "text": "And if we have inserted 4 records in to it using INSERT statements as −" }, { "code": null, "e": 26886, "s": 26692, "text": "mysql> INSERT INTO EMPLOYEE VALUES\n ('Krishna', 'Sharma', 19, 'M', 2000),\n ('Raj', 'Kandukuri', 20, 'M', 7000),\n ('Ramya', 'Ramapriya', 25, 'F', 5000),\n ('Mac', 'Mohan', 26, 'M', 2000);" }, { "code": null, "e": 26986, "s": 26886, "text": "Following MySQL statement retrieves the records of the employees whose income is greater than 4000." }, { "code": null, "e": 27363, "s": 26986, "text": "mysql> SELECT * FROM EMPLOYEE WHERE INCOME > 4000;\n+------------+-----------+------+------+--------+\n| FIRST_NAME | LAST_NAME | AGE | SEX | INCOME |\n+------------+-----------+------+------+--------+\n| Raj | Kandukuri | 20 | M | 7000 |\n| Ramya | Ramapriya | 25 | F | 5000 |\n+------------+-----------+------+------+--------+\n2 rows in set (0.00 sec)\n" }, { "code": null, "e": 27429, "s": 27363, "text": "To fetch specific records from a table using the python program −" }, { "code": null, "e": 27461, "s": 27429, "text": "import mysql.connector package." }, { "code": null, "e": 27493, "s": 27461, "text": "import mysql.connector package." }, { "code": null, "e": 27681, "s": 27493, "text": "Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it." }, { "code": null, "e": 27869, "s": 27681, "text": "Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it." }, { "code": null, "e": 27964, "s": 27869, "text": "Create a cursor object by invoking the cursor() method on the connection object created above." }, { "code": null, "e": 28059, "s": 27964, "text": "Create a cursor object by invoking the cursor() method on the connection object created above." }, { "code": null, "e": 28167, "s": 28059, "text": "Then, execute the SELECT statement with WHERE clause, by passing it as a parameter to the execute() method." }, { "code": null, "e": 28275, "s": 28167, "text": "Then, execute the SELECT statement with WHERE clause, by passing it as a parameter to the execute() method." }, { "code": null, "e": 28424, "s": 28275, "text": "Following example creates a table named Employee and populates it. Then using the where clause it retrieves the records with age value less than 23." }, { "code": null, "e": 29417, "s": 28424, "text": "import mysql.connector\n\n#establishing the connection\nconn = mysql.connector.connect(\n user='root', password='password', host='127.0.0.1', database='mydb')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Doping EMPLOYEE table if already exists.\ncursor.execute(\"DROP TABLE IF EXISTS EMPLOYEE\")\nsql = '''CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT,\n SEX CHAR(1),\n INCOME FLOAT\n)'''\ncursor.execute(sql)\n\n#Populating the table\ninsert_stmt = \"INSERT INTO EMPLOYEE (FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) \n VALUES (%s, %s, %s, %s, %s)\"\n\ndata = [('Krishna', 'Sharma', 19, 'M', 2000), ('Raj', 'Kandukuri', 20, 'M', 7000),\n('Ramya', 'Ramapriya', 25, 'F', 5000),('Mac', 'Mohan', 26, 'M', 2000)]\ncursor.executemany(insert_stmt, data)\nconn.commit()\n\n#Retrieving specific records using the where clause\ncursor.execute(\"SELECT * from EMPLOYEE WHERE AGE <23\")\nprint(cursor.fetchall())\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 29498, "s": 29417, "text": "[('Krishna', 'Sharma', 19, 'M', 2000.0), ('Raj', 'Kandukuri', 20, 'M', 7000.0)]\n" }, { "code": null, "e": 29773, "s": 29498, "text": "While fetching data using SELECT query, you can sort the results in desired order (ascending or descending) using the OrderBy clause. By default, this clause sorts results in ascending order, if you need to arrange them in descending order you need to use “DESC” explicitly." }, { "code": null, "e": 29816, "s": 29773, "text": "Following is the syntax SELECT column-list" }, { "code": null, "e": 29928, "s": 29816, "text": "FROM table_name\n[WHERE condition]\n[ORDER BY column1, column2,.. columnN] [ASC | DESC]; of the ORDER BY clause:\n" }, { "code": null, "e": 29993, "s": 29928, "text": "Assume we have created a table in MySQL with name EMPLOYEES as −" }, { "code": null, "e": 30163, "s": 29993, "text": "mysql> CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT,\n SEX CHAR(1),\n INCOME FLOAT\n);\nQuery OK, 0 rows affected (0.36 sec)" }, { "code": null, "e": 30235, "s": 30163, "text": "And if we have inserted 4 records in to it using INSERT statements as −" }, { "code": null, "e": 30430, "s": 30235, "text": "mysql> INSERT INTO EMPLOYEE VALUES\n ('Krishna', 'Sharma', 19, 'M', 2000),\n ('Raj', 'Kandukuri', 20, 'M', 7000),\n ('Ramya', 'Ramapriya', 25, 'F', 5000),\n ('Mac', 'Mohan', 26, 'M', 2000);\n" }, { "code": null, "e": 30526, "s": 30430, "text": "Following statement retrieves the contents of the EMPLOYEE table in ascending order of the age." }, { "code": null, "e": 30996, "s": 30526, "text": "mysql> SELECT * FROM EMPLOYEE ORDER BY AGE;\n+------------+-----------+------+------+--------+\n| FIRST_NAME | LAST_NAME | AGE | SEX | INCOME |\n+------------+-----------+------+------+--------+\n| Krishna | Sharma | 19 | M | 2000 |\n| Raj | Kandukuri | 20 | M | 7000 |\n| Ramya | Ramapriya | 25 | F | 5000 |\n| Mac | Mohan | 26 | M | 2000 |\n+------------+-----------+------+------+--------+\n4 rows in set (0.04 sec)\n" }, { "code": null, "e": 31059, "s": 30996, "text": "You can also retrieve data in descending order using DESC as −" }, { "code": null, "e": 31549, "s": 31059, "text": "mysql> SELECT * FROM EMPLOYEE ORDER BY FIRST_NAME, INCOME DESC;\n+------------+-----------+------+------+--------+\n| FIRST_NAME | LAST_NAME | AGE | SEX | INCOME |\n+------------+-----------+------+------+--------+\n| Krishna | Sharma | 19 | M | 2000 |\n| Mac | Mohan | 26 | M | 2000 |\n| Raj | Kandukuri | 20 | M | 7000 |\n| Ramya | Ramapriya | 25 | F | 5000 |\n+------------+-----------+------+------+--------+\n4 rows in set (0.00 sec)\n" }, { "code": null, "e": 31730, "s": 31549, "text": "To retrieve contents of a table in specific order, invoke the execute() method on the cursor object and, pass the SELECT statement along with ORDER BY clause, as a parameter to it." }, { "code": null, "e": 31916, "s": 31730, "text": "In the following example we are creating a table with name and Employee, populating it, and retrieving its records back in the (ascending) order of their age, using the ORDER BY clause." }, { "code": null, "e": 32922, "s": 31916, "text": "import mysql.connector\n\n#establishing the connection\nconn = mysql.connector.connect(\n user='root', password='password', host='127.0.0.1', database='mydb')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Doping EMPLOYEE table if already exists.\ncursor.execute(\"DROP TABLE IF EXISTS EMPLOYEE\")\nsql = '''CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT,\n SEX CHAR(1),\n INCOME FLOAT\n)'''\ncursor.execute(sql)\n\n#Populating the table\ninsert_stmt = \"INSERT INTO EMPLOYEE (FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) \n VALUES (%s, %s, %s, %s, %s)\"\n\ndata = [('Krishna', 'Sharma', 26, 'M', 2000), \n ('Raj', 'Kandukuri', 20, 'M', 7000),\n ('Ramya', 'Ramapriya', 29, 'F', 5000),\n ('Mac', 'Mohan', 26, 'M', 2000)]\ncursor.executemany(insert_stmt, data)\nconn.commit()\n\n#Retrieving specific records using the ORDER BY clause\ncursor.execute(\"SELECT * from EMPLOYEE ORDER BY AGE\")\nprint(cursor.fetchall())\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 33092, "s": 32922, "text": "[('Raj', 'Kandukuri', 20, 'M', 7000.0), \n ('Krishna', 'Sharma', 26, 'M', 2000.0), \n ('Mac', 'Mohan', 26, 'M', 2000.0), \n ('Ramya', 'Ramapriya', 29, 'F', 5000.0)\n]\n" }, { "code": null, "e": 33190, "s": 33092, "text": "In the same way you can retrieve data from a table in descending order using the ORDER BY clause." }, { "code": null, "e": 33603, "s": 33190, "text": "import mysql.connector\n\n#establishing the connection\nconn = mysql.connector.connect(\n user='root', password='password', host='127.0.0.1', database='mydb')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Retrieving specific records using the ORDERBY clause\ncursor.execute(\"SELECT * from EMPLOYEE ORDER BY INCOME DESC\")\nprint(cursor.fetchall())\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 33773, "s": 33603, "text": "[('Raj', 'Kandukuri', 20, 'M', 7000.0), \n ('Ramya', 'Ramapriya', 29, 'F', 5000.0), \n ('Krishna', 'Sharma', 26, 'M', 2000.0), \n ('Mac', 'Mohan', 26, 'M', 2000.0)\n]\n" }, { "code": null, "e": 34036, "s": 33773, "text": "UPDATE Operation on any database updates one or more records, which are already available in the database. You can update the values of existing records in MySQL using the UPDATE statement. To update specific rows, you need to use the WHERE clause along with it." }, { "code": null, "e": 34095, "s": 34036, "text": "Following is the syntax of the UPDATE statement in MySQL −" }, { "code": null, "e": 34194, "s": 34095, "text": "UPDATE table_name\nSET column1 = value1, column2 = value2...., columnN = valueN\nWHERE [condition];\n" }, { "code": null, "e": 34268, "s": 34194, "text": "You can combine N number of conditions using the AND or the OR operators." }, { "code": null, "e": 34333, "s": 34268, "text": "Assume we have created a table in MySQL with name EMPLOYEES as −" }, { "code": null, "e": 34503, "s": 34333, "text": "mysql> CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT,\n SEX CHAR(1),\n INCOME FLOAT\n);\nQuery OK, 0 rows affected (0.36 sec)" }, { "code": null, "e": 34575, "s": 34503, "text": "And if we have inserted 4 records in to it using INSERT statements as −" }, { "code": null, "e": 34770, "s": 34575, "text": "mysql> INSERT INTO EMPLOYEE VALUES\n ('Krishna', 'Sharma', 19, 'M', 2000),\n ('Raj', 'Kandukuri', 20, 'M', 7000),\n ('Ramya', 'Ramapriya', 25, 'F', 5000),\n ('Mac', 'Mohan', 26, 'M', 2000);\n" }, { "code": null, "e": 34850, "s": 34770, "text": "Following MySQL statement increases the age of all male employees by one year −" }, { "code": null, "e": 34985, "s": 34850, "text": "mysql> UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = 'M';\nQuery OK, 3 rows affected (0.06 sec)\nRows matched: 3 Changed: 3 Warnings: 0\n" }, { "code": null, "e": 35064, "s": 34985, "text": "If you retrieve the contents of the table, you can see the updated values as −" }, { "code": null, "e": 35521, "s": 35064, "text": "mysql> select * from EMPLOYEE;\n+------------+-----------+------+------+--------+\n| FIRST_NAME | LAST_NAME | AGE | SEX | INCOME |\n+------------+-----------+------+------+--------+\n| Krishna | Sharma | 20 | M | 2000 |\n| Raj | Kandukuri | 21 | M | 7000 |\n| Ramya | Ramapriya | 25 | F | 5000 |\n| Mac | Mohan | 27 | M | 2000 |\n+------------+-----------+------+------+--------+\n4 rows in set (0.00 sec)\n" }, { "code": null, "e": 35578, "s": 35521, "text": "To update the records in a table in MySQL using python −" }, { "code": null, "e": 35610, "s": 35578, "text": "import mysql.connector package." }, { "code": null, "e": 35642, "s": 35610, "text": "import mysql.connector package." }, { "code": null, "e": 35830, "s": 35642, "text": "Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it." }, { "code": null, "e": 36018, "s": 35830, "text": "Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it." }, { "code": null, "e": 36113, "s": 36018, "text": "Create a cursor object by invoking the cursor() method on the connection object created above." }, { "code": null, "e": 36208, "s": 36113, "text": "Create a cursor object by invoking the cursor() method on the connection object created above." }, { "code": null, "e": 36297, "s": 36208, "text": "Then, execute the UPDATE statement by passing it as a parameter to the execute() method." }, { "code": null, "e": 36386, "s": 36297, "text": "Then, execute the UPDATE statement by passing it as a parameter to the execute() method." }, { "code": null, "e": 36452, "s": 36386, "text": "The following example increases age of all the males by one year." }, { "code": null, "e": 37164, "s": 36452, "text": "import mysql.connector\n\n#establishing the connection\nconn = mysql.connector.connect(\n user='root', password='password', host='127.0.0.1', database='mydb')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Preparing the query to update the records\nsql = '''UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = 'M' '''\ntry:\n # Execute the SQL command\n cursor.execute(sql)\n \n # Commit your changes in the database\n conn.commit()\nexcept:\n # Rollback in case there is any error\n conn.rollback()\n \n#Retrieving data\nsql = '''SELECT * from EMPLOYEE'''\n\n#Executing the query\ncursor.execute(sql)\n\n#Displaying the result\nprint(cursor.fetchall())\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 37295, "s": 37164, "text": "[('Krishna', 'Sharma', 22, 'M', 2000.0), \n ('Raj', 'Kandukuri', 23, 'M', 7000.0), \n ('Ramya', 'Ramapriya', 26, 'F', 5000.0)\n]\n" }, { "code": null, "e": 37448, "s": 37295, "text": "To delete records from a MySQL table, you need to use the DELETE FROM statement. To remove specific records, you need to use WHERE clause along with it." }, { "code": null, "e": 37503, "s": 37448, "text": "Following is the syntax of the DELETE query in MYSQL −" }, { "code": null, "e": 37542, "s": 37503, "text": "DELETE FROM table_name [WHERE Clause]\n" }, { "code": null, "e": 37607, "s": 37542, "text": "Assume we have created a table in MySQL with name EMPLOYEES as −" }, { "code": null, "e": 37777, "s": 37607, "text": "mysql> CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT,\n SEX CHAR(1),\n INCOME FLOAT\n);\nQuery OK, 0 rows affected (0.36 sec)" }, { "code": null, "e": 37849, "s": 37777, "text": "And if we have inserted 4 records in to it using INSERT statements as −" }, { "code": null, "e": 38044, "s": 37849, "text": "mysql> INSERT INTO EMPLOYEE VALUES\n ('Krishna', 'Sharma', 19, 'M', 2000),\n ('Raj', 'Kandukuri', 20, 'M', 7000),\n ('Ramya', 'Ramapriya', 25, 'F', 5000),\n ('Mac', 'Mohan', 26, 'M', 2000);\n" }, { "code": null, "e": 38128, "s": 38044, "text": "Following MySQL statement deletes the record of the employee with FIRST_NAME ”Mac”." }, { "code": null, "e": 38218, "s": 38128, "text": "mysql> DELETE FROM EMPLOYEE WHERE FIRST_NAME = 'Mac';\nQuery OK, 1 row affected (0.12 sec)" }, { "code": null, "e": 38315, "s": 38218, "text": "If you retrieve the contents of the table, you can see only 3 records since we have deleted one." }, { "code": null, "e": 38722, "s": 38315, "text": "mysql> select * from EMPLOYEE;\n+------------+-----------+------+------+--------+\n| FIRST_NAME | LAST_NAME | AGE | SEX | INCOME |\n+------------+-----------+------+------+--------+\n| Krishna | Sharma | 20 | M | 2000 |\n| Raj | Kandukuri | 21 | M | 7000 |\n| Ramya | Ramapriya | 25 | F | 5000 |\n+------------+-----------+------+------+--------+\n3 rows in set (0.00 sec)\n" }, { "code": null, "e": 38841, "s": 38722, "text": "If you execute the DELETE statement without the WHERE clause all the records from the specified table will be deleted." }, { "code": null, "e": 38908, "s": 38841, "text": "mysql> DELETE FROM EMPLOYEE;\nQuery OK, 3 rows affected (0.09 sec)\n" }, { "code": null, "e": 38994, "s": 38908, "text": "If you retrieve the contents of the table, you will get an empty set as shown below −" }, { "code": null, "e": 39047, "s": 38994, "text": "mysql> select * from EMPLOYEE;\nEmpty set (0.00 sec)\n" }, { "code": null, "e": 39133, "s": 39047, "text": "DELETE operation is required when you want to delete some records from your database." }, { "code": null, "e": 39168, "s": 39133, "text": "To delete the records in a table −" }, { "code": null, "e": 39200, "s": 39168, "text": "import mysql.connector package." }, { "code": null, "e": 39232, "s": 39200, "text": "import mysql.connector package." }, { "code": null, "e": 39420, "s": 39232, "text": "Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it." }, { "code": null, "e": 39608, "s": 39420, "text": "Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it." }, { "code": null, "e": 39703, "s": 39608, "text": "Create a cursor object by invoking the cursor() method on the connection object created above." }, { "code": null, "e": 39798, "s": 39703, "text": "Create a cursor object by invoking the cursor() method on the connection object created above." }, { "code": null, "e": 39887, "s": 39798, "text": "Then, execute the DELETE statement by passing it as a parameter to the execute() method." }, { "code": null, "e": 39976, "s": 39887, "text": "Then, execute the DELETE statement by passing it as a parameter to the execute() method." }, { "code": null, "e": 40060, "s": 39976, "text": "Following program deletes all the records from EMPLOYEE whose AGE is more than 20 −" }, { "code": null, "e": 40875, "s": 40060, "text": "import mysql.connector\n\n#establishing the connection\nconn = mysql.connector.connect(\n user='root', password='password', host='127.0.0.1', database='mydb')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Retrieving single row\nprint(\"Contents of the table: \")\ncursor.execute(\"SELECT * from EMPLOYEE\")\nprint(cursor.fetchall())\n\n#Preparing the query to delete records\nsql = \"DELETE FROM EMPLOYEE WHERE AGE > '%d'\" % (25)\n\ntry:\n # Execute the SQL command\n cursor.execute(sql)\n \n # Commit your changes in the database\n conn.commit()\nexcept:\n # Roll back in case there is any error\n conn.rollback()\n\n#Retrieving data\nprint(\"Contents of the table after delete operation \")\ncursor.execute(\"SELECT * from EMPLOYEE\")\nprint(cursor.fetchall())\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 41283, "s": 40875, "text": "Contents of the table:\n[('Krishna', 'Sharma', 22, 'M', 2000.0), \n ('Raj', 'Kandukuri', 23, 'M', 7000.0), \n ('Ramya', 'Ramapriya', 26, 'F', 5000.0), \n ('Mac', 'Mohan', 20, 'M', 2000.0), \n ('Ramya', 'Rama priya', 27, 'F', 9000.0)]\n\nContents of the table after delete operation:\n[('Krishna', 'Sharma', 22, 'M', 2000.0), \n ('Raj', 'Kandukuri', 23, 'M', 7000.0), \n ('Mac', 'Mohan', 20, 'M', 2000.0)]\n" }, { "code": null, "e": 41413, "s": 41283, "text": "You can remove an entire table using the DROP TABLE statement. You just need to specify the name of the table you need to delete." }, { "code": null, "e": 41476, "s": 41413, "text": "Following is the syntax of the DROP TABLE statement in MySQL −" }, { "code": null, "e": 41500, "s": 41476, "text": "DROP TABLE table_name;\n" }, { "code": null, "e": 41592, "s": 41500, "text": "Before deleting a table get the list of tables using the SHOW TABLES statement as follows −" }, { "code": null, "e": 41818, "s": 41592, "text": "mysql> SHOW TABLES;\n+-----------------+\n| Tables_in_mydb |\n+-----------------+\n| contact |\n| cricketers_data |\n| employee |\n| sample |\n| tutorials |\n+-----------------+\n5 rows in set (0.00 sec)\n" }, { "code": null, "e": 41900, "s": 41818, "text": "Following statement removes the table named sample from the database completely −" }, { "code": null, "e": 41964, "s": 41900, "text": "mysql> DROP TABLE sample;\nQuery OK, 0 rows affected (0.29 sec)\n" }, { "code": null, "e": 42104, "s": 41964, "text": "Since we have deleted the table named sample from MySQL, if you get the list of tables again you will not find the table name sample in it." }, { "code": null, "e": 42310, "s": 42104, "text": "mysql> SHOW TABLES;\n+-----------------+\n| Tables_in_mydb |\n+-----------------+\n| contact |\n| cricketers_data |\n| employee |\n| tutorials |\n+-----------------+\n4 rows in set (0.00 sec)\n" }, { "code": null, "e": 42522, "s": 42310, "text": "You can drop a table whenever you need to, using the DROP statement of MYSQL, but you need to be very careful while deleting any existing table because the data lost will not be recovered after deleting a table." }, { "code": null, "e": 42672, "s": 42522, "text": "To drop a table from a MYSQL database using python invoke the execute() method on the cursor object and pass the drop statement as a parameter to it." }, { "code": null, "e": 42736, "s": 42672, "text": "Following table drops a table named EMPLOYEE from the database." }, { "code": null, "e": 43408, "s": 42736, "text": "import mysql.connector\n\n#establishing the connection conn = mysql.connector.connect(\n user='root', password='password', host='127.0.0.1', database='mydb'\n)\n\n#Creating a cursor object using the cursor() method \ncursor = conn.cursor()\n\n#Retrieving the list of tables print(\"List of tables in the database: \") \n cursor.execute(\"SHOW Tables\") print(cursor.fetchall())\n\n#Doping EMPLOYEE table if already exists cursor.execute\n (\"DROP TABLE EMPLOYEE\") print(\"Table dropped... \")\n\n#Retrieving the list of tables print(\n \"List of tables after dropping the EMPLOYEE table: \") \n cursor.execute(\"SHOW Tables\") print(cursor.fetchall())\n\n#Closing the connection conn.close()" }, { "code": null, "e": 43621, "s": 43408, "text": "List of tables in the database:\n[('employee',), ('employeedata',), ('sample',), ('tutorials',)]\nTable dropped...\nList of tables after dropping the EMPLOYEE table:\n[('employeedata',), ('sample',), ('tutorials',)]\n" }, { "code": null, "e": 43707, "s": 43621, "text": "If you try to drop a table which does not exist in the database, an error occurs as −" }, { "code": null, "e": 43797, "s": 43707, "text": "mysql.connector.errors.ProgrammingError: 1051 (42S02): \n Unknown table 'mydb.employee'\n" }, { "code": null, "e": 43928, "s": 43797, "text": "You can prevent this error by verifying whether the table exists before deleting, by adding the IF EXISTS to the DELETE statement." }, { "code": null, "e": 44592, "s": 43928, "text": "import mysql.connector\n\n#establishing the connection\nconn = mysql.connector.connect(\n user='root', password='password', host='127.0.0.1', database='mydb')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Retrieving the list of tables\nprint(\"List of tables in the database: \")\ncursor.execute(\"SHOW Tables\")\nprint(cursor.fetchall())\n\n#Doping EMPLOYEE table if already exists\ncursor.execute(\"DROP TABLE IF EXISTS EMPLOYEE\")\nprint(\"Table dropped... \")\n\n#Retrieving the list of tables\nprint(\"List of tables after dropping the EMPLOYEE table: \")\ncursor.execute(\"SHOW Tables\")\nprint(cursor.fetchall())\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 44790, "s": 44592, "text": "List of tables in the database:\n[('employeedata',), ('sample',), ('tutorials',)]\nTable dropped...\nList of tables after dropping the EMPLOYEE table:\n[('employeedata',), ('sample',),\n('tutorials',)]\n" }, { "code": null, "e": 44911, "s": 44790, "text": "While fetching records if you want to limit them by a particular number, you can do so, using the LIMIT clause of MYSQL." }, { "code": null, "e": 44976, "s": 44911, "text": "Assume we have created a table in MySQL with name EMPLOYEES as −" }, { "code": null, "e": 45146, "s": 44976, "text": "mysql> CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT,\n SEX CHAR(1),\n INCOME FLOAT\n);\nQuery OK, 0 rows affected (0.36 sec)" }, { "code": null, "e": 45218, "s": 45146, "text": "And if we have inserted 4 records in to it using INSERT statements as −" }, { "code": null, "e": 45412, "s": 45218, "text": "mysql> INSERT INTO EMPLOYEE VALUES\n ('Krishna', 'Sharma', 19, 'M', 2000),\n ('Raj', 'Kandukuri', 20, 'M', 7000),\n ('Ramya', 'Ramapriya', 25, 'F', 5000),\n ('Mac', 'Mohan', 26, 'M', 2000);" }, { "code": null, "e": 45510, "s": 45412, "text": "Following SQL statement retrieves first two records of the Employee table using the LIMIT clause." }, { "code": null, "e": 45868, "s": 45510, "text": "SELECT * FROM EMPLOYEE LIMIT 2;\n+------------+-----------+------+------+--------+\n| FIRST_NAME | LAST_NAME | AGE | SEX | INCOME |\n+------------+-----------+------+------+--------+\n| Krishna | Sharma | 19 | M | 2000 |\n| Raj | Kandukuri | 20 | M | 7000 |\n+------------+-----------+------+------+--------+\n2 rows in set (0.00 sec)\n" }, { "code": null, "e": 46026, "s": 45868, "text": "If you invoke the execute() method on the cursor object by passing the SELECT query along with the LIMIT clause, you can retrieve required number of records." }, { "code": null, "e": 46176, "s": 46026, "text": "To drop a table from a MYSQL database using python invoke the execute() method on the cursor object and pass the drop statement as a parameter to it." }, { "code": null, "e": 46318, "s": 46176, "text": "Following python example creates and populates a table with name EMPLOYEE and, using the LIMIT clause it fetches the first two records of it." }, { "code": null, "e": 46760, "s": 46318, "text": "import mysql.connector\n\n#establishing the connection\nconn = mysql.connector.connect(\n user='root', password='password', host='127.0.0.1', database='mydb')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Retrieving single row\nsql = '''SELECT * from EMPLOYEE LIMIT 2'''\n\n#Executing the query\ncursor.execute(sql)\n\n#Fetching the data\nresult = cursor.fetchall();\nprint(result)\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 46841, "s": 46760, "text": "[('Krishna', 'Sharma', 26, 'M', 2000.0), ('Raj', 'Kandukuri', 20, 'M', 7000.0)]\n" }, { "code": null, "e": 46956, "s": 46841, "text": "If you need to limit the records starting from nth record (not 1st), you can do so, using OFFSET along with LIMIT." }, { "code": null, "e": 47407, "s": 46956, "text": "import mysql.connector\n\n#establishing the connection\nconn = mysql.connector.connect(\n user='root', password='password', host='127.0.0.1', database='mydb')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Retrieving single row\nsql = '''SELECT * from EMPLOYEE LIMIT 2 OFFSET 2'''\n\n#Executing the query\ncursor.execute(sql)\n\n#Fetching the data\nresult = cursor.fetchall();\nprint(result)\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 47485, "s": 47407, "text": "[('Ramya', 'Ramapriya', 29, 'F', 5000.0), ('Mac', 'Mohan', 26, 'M', 2000.0)]\n" }, { "code": null, "e": 47596, "s": 47485, "text": "When you have divided the data in two tables you can fetch combined records from these two tables using Joins." }, { "code": null, "e": 47691, "s": 47596, "text": "Suppose we have created a table with name EMPLOYEE and populated data into it as shown below −" }, { "code": null, "e": 48217, "s": 47691, "text": "mysql> CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT,\n SEX CHAR(1),\n INCOME FLOAT,\n CONTACT INT\n);\nQuery OK, 0 rows affected (0.36 sec)\nINSERT INTO Employee VALUES ('Ramya', 'Rama Priya', 27, 'F', 9000, 101), \n ('Vinay', 'Bhattacharya', 20, 'M', 6000, 102), \n ('Sharukh', 'Sheik', 25, 'M', 8300, 103), \n ('Sarmista', 'Sharma', 26, 'F', 10000, 104), \n ('Trupthi', 'Mishra', 24, 'F', 6000, 105);\nQuery OK, 5 rows affected (0.08 sec)\nRecords: 5 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 48278, "s": 48217, "text": "Then, if we have created another table and populated it as −" }, { "code": null, "e": 48420, "s": 48278, "text": "CREATE TABLE CONTACT(\n ID INT NOT NULL,\n EMAIL CHAR(20) NOT NULL,\n PHONE LONG,\n CITY CHAR(20)\n);\nQuery OK, 0 rows affected (0.49 sec)" }, { "code": null, "e": 48714, "s": 48420, "text": "INSERT INTO CONTACT (ID, EMAIL, CITY) VALUES \n (101, '[email protected]', 'Hyderabad'), \n (102, '[email protected]', 'Vishakhapatnam'), \n (103, '[email protected]', 'Pune'), \n (104, '[email protected]', 'Mumbai');\nQuery OK, 4 rows affected (0.10 sec)\nRecords: 4 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 48792, "s": 48714, "text": "Following statement retrieves data combining the values in these two tables −" }, { "code": null, "e": 49821, "s": 48792, "text": "mysql> SELECT * from EMPLOYEE INNER JOIN CONTACT ON EMPLOYEE.CONTACT = CONTACT.ID;\n+------------+--------------+------+------+--------+---------+-----+--------------------+-------+----------------+\n| FIRST_NAME | LAST_NAME | AGE | SEX | INCOME | CONTACT | ID | EMAIL | PHONE | CITY |\n+------------+--------------+------+------+--------+---------+-----+--------------------+-------+----------------+\n| Ramya | Rama Priya | 27 | F | 9000 | 101 | 101 | [email protected] | NULL | Hyderabad |\n| Vinay | Bhattacharya | 20 | M | 6000 | 102 | 102 | [email protected] | NULL | Vishakhapatnam |\n| Sharukh | Sheik | 25 | M | 8300 | 103 | 103 | [email protected] | NULL | Pune |\n| Sarmista | Sharma | 26 | F | 10000 | 104 | 104 | [email protected] | NULL | Mumbai |\n+------------+--------------+------+------+--------+---------+-----+--------------------+-------+----------------+\n4 rows in set (0.00 sec)\n" }, { "code": null, "e": 49965, "s": 49821, "text": "Following example retrieves data from the above two tables combined by contact column of the EMPLOYEE table and ID column of the CONTACT table." }, { "code": null, "e": 50466, "s": 49965, "text": "import mysql.connector\n\n#establishing the connection\nconn = mysql.connector.connect(\n user='root', password='password', host='127.0.0.1', database='mydb'\n)\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Retrieving single row\nsql = '''SELECT * from EMPLOYEE INNER JOIN CONTACT ON EMPLOYEE.CONTACT = CONTACT.ID'''\n\n#Executing the query\ncursor.execute(sql)\n\n#Fetching 1st row from the table\nresult = cursor.fetchall();\nprint(result)\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 50846, "s": 50466, "text": "[('Krishna', 'Sharma', 26, 'M', 2000, 101, 101, '[email protected]', 9848022338, 'Hyderabad'), \n ('Raj', 'Kandukuri', 20, 'M', 7000, 102, 102, '[email protected]', 9848022339, 'Vishakhapatnam'), \n ('Ramya', 'Ramapriya', 29, 'F', 5000, 103, 103, '[email protected]', 9848022337, 'Pune'), \n ('Mac', 'Mohan', 26, 'M', 2000, 104, 104, '[email protected]', 9848022330, 'Mumbai')]\n" }, { "code": null, "e": 50982, "s": 50846, "text": "The MySQLCursor of mysql-connector-python (and similar libraries) is used to execute statements to communicate with the MySQL database." }, { "code": null, "e": 51088, "s": 50982, "text": "Using the methods of it you can execute SQL statements, fetch data from the result sets, call procedures." }, { "code": null, "e": 51175, "s": 51088, "text": "You can create Cursor object using the cursor() method of the Connection object/class." }, { "code": null, "e": 51408, "s": 51175, "text": "import mysql.connector\n\n#establishing the connection\nconn = mysql.connector.connect(\n user='root', password='password', host='127.0.0.1', database='mydb'\n)\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()" }, { "code": null, "e": 51479, "s": 51408, "text": "Following are the various methods provided by the Cursor class/object." }, { "code": null, "e": 51490, "s": 51479, "text": "callproc()" }, { "code": null, "e": 51554, "s": 51490, "text": "This method is used to call existing procedures MySQL database." }, { "code": null, "e": 51562, "s": 51554, "text": "close()" }, { "code": null, "e": 51618, "s": 51562, "text": "This method is used to close the current cursor object." }, { "code": null, "e": 51625, "s": 51618, "text": "Info()" }, { "code": null, "e": 51677, "s": 51625, "text": "This method gives information about the last query." }, { "code": null, "e": 51691, "s": 51677, "text": "executemany()" }, { "code": null, "e": 51810, "s": 51691, "text": "This method accepts a list series of parameters list. Prepares an MySQL query and executes it with all the parameters." }, { "code": null, "e": 51820, "s": 51810, "text": "execute()" }, { "code": null, "e": 51899, "s": 51820, "text": "This method accepts a MySQL query as a parameter and executes the given query." }, { "code": null, "e": 51910, "s": 51899, "text": "fetchall()" }, { "code": null, "e": 52087, "s": 51910, "text": "This method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows it returns the remaining ones)" }, { "code": null, "e": 52098, "s": 52087, "text": "fetchone()" }, { "code": null, "e": 52183, "s": 52098, "text": "This method fetches the next row in the result of a query and returns it as a tuple." }, { "code": null, "e": 52195, "s": 52183, "text": "fetchmany()" }, { "code": null, "e": 52330, "s": 52195, "text": "This method is similar to the fetchone() but, it retrieves the next set of rows in the result set of a query, instead of a single row." }, { "code": null, "e": 52345, "s": 52330, "text": "etchwarnings()" }, { "code": null, "e": 52416, "s": 52345, "text": "This method returns the warnings generated by the last executed query." }, { "code": null, "e": 52467, "s": 52416, "text": "Following are the properties of the Cursor class −" }, { "code": null, "e": 52480, "s": 52467, "text": "column_names" }, { "code": null, "e": 52577, "s": 52480, "text": "This is a read only property which returns the list containing the column names of a result-set." }, { "code": null, "e": 52589, "s": 52577, "text": "description" }, { "code": null, "e": 52696, "s": 52589, "text": "This is a read only property which returns the list containing the description of columns in a result-set." }, { "code": null, "e": 52706, "s": 52696, "text": "lastrowid" }, { "code": null, "e": 52882, "s": 52706, "text": "This is a read only property, if there are any auto-incremented columns in the table, this returns the value generated for that column in the last INSERT or, UPDATE operation." }, { "code": null, "e": 52891, "s": 52882, "text": "rowcount" }, { "code": null, "e": 52981, "s": 52891, "text": "This returns the number of rows returned/updated in case of SELECT and UPDATE operations." }, { "code": null, "e": 52991, "s": 52981, "text": "statement" }, { "code": null, "e": 53042, "s": 52991, "text": "This property returns the last executed statement." }, { "code": null, "e": 53284, "s": 53042, "text": "PostgreSQL is a powerful, open source object-relational database system. It has more than 15 years of active development phase and a proven architecture that has earned it a strong reputation for reliability, data integrity, and correctness." }, { "code": null, "e": 53441, "s": 53284, "text": "To communicate with PostgreSQL using Python you need to install psycopg, an adapter provided for python programming, the current version of this is psycog2." }, { "code": null, "e": 53581, "s": 53441, "text": "psycopg2 was written with the aim of being very small and fast, and stable as a rock. It is available under PIP (package manager of python)" }, { "code": null, "e": 53681, "s": 53581, "text": "First of all, make sure python and PIP is installed in your system properly and, PIP is up-to-date." }, { "code": null, "e": 53753, "s": 53681, "text": "To upgrade PIP, open command prompt and execute the following command −" }, { "code": null, "e": 54151, "s": 53753, "text": "C:\\Users\\Tutorialspoint>python -m pip install --upgrade pip\nCollecting pip\nUsing cached https://files.pythonhosted.org/packages/8d/07/f7d7ced2f97ca3098c16565efbe6b15fafcba53e8d9bdb431e09140514b0/pip-19.2.2-py2.py3-none-any.whl\nInstalling collected packages: pip\nFound existing installation: pip 19.0.3\nUninstalling pip-19.0.3:\nSuccessfully uninstalled pip-19.0.3\nSuccessfully installed pip-19.2.2\n" }, { "code": null, "e": 54260, "s": 54151, "text": "Then, open command prompt in admin mode and execute the pip install psycopg2-binary command as shown below −" }, { "code": null, "e": 54591, "s": 54260, "text": "C:\\WINDOWS\\system32>pip install psycopg2-binary\nCollecting psycopg2-binary\nUsing cached https://files.pythonhosted.org/packages/80/79/d0d13ce4c2f1addf4786f4a2ded802c2df66ddf3c1b1a982ed8d4cb9fc6d/psycopg2_binary-2.8.3-cp37-cp37m-win32.whl\nInstalling collected packages: psycopg2-binary\nSuccessfully installed psycopg2-binary-2.8.3\n" }, { "code": null, "e": 54680, "s": 54591, "text": "To verify the installation, create a sample python script with the following line in it." }, { "code": null, "e": 54704, "s": 54680, "text": "import mysql.connector\n" }, { "code": null, "e": 54792, "s": 54704, "text": "If the installation is successful, when you execute it, you should not get any errors −" }, { "code": null, "e": 54852, "s": 54792, "text": "D:\\Python_PostgreSQL>import psycopg2\nD:\\Python_PostgreSQL>\n" }, { "code": null, "e": 55224, "s": 54852, "text": "PostgreSQL provides its own shell to execute queries. To establish connection with the PostgreSQL database, make sure that you have installed it properly in your system. Open the PostgreSQL shell prompt and pass details like Server, Database, username, and password. If all the details you have given are appropriate, a connection is established with PostgreSQL database." }, { "code": null, "e": 55340, "s": 55224, "text": "While passing the details you can go with the default server, database, port and, user name suggested by the shell." }, { "code": null, "e": 55680, "s": 55340, "text": "The connection class of the psycopg2 represents/handles an instance of a connection. You can create new connections using the connect() function. This accepts the basic connection parameters such as dbname, user, password, host, port and returns a connection object. Using this function, you can establish a connection with the PostgreSQL." }, { "code": null, "e": 55969, "s": 55680, "text": "The following Python code shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned. The name of the default database of PostgreSQL is postrgre. Therefore, we are supplying it as the database name." }, { "code": null, "e": 56550, "s": 55969, "text": "import psycopg2\n\n#establishing the connection\nconn = psycopg2.connect(\n database=\"postgres\", user='postgres', password='password', host='127.0.0.1', port= '5432'\n)\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Executing an MYSQL function using the execute() method\ncursor.execute(\"select version()\")\n\n# Fetch a single row using fetchone() method.\ndata = cursor.fetchone()\nprint(\"Connection established to: \",data)\n\n#Closing the connection\nconn.close()\nConnection established to: (\n 'PostgreSQL 11.5, compiled by Visual C++ build 1914, 64-bit',\n)" }, { "code": null, "e": 56647, "s": 56550, "text": "Connection established to: (\n 'PostgreSQL 11.5, compiled by Visual C++ build 1914, 64-bit',\n)\n" }, { "code": null, "e": 56854, "s": 56647, "text": "You can create a database in PostgreSQL using the CREATE DATABASE statement. You can execute this statement in PostgreSQL shell prompt by specifying the name of the database to be created after the command." }, { "code": null, "e": 56912, "s": 56854, "text": "Following is the syntax of the CREATE DATABASE statement." }, { "code": null, "e": 56937, "s": 56912, "text": "CREATE DATABASE dbname;\n" }, { "code": null, "e": 57004, "s": 56937, "text": "Following statement creates a database named testdb in PostgreSQL." }, { "code": null, "e": 57055, "s": 57004, "text": "postgres=# CREATE DATABASE testdb;\nCREATE DATABASE" }, { "code": null, "e": 57211, "s": 57055, "text": "You can list out the database in PostgreSQL using the \\l command. If you verify the list of databases, you can find the newly created database as follows −" }, { "code": null, "e": 57842, "s": 57211, "text": "postgres=# \\l\n List of databases\nName | Owner | Encoding | Collate | Ctype |\n-----------+----------+----------+----------------------------+-------------+\nmydb | postgres | UTF8 | English_United States.1252 | ........... |\npostgres | postgres | UTF8 | English_United States.1252 | ........... |\ntemplate0 | postgres | UTF8 | English_United States.1252 | ........... |\ntemplate1 | postgres | UTF8 | English_United States.1252 | ........... |\ntestdb | postgres | UTF8 | English_United States.1252 | ........... |\n(5 rows)\n" }, { "code": null, "e": 57987, "s": 57842, "text": "You can also create a database in PostgreSQL from command prompt using the command createdb, a wrapper around the SQL statement CREATE DATABASE." }, { "code": null, "e": 58085, "s": 57987, "text": "C:\\Program Files\\PostgreSQL\\11\\bin> createdb -h localhost -p 5432 -U postgres sampledb\nPassword:\n" }, { "code": null, "e": 58287, "s": 58085, "text": "The cursor class of psycopg2 provides various methods execute various PostgreSQL commands, fetch records and copy data. You can create a cursor object using the cursor() method of the Connection class." }, { "code": null, "e": 58381, "s": 58287, "text": "The execute() method of this class accepts a PostgreSQL query as a parameter and executes it." }, { "code": null, "e": 58481, "s": 58381, "text": "Therefore, to create a database in PostgreSQL, execute the CREATE DATABASE query using this method." }, { "code": null, "e": 58560, "s": 58481, "text": "Following python example creates a database named mydb in PostgreSQL database." }, { "code": null, "e": 59025, "s": 58560, "text": "import psycopg2\n\n#establishing the connection\nconn = psycopg2.connect(\n database=\"postgres\", user='postgres', password='password', host='127.0.0.1', port= '5432'\n)\nconn.autocommit = True\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Preparing query to create a database\nsql = '''CREATE database mydb''';\n\n#Creating a database\ncursor.execute(sql)\nprint(\"Database created successfully........\")\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 59064, "s": 59025, "text": "Database created successfully........\n" }, { "code": null, "e": 59252, "s": 59064, "text": "You can create a new table in a database in PostgreSQL using the CREATE TABLE statement. While executing this you need to specify the name of the table, column names and their data types." }, { "code": null, "e": 59321, "s": 59252, "text": "Following is the syntax of the CREATE TABLE statement in PostgreSQL." }, { "code": null, "e": 59443, "s": 59321, "text": "CREATE TABLE table_name(\n column1 datatype,\n column2 datatype,\n column3 datatype,\n .....\n columnN datatype,\n);\n" }, { "code": null, "e": 59513, "s": 59443, "text": "Following example creates a table with name CRICKETERS in PostgreSQL." }, { "code": null, "e": 59700, "s": 59513, "text": "postgres=# CREATE TABLE CRICKETERS (\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Age INT,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255)\n);\nCREATE TABLE\npostgres=#" }, { "code": null, "e": 59902, "s": 59700, "text": "You can get the list of tables in a database in PostgreSQL using the \\dt command. After creating a table, if you can verify the list of tables you can observe the newly created table in it as follows −" }, { "code": null, "e": 60085, "s": 59902, "text": "postgres=# \\dt\n List of relations\nSchema | Name | Type | Owner\n--------+------------+-------+----------\npublic | cricketers | table | postgres\n(1 row)\npostgres=#\n" }, { "code": null, "e": 60177, "s": 60085, "text": "In the same way, you can get the description of the created table using \\d as shown below −" }, { "code": null, "e": 60734, "s": 60177, "text": "postgres=# \\d cricketers\n Table \"public.cricketers\"\nColumn | Type | Collation | Nullable | Default\n----------------+------------------------+-----------+----------+---------\nfirst_name | character varying(255) | | |\nlast_name | character varying(255) | | |\nage | integer | | |\nplace_of_birth | character varying(255) | | |\ncountry | character varying(255) | | |\npostgres=#\n" }, { "code": null, "e": 60866, "s": 60734, "text": "To create a table using python you need to execute the CREATE TABLE statement using the execute() method of the Cursor of pyscopg2." }, { "code": null, "e": 60931, "s": 60866, "text": "The following Python example creates a table with name employee." }, { "code": null, "e": 61546, "s": 60931, "text": "import psycopg2\n\n#Establishing the connection\nconn = psycopg2.connect(\n database=\"mydb\", user='postgres', password='password', host='127.0.0.1', port= '5432'\n)\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Doping EMPLOYEE table if already exists.\ncursor.execute(\"DROP TABLE IF EXISTS EMPLOYEE\")\n\n#Creating table as per requirement\nsql ='''CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT,\n SEX CHAR(1),\n INCOME FLOAT\n)'''\ncursor.execute(sql)\nprint(\"Table created successfully........\")\nconn.commit()\n#Closing the connection\nconn.close()" }, { "code": null, "e": 61582, "s": 61546, "text": "Table created successfully........\n" }, { "code": null, "e": 61773, "s": 61582, "text": "You can insert record into an existing table in PostgreSQL using the INSERT INTO statement. While executing this, you need to specify the name of the table, and values for the columns in it." }, { "code": null, "e": 61835, "s": 61773, "text": "Following is the recommended syntax of the INSERT statement −" }, { "code": null, "e": 61941, "s": 61835, "text": "INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)\nVALUES (value1, value2, value3,...valueN);\n" }, { "code": null, "e": 62099, "s": 61941, "text": "Where, column1, column2, column3,.. are the names of the columns of a table, and value1, value2, value3,... are the values you need to insert into the table." }, { "code": null, "e": 62201, "s": 62099, "text": "Assume we have created a table with name CRICKETERS using the CREATE TABLE statement as shown below −" }, { "code": null, "e": 62388, "s": 62201, "text": "postgres=# CREATE TABLE CRICKETERS (\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Age INT,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255)\n);\nCREATE TABLE\npostgres=#" }, { "code": null, "e": 62462, "s": 62388, "text": "Following PostgreSQL statement inserts a row in the above created table −" }, { "code": null, "e": 62632, "s": 62462, "text": "postgres=# insert into CRICKETERS (\n First_Name, Last_Name, Age, Place_Of_Birth, Country) \n values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');\nINSERT 0 1\npostgres=#\n" }, { "code": null, "e": 62799, "s": 62632, "text": "While inserting records using the INSERT INTO statement, if you skip any columns names Record will be inserted leaving empty spaces at columns which you have skipped." }, { "code": null, "e": 62926, "s": 62799, "text": "postgres=# insert into CRICKETERS (First_Name, Last_Name, Country) \n values('Jonathan', 'Trott', 'SouthAfrica');\nINSERT 0 1\n" }, { "code": null, "e": 63091, "s": 62926, "text": "You can also insert records into a table without specifying the column names, if the order of values you pass is same as their respective column names in the table." }, { "code": null, "e": 63393, "s": 63091, "text": "postgres=# insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');\nINSERT 0 1\npostgres=# insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');\nINSERT 0 1\npostgres=# insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');\nINSERT 0 1\npostgres=#" }, { "code": null, "e": 63506, "s": 63393, "text": "After inserting the records into a table you can verify its contents using the SELECT statement as shown below −" }, { "code": null, "e": 63963, "s": 63506, "text": "postgres=# SELECT * from CRICKETERS;\nfirst_name | last_name | age | place_of_birth | country\n------------+------------+-----+----------------+-------------\nShikhar | Dhawan | 33 | Delhi | India\nJonathan | Trott | | | SouthAfrica\nKumara | Sangakkara | 41 | Matale | Srilanka\nVirat | Kohli | 30 | Delhi | India\nRohit | Sharma | 32 | Nagpur | India\n(5 rows)\n" }, { "code": null, "e": 64100, "s": 63963, "text": "The cursor class of psycopg2 provides a method with name execute() method. This method accepts the query as a parameter and executes it." }, { "code": null, "e": 64168, "s": 64100, "text": "Therefore, to insert data into a table in PostgreSQL using python −" }, { "code": null, "e": 64193, "s": 64168, "text": "Import psycopg2 package." }, { "code": null, "e": 64218, "s": 64193, "text": "Import psycopg2 package." }, { "code": null, "e": 64390, "s": 64218, "text": "Create a connection object using the connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it." }, { "code": null, "e": 64562, "s": 64390, "text": "Create a connection object using the connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it." }, { "code": null, "e": 64647, "s": 64562, "text": "Turn off the auto-commit mode by setting false as value to the attribute autocommit." }, { "code": null, "e": 64732, "s": 64647, "text": "Turn off the auto-commit mode by setting false as value to the attribute autocommit." }, { "code": null, "e": 64867, "s": 64732, "text": "The cursor() method of the Connection class of the psycopg2 library returns a cursor object. Create a cursor object using this method." }, { "code": null, "e": 65002, "s": 64867, "text": "The cursor() method of the Connection class of the psycopg2 library returns a cursor object. Create a cursor object using this method." }, { "code": null, "e": 65099, "s": 65002, "text": "Then, execute the INSERT statement(s) by passing it/them as a parameter to the execute() method." }, { "code": null, "e": 65196, "s": 65099, "text": "Then, execute the INSERT statement(s) by passing it/them as a parameter to the execute() method." }, { "code": null, "e": 65336, "s": 65196, "text": "Following Python program creates a table with name EMPLOYEE in PostgreSQL database and inserts records into it using the execute() method −" }, { "code": null, "e": 66474, "s": 65336, "text": "import psycopg2\n\n#Establishing the connection\nconn = psycopg2.connect(\n database=\"mydb\", user='postgres', password='password', host='127.0.0.1', port= '5432'\n)\n#Setting auto commit false\nconn.autocommit = True\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n# Preparing SQL queries to INSERT a record into the database.\ncursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX,\n INCOME) VALUES ('Ramya', 'Rama priya', 27, 'F', 9000)''')\ncursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX,\n INCOME) VALUES ('Vinay', 'Battacharya', 20, 'M', 6000)''')\ncursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX,\n INCOME) VALUES ('Sharukh', 'Sheik', 25, 'M', 8300)''')\ncursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX,\n INCOME) VALUES ('Sarmista', 'Sharma', 26, 'F', 10000)''')\ncursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX,\n INCOME) VALUES ('Tripthi', 'Mishra', 24, 'F', 6000)''')\n\n# Commit your changes in the database\nconn.commit()\nprint(\"Records inserted........\")\n\n# Closing the connection\nconn.close()" }, { "code": null, "e": 66500, "s": 66474, "text": "Records inserted........\n" }, { "code": null, "e": 66731, "s": 66500, "text": "You can retrieve the contents of an existing table in PostgreSQL using the SELECT statement. At this statement, you need to specify the name of the table and, it returns its contents in tabular format which is known as result set." }, { "code": null, "e": 66795, "s": 66731, "text": "Following is the syntax of the SELECT statement in PostgreSQL −" }, { "code": null, "e": 66846, "s": 66795, "text": "SELECT column1, column2, columnN FROM table_name;\n" }, { "code": null, "e": 66926, "s": 66846, "text": "Assume we have created a table with name CRICKETERS using the following query −" }, { "code": null, "e": 67105, "s": 66926, "text": "postgres=# CREATE TABLE CRICKETERS (\n First_Name VARCHAR(255), Last_Name VARCHAR(255), \n Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255)\n);\nCREATE TABLE\npostgres=#" }, { "code": null, "e": 67177, "s": 67105, "text": "And if we have inserted 5 records in to it using INSERT statements as −" }, { "code": null, "e": 67669, "s": 67177, "text": "postgres=# insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');\nINSERT 0 1\npostgres=# insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');\nINSERT 0 1\npostgres=# insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');\nINSERT 0 1\npostgres=# insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');\nINSERT 0 1\npostgres=# insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');\nINSERT 0 1" }, { "code": null, "e": 67790, "s": 67669, "text": "Following SELECT query retrieves the values of the columns FIRST_NAME, LAST_NAME and, COUNTRY from the CRICKETERS table." }, { "code": null, "e": 68115, "s": 67790, "text": "postgres=# SELECT FIRST_NAME, LAST_NAME, COUNTRY FROM CRICKETERS;\nfirst_name | last_name | country\n------------+------------+-------------\nShikhar | Dhawan | India\nJonathan | Trott | SouthAfrica\nKumara | Sangakkara | Srilanka\nVirat | Kohli | India\nRohit | Sharma | India\n(5 rows)\n" }, { "code": null, "e": 68241, "s": 68115, "text": "If you want to retrieve all the columns of each record you need to replace the names of the columns with \"*\" as shown below −" }, { "code": null, "e": 68709, "s": 68241, "text": "postgres=# SELECT * FROM CRICKETERS;\nfirst_name | last_name | age | place_of_birth | country\n------------+------------+-----+----------------+-------------\nShikhar | Dhawan | 33 | Delhi | India\nJonathan | Trott | 38 | CapeTown | SouthAfrica\nKumara | Sangakkara | 41 | Matale | Srilanka\nVirat | Kohli | 30 | Delhi | India\nRohit | Sharma | 32 | Nagpur | India\n(5 rows)\npostgres=#\n" }, { "code": null, "e": 68884, "s": 68709, "text": "READ Operation on any database means to fetch some useful information from the database. You can fetch data from PostgreSQL using the fetch() method provided by the psycopg2." }, { "code": null, "e": 68978, "s": 68884, "text": "The Cursor class provides three methods namely fetchall(), fetchmany() and, fetchone() where," }, { "code": null, "e": 69167, "s": 68978, "text": "The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows, it returns the remaining ones)." }, { "code": null, "e": 69356, "s": 69167, "text": "The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows, it returns the remaining ones)." }, { "code": null, "e": 69451, "s": 69356, "text": "The fetchone() method fetches the next row in the result of a query and returns it as a tuple." }, { "code": null, "e": 69546, "s": 69451, "text": "The fetchone() method fetches the next row in the result of a query and returns it as a tuple." }, { "code": null, "e": 69692, "s": 69546, "text": "The fetchmany() method is similar to the fetchone() but, it retrieves the next set of rows in the result set of a query, instead of a single row." }, { "code": null, "e": 69838, "s": 69692, "text": "The fetchmany() method is similar to the fetchone() but, it retrieves the next set of rows in the result set of a query, instead of a single row." }, { "code": null, "e": 69935, "s": 69838, "text": "Note − A result set is an object that is returned when a cursor object is used to query a table." }, { "code": null, "e": 70071, "s": 69935, "text": "The following Python program connects to a database named mydb of PostgreSQL and retrieves all the records from a table named EMPLOYEE." }, { "code": null, "e": 70665, "s": 70071, "text": "import psycopg2\n\n#establishing the connection\nconn = psycopg2.connect(\n database=\"mydb\", user='postgres', password='password', host='127.0.0.1', port= '5432'\n)\n\n#Setting auto commit false\nconn.autocommit = True\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Retrieving data\ncursor.execute('''SELECT * from EMPLOYEE''')\n\n#Fetching 1st row from the table\nresult = cursor.fetchone();\nprint(result)\n\n#Fetching 1st row from the table\nresult = cursor.fetchall();\nprint(result)\n\n#Commit your changes in the database\nconn.commit()\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 70872, "s": 70665, "text": "('Ramya', 'Rama priya', 27, 'F', 9000.0)\n[('Vinay', 'Battacharya', 20, 'M', 6000.0),\n('Sharukh', 'Sheik', 25, 'M', 8300.0),\n('Sarmista', 'Sharma', 26, 'F', 10000.0),\n('Tripthi', 'Mishra', 24, 'F', 6000.0)]\n" }, { "code": null, "e": 71083, "s": 70872, "text": "While performing SELECT, UPDATE or, DELETE operations, you can specify condition to filter the records using the WHERE clause. The operation will be performed on the records which satisfies the given condition." }, { "code": null, "e": 71143, "s": 71083, "text": "Following is the syntax of the WHERE clause in PostgreSQL −" }, { "code": null, "e": 71218, "s": 71143, "text": "SELECT column1, column2, columnN\nFROM table_name\nWHERE [search_condition]\n" }, { "code": null, "e": 71376, "s": 71218, "text": "You can specify a search_condition using comparison or logical operators. like >, <, =, LIKE, NOT, etc. The following examples would make this concept clear." }, { "code": null, "e": 71456, "s": 71376, "text": "Assume we have created a table with name CRICKETERS using the following query −" }, { "code": null, "e": 71636, "s": 71456, "text": "postgres=# CREATE TABLE CRICKETERS ( \n First_Name VARCHAR(255), Last_Name VARCHAR(255), \n Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255)\n);\nCREATE TABLE\npostgres=#" }, { "code": null, "e": 71708, "s": 71636, "text": "And if we have inserted 5 records in to it using INSERT statements as −" }, { "code": null, "e": 72200, "s": 71708, "text": "postgres=# insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');\nINSERT 0 1\npostgres=# insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');\nINSERT 0 1\npostgres=# insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');\nINSERT 0 1\npostgres=# insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');\nINSERT 0 1\npostgres=# insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');\nINSERT 0 1" }, { "code": null, "e": 72280, "s": 72200, "text": "Following SELECT statement retrieves the records whose age is greater than 35 −" }, { "code": null, "e": 72595, "s": 72280, "text": "postgres=# SELECT * FROM CRICKETERS WHERE AGE > 35;\nfirst_name | last_name | age | place_of_birth | country\n------------+------------+-----+----------------+-------------\nJonathan | Trott | 38 | CapeTown | SouthAfrica\nKumara | Sangakkara | 41 | Matale | Srilanka\n(2 rows)\npostgres=#\n" }, { "code": null, "e": 72761, "s": 72595, "text": "To fetch specific records from a table using the python program execute the SELECT statement with WHERE clause, by passing it as a parameter to the execute() method." }, { "code": null, "e": 72840, "s": 72761, "text": "Following python example demonstrates the usage of WHERE command using python." }, { "code": null, "e": 73937, "s": 72840, "text": "import psycopg2\n\n#establishing the connection\nconn = psycopg2.connect(\n database=\"mydb\", user='postgres', password='password', host='127.0.0.1', port= '5432'\n)\n\n#Setting auto commit false\nconn.autocommit = True\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Doping EMPLOYEE table if already exists.\ncursor.execute(\"DROP TABLE IF EXISTS EMPLOYEE\")\nsql = '''CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT,\n SEX CHAR(1),\n INCOME FLOAT\n)'''\ncursor.execute(sql)\n\n#Populating the table\ninsert_stmt = \"INSERT INTO EMPLOYEE (FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) \n VALUES (%s, %s, %s, %s, %s)\"\ndata = [('Krishna', 'Sharma', 19, 'M', 2000), \n ('Raj', 'Kandukuri', 20, 'M', 7000),\n ('Ramya', 'Ramapriya', 25, 'M', 5000),\n ('Mac', 'Mohan', 26, 'M', 2000)]\ncursor.executemany(insert_stmt, data)\n\n#Retrieving specific records using the where clause\ncursor.execute(\"SELECT * from EMPLOYEE WHERE AGE <23\")\nprint(cursor.fetchall())\n\n#Commit your changes in the database\nconn.commit()\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 74018, "s": 73937, "text": "[('Krishna', 'Sharma', 19, 'M', 2000.0), ('Raj', 'Kandukuri', 20, 'M', 7000.0)]\n" }, { "code": null, "e": 74144, "s": 74018, "text": "Usually if you try to retrieve data from a table, you will get the records in the same order in which you have inserted them." }, { "code": null, "e": 74308, "s": 74144, "text": "Using the ORDER BY clause, while retrieving the records of a table you can sort the resultant records in ascending or descending order based on the desired column." }, { "code": null, "e": 74370, "s": 74308, "text": "Following is the syntax of the ORDER BY clause in PostgreSQL." }, { "code": null, "e": 74478, "s": 74370, "text": "SELECT column-list\nFROM table_name\n[WHERE condition]\n[ORDER BY column1, column2, .. columnN] [ASC | DESC];\n" }, { "code": null, "e": 74558, "s": 74478, "text": "Assume we have created a table with name CRICKETERS using the following query −" }, { "code": null, "e": 74738, "s": 74558, "text": "postgres=# CREATE TABLE CRICKETERS ( \n First_Name VARCHAR(255), Last_Name VARCHAR(255), \n Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255)\n);\nCREATE TABLE\npostgres=#" }, { "code": null, "e": 74810, "s": 74738, "text": "And if we have inserted 5 records in to it using INSERT statements as −" }, { "code": null, "e": 75302, "s": 74810, "text": "postgres=# insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');\nINSERT 0 1\npostgres=# insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');\nINSERT 0 1\npostgres=# insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');\nINSERT 0 1\npostgres=# insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');\nINSERT 0 1\npostgres=# insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');\nINSERT 0 1" }, { "code": null, "e": 75410, "s": 75302, "text": "Following SELECT statement retrieves the rows of the CRICKETERS table in the ascending order of their age −" }, { "code": null, "e": 75883, "s": 75410, "text": "postgres=# SELECT * FROM CRICKETERS ORDER BY AGE;\nfirst_name | last_name | age | place_of_birth | country\n------------+------------+-----+----------------+-------------\nVirat | Kohli | 30 | Delhi | India\nRohit | Sharma | 32 | Nagpur | India\nShikhar | Dhawan | 33 | Delhi | India\nJonathan | Trott | 38 | CapeTown | SouthAfrica\nKumara | Sangakkara | 41 | Matale | Srilanka\n(5 rows)es:\n" }, { "code": null, "e": 76058, "s": 75883, "text": "You can use more than one column to sort the records of a table. Following SELECT statements sort the records of the CRICKETERS table based on the columns age and FIRST_NAME." }, { "code": null, "e": 76540, "s": 76058, "text": "postgres=# SELECT * FROM CRICKETERS ORDER BY AGE, FIRST_NAME;\nfirst_name | last_name | age | place_of_birth | country\n------------+------------+-----+----------------+-------------\nVirat | Kohli | 30 | Delhi | India\nRohit | Sharma | 32 | Nagpur | India\nShikhar | Dhawan | 33 | Delhi | India\nJonathan | Trott | 38 | CapeTown | SouthAfrica\nKumara | Sangakkara | 41 | Matale | Srilanka\n(5 rows)\n" }, { "code": null, "e": 76685, "s": 76540, "text": "By default, the ORDER BY clause sorts the records of a table in ascending order. You can arrange the results in descending order using DESC as −" }, { "code": null, "e": 77160, "s": 76685, "text": "postgres=# SELECT * FROM CRICKETERS ORDER BY AGE DESC;\nfirst_name | last_name | age | place_of_birth | country\n------------+------------+-----+----------------+-------------\nKumara | Sangakkara | 41 | Matale | Srilanka\nJonathan | Trott | 38 | CapeTown | SouthAfrica\nShikhar | Dhawan | 33 | Delhi | India\nRohit | Sharma | 32 | Nagpur | India\nVirat | Kohli | 30 | Delhi | India\n(5 rows)\n" }, { "code": null, "e": 77341, "s": 77160, "text": "To retrieve contents of a table in specific order, invoke the execute() method on the cursor object and, pass the SELECT statement along with ORDER BY clause, as a parameter to it." }, { "code": null, "e": 77528, "s": 77341, "text": "In the following example, we are creating a table with name and Employee, populating it, and retrieving its records back in the (ascending) order of their age, using the ORDER BY clause." }, { "code": null, "e": 78708, "s": 77528, "text": "import psycopg2\n\n#establishing the connection\nconn = psycopg2.connect(\n database=\"mydb\", user='postgres', password='password', host='127.0.0.1', port= '5432'\n)\n\n#Setting auto commit false\nconn.autocommit = True\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Doping EMPLOYEE table if already exists.\ncursor.execute(\"DROP TABLE IF EXISTS EMPLOYEE\")\n\n#Creating a table\nsql = '''CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT, SEX CHAR(1),\n INCOME INT,\n CONTACT INT\n)'''\ncursor.execute(sql)\n\n#Populating the table\ninsert_stmt = \"INSERT INTO EMPLOYEE (\n FIRST_NAME, LAST_NAME, AGE, SEX, INCOME, CONTACT) VALUES \n (%s, %s, %s, %s, %s, %s)\"\ndata = [('Krishna', 'Sharma', 26, 'M', 2000, 101), \n ('Raj', 'Kandukuri', 20, 'M', 7000, 102),\n ('Ramya', 'Ramapriya', 29, 'F', 5000, 103),\n ('Mac', 'Mohan', 26, 'M', 2000, 104)]\ncursor.executemany(insert_stmt, data)\nconn.commit()\n\n#Retrieving specific records using the ORDER BY clause\ncursor.execute(\"SELECT * from EMPLOYEE ORDER BY AGE\")\nprint(cursor.fetchall())\n\n#Commit your changes in the database\nconn.commit()\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 78791, "s": 78708, "text": "[('Sharukh', 'Sheik', 25, 'M', 8300.0), ('Sarmista', 'Sharma', 26, 'F', 10000.0)]\n" }, { "code": null, "e": 78965, "s": 78791, "text": "You can modify the contents of existing records of a table in PostgreSQL using the UPDATE statement. To update specific rows, you need to use the WHERE clause along with it." }, { "code": null, "e": 79029, "s": 78965, "text": "Following is the syntax of the UPDATE statement in PostgreSQL −" }, { "code": null, "e": 79128, "s": 79029, "text": "UPDATE table_name\nSET column1 = value1, column2 = value2...., columnN = valueN\nWHERE [condition];\n" }, { "code": null, "e": 79208, "s": 79128, "text": "Assume we have created a table with name CRICKETERS using the following query −" }, { "code": null, "e": 79388, "s": 79208, "text": "postgres=# CREATE TABLE CRICKETERS ( \n First_Name VARCHAR(255), Last_Name VARCHAR(255), \n Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255)\n);\nCREATE TABLE\npostgres=#" }, { "code": null, "e": 79460, "s": 79388, "text": "And if we have inserted 5 records in to it using INSERT statements as −" }, { "code": null, "e": 79952, "s": 79460, "text": "postgres=# insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');\nINSERT 0 1\npostgres=# insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');\nINSERT 0 1\npostgres=# insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');\nINSERT 0 1\npostgres=# insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');\nINSERT 0 1\npostgres=# insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');\nINSERT 0 1" }, { "code": null, "e": 80037, "s": 79952, "text": "Following statement modifies the age of the cricketer, whose first name is Shikhar −" }, { "code": null, "e": 80130, "s": 80037, "text": "postgres=# UPDATE CRICKETERS SET AGE = 45 WHERE FIRST_NAME = 'Shikhar' ;\nUPDATE 1\npostgres=#" }, { "code": null, "e": 80241, "s": 80130, "text": "If you retrieve the record whose FIRST_NAME is Shikhar you observe that the age value has been changed to 45 −" }, { "code": null, "e": 80497, "s": 80241, "text": "postgres=# SELECT * FROM CRICKETERS WHERE FIRST_NAME = 'Shikhar';\nfirst_name | last_name | age | place_of_birth | country\n------------+-----------+-----+----------------+---------\nShikhar | Dhawan | 45 | Delhi | India\n(1 row)\npostgres=#\n" }, { "code": null, "e": 80673, "s": 80497, "text": "If you haven’t used the WHERE clause, values of all the records will be updated. Following UPDATE statement increases the age of all the records in the CRICKETERS table by 1 −" }, { "code": null, "e": 80729, "s": 80673, "text": "postgres=# UPDATE CRICKETERS SET AGE = AGE+1;\nUPDATE 5\n" }, { "code": null, "e": 80829, "s": 80729, "text": "If you retrieve the contents of the table using SELECT command, you can see the updated values as −" }, { "code": null, "e": 81286, "s": 80829, "text": "postgres=# SELECT * FROM CRICKETERS;\nfirst_name | last_name | age | place_of_birth | country\n------------+------------+-----+----------------+-------------\nJonathan | Trott | 39 | CapeTown | SouthAfrica\nKumara | Sangakkara | 42 | Matale | Srilanka\nVirat | Kohli | 31 | Delhi | India\nRohit | Sharma | 33 | Nagpur | India\nShikhar | Dhawan | 46 | Delhi | India\n(5 rows)\n" }, { "code": null, "e": 81423, "s": 81286, "text": "The cursor class of psycopg2 provides a method with name execute() method. This method accepts the query as a parameter and executes it." }, { "code": null, "e": 81491, "s": 81423, "text": "Therefore, to insert data into a table in PostgreSQL using python −" }, { "code": null, "e": 81516, "s": 81491, "text": "Import psycopg2 package." }, { "code": null, "e": 81541, "s": 81516, "text": "Import psycopg2 package." }, { "code": null, "e": 81713, "s": 81541, "text": "Create a connection object using the connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it." }, { "code": null, "e": 81885, "s": 81713, "text": "Create a connection object using the connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it." }, { "code": null, "e": 81970, "s": 81885, "text": "Turn off the auto-commit mode by setting false as value to the attribute autocommit." }, { "code": null, "e": 82055, "s": 81970, "text": "Turn off the auto-commit mode by setting false as value to the attribute autocommit." }, { "code": null, "e": 82190, "s": 82055, "text": "The cursor() method of the Connection class of the psycopg2 library returns a cursor object. Create a cursor object using this method." }, { "code": null, "e": 82325, "s": 82190, "text": "The cursor() method of the Connection class of the psycopg2 library returns a cursor object. Create a cursor object using this method." }, { "code": null, "e": 82414, "s": 82325, "text": "Then, execute the UPDATE statement by passing it as a parameter to the execute() method." }, { "code": null, "e": 82503, "s": 82414, "text": "Then, execute the UPDATE statement by passing it as a parameter to the execute() method." }, { "code": null, "e": 82596, "s": 82503, "text": "Following Python code updates the contents of the Employee table and retrieves the results −" }, { "code": null, "e": 83460, "s": 82596, "text": "import psycopg2\n\n#establishing the connection\nconn = psycopg2.connect(\n database=\"mydb\", user='postgres', password='password', host='127.0.0.1', port= '5432'\n)\n\n#Setting auto commit false\nconn.autocommit = True\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Fetching all the rows before the update\nprint(\"Contents of the Employee table: \")\nsql = '''SELECT * from EMPLOYEE'''\ncursor.execute(sql)\nprint(cursor.fetchall())\n\n#Updating the records\nsql = \"UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = 'M'\"\ncursor.execute(sql)\nprint(\"Table updated...... \")\n\n#Fetching all the rows after the update\nprint(\"Contents of the Employee table after the update operation: \")\nsql = '''SELECT * from EMPLOYEE'''\ncursor.execute(sql)\nprint(cursor.fetchall())\n\n#Commit your changes in the database\nconn.commit()\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 84018, "s": 83460, "text": "Contents of the Employee table:\n[('Ramya', 'Rama priya', 27, 'F', 9000.0), \n ('Vinay', 'Battacharya', 20, 'M', 6000.0), \n ('Sharukh', 'Sheik', 25, 'M', 8300.0), \n ('Sarmista', 'Sharma', 26, 'F', 10000.0), \n ('Tripthi', 'Mishra', 24, 'F', 6000.0)]\nTable updated......\nContents of the Employee table after the update operation:\n[('Ramya', 'Rama priya', 27, 'F', 9000.0), \n ('Sarmista', 'Sharma', 26, 'F', 10000.0), \n ('Tripthi', 'Mishra', 24, 'F', 6000.0), \n ('Vinay', 'Battacharya', 21, 'M', 6000.0), \n ('Sharukh', 'Sheik', 26, 'M', 8300.0)]\n" }, { "code": null, "e": 84194, "s": 84018, "text": "You can delete the records in an existing table using the DELETE FROM statement of PostgreSQL database. To remove specific records, you need to use WHERE clause along with it." }, { "code": null, "e": 84254, "s": 84194, "text": "Following is the syntax of the DELETE query in PostgreSQL −" }, { "code": null, "e": 84293, "s": 84254, "text": "DELETE FROM table_name [WHERE Clause]\n" }, { "code": null, "e": 84373, "s": 84293, "text": "Assume we have created a table with name CRICKETERS using the following query −" }, { "code": null, "e": 84553, "s": 84373, "text": "postgres=# CREATE TABLE CRICKETERS ( \n First_Name VARCHAR(255), Last_Name VARCHAR(255), \n Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255)\n);\nCREATE TABLE\npostgres=#" }, { "code": null, "e": 84625, "s": 84553, "text": "And if we have inserted 5 records in to it using INSERT statements as −" }, { "code": null, "e": 85122, "s": 84625, "text": "postgres=# insert into CRICKETERS values ('Shikhar', 'Dhawan', 33, 'Delhi', 'India');\nINSERT 0 1\npostgres=# insert into CRICKETERS values ('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');\nINSERT 0 1\npostgres=# insert into CRICKETERS values ('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');\nINSERT 0 1\npostgres=# insert into CRICKETERS values ('Virat', 'Kohli', 30, 'Delhi', 'India');\nINSERT 0 1\npostgres=# insert into CRICKETERS values ('Rohit', 'Sharma', 32, 'Nagpur', 'India');\nINSERT 0 1" }, { "code": null, "e": 85213, "s": 85122, "text": "Following statement deletes the record of the cricketer whose last name is 'Sangakkara'. −" }, { "code": null, "e": 85289, "s": 85213, "text": "postgres=# DELETE FROM CRICKETERS WHERE LAST_NAME = 'Sangakkara';\nDELETE 1\n" }, { "code": null, "e": 85413, "s": 85289, "text": "If you retrieve the contents of the table using the SELECT statement, you can see only 4 records since we have deleted one." }, { "code": null, "e": 85805, "s": 85413, "text": "postgres=# SELECT * FROM CRICKETERS;\nfirst_name | last_name | age | place_of_birth | country\n------------+-----------+-----+----------------+-------------\nJonathan | Trott | 39 | CapeTown | SouthAfrica\nVirat | Kohli | 31 | Delhi | India\nRohit | Sharma | 33 | Nagpur | India\nShikhar | Dhawan | 46 | Delhi | India\n(4 rows)\n" }, { "code": null, "e": 85929, "s": 85805, "text": "If you execute the DELETE FROM statement without the WHERE clause all the records from the specified table will be deleted." }, { "code": null, "e": 85974, "s": 85929, "text": "postgres=# DELETE FROM CRICKETERS;\nDELETE 4\n" }, { "code": null, "e": 86148, "s": 85974, "text": "Since you have deleted all the records, if you try to retrieve the contents of the CRICKETERS table, using SELECT statement you will get an empty result set as shown below −" }, { "code": null, "e": 86310, "s": 86148, "text": "postgres=# SELECT * FROM CRICKETERS;\nfirst_name | last_name | age | place_of_birth | country\n------------+-----------+-----+----------------+---------\n(0 rows)\n" }, { "code": null, "e": 86447, "s": 86310, "text": "The cursor class of psycopg2 provides a method with name execute() method. This method accepts the query as a parameter and executes it." }, { "code": null, "e": 86515, "s": 86447, "text": "Therefore, to insert data into a table in PostgreSQL using python −" }, { "code": null, "e": 86540, "s": 86515, "text": "Import psycopg2 package." }, { "code": null, "e": 86565, "s": 86540, "text": "Import psycopg2 package." }, { "code": null, "e": 86737, "s": 86565, "text": "Create a connection object using the connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it." }, { "code": null, "e": 86909, "s": 86737, "text": "Create a connection object using the connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it." }, { "code": null, "e": 86994, "s": 86909, "text": "Turn off the auto-commit mode by setting false as value to the attribute autocommit." }, { "code": null, "e": 87079, "s": 86994, "text": "Turn off the auto-commit mode by setting false as value to the attribute autocommit." }, { "code": null, "e": 87214, "s": 87079, "text": "The cursor() method of the Connection class of the psycopg2 library returns a cursor object. Create a cursor object using this method." }, { "code": null, "e": 87349, "s": 87214, "text": "The cursor() method of the Connection class of the psycopg2 library returns a cursor object. Create a cursor object using this method." }, { "code": null, "e": 87438, "s": 87349, "text": "Then, execute the UPDATE statement by passing it as a parameter to the execute() method." }, { "code": null, "e": 87527, "s": 87438, "text": "Then, execute the UPDATE statement by passing it as a parameter to the execute() method." }, { "code": null, "e": 87621, "s": 87527, "text": "Following Python code deletes records of the EMPLOYEE table with age values greater than 25 −" }, { "code": null, "e": 88367, "s": 87621, "text": "import psycopg2\n\n#establishing the connection\nconn = psycopg2.connect(\n database=\"mydb\", user='postgres', password='password', host='127.0.0.1', port= '5432'\n)\n\n#Setting auto commit false\nconn.autocommit = True\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Retrieving contents of the table\nprint(\"Contents of the table: \")\ncursor.execute('''SELECT * from EMPLOYEE''')\nprint(cursor.fetchall())\n\n#Deleting records\ncursor.execute('''DELETE FROM EMPLOYEE WHERE AGE > 25''')\n\n#Retrieving data after delete\nprint(\"Contents of the table after delete operation \")\ncursor.execute(\"SELECT * from EMPLOYEE\")\nprint(cursor.fetchall())\n\n#Commit your changes in the database\nconn.commit()\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 88748, "s": 88367, "text": "Contents of the table:\n[('Ramya', 'Rama priya', 27, 'F', 9000.0), \n ('Sarmista', 'Sharma', 26, 'F', 10000.0), \n ('Tripthi', 'Mishra', 24, 'F', 6000.0), \n ('Vinay', 'Battacharya', 21, 'M', 6000.0), \n ('Sharukh', 'Sheik', 26, 'M', 8300.0)]\nContents of the table after delete operation:\n[('Tripthi', 'Mishra', 24, 'F', 6000.0), \n ('Vinay', 'Battacharya', 21, 'M', 6000.0)]\n" }, { "code": null, "e": 88826, "s": 88748, "text": "You can drop a table from PostgreSQL database using the DROP TABLE statement." }, { "code": null, "e": 88894, "s": 88826, "text": "Following is the syntax of the DROP TABLE statement in PostgreSQL −" }, { "code": null, "e": 88918, "s": 88894, "text": "DROP TABLE table_name;\n" }, { "code": null, "e": 89017, "s": 88918, "text": "Assume we have created two tables with name CRICKETERS and EMPLOYEES using the following queries −" }, { "code": null, "e": 89349, "s": 89017, "text": "postgres=# CREATE TABLE CRICKETERS (\n First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, \n Place_Of_Birth VARCHAR(255), Country VARCHAR(255)\n);\nCREATE TABLE\npostgres=#\npostgres=# CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, \n SEX CHAR(1), INCOME FLOAT\n);\nCREATE TABLE\npostgres=#" }, { "code": null, "e": 89453, "s": 89349, "text": "Now if you verify the list of tables using the “\\dt” command, you can see the above created tables as −" }, { "code": null, "e": 89666, "s": 89453, "text": "postgres=# \\dt;\nList of relations\nSchema | Name | Type | Owner\n--------+------------+-------+----------\npublic | cricketers | table | postgres\npublic | employee | table | postgres\n(2 rows)\npostgres=#\n" }, { "code": null, "e": 89739, "s": 89666, "text": "Following statement deletes the table named Employee from the database −" }, { "code": null, "e": 89783, "s": 89739, "text": "postgres=# DROP table employee;\nDROP TABLE\n" }, { "code": null, "e": 89906, "s": 89783, "text": "Since you have deleted the Employee table, if you retrieve the list of tables again, you can observe only one table in it." }, { "code": null, "e": 90078, "s": 89906, "text": "postgres=# \\dt;\nList of relations\nSchema | Name | Type | Owner\n--------+------------+-------+----------\npublic | cricketers | table | postgres\n(1 row)\npostgres=#\n" }, { "code": null, "e": 90229, "s": 90078, "text": "If you try to delete the Employee table again, since you have already deleted it, you will get an error saying “table does not exist” as shown below −" }, { "code": null, "e": 90312, "s": 90229, "text": "postgres=# DROP table employee;\nERROR: table \"employee\" does not exist\npostgres=#\n" }, { "code": null, "e": 90462, "s": 90312, "text": "To resolve this, you can use the IF EXISTS clause along with the DELTE statement. This removes the table if it exists else skips the DLETE operation." }, { "code": null, "e": 90576, "s": 90462, "text": "postgres=# DROP table IF EXISTS employee;\nNOTICE: table \"employee\" does not exist, skipping\nDROP TABLE\npostgres=#" }, { "code": null, "e": 90779, "s": 90576, "text": "You can drop a table whenever you need to, using the DROP statement. But you need to be very careful while deleting any existing table because the data lost will not be recovered after deleting a table." }, { "code": null, "e": 91260, "s": 90779, "text": "import psycopg2\n\n#establishing the connection\nconn = psycopg2.connect(\n database=\"mydb\", user='postgres', password='password', host='127.0.0.1', port= '5432'\n)\n\n#Setting auto commit false\nconn.autocommit = True\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Doping EMPLOYEE table if already exists\ncursor.execute(\"DROP TABLE emp\")\nprint(\"Table dropped... \")\n\n#Commit your changes in the database\nconn.commit()\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 91279, "s": 91260, "text": "#Table dropped...\n" }, { "code": null, "e": 91399, "s": 91279, "text": "While executing a PostgreSQL SELECT statement you can limit the number of records in its result using the LIMIT clause." }, { "code": null, "e": 91458, "s": 91399, "text": "Following is the syntax of the LMIT clause in PostgreSQL −" }, { "code": null, "e": 91527, "s": 91458, "text": "SELECT column1, column2, columnN\nFROM table_name\nLIMIT [no of rows]\n" }, { "code": null, "e": 91607, "s": 91527, "text": "Assume we have created a table with name CRICKETERS using the following query −" }, { "code": null, "e": 91787, "s": 91607, "text": "postgres=# CREATE TABLE CRICKETERS ( \n First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, \n Place_Of_Birth VARCHAR(255), Country VARCHAR(255)\n);\nCREATE TABLE\npostgres=#" }, { "code": null, "e": 91859, "s": 91787, "text": "And if we have inserted 5 records in to it using INSERT statements as −" }, { "code": null, "e": 92356, "s": 91859, "text": "postgres=# insert into CRICKETERS values ('Shikhar', 'Dhawan', 33, 'Delhi', 'India');\nINSERT 0 1\npostgres=# insert into CRICKETERS values ('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');\nINSERT 0 1\npostgres=# insert into CRICKETERS values ('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');\nINSERT 0 1\npostgres=# insert into CRICKETERS values ('Virat', 'Kohli', 30, 'Delhi', 'India');\nINSERT 0 1\npostgres=# insert into CRICKETERS values ('Rohit', 'Sharma', 32, 'Nagpur', 'India');\nINSERT 0 1" }, { "code": null, "e": 92455, "s": 92356, "text": "Following statement retrieves the first 3 records of the Cricketers table using the LIMIT clause −" }, { "code": null, "e": 92808, "s": 92455, "text": "postgres=# SELECT * FROM CRICKETERS LIMIT 3;\nfirst_name | last_name | age | place_of_birth | country\n------------+------------+-----+----------------+-------------\nShikhar | Dhawan | 33 | Delhi | India\nJonathan | Trott | 38 | CapeTown | SouthAfrica\nKumara | Sangakkara | 41 | Matale | Srilanka\n(3 rows)\n" }, { "code": null, "e": 92935, "s": 92808, "text": "If you want to get records starting from a particular record (offset) you can do so, using the OFFSET clause along with LIMIT." }, { "code": null, "e": 93299, "s": 92935, "text": "postgres=# SELECT * FROM CRICKETERS LIMIT 3 OFFSET 2;\nfirst_name | last_name | age | place_of_birth | country\n------------+------------+-----+----------------+----------\nKumara | Sangakkara | 41 | Matale | Srilanka\nVirat | Kohli | 30 | Delhi | India\nRohit | Sharma | 32 | Nagpur | India\n(3 rows)\npostgres=#\n" }, { "code": null, "e": 93426, "s": 93299, "text": "Following python example retrieves the contents of a table named EMPLOYEE, limiting the number of records in the result to 2 −" }, { "code": null, "e": 93985, "s": 93426, "text": "import psycopg2\n\n#establishing the connection\nconn = psycopg2.connect(\n database=\"mydb\", user='postgres', password='password', host='127.0.0.1', port= '5432'\n)\n\n#Setting auto commit false\nconn.autocommit = True\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Retrieving single row\nsql = '''SELECT * from EMPLOYEE LIMIT 2 OFFSET 2'''\n\n#Executing the query\ncursor.execute(sql)\n\n#Fetching the data\nresult = cursor.fetchall();\nprint(result)\n\n#Commit your changes in the database\nconn.commit()\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 94068, "s": 93985, "text": "[('Sharukh', 'Sheik', 25, 'M', 8300.0), ('Sarmista', 'Sharma', 26, 'F', 10000.0)]\n" }, { "code": null, "e": 94179, "s": 94068, "text": "When you have divided the data in two tables you can fetch combined records from these two tables using Joins." }, { "code": null, "e": 94279, "s": 94179, "text": "Assume we have created a table with name CRICKETERS and inserted 5 records into it as shown below −" }, { "code": null, "e": 94901, "s": 94279, "text": "postgres=# CREATE TABLE CRICKETERS (\n First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, \n Place_Of_Birth VARCHAR(255), Country VARCHAR(255)\n);\npostgres=# insert into CRICKETERS values (\n 'Shikhar', 'Dhawan', 33, 'Delhi', 'India'\n);\npostgres=# insert into CRICKETERS values (\n 'Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica'\n);\npostgres=# insert into CRICKETERS values (\n 'Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka'\n);\npostgres=# insert into CRICKETERS values (\n 'Virat', 'Kohli', 30, 'Delhi', 'India'\n);\npostgres=# insert into CRICKETERS values (\n 'Rohit', 'Sharma', 32, 'Nagpur', 'India'\n);" }, { "code": null, "e": 94994, "s": 94901, "text": "And, if we have created another table with name OdiStats and inserted 5 records into it as −" }, { "code": null, "e": 95516, "s": 94994, "text": "postgres=# CREATE TABLE ODIStats (\n First_Name VARCHAR(255), Matches INT, Runs INT, AVG FLOAT, \n Centuries INT, HalfCenturies INT\n);\npostgres=# insert into OdiStats values ('Shikhar', 133, 5518, 44.5, 17, 27);\npostgres=# insert into OdiStats values ('Jonathan', 68, 2819, 51.25, 4, 22);\npostgres=# insert into OdiStats values ('Kumara', 404, 14234, 41.99, 25, 93);\npostgres=# insert into OdiStats values ('Virat', 239, 11520, 60.31, 43, 54);\npostgres=# insert into OdiStats values ('Rohit', 218, 8686, 48.53, 24, 42);" }, { "code": null, "e": 95594, "s": 95516, "text": "Following statement retrieves data combining the values in these two tables −" }, { "code": null, "e": 96399, "s": 95594, "text": "postgres=# SELECT\nCricketers.First_Name, Cricketers.Last_Name, Cricketers.Country,\nOdiStats.matches, OdiStats.runs, OdiStats.centuries, OdiStats.halfcenturies\nfrom Cricketers INNER JOIN OdiStats ON Cricketers.First_Name = OdiStats.First_Name;\nfirst_name | last_name | country | matches | runs | centuries | halfcenturies\n------------+------------+-------------+---------+-------+-----------+---------------\nShikhar | Dhawan | India | 133 | 5518 | 17 | 27\nJonathan | Trott | SouthAfrica | 68 | 2819 | 4 | 22\nKumara | Sangakkara | Srilanka | 404 | 14234 | 25 | 93\nVirat | Kohli | India | 239 | 11520 | 43 | 54\nRohit | Sharma | India | 218 | 8686 | 24 | 42\n(5 rows)\npostgres=#\n" }, { "code": null, "e": 96510, "s": 96399, "text": "When you have divided the data in two tables you can fetch combined records from these two tables using Joins." }, { "code": null, "e": 96579, "s": 96510, "text": "Following python program demonstrates the usage of the JOIN clause −" }, { "code": null, "e": 97176, "s": 96579, "text": "import psycopg2\n\n#establishing the connection\nconn = psycopg2.connect(\n database=\"mydb\", user='postgres', password='password', host='127.0.0.1', port= '5432'\n)\n#Setting auto commit false\nconn.autocommit = True\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Retrieving single row\nsql = '''SELECT * from EMP INNER JOIN CONTACT ON EMP.CONTACT = CONTACT.ID'''\n\n#Executing the query\ncursor.execute(sql)\n\n#Fetching 1st row from the table\nresult = cursor.fetchall();\nprint(result)\n\n#Commit your changes in the database\nconn.commit()\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 97528, "s": 97176, "text": "[('Ramya', 'Rama priya', 27, 'F', 9000.0, 101, 101, '[email protected]', 'Hyderabad'), \n ('Vinay', 'Battacharya', 20, 'M', 6000.0, 102, 102, '[email protected]', 'Vishakhapatnam'), \n ('Sharukh', 'Sheik', 25, 'M', 8300.0, 103, 103, '[email protected] ', 'Pune'), \n ('Sarmista', 'Sharma', 26, 'F', 10000.0, 104, 104, '[email protected]', 'Mumbai')]\n" }, { "code": null, "e": 97654, "s": 97528, "text": "The Cursor class of the psycopg library provide methods to execute the PostgreSQL commands in the database using python code." }, { "code": null, "e": 97760, "s": 97654, "text": "Using the methods of it you can execute SQL statements, fetch data from the result sets, call procedures." }, { "code": null, "e": 97847, "s": 97760, "text": "You can create Cursor object using the cursor() method of the Connection object/class." }, { "code": null, "e": 98136, "s": 97847, "text": "import psycopg2\n\n#establishing the connection\nconn = psycopg2.connect(\n database=\"mydb\", user='postgres', password='password', host='127.0.0.1', port= '5432'\n)\n\n#Setting auto commit false\nconn.autocommit = True\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()" }, { "code": null, "e": 98207, "s": 98136, "text": "Following are the various methods provided by the Cursor class/object." }, { "code": null, "e": 98218, "s": 98207, "text": "callproc()" }, { "code": null, "e": 98287, "s": 98218, "text": "This method is used to call existing procedures PostgreSQL database." }, { "code": null, "e": 98295, "s": 98287, "text": "close()" }, { "code": null, "e": 98351, "s": 98295, "text": "This method is used to close the current cursor object." }, { "code": null, "e": 98365, "s": 98351, "text": "executemany()" }, { "code": null, "e": 98484, "s": 98365, "text": "This method accepts a list series of parameters list. Prepares an MySQL query and executes it with all the parameters." }, { "code": null, "e": 98494, "s": 98484, "text": "execute()" }, { "code": null, "e": 98573, "s": 98494, "text": "This method accepts a MySQL query as a parameter and executes the given query." }, { "code": null, "e": 98584, "s": 98573, "text": "fetchall()" }, { "code": null, "e": 98761, "s": 98584, "text": "This method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows it returns the remaining ones)" }, { "code": null, "e": 98772, "s": 98761, "text": "fetchone()" }, { "code": null, "e": 98857, "s": 98772, "text": "This method fetches the next row in the result of a query and returns it as a tuple." }, { "code": null, "e": 98869, "s": 98857, "text": "fetchmany()" }, { "code": null, "e": 99004, "s": 98869, "text": "This method is similar to the fetchone() but, it retrieves the next set of rows in the result set of a query, instead of a single row." }, { "code": null, "e": 99055, "s": 99004, "text": "Following are the properties of the Cursor class −" }, { "code": null, "e": 99067, "s": 99055, "text": "description" }, { "code": null, "e": 99174, "s": 99067, "text": "This is a read only property which returns the list containing the description of columns in a result-set." }, { "code": null, "e": 99183, "s": 99174, "text": "astrowid" }, { "code": null, "e": 99359, "s": 99183, "text": "This is a read only property, if there are any auto-incremented columns in the table, this returns the value generated for that column in the last INSERT or, UPDATE operation." }, { "code": null, "e": 99368, "s": 99359, "text": "rowcount" }, { "code": null, "e": 99458, "s": 99368, "text": "This returns the number of rows returned/updated in case of SELECT and UPDATE operations." }, { "code": null, "e": 99465, "s": 99458, "text": "closed" }, { "code": null, "e": 99559, "s": 99465, "text": "This property specifies whether a cursor is closed or not, if so it returns true, else false." }, { "code": null, "e": 99570, "s": 99559, "text": "connection" }, { "code": null, "e": 99657, "s": 99570, "text": "This returns a reference to the connection object using which this cursor was created." }, { "code": null, "e": 99662, "s": 99657, "text": "name" }, { "code": null, "e": 99708, "s": 99662, "text": "This property returns the name of the cursor." }, { "code": null, "e": 99719, "s": 99708, "text": "scrollable" }, { "code": null, "e": 99786, "s": 99719, "text": "This property specifies whether a particular cursor is scrollable." }, { "code": null, "e": 100102, "s": 99786, "text": "SQLite3 can be integrated with Python using sqlite3 module, which was written by Gerhard Haring. It provides an SQL interface compliant with the DB-API 2.0 specification described by PEP 249. You do not need to install this module separately because it is shipped by default along with Python version 2.5.x onwards." }, { "code": null, "e": 100305, "s": 100102, "text": "To use sqlite3 module, you must first create a connection object that represents the database and then optionally you can create a cursor object, which will help you in executing all the SQL statements." }, { "code": null, "e": 100572, "s": 100305, "text": "Following are important sqlite3 module routines, which can suffice your requirement to work with SQLite database from your Python program. If you are looking for a more sophisticated application, then you can look into Python sqlite3 module's official documentation." }, { "code": null, "e": 100635, "s": 100572, "text": "sqlite3.connect(database [,timeout ,other optional arguments])" }, { "code": null, "e": 100867, "s": 100635, "text": "This API opens a connection to the SQLite database file. You can use \":memory:\" to open a database connection to a database that resides in RAM instead of on disk. If database is opened successfully, it returns a connection object." }, { "code": null, "e": 100900, "s": 100867, "text": "connection.cursor([cursorClass])" }, { "code": null, "e": 101137, "s": 100900, "text": "This routine creates a cursor which will be used throughout your database programming with Python. This method accepts a single optional parameter cursorClass. If supplied, this must be a custom cursor class that extends sqlite3.Cursor." }, { "code": null, "e": 101181, "s": 101137, "text": "cursor.execute(sql [, optional parameters])" }, { "code": null, "e": 101414, "s": 101181, "text": "This routine executes an SQL statement. The SQL statement may be parameterized (i. e. placeholders instead of SQL literals). The sqlite3 module supports two kinds of placeholders: question marks and named placeholders (named style)." }, { "code": null, "e": 101491, "s": 101414, "text": "For example − cursor.execute(\"insert into people values (?, ?)\", (who, age))" }, { "code": null, "e": 101539, "s": 101491, "text": "connection.execute(sql [, optional parameters])" }, { "code": null, "e": 101765, "s": 101539, "text": "This routine is a shortcut of the above execute method provided by the cursor object and it creates an intermediate cursor object by calling the cursor method, then calls the cursor's execute method with the parameters given." }, { "code": null, "e": 101808, "s": 101765, "text": "cursor.executemany(sql, seq_of_parameters)" }, { "code": null, "e": 101916, "s": 101808, "text": "This routine executes an SQL command against all parameter sequences or mappings found in the sequence sql." }, { "code": null, "e": 101958, "s": 101916, "text": "connection.executemany(sql[, parameters])" }, { "code": null, "e": 102128, "s": 101958, "text": "This routine is a shortcut that creates an intermediate cursor object by calling the cursor method, then calls the cursor.s executemany method with the parameters given." }, { "code": null, "e": 102161, "s": 102128, "text": "cursor.executescript(sql_script)" }, { "code": null, "e": 102400, "s": 102161, "text": "This routine executes multiple SQL statements at once provided in the form of script. It issues a COMMIT statement first, then executes the SQL script it gets as a parameter. All the SQL statements should be separated by a semi colon (;)." }, { "code": null, "e": 102437, "s": 102400, "text": "connection.executescript(sql_script)" }, { "code": null, "e": 102609, "s": 102437, "text": "This routine is a shortcut that creates an intermediate cursor object by calling the cursor method, then calls the cursor's executescript method with the parameters given." }, { "code": null, "e": 102636, "s": 102609, "text": "connection.total_changes()" }, { "code": null, "e": 102779, "s": 102636, "text": "This routine returns the total number of database rows that have been modified, inserted, or deleted since the database connection was opened." }, { "code": null, "e": 102799, "s": 102779, "text": "connection.commit()" }, { "code": null, "e": 102972, "s": 102799, "text": "This method commits the current transaction. If you don't call this method, anything you did since the last call to commit() is not visible from other database connections." }, { "code": null, "e": 102994, "s": 102972, "text": "connection.rollback()" }, { "code": null, "e": 103078, "s": 102994, "text": "This method rolls back any changes to the database since the last call to commit()." }, { "code": null, "e": 103097, "s": 103078, "text": "connection.close()" }, { "code": null, "e": 103296, "s": 103097, "text": "This method closes the database connection. Note that this does not automatically call commit(). If you just close your database connection without calling commit() first, your changes will be lost!" }, { "code": null, "e": 103314, "s": 103296, "text": "cursor.fetchone()" }, { "code": null, "e": 103439, "s": 103314, "text": "This method fetches the next row of a query result set, returning a single sequence, or None when no more data is available." }, { "code": null, "e": 103483, "s": 103439, "text": "cursor.fetchmany([size = cursor.arraysize])" }, { "code": null, "e": 103696, "s": 103483, "text": "This routine fetches the next set of rows of a query result, returning a list. An empty list is returned when no more rows are available. The method tries to fetch as many rows as indicated by the size parameter." }, { "code": null, "e": 103714, "s": 103696, "text": "cursor.fetchall()" }, { "code": null, "e": 103847, "s": 103714, "text": "This routine fetches all (remaining) rows of a query result, returning a list. An empty list is returned when no rows are available." }, { "code": null, "e": 104021, "s": 103847, "text": "To establish connection with SQLite Open command prompt, browse through the location of where you have installed SQLite and just execute the command sqlite3 as shown below −" }, { "code": null, "e": 104184, "s": 104021, "text": "You can communicate with SQLite2 database using the SQLite3 python module. To do so, first of all you need to establish a connection (create a connection object)." }, { "code": null, "e": 104259, "s": 104184, "text": "To establish a connection with SQLite3 database using python you need to −" }, { "code": null, "e": 104313, "s": 104259, "text": "Import the sqlite3 module using the import statement." }, { "code": null, "e": 104367, "s": 104313, "text": "Import the sqlite3 module using the import statement." }, { "code": null, "e": 104495, "s": 104367, "text": "The connect() method accepts the name of the database you need to connect with as a parameter and, returns a Connection object." }, { "code": null, "e": 104623, "s": 104495, "text": "The connect() method accepts the name of the database you need to connect with as a parameter and, returns a Connection object." }, { "code": null, "e": 104675, "s": 104623, "text": "import sqlite3\nconn = sqlite3.connect('example.db')" }, { "code": null, "e": 104719, "s": 104675, "text": "print(\"Connection established ..........\")\n" }, { "code": null, "e": 104797, "s": 104719, "text": "Using the SQLite CREATE TABLE statement you can create a table in a database." }, { "code": null, "e": 104860, "s": 104797, "text": "Following is the syntax to create a table in SQLite database −" }, { "code": null, "e": 105028, "s": 104860, "text": "CREATE TABLE database_name.table_name(\n column1 datatype PRIMARY KEY(one or more columns),\n column2 datatype,\n column3 datatype,\n .....\n columnN datatype\n);\n" }, { "code": null, "e": 105119, "s": 105028, "text": "Following SQLite query/statement creates a table with name CRICKETERS in SQLite database −" }, { "code": null, "e": 105287, "s": 105119, "text": "sqlite> CREATE TABLE CRICKETERS (\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Age int,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255)\n);\nsqlite>" }, { "code": null, "e": 105403, "s": 105287, "text": "Let us create one more table OdiStats describing the One-day cricket statistics of each player in CRICKETERS table." }, { "code": null, "e": 105555, "s": 105403, "text": "sqlite> CREATE TABLE ODIStats (\n First_Name VARCHAR(255),\n Matches INT,\n Runs INT,\n AVG FLOAT,\n Centuries INT,\n HalfCenturies INT\n);\nsqlite" }, { "code": null, "e": 105758, "s": 105555, "text": "You can get the list of tables in a database in SQLite database using the .tables command. After creating a table, if you can verify the list of tables you can observe the newly created table in it as −" }, { "code": null, "e": 105804, "s": 105758, "text": "sqlite> . tables\nCRICKETERS ODIStats\nsqlite>\n" }, { "code": null, "e": 105952, "s": 105804, "text": "The Cursor object contains all the methods to execute quires and fetch data etc. The cursor method of the connection class returns a cursor object." }, { "code": null, "e": 106015, "s": 105952, "text": "Therefore, to create a table in SQLite database using python −" }, { "code": null, "e": 106080, "s": 106015, "text": "Establish connection with a database using the connect() method." }, { "code": null, "e": 106145, "s": 106080, "text": "Establish connection with a database using the connect() method." }, { "code": null, "e": 106240, "s": 106145, "text": "Create a cursor object by invoking the cursor() method on the above created connection object." }, { "code": null, "e": 106335, "s": 106240, "text": "Create a cursor object by invoking the cursor() method on the above created connection object." }, { "code": null, "e": 106422, "s": 106335, "text": "Now execute the CREATE TABLE statement using the execute() method of the Cursor class." }, { "code": null, "e": 106509, "s": 106422, "text": "Now execute the CREATE TABLE statement using the execute() method of the Cursor class." }, { "code": null, "e": 106578, "s": 106509, "text": "Following Python program creates a table named Employee in SQLite3 −" }, { "code": null, "e": 107147, "s": 106578, "text": "import sqlite3\n\n#Connecting to sqlite\nconn = sqlite3.connect('example.db')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Doping EMPLOYEE table if already exists.\ncursor.execute(\"DROP TABLE IF EXISTS EMPLOYEE\")\n\n#Creating table as per requirement\nsql ='''CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT,\n SEX CHAR(1),\n INCOME FLOAT\n)'''\ncursor.execute(sql)\nprint(\"Table created successfully........\")\n\n# Commit your changes in the database\nconn.commit()\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 107183, "s": 107147, "text": "Table created successfully........\n" }, { "code": null, "e": 107382, "s": 107183, "text": "You can add new rows to an existing table of SQLite using the INSERT INTO statement. In this, you need to specify the name of the table, column names, and values (in the same order as column names)." }, { "code": null, "e": 107444, "s": 107382, "text": "Following is the recommended syntax of the INSERT statement −" }, { "code": null, "e": 107550, "s": 107444, "text": "INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)\nVALUES (value1, value2, value3,...valueN);\n" }, { "code": null, "e": 107707, "s": 107550, "text": "Where, column1, column2, column3,.. are the names of the columns of a table and value1, value2, value3,... are the values you need to insert into the table." }, { "code": null, "e": 107809, "s": 107707, "text": "Assume we have created a table with name CRICKETERS using the CREATE TABLE statement as shown below −" }, { "code": null, "e": 107977, "s": 107809, "text": "sqlite> CREATE TABLE CRICKETERS (\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Age int,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255)\n);\nsqlite>" }, { "code": null, "e": 108050, "s": 107977, "text": "Following PostgreSQL statement inserts a row in the above created table." }, { "code": null, "e": 108203, "s": 108050, "text": "sqlite> insert into CRICKETERS \n (First_Name, Last_Name, Age, Place_Of_Birth, Country) values\n ('Shikhar', 'Dhawan', 33, 'Delhi', 'India');\nsqlite>\n" }, { "code": null, "e": 108376, "s": 108203, "text": "While inserting records using the INSERT INTO statement, if you skip any columns names, this record will be inserted leaving empty spaces at columns which you have skipped." }, { "code": null, "e": 108502, "s": 108376, "text": "sqlite> insert into CRICKETERS \n (First_Name, Last_Name, Country) values \n ('Jonathan', 'Trott', 'SouthAfrica');\nsqlite>\n" }, { "code": null, "e": 108667, "s": 108502, "text": "You can also insert records into a table without specifying the column names, if the order of values you pass is same as their respective column names in the table." }, { "code": null, "e": 108924, "s": 108667, "text": "sqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');\nsqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');\nsqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');\nsqlite>" }, { "code": null, "e": 109037, "s": 108924, "text": "After inserting the records into a table you can verify its contents using the SELECT statement as shown below −" }, { "code": null, "e": 109309, "s": 109037, "text": "sqlite> select * from cricketers;\nShikhar | Dhawan | 33 | Delhi | India\nJonathan | Trott | | | SouthAfrica\nKumara | Sangakkara | 41 | Matale | Srilanka\nVirat | Kohli | 30 | Delhi | India\nRohit | Sharma | 32 | Nagpur | India\nsqlite>\n" }, { "code": null, "e": 109366, "s": 109309, "text": "To add records to an existing table in SQLite database −" }, { "code": null, "e": 109390, "s": 109366, "text": "Import sqlite3 package." }, { "code": null, "e": 109414, "s": 109390, "text": "Import sqlite3 package." }, { "code": null, "e": 109526, "s": 109414, "text": "Create a connection object using the connect() method by passing the name of the database as a parameter to it." }, { "code": null, "e": 109638, "s": 109526, "text": "Create a connection object using the connect() method by passing the name of the database as a parameter to it." }, { "code": null, "e": 109825, "s": 109638, "text": "The cursor() method returns a cursor object using which you can communicate with SQLite3. Create a cursor object by invoking the cursor() object on the (above created) Connection object." }, { "code": null, "e": 110012, "s": 109825, "text": "The cursor() method returns a cursor object using which you can communicate with SQLite3. Create a cursor object by invoking the cursor() object on the (above created) Connection object." }, { "code": null, "e": 110121, "s": 110012, "text": "Then, invoke the execute() method on the cursor object, by passing an INSERT statement as a parameter to it." }, { "code": null, "e": 110230, "s": 110121, "text": "Then, invoke the execute() method on the cursor object, by passing an INSERT statement as a parameter to it." }, { "code": null, "e": 110304, "s": 110230, "text": "Following python example inserts records into to a table named EMPLOYEE −" }, { "code": null, "e": 111334, "s": 110304, "text": "import sqlite3\n\n#Connecting to sqlite\nconn = sqlite3.connect('example.db')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n# Preparing SQL queries to INSERT a record into the database.\ncursor.execute('''INSERT INTO EMPLOYEE(\n FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES \n ('Ramya', 'Rama Priya', 27, 'F', 9000)''')\n\ncursor.execute('''INSERT INTO EMPLOYEE(\n FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES \n ('Vinay', 'Battacharya', 20, 'M', 6000)''')\n\ncursor.execute('''INSERT INTO EMPLOYEE(\n FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES \n ('Sharukh', 'Sheik', 25, 'M', 8300)''')\n\ncursor.execute('''INSERT INTO EMPLOYEE(\n FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES \n ('Sarmista', 'Sharma', 26, 'F', 10000)''')\n\ncursor.execute('''INSERT INTO EMPLOYEE(\n FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES \n ('Tripthi', 'Mishra', 24, 'F', 6000)''')\n\n# Commit your changes in the database\nconn.commit()\nprint(\"Records inserted........\")\n\n# Closing the connection\nconn.close()" }, { "code": null, "e": 111360, "s": 111334, "text": "Records inserted........\n" }, { "code": null, "e": 111546, "s": 111360, "text": "You can retrieve data from an SQLite table using the SELCT query. This query/statement returns contents of the specified relation (table) in tabular form and it is called as result-set." }, { "code": null, "e": 111606, "s": 111546, "text": "Following is the syntax of the SELECT statement in SQLite −" }, { "code": null, "e": 111657, "s": 111606, "text": "SELECT column1, column2, columnN FROM table_name;\n" }, { "code": null, "e": 111737, "s": 111657, "text": "Assume we have created a table with name CRICKETERS using the following query −" }, { "code": null, "e": 111905, "s": 111737, "text": "sqlite> CREATE TABLE CRICKETERS (\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Age int,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255)\n);\nsqlite>" }, { "code": null, "e": 111977, "s": 111905, "text": "And if we have inserted 5 records in to it using INSERT statements as −" }, { "code": null, "e": 112407, "s": 111977, "text": "sqlite> insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');\nsqlite> insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');\nsqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');\nsqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');\nsqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');\nsqlite>" }, { "code": null, "e": 112528, "s": 112407, "text": "Following SELECT query retrieves the values of the columns FIRST_NAME, LAST_NAME and, COUNTRY from the CRICKETERS table." }, { "code": null, "e": 112748, "s": 112528, "text": "sqlite> SELECT FIRST_NAME, LAST_NAME, COUNTRY FROM CRICKETERS;\nShikhar |Dhawan |India\nJonathan |Trott |SouthAfrica\nKumara |Sangakkara |Srilanka\nVirat |Kohli |India\nRohit |Sharma |India\nsqlite>" }, { "code": null, "e": 112996, "s": 112748, "text": "As you observe, the SELECT statement of the SQLite database just returns the records of the specified tables. To get a formatted output you need to set the header, and mode using the respective commands before the SELECT statement as shown below −" }, { "code": null, "e": 113389, "s": 112996, "text": "sqlite> .header on\nsqlite> .mode column\nsqlite> SELECT FIRST_NAME, LAST_NAME, COUNTRY FROM CRICKETERS;\nFirst_Name Last_Name Country\n---------- -------------------- ----------\nShikhar Dhawan India\nJonathan Trott SouthAfric\nKumara Sangakkara Srilanka\nVirat Kohli India\nRohit Sharma India\nsqlite>\n" }, { "code": null, "e": 113516, "s": 113389, "text": "If you want to retrieve all the columns of each record, you need to replace the names of the columns with \"*\" as shown below −" }, { "code": null, "e": 113992, "s": 113516, "text": "sqlite> .header on\nsqlite> .mode column\nsqlite> SELECT * FROM CRICKETERS;\nFirst_Name Last_Name Age Place_Of_Birth Country\n---------- ---------- ---------- -------------- ----------\nShikhar Dhawan 33 Delhi India\nJonathan Trott 38 CapeTown SouthAfric\nKumara Sangakkara 41 Matale Srilanka\nVirat Kohli 30 Delhi India\nRohit Sharma 32 Nagpur India\nsqlite>\n" }, { "code": null, "e": 114277, "s": 113992, "text": "In SQLite by default the width of the columns is 10 values beyond this width are chopped (observe the country column of 2nd row in above table). You can set the width of each column to required value using the .width command, before retrieving the contents of a table as shown below −" }, { "code": null, "e": 114680, "s": 114277, "text": "sqlite> .width 10, 10, 4, 10, 13\nsqlite> SELECT * FROM CRICKETERS;\nFirst_Name Last_Name Age Place_Of_B Country\n---------- ---------- ---- ---------- -------------\nShikhar Dhawan 33 Delhi India\nJonathan Trott 38 CapeTown SouthAfrica\nKumara Sangakkara 41 Matale Srilanka\nVirat Kohli 30 Delhi India\nRohit Sharma 32 Nagpur India\nsqlite>\n" }, { "code": null, "e": 114862, "s": 114680, "text": "READ Operation on any database means to fetch some useful information from the database. You can fetch data from MYSQL using the fetch() method provided by the sqlite python module." }, { "code": null, "e": 114964, "s": 114862, "text": "The sqlite3.Cursor class provides three methods namely fetchall(), fetchmany() and, fetchone() where," }, { "code": null, "e": 115152, "s": 114964, "text": "The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows it returns the remaining ones)." }, { "code": null, "e": 115340, "s": 115152, "text": "The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows it returns the remaining ones)." }, { "code": null, "e": 115435, "s": 115340, "text": "The fetchone() method fetches the next row in the result of a query and returns it as a tuple." }, { "code": null, "e": 115530, "s": 115435, "text": "The fetchone() method fetches the next row in the result of a query and returns it as a tuple." }, { "code": null, "e": 115676, "s": 115530, "text": "The fetchmany() method is similar to the fetchone() but, it retrieves the next set of rows in the result set of a query, instead of a single row." }, { "code": null, "e": 115822, "s": 115676, "text": "The fetchmany() method is similar to the fetchone() but, it retrieves the next set of rows in the result set of a query, instead of a single row." }, { "code": null, "e": 115919, "s": 115822, "text": "Note − A result set is an object that is returned when a cursor object is used to query a table." }, { "code": null, "e": 116173, "s": 115919, "text": "Following example fetches all the rows of the EMPLOYEE table using the SELECT query and from the obtained result set initially, we are retrieving the first row using the fetchone() method and then fetching the remaining rows using the fetchall() method." }, { "code": null, "e": 116290, "s": 116173, "text": "Following Python program shows how to fetch and display records from the COMPANY table created in the above example." }, { "code": null, "e": 116746, "s": 116290, "text": "import sqlite3\n\n#Connecting to sqlite\nconn = sqlite3.connect('example.db')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Retrieving data\ncursor.execute('''SELECT * from EMPLOYEE''')\n\n#Fetching 1st row from the table\nresult = cursor.fetchone();\nprint(result)\n\n#Fetching 1st row from the table\nresult = cursor.fetchall();\nprint(result)\n\n#Commit your changes in the database\nconn.commit()\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 116963, "s": 116746, "text": "('Ramya', 'Rama priya', 27, 'F', 9000.0)\n[('Vinay', 'Battacharya', 20, 'M', 6000.0),\n ('Sharukh', 'Sheik', 25, 'M', 8300.0),\n ('Sarmista', 'Sharma', 26, 'F', 10000.0),\n ('Tripthi', 'Mishra', 24, 'F', 6000.0)\n]\n" }, { "code": null, "e": 117146, "s": 116963, "text": "If you want to fetch, delete or, update particular rows of a table in SQLite, you need to use the where clause to specify condition to filter the rows of the table for the operation." }, { "code": null, "e": 117282, "s": 117146, "text": "For example, if you have a SELECT statement with where clause, only the rows which satisfies the specified condition will be retrieved." }, { "code": null, "e": 117338, "s": 117282, "text": "Following is the syntax of the WHERE clause in SQLite −" }, { "code": null, "e": 117413, "s": 117338, "text": "SELECT column1, column2, columnN\nFROM table_name\nWHERE [search_condition]\n" }, { "code": null, "e": 117571, "s": 117413, "text": "You can specify a search_condition using comparison or logical operators. like >, <, =, LIKE, NOT, etc. The following examples would make this concept clear." }, { "code": null, "e": 117651, "s": 117571, "text": "Assume we have created a table with name CRICKETERS using the following query −" }, { "code": null, "e": 117819, "s": 117651, "text": "sqlite> CREATE TABLE CRICKETERS (\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Age int,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255)\n);\nsqlite>" }, { "code": null, "e": 117891, "s": 117819, "text": "And if we have inserted 5 records in to it using INSERT statements as −" }, { "code": null, "e": 118321, "s": 117891, "text": "sqlite> insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');\nsqlite> insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');\nsqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');\nsqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');\nsqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');\nsqlite>" }, { "code": null, "e": 118401, "s": 118321, "text": "Following SELECT statement retrieves the records whose age is greater than 35 −" }, { "code": null, "e": 118654, "s": 118401, "text": "sqlite> SELECT * FROM CRICKETERS WHERE AGE > 35;\nFirst_Name Last_Name Age Place_Of_B Country\n---------- ---------- ---- ---------- -------------\nJonathan Trott 38 CapeTown SouthAfrica\nKumara Sangakkara 41 Matale Srilanka\nsqlite>\n" }, { "code": null, "e": 118810, "s": 118654, "text": "The Cursor object/class contains all the methods to execute queries and fetch data, etc. The cursor method of the connection class returns a cursor object." }, { "code": null, "e": 118873, "s": 118810, "text": "Therefore, to create a table in SQLite database using python −" }, { "code": null, "e": 118938, "s": 118873, "text": "Establish connection with a database using the connect() method." }, { "code": null, "e": 119003, "s": 118938, "text": "Establish connection with a database using the connect() method." }, { "code": null, "e": 119098, "s": 119003, "text": "Create a cursor object by invoking the cursor() method on the above created connection object." }, { "code": null, "e": 119193, "s": 119098, "text": "Create a cursor object by invoking the cursor() method on the above created connection object." }, { "code": null, "e": 119280, "s": 119193, "text": "Now execute the CREATE TABLE statement using the execute() method of the Cursor class." }, { "code": null, "e": 119367, "s": 119280, "text": "Now execute the CREATE TABLE statement using the execute() method of the Cursor class." }, { "code": null, "e": 119516, "s": 119367, "text": "Following example creates a table named Employee and populates it. Then using the where clause it retrieves the records with age value less than 23." }, { "code": null, "e": 120851, "s": 119516, "text": "import sqlite3\n\n#Connecting to sqlite\nconn = sqlite3.connect('example.db')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Doping EMPLOYEE table if already exists.\ncursor.execute(\"DROP TABLE IF EXISTS EMPLOYEE\")\nsql = '''CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT,\n SEX CHAR(1),\n INCOME FLOAT\n)'''\ncursor.execute(sql)\n\n#Populating the table\ncursor.execute('''INSERT INTO EMPLOYEE(\n FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES \n ('Ramya', 'Rama priya', 27, 'F', 9000)''')\n\ncursor.execute('''INSERT INTO EMPLOYEE\n (FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES \n ('Vinay', 'Battacharya', 20, 'M', 6000)''')\n\ncursor.execute('''INSERT INTO EMPLOYEE(\n FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES \n ('Sharukh', 'Sheik', 25, 'M', 8300)''')\n\ncursor.execute('''INSERT INTO EMPLOYEE(\n FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES \n ('Sarmista', 'Sharma', 26, 'F', 10000)''')\n\ncursor.execute('''INSERT INTO EMPLOYEE(\n FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES \n ('Tripthi', 'Mishra', 24, 'F', 6000)''')\n\n#Retrieving specific records using the where clause\ncursor.execute(\"SELECT * from EMPLOYEE WHERE AGE <23\")\nprint(cursor.fetchall())\n\n#Commit your changes in the database\nconn.commit()\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 120896, "s": 120851, "text": "[('Vinay', 'Battacharya', 20, 'M', 6000.0)]\n" }, { "code": null, "e": 121012, "s": 120896, "text": "While fetching data using SELECT query, you will get the records in the same order in which you have inserted them." }, { "code": null, "e": 121248, "s": 121012, "text": "You can sort the results in desired order (ascending or descending) using the Order By clause. By default, this clause sorts results in ascending order, if you need to arrange them in descending order you need to use “DESC” explicitly." }, { "code": null, "e": 121306, "s": 121248, "text": "Following is the syntax of the ORDER BY clause in SQLite." }, { "code": null, "e": 121414, "s": 121306, "text": "SELECT column-list\nFROM table_name\n[WHERE condition]\n[ORDER BY column1, column2, .. columnN] [ASC | DESC];\n" }, { "code": null, "e": 121494, "s": 121414, "text": "Assume we have created a table with name CRICKETERS using the following query −" }, { "code": null, "e": 121662, "s": 121494, "text": "sqlite> CREATE TABLE CRICKETERS (\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Age int,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255)\n);\nsqlite>" }, { "code": null, "e": 121734, "s": 121662, "text": "And if we have inserted 5 records in to it using INSERT statements as −" }, { "code": null, "e": 122164, "s": 121734, "text": "sqlite> insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');\nsqlite> insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');\nsqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');\nsqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');\nsqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');\nsqlite>" }, { "code": null, "e": 122272, "s": 122164, "text": "Following SELECT statement retrieves the rows of the CRICKETERS table in the ascending order of their age −" }, { "code": null, "e": 122655, "s": 122272, "text": "sqlite> SELECT * FROM CRICKETERS ORDER BY AGE;\nFirst_Name Last_Name Age Place_Of_B Country\n---------- ---------- ---- ---------- -------------\nVirat Kohli 30 Delhi India\nRohit Sharma 32 Nagpur India\nShikhar Dhawan 33 Delhi India\nJonathan Trott 38 CapeTown SouthAfrica\nKumara Sangakkara 41 Matale Srilanka\nsqlite>\n" }, { "code": null, "e": 122831, "s": 122655, "text": "You can use more than one column to sort the records of a table. Following SELECT statements sorts the records of the CRICKETERS table based on the columns AGE and FIRST_NAME." }, { "code": null, "e": 123226, "s": 122831, "text": "sqlite> SELECT * FROM CRICKETERS ORDER BY AGE, FIRST_NAME;\nFirst_Name Last_Name Age Place_Of_B Country\n---------- ---------- ---- ---------- -------------\nVirat Kohli 30 Delhi India\nRohit Sharma 32 Nagpur India\nShikhar Dhawan 33 Delhi India\nJonathan Trott 38 CapeTown SouthAfrica\nKumara Sangakkara 41 Matale Srilanka\nsqlite>\n" }, { "code": null, "e": 123370, "s": 123226, "text": "By default, the ORDER BY clause sorts the records of a table in ascending order you can arrange the results in descending order using DESC as −" }, { "code": null, "e": 123758, "s": 123370, "text": "sqlite> SELECT * FROM CRICKETERS ORDER BY AGE DESC;\nFirst_Name Last_Name Age Place_Of_B Country\n---------- ---------- ---- ---------- -------------\nKumara Sangakkara 41 Matale Srilanka\nJonathan Trott 38 CapeTown SouthAfrica\nShikhar Dhawan 33 Delhi India\nRohit Sharma 32 Nagpur India\nVirat Kohli 30 Delhi India\nsqlite>\n" }, { "code": null, "e": 123939, "s": 123758, "text": "To retrieve contents of a table in specific order, invoke the execute() method on the cursor object and, pass the SELECT statement along with ORDER BY clause, as a parameter to it." }, { "code": null, "e": 124125, "s": 123939, "text": "In the following example we are creating a table with name and Employee, populating it, and retrieving its records back in the (ascending) order of their age, using the ORDER BY clause." }, { "code": null, "e": 125280, "s": 124125, "text": "import psycopg2\n\n#establishing the connection\nconn = psycopg2.connect(\n database=\"mydb\", user='postgres', password='password', host='127.0.0.1', port= '5432'\n)\n#Setting auto commit false\nconn.autocommit = True\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Doping EMPLOYEE table if already exists.\ncursor.execute(\"DROP TABLE IF EXISTS EMPLOYEE\")\n\n#Creating a table\nsql = '''CREATE TABLE EMPLOYEE(\nFIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT, SEX CHAR(1),\n INCOME INT,\n CONTACT INT\n)'''\ncursor.execute(sql)\n\n#Populating the table\n#Populating the table\ncursor.execute('''INSERT INTO EMPLOYEE\n (FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES \n ('Ramya', 'Rama priya', 27, 'F', 9000),\n ('Vinay', 'Battacharya', 20, 'M', 6000), \n ('Sharukh', 'Sheik', 25, 'M', 8300), \n ('Sarmista', 'Sharma', 26, 'F', 10000),\n ('Tripthi', 'Mishra', 24, 'F', 6000)''')\nconn.commit()\n\n#Retrieving specific records using the ORDER BY clause\ncursor.execute(\"SELECT * from EMPLOYEE ORDER BY AGE\")\nprint(cursor.fetchall())\n\n#Commit your changes in the database\nconn.commit()\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 125520, "s": 125280, "text": "[('Vinay', 'Battacharya', 20, 'M', 6000, None),\n ('Tripthi', 'Mishra', 24, 'F', 6000, None),\n ('Sharukh', 'Sheik', 25, 'M', 8300, None),\n ('Sarmista', 'Sharma', 26, 'F', 10000, None),\n ('Ramya', 'Rama priya', 27, 'F', 9000, None)]\n" }, { "code": null, "e": 125746, "s": 125520, "text": "UPDATE Operation on any database implies modifying the values of one or more records of a table, which are already available in the database. You can update the values of existing records in SQLite using the UPDATE statement." }, { "code": null, "e": 125819, "s": 125746, "text": "To update specific rows, you need to use the WHERE clause along with it." }, { "code": null, "e": 125879, "s": 125819, "text": "Following is the syntax of the UPDATE statement in SQLite −" }, { "code": null, "e": 125978, "s": 125879, "text": "UPDATE table_name\nSET column1 = value1, column2 = value2...., columnN = valueN\nWHERE [condition];\n" }, { "code": null, "e": 126058, "s": 125978, "text": "Assume we have created a table with name CRICKETERS using the following query −" }, { "code": null, "e": 126226, "s": 126058, "text": "sqlite> CREATE TABLE CRICKETERS (\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Age int,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255)\n);\nsqlite>" }, { "code": null, "e": 126298, "s": 126226, "text": "And if we have inserted 5 records in to it using INSERT statements as −" }, { "code": null, "e": 126728, "s": 126298, "text": "sqlite> insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');\nsqlite> insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');\nsqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');\nsqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');\nsqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');\nsqlite>" }, { "code": null, "e": 126813, "s": 126728, "text": "Following Statement modifies the age of the cricketer, whose first name is Shikhar −" }, { "code": null, "e": 126892, "s": 126813, "text": "sqlite> UPDATE CRICKETERS SET AGE = 45 WHERE FIRST_NAME = 'Shikhar' ;\nsqlite>\n" }, { "code": null, "e": 127003, "s": 126892, "text": "If you retrieve the record whose FIRST_NAME is Shikhar you observe that the age value has been changed to 45 −" }, { "code": null, "e": 127217, "s": 127003, "text": "sqlite> SELECT * FROM CRICKETERS WHERE FIRST_NAME = 'Shikhar';\nFirst_Name Last_Name Age Place_Of_B Country\n---------- ---------- ---- ---------- -------------\nShikhar Dhawan 45 Delhi India\nsqlite>\n" }, { "code": null, "e": 127392, "s": 127217, "text": "If you haven’t used the WHERE clause values of all the records will be updated. Following UPDATE statement increases the age of all the records in the CRICKETERS table by 1 −" }, { "code": null, "e": 127444, "s": 127392, "text": "sqlite> UPDATE CRICKETERS SET AGE = AGE+1;\nsqlite>\n" }, { "code": null, "e": 127544, "s": 127444, "text": "If you retrieve the contents of the table using SELECT command, you can see the updated values as −" }, { "code": null, "e": 127914, "s": 127544, "text": "sqlite> SELECT * FROM CRICKETERS;\nFirst_Name Last_Name Age Place_Of_B Country\n---------- ---------- ---- ---------- -------------\nShikhar Dhawan 46 Delhi India\nJonathan Trott 39 CapeTown SouthAfrica\nKumara Sangakkara 42 Matale Srilanka\nVirat Kohli 31 Delhi India\nRohit Sharma 33 Nagpur India\nsqlite>\n" }, { "code": null, "e": 127971, "s": 127914, "text": "To add records to an existing table in SQLite database −" }, { "code": null, "e": 127995, "s": 127971, "text": "Import sqlite3 package." }, { "code": null, "e": 128019, "s": 127995, "text": "Import sqlite3 package." }, { "code": null, "e": 128131, "s": 128019, "text": "Create a connection object using the connect() method by passing the name of the database as a parameter to it." }, { "code": null, "e": 128243, "s": 128131, "text": "Create a connection object using the connect() method by passing the name of the database as a parameter to it." }, { "code": null, "e": 128431, "s": 128243, "text": "The cursor() method returns a cursor object using which you can communicate with SQLite3 . Create a cursor object by invoking the cursor() object on the (above created) Connection object." }, { "code": null, "e": 128619, "s": 128431, "text": "The cursor() method returns a cursor object using which you can communicate with SQLite3 . Create a cursor object by invoking the cursor() object on the (above created) Connection object." }, { "code": null, "e": 128728, "s": 128619, "text": "Then, invoke the execute() method on the cursor object, by passing an UPDATE statement as a parameter to it." }, { "code": null, "e": 128837, "s": 128728, "text": "Then, invoke the execute() method on the cursor object, by passing an UPDATE statement as a parameter to it." }, { "code": null, "e": 128981, "s": 128837, "text": "Following Python example, creates a table with name EMPLOYEE, inserts 5 records into it and, increases the age of all the male employees by 1 −" }, { "code": null, "e": 130310, "s": 128981, "text": "import sqlite3\n\n#Connecting to sqlite\nconn = sqlite3.connect('example.db')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Doping EMPLOYEE table if already exists.\ncursor.execute(\"DROP TABLE IF EXISTS EMPLOYEE\")\n\n#Creating table as per requirement\nsql ='''CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT,\n SEX CHAR(1),\n INCOME FLOAT\n)'''\ncursor.execute(sql)\n\n#Inserting data\ncursor.execute('''INSERT INTO EMPLOYEE\n (FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES \n ('Ramya', 'Rama priya', 27, 'F', 9000),\n ('Vinay', 'Battacharya', 20, 'M', 6000), \n ('Sharukh', 'Sheik', 25, 'M', 8300), \n ('Sarmista', 'Sharma', 26, 'F', 10000),\n ('Tripthi', 'Mishra', 24, 'F', 6000)''')\nconn.commit()\n\n#Fetching all the rows before the update\nprint(\"Contents of the Employee table: \")\ncursor.execute('''SELECT * from EMPLOYEE''')\nprint(cursor.fetchall())\n\n#Updating the records\nsql = '''UPDATE EMPLOYEE SET AGE=AGE+1 WHERE SEX = 'M' '''\ncursor.execute(sql)\nprint(\"Table updated...... \")\n\n#Fetching all the rows after the update\nprint(\"Contents of the Employee table after the update operation: \")\ncursor.execute('''SELECT * from EMPLOYEE''')\nprint(cursor.fetchall())\n\n#Commit your changes in the database\nconn.commit()\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 130868, "s": 130310, "text": "Contents of the Employee table:\n[('Ramya', 'Rama priya', 27, 'F', 9000.0), \n ('Vinay', 'Battacharya', 20, 'M', 6000.0), \n ('Sharukh', 'Sheik', 25, 'M', 8300.0), \n ('Sarmista', 'Sharma', 26, 'F', 10000.0), \n ('Tripthi', 'Mishra', 24, 'F', 6000.0)]\nTable updated......\nContents of the Employee table after the update operation:\n[('Ramya', 'Rama priya', 27, 'F', 9000.0), \n ('Vinay', 'Battacharya', 21, 'M', 6000.0), \n ('Sharukh', 'Sheik', 26, 'M', 8300.0), \n ('Sarmista', 'Sharma', 26, 'F', 10000.0), \n ('Tripthi', 'Mishra', 24, 'F', 6000.0)]\n" }, { "code": null, "e": 131022, "s": 130868, "text": "To delete records from a SQLite table, you need to use the DELETE FROM statement. To remove specific records, you need to use WHERE clause along with it." }, { "code": null, "e": 131095, "s": 131022, "text": "To update specific rows, you need to use the WHERE clause along with it." }, { "code": null, "e": 131151, "s": 131095, "text": "Following is the syntax of the DELETE query in SQLite −" }, { "code": null, "e": 131190, "s": 131151, "text": "DELETE FROM table_name [WHERE Clause]\n" }, { "code": null, "e": 131270, "s": 131190, "text": "Assume we have created a table with name CRICKETERS using the following query −" }, { "code": null, "e": 131438, "s": 131270, "text": "sqlite> CREATE TABLE CRICKETERS (\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Age int,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255)\n);\nsqlite>" }, { "code": null, "e": 131510, "s": 131438, "text": "And if we have inserted 5 records in to it using INSERT statements as −" }, { "code": null, "e": 131940, "s": 131510, "text": "sqlite> insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');\nsqlite> insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');\nsqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');\nsqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');\nsqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');\nsqlite>" }, { "code": null, "e": 132029, "s": 131940, "text": "Following statement deletes the record of the cricketer whose last name is 'Sangakkara'." }, { "code": null, "e": 132101, "s": 132029, "text": "sqlite> DELETE FROM CRICKETERS WHERE LAST_NAME = 'Sangakkara';\nsqlite>\n" }, { "code": null, "e": 132225, "s": 132101, "text": "If you retrieve the contents of the table using the SELECT statement, you can see only 4 records since we have deleted one." }, { "code": null, "e": 132548, "s": 132225, "text": "sqlite> SELECT * FROM CRICKETERS;\nFirst_Name Last_Name Age Place_Of_B Country\n---------- ---------- ---- ---------- -------------\nShikhar Dhawan 46 Delhi India\nJonathan Trott 39 CapeTown SouthAfrica\nVirat Kohli 31 Delhi India\nRohit Sharma 33 Nagpur India\nsqlite>\n" }, { "code": null, "e": 132673, "s": 132548, "text": "If you execute the DELETE FROM statement without the WHERE clause, all the records from the specified table will be deleted." }, { "code": null, "e": 132714, "s": 132673, "text": "sqlite> DELETE FROM CRICKETERS;\nsqlite>\n" }, { "code": null, "e": 132888, "s": 132714, "text": "Since you have deleted all the records, if you try to retrieve the contents of the CRICKETERS table, using SELECT statement you will get an empty result set as shown below −" }, { "code": null, "e": 132931, "s": 132888, "text": "sqlite> SELECT * FROM CRICKETERS;\nsqlite>\n" }, { "code": null, "e": 132988, "s": 132931, "text": "To add records to an existing table in SQLite database −" }, { "code": null, "e": 133012, "s": 132988, "text": "Import sqlite3 package." }, { "code": null, "e": 133036, "s": 133012, "text": "Import sqlite3 package." }, { "code": null, "e": 133148, "s": 133036, "text": "Create a connection object using the connect() method by passing the name of the database as a parameter to it." }, { "code": null, "e": 133260, "s": 133148, "text": "Create a connection object using the connect() method by passing the name of the database as a parameter to it." }, { "code": null, "e": 133448, "s": 133260, "text": "The cursor() method returns a cursor object using which you can communicate with SQLite3 . Create a cursor object by invoking the cursor() object on the (above created) Connection object." }, { "code": null, "e": 133636, "s": 133448, "text": "The cursor() method returns a cursor object using which you can communicate with SQLite3 . Create a cursor object by invoking the cursor() object on the (above created) Connection object." }, { "code": null, "e": 133745, "s": 133636, "text": "Then, invoke the execute() method on the cursor object, by passing an DELETE statement as a parameter to it." }, { "code": null, "e": 133854, "s": 133745, "text": "Then, invoke the execute() method on the cursor object, by passing an DELETE statement as a parameter to it." }, { "code": null, "e": 133951, "s": 133854, "text": "Following python example deletes the records from EMPLOYEE table with age value greater than 25." }, { "code": null, "e": 134559, "s": 133951, "text": "import sqlite3\n\n#Connecting to sqlite\nconn = sqlite3.connect('example.db')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Retrieving contents of the table\nprint(\"Contents of the table: \")\ncursor.execute('''SELECT * from EMPLOYEE''')\nprint(cursor.fetchall())\n\n#Deleting records\ncursor.execute('''DELETE FROM EMPLOYEE WHERE AGE > 25''')\n\n#Retrieving data after delete\nprint(\"Contents of the table after delete operation \")\ncursor.execute(\"SELECT * from EMPLOYEE\")\nprint(cursor.fetchall())\n\n#Commit your changes in the database\nconn.commit()\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 134939, "s": 134559, "text": "Contents of the table:\n[('Ramya', 'Rama priya', 27, 'F', 9000.0), \n ('Vinay', 'Battacharya', 21, 'M', 6000.0), \n ('Sharukh', 'Sheik', 26, 'M', 8300.0), \n ('Sarmista', 'Sharma', 26, 'F', 10000.0), \n ('Tripthi', 'Mishra', 24, 'F', 6000.0)]\nContents of the table after delete operation\n[('Vinay', 'Battacharya', 21, 'M', 6000.0), \n ('Tripthi', 'Mishra', 24, 'F', 6000.0)]\n" }, { "code": null, "e": 135069, "s": 134939, "text": "You can remove an entire table using the DROP TABLE statement. You just need to specify the name of the table you need to delete." }, { "code": null, "e": 135137, "s": 135069, "text": "Following is the syntax of the DROP TABLE statement in PostgreSQL −" }, { "code": null, "e": 135161, "s": 135137, "text": "DROP TABLE table_name;\n" }, { "code": null, "e": 135260, "s": 135161, "text": "Assume we have created two tables with name CRICKETERS and EMPLOYEES using the following queries −" }, { "code": null, "e": 135546, "s": 135260, "text": "sqlite> CREATE TABLE CRICKETERS (\n First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, \n Place_Of_Birth VARCHAR(255), Country VARCHAR(255)\n);\nsqlite> CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, \n SEX CHAR(1), INCOME FLOAT\n);\nsqlite>" }, { "code": null, "e": 135666, "s": 135546, "text": "Now if you verify the list of tables using the .tables command, you can see the above created tables in it ( list) as −" }, { "code": null, "e": 135711, "s": 135666, "text": "sqlite> .tables\nCRICKETERS EMPLOYEE\nsqlite>\n" }, { "code": null, "e": 135784, "s": 135711, "text": "Following statement deletes the table named Employee from the database −" }, { "code": null, "e": 135822, "s": 135784, "text": "sqlite> DROP table employee;\nsqlite>\n" }, { "code": null, "e": 135945, "s": 135822, "text": "Since you have deleted the Employee table, if you retrieve the list of tables again, you can observe only one table in it." }, { "code": null, "e": 135981, "s": 135945, "text": "sqlite> .tables\nCRICKETERS\nsqlite>\n" }, { "code": null, "e": 136124, "s": 135981, "text": "If you try to delete the Employee table again, since you have already deleted it you will get an error saying “no such table” as shown below −" }, { "code": null, "e": 136193, "s": 136124, "text": "sqlite> DROP table employee;\nError: no such table: employee\nsqlite>\n" }, { "code": null, "e": 136343, "s": 136193, "text": "To resolve this, you can use the IF EXISTS clause along with the DELTE statement. This removes the table if it exists else skips the DLETE operation." }, { "code": null, "e": 136391, "s": 136343, "text": "sqlite> DROP table IF EXISTS employee;\nsqlite>\n" }, { "code": null, "e": 136603, "s": 136391, "text": "You can drop a table whenever you need to, using the DROP statement of MYSQL, but you need to be very careful while deleting any existing table because the data lost will not be recovered after deleting a table." }, { "code": null, "e": 136755, "s": 136603, "text": "To drop a table from a SQLite3 database using python invoke the execute() method on the cursor object and pass the drop statement as a parameter to it." }, { "code": null, "e": 137098, "s": 136755, "text": "import sqlite3\n\n#Connecting to sqlite\nconn = sqlite3.connect('example.db')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Doping EMPLOYEE table if already exists\ncursor.execute(\"DROP TABLE emp\")\nprint(\"Table dropped... \")\n\n#Commit your changes in the database\nconn.commit()\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 137116, "s": 137098, "text": "Table dropped...\n" }, { "code": null, "e": 137238, "s": 137116, "text": "While fetching records if you want to limit them by a particular number, you can do so, using the LIMIT clause of SQLite." }, { "code": null, "e": 137294, "s": 137238, "text": "Following is the syntax of the LIMIT clause in SQLite −" }, { "code": null, "e": 137363, "s": 137294, "text": "SELECT column1, column2, columnN\nFROM table_name\nLIMIT [no of rows]\n" }, { "code": null, "e": 137443, "s": 137363, "text": "Assume we have created a table with name CRICKETERS using the following query −" }, { "code": null, "e": 137611, "s": 137443, "text": "sqlite> CREATE TABLE CRICKETERS (\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Age int,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255)\n);\nsqlite>" }, { "code": null, "e": 137683, "s": 137611, "text": "And if we have inserted 5 records in to it using INSERT statements as −" }, { "code": null, "e": 138113, "s": 137683, "text": "sqlite> insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');\nsqlite> insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');\nsqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');\nsqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');\nsqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');\nsqlite>" }, { "code": null, "e": 138212, "s": 138113, "text": "Following statement retrieves the first 3 records of the Cricketers table using the LIMIT clause −" }, { "code": null, "e": 138502, "s": 138212, "text": "sqlite> SELECT * FROM CRICKETERS LIMIT 3;\nFirst_Name Last_Name Age Place_Of_B Country\n---------- ---------- ---- ---------- -------------\nShikhar Dhawan 33 Delhi India\nJonathan Trott 38 CapeTown SouthAfrica\nKumara Sangakkara 41 Matale Srilanka\nsqlite>\n" }, { "code": null, "e": 138617, "s": 138502, "text": "If you need to limit the records starting from nth record (not 1st), you can do so, using OFFSET along with LIMIT." }, { "code": null, "e": 138910, "s": 138617, "text": "sqlite> SELECT * FROM CRICKETERS LIMIT 3 OFFSET 2;\nFirst_Name Last_Name Age Place_Of_B Country\n---------- ---------- ---- ---------- -------------\nKumara Sangakkara 41 Matale Srilanka\nVirat Kohli 30 Delhi India\nRohit Sharma 32 Nagpur India\nsqlite>\n" }, { "code": null, "e": 139068, "s": 138910, "text": "If you Invoke the execute() method on the cursor object by passing the SELECT query along with the LIMIT clause, you can retrieve required number of records." }, { "code": null, "e": 139171, "s": 139068, "text": "Following python example retrieves the first two records of the EMPLOYEE table using the LIMIT clause." }, { "code": null, "e": 139583, "s": 139171, "text": "import sqlite3\n\n#Connecting to sqlite\nconn = sqlite3.connect('example.db')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Retrieving single row\nsql = '''SELECT * from EMPLOYEE LIMIT 3'''\n\n#Executing the query\ncursor.execute(sql)\n\n#Fetching the data\nresult = cursor.fetchall();\nprint(result)\n\n#Commit your changes in the database\nconn.commit()\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 139717, "s": 139583, "text": "[('Ramya', 'Rama priya', 27, 'F', 9000.0), \n ('Vinay', 'Battacharya', 20, 'M', 6000.0), \n ('Sharukh', 'Sheik', 25, 'M', 8300.0)]\n" }, { "code": null, "e": 139828, "s": 139717, "text": "When you have divided the data in two tables you can fetch combined records from these two tables using Joins." }, { "code": null, "e": 139908, "s": 139828, "text": "Assume we have created a table with name CRICKETERS using the following query −" }, { "code": null, "e": 140077, "s": 139908, "text": "sqlite> CREATE TABLE CRICKETERS (\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Age int,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255)\n);\nsqlite>\n" }, { "code": null, "e": 140193, "s": 140077, "text": "Let us create one more table OdiStats describing the One-day cricket statistics of each player in CRICKETERS table." }, { "code": null, "e": 140346, "s": 140193, "text": "sqlite> CREATE TABLE ODIStats (\n First_Name VARCHAR(255),\n Matches INT,\n Runs INT,\n AVG FLOAT,\n Centuries INT,\n HalfCenturies INT\n);\nsqlite>" }, { "code": null, "e": 140424, "s": 140346, "text": "Following statement retrieves data combining the values in these two tables −" }, { "code": null, "e": 141205, "s": 140424, "text": "sqlite> SELECT\n Cricketers.First_Name, Cricketers.Last_Name, Cricketers.Country,\n OdiStats.matches, OdiStats.runs, OdiStats.centuries, OdiStats.halfcenturies\n from Cricketers INNER JOIN OdiStats ON Cricketers.First_Name = OdiStats.First_Name;\nFirst_Name Last_Name Country Matches Runs Centuries HalfCenturies\n---------- ---------- ------- ---------- ------------- ---------- ----------\nShikhar Dhawan Indi 133 5518 17 27\nJonathan Trott Sout 68 2819 4 22\nKumara Sangakkara Sril 404 14234 25 93\nVirat Kohli Indi 239 11520 43 54\nRohit Sharma Indi 218 8686 24 42\nsqlite>\n" }, { "code": null, "e": 141275, "s": 141205, "text": "Following SQLite example, demonstrates the JOIN clause using python −" }, { "code": null, "e": 141729, "s": 141275, "text": "import sqlite3\n\n#Connecting to sqlite\nconn = sqlite3.connect('example.db')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Retrieving data\nsql = '''SELECT * from EMP INNER JOIN CONTACT ON EMP.CONTACT = CONTACT.ID'''\n\n#Executing the query\ncursor.execute(sql)\n\n#Fetching 1st row from the table\nresult = cursor.fetchall();\nprint(result)\n\n#Commit your changes in the database\nconn.commit()\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 142079, "s": 141729, "text": "[('Ramya', 'Rama priya', 27, 'F', 9000.0, 101, 101, '[email protected]', 'Hyderabad'), \n ('Vinay', 'Battacharya', 20, 'M', 6000.0, 102, 102,'[email protected]', 'Vishakhapatnam'), \n ('Sharukh', 'Sheik', 25, 'M', 8300.0, 103, 103, '[email protected]', 'Pune'), \n ('Sarmista', 'Sharma', 26, 'F', 10000.0, 104, 104, '[email protected]', 'Mumbai')]\n" }, { "code": null, "e": 142321, "s": 142079, "text": "The sqlite3.Cursor class is an instance using which you can invoke methods that execute SQLite statements, fetch data from the result sets of the queries. You can create Cursor object using the cursor() method of the Connection object/class." }, { "code": null, "e": 142472, "s": 142321, "text": "import sqlite3\n\n#Connecting to sqlite\nconn = sqlite3.connect('example.db')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()" }, { "code": null, "e": 142543, "s": 142472, "text": "Following are the various methods provided by the Cursor class/object." }, { "code": null, "e": 142553, "s": 142543, "text": "execute()" }, { "code": null, "e": 142733, "s": 142553, "text": "This routine executes an SQL statement. The SQL statement may be parameterized (i.e., placeholders instead of SQL literals). The psycopg2 module supports placeholder using %s sign" }, { "code": null, "e": 142810, "s": 142733, "text": "For example:cursor.execute(\"insert into people values (%s, %s)\", (who, age))" }, { "code": null, "e": 142824, "s": 142810, "text": "executemany()" }, { "code": null, "e": 142932, "s": 142824, "text": "This routine executes an SQL command against all parameter sequences or mappings found in the sequence sql." }, { "code": null, "e": 142943, "s": 142932, "text": "fetchone()" }, { "code": null, "e": 143068, "s": 142943, "text": "This method fetches the next row of a query result set, returning a single sequence, or None when no more data is available." }, { "code": null, "e": 143080, "s": 143068, "text": "fetchmany()" }, { "code": null, "e": 143293, "s": 143080, "text": "This routine fetches the next set of rows of a query result, returning a list. An empty list is returned when no more rows are available. The method tries to fetch as many rows as indicated by the size parameter." }, { "code": null, "e": 143304, "s": 143293, "text": "fetchall()" }, { "code": null, "e": 143437, "s": 143304, "text": "This routine fetches all (remaining) rows of a query result, returning a list. An empty list is returned when no rows are available." }, { "code": null, "e": 143488, "s": 143437, "text": "Following are the properties of the Cursor class −" }, { "code": null, "e": 143498, "s": 143488, "text": "arraySize" }, { "code": null, "e": 143595, "s": 143498, "text": "This is a read/write property you can set the number of rows returned by the fetchmany() method." }, { "code": null, "e": 143607, "s": 143595, "text": "description" }, { "code": null, "e": 143714, "s": 143607, "text": "This is a read only property which returns the list containing the description of columns in a result-set." }, { "code": null, "e": 143724, "s": 143714, "text": "lastrowid" }, { "code": null, "e": 143900, "s": 143724, "text": "This is a read only property, if there are any auto-incremented columns in the table, this returns the value generated for that column in the last INSERT or, UPDATE operation." }, { "code": null, "e": 143909, "s": 143900, "text": "rowcount" }, { "code": null, "e": 143999, "s": 143909, "text": "This returns the number of rows returned/updated in case of SELECT and UPDATE operations." }, { "code": null, "e": 144010, "s": 143999, "text": "connection" }, { "code": null, "e": 144102, "s": 144010, "text": "This read-only attribute provides the SQLite database Connection used by the Cursor object." }, { "code": null, "e": 144257, "s": 144102, "text": "Pymongo is a python distribution which provides tools to work with MongoDB, it is the most preferred way to communicate with MongoDB database from python." }, { "code": null, "e": 144401, "s": 144257, "text": "To install pymongo first of all make sure you have installed python3 (along with PIP) and MongoDB properly. Then execute the following command." }, { "code": null, "e": 144692, "s": 144401, "text": "C:\\WINDOWS\\system32>pip install pymongo\nCollecting pymongo\nUsing cached https://files.pythonhosted.org/packages/cb/a6/b0ae3781b0ad75825e00e29dc5489b53512625e02328d73556e1ecdf12f8/pymongo-3.9.0-cp37-cp37m-win32.whl\nInstalling collected packages: pymongo\nSuccessfully installed pymongo-3.9.0\n" }, { "code": null, "e": 144807, "s": 144692, "text": "Once you have installed pymongo, open a new text document, paste the following line in it and, save it as test.py." }, { "code": null, "e": 144823, "s": 144807, "text": "import pymongo\n" }, { "code": null, "e": 144937, "s": 144823, "text": "If you have installed pymongo properly, if you execute the test.py as shown below, you should not get any issues." }, { "code": null, "e": 144983, "s": 144937, "text": "D:\\Python_MongoDB>test.py\nD:\\Python_MongoDB>\n" }, { "code": null, "e": 145071, "s": 144983, "text": "Unlike other databases, MongoDB does not provide separate command to create a database." }, { "code": null, "e": 145343, "s": 145071, "text": "In general, the use command is used to select/switch to the specific database. This command initially verifies whether the database we specify exists, if so, it connects to it. If the database, we specify with the use command doesn’t exist a new database will be created." }, { "code": null, "e": 145414, "s": 145343, "text": "Therefore, you can create a database in MongoDB using the Use command." }, { "code": null, "e": 145469, "s": 145414, "text": "Basic syntax of use DATABASE statement is as follows −" }, { "code": null, "e": 145488, "s": 145469, "text": "use DATABASE_NAME\n" }, { "code": null, "e": 145540, "s": 145488, "text": "Following command creates a database named in mydb." }, { "code": null, "e": 145571, "s": 145540, "text": ">use mydb\nswitched to db mydb\n" }, { "code": null, "e": 145661, "s": 145571, "text": "You can verify your creation by using the db command, this displays the current database." }, { "code": null, "e": 145671, "s": 145661, "text": ">db\nmydb\n" }, { "code": null, "e": 145836, "s": 145671, "text": "To connect to MongoDB using pymongo, you need to import and create a MongoClient, then you can directly access the database you need to create in attribute passion." }, { "code": null, "e": 145885, "s": 145836, "text": "Following example creates a database in MangoDB." }, { "code": null, "e": 146173, "s": 145885, "text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['mydb']\nprint(\"Database created........\")\n\n#Verification\nprint(\"List of databases after creating new one\")\nprint(client.list_database_names())" }, { "code": null, "e": 146278, "s": 146173, "text": "Database created........\nList of databases after creating new one:\n['admin', 'config', 'local', 'mydb']\n" }, { "code": null, "e": 146402, "s": 146278, "text": "You can also specify the port and host names while creating a MongoClient and can access the databases in dictionary style." }, { "code": null, "e": 146589, "s": 146402, "text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['mydb']\nprint(\"Database created........\")" }, { "code": null, "e": 146615, "s": 146589, "text": "Database created........\n" }, { "code": null, "e": 146717, "s": 146615, "text": "A collection in MongoDB holds a set of documents, it is analogous to a table in relational databases." }, { "code": null, "e": 146908, "s": 146717, "text": "You can create a collection using the createCollection() method. This method accepts a String value representing the name of the collection to be created and an options (optional) parameter." }, { "code": null, "e": 146951, "s": 146908, "text": "Using this you can specify the following −" }, { "code": null, "e": 146979, "s": 146951, "text": "The size of the collection." }, { "code": null, "e": 147041, "s": 146979, "text": "The max number of documents allowed in the capped collection." }, { "code": null, "e": 147127, "s": 147041, "text": "Whether the collection we create should be capped collection (fixed size collection)." }, { "code": null, "e": 147184, "s": 147127, "text": "Whether the collection we create should be auto-indexed." }, { "code": null, "e": 147243, "s": 147184, "text": "Following is the syntax to create a collection in MongoDB." }, { "code": null, "e": 147282, "s": 147243, "text": "db.createCollection(\"CollectionName\")\n" }, { "code": null, "e": 147345, "s": 147282, "text": "Following method creates a collection named ExampleCollection." }, { "code": null, "e": 147435, "s": 147345, "text": "> use mydb\nswitched to db mydb\n> db.createCollection(\"ExampleCollection\")\n{ \"ok\" : 1 }\n>\n" }, { "code": null, "e": 147545, "s": 147435, "text": "Similarly, following is a query that creates a collection using the options of the createCollection() method." }, { "code": null, "e": 147660, "s": 147545, "text": ">db.createCollection(\"mycol\", { capped : true, autoIndexId : true, size :\n6142800, max : 10000 } )\n{ \"ok\" : 1 }\n>\n" }, { "code": null, "e": 147759, "s": 147660, "text": "Following python example connects to a database in MongoDB (mydb) and, creates a collection in it." }, { "code": null, "e": 147999, "s": 147759, "text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['mydb']\n\n#Creating a collection\ncollection = db['example']\nprint(\"Collection created........\")" }, { "code": null, "e": 148027, "s": 147999, "text": "Collection created........\n" }, { "code": null, "e": 148143, "s": 148027, "text": "You can store documents into MongoDB using the insert() method. This method accepts a JSON document as a parameter." }, { "code": null, "e": 148189, "s": 148143, "text": "Following is the syntax of the insert method." }, { "code": null, "e": 148232, "s": 148189, "text": ">db.COLLECTION_NAME.insert(DOCUMENT_NAME)\n" }, { "code": null, "e": 148483, "s": 148232, "text": "> use mydb\nswitched to db mydb\n> db.createCollection(\"sample\")\n{ \"ok\" : 1 }\n> doc1 = {\"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"}\n{ \"name\" : \"Ram\", \"age\" : \"26\", \"city\" : \"Hyderabad\" }\n> db.sample.insert(doc1)\nWriteResult({ \"nInserted\" : 1 })\n>\n" }, { "code": null, "e": 148560, "s": 148483, "text": "Similarly, you can also insert multiple documents using the insert() method." }, { "code": null, "e": 149493, "s": 148560, "text": "> use testDB\nswitched to db testDB\n> db.createCollection(\"sample\")\n{ \"ok\" : 1 }\n> data = \n[\n {\n \"_id\": \"1001\", \n \"name\": \"Ram\", \n \"age\": \"26\", \n \"city\": \"Hyderabad\"\n }, \n {\n \"_id\": \"1002\", \n \"name\" : \"Rahim\", \n \"age\" : 27, \n \"city\" : \"Bangalore\" \n }, \n {\n \"_id\": \"1003\", \n \"name\" : \"Robert\", \n \"age\" : 28, \n \"city\" : \"Mumbai\" \n }\n]\n[\n {\n \"_id\" : \"1001\",\n \"name\" : \"Ram\",\n \"age\" : \"26\",\n \"city\" : \"Hyderabad\"\n },\n {\n \"_id\" : \"1002\",\n \"name\" : \"Rahim\",\n \"age\" : 27,\n \"city\" : \"Bangalore\"\n },\n {\n \"_id\" : \"1003\",\n \"name\" : \"Robert\",\n \"age\" : 28,\n \"city\" : \"Mumbai\"\n }\n]\n> db.sample.insert(data)\nBulkWriteResult\n({\n \"writeErrors\" : [ ],\n \"writeConcernErrors\" : [ ],\n \"nInserted\" : 3,\n \"nUpserted\" : 0,\n \"nMatched\" : 0,\n \"nModified\" : 0,\n \"nRemoved\" : 0,\n \"upserted\" : [ ]\n})\n>" }, { "code": null, "e": 149638, "s": 149493, "text": "Pymongo provides a method named insert_one() to insert a document in MangoDB. To this method, we need to pass the document in dictionary format." }, { "code": null, "e": 149708, "s": 149638, "text": "Following example inserts a document in the collection named example." }, { "code": null, "e": 150047, "s": 149708, "text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['mydb']\n\n#Creating a collection\ncoll = db['example']\n\n#Inserting document into a collection\ndoc1 = {\"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"}\ncoll.insert_one(doc1)\nprint(coll.find_one())" }, { "code": null, "e": 150160, "s": 150047, "text": "{\n '_id': ObjectId('5d63ad6ce043e2a93885858b'), \n 'name': 'Ram', \n 'age': '26', \n 'city': 'Hyderabad'\n}\n" }, { "code": null, "e": 150262, "s": 150160, "text": "To insert multiple documents into MongoDB using pymongo, you need to invoke the insert_many() method." }, { "code": null, "e": 150895, "s": 150262, "text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['mydb']\n\n#Creating a collection\ncoll = db['example']\n\n#Inserting document into a collection\ndata = \n[\n {\n \"_id\": \"101\", \n \"name\": \"Ram\", \n \"age\": \"26\", \n \"city\": \"Hyderabad\"\n },\n {\n \"_id\": \"102\", \n \"name\": \"Rahim\", \n \"age\": \"27\", \n \"city\": \"Bangalore\"\n },\n {\n \"_id\": \"103\", \n \"name\": \"Robert\", \n \"age\": \"28\", \n \"city\": \"Mumbai\"\n }\n]\nres = coll.insert_many(data)\nprint(\"Data inserted ......\")\nprint(res.inserted_ids)" }, { "code": null, "e": 150939, "s": 150895, "text": "Data inserted ......\n['101', '102', '103']\n" }, { "code": null, "e": 151105, "s": 150939, "text": "You can read/retrieve stored documents from MongoDB using the find() method. This method retrieves and displays all the documents in MongoDB in a non-structured way." }, { "code": null, "e": 151151, "s": 151105, "text": "Following is the syntax of the find() method." }, { "code": null, "e": 151178, "s": 151151, "text": ">db.CollectionName.find()\n" }, { "code": null, "e": 151302, "s": 151178, "text": "Assume we have inserted 3 documents into a database named testDB in a collection named sample using the following queries −" }, { "code": null, "e": 151599, "s": 151302, "text": "> use testDB\n> db.createCollection(\"sample\")\n> data = [\n {\"_id\": \"1001\", \"name\" : \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n {\"_id\": \"1002\", \"name\" : \"Rahim\", \"age\" : 27, \"city\" : \"Bangalore\" },\n {\"_id\": \"1003\", \"name\" : \"Robert\", \"age\" : 28, \"city\" : \"Mumbai\" }\n]\n> db.sample.insert(data)\n" }, { "code": null, "e": 151668, "s": 151599, "text": "You can retrieve the inserted documents using the find() method as −" }, { "code": null, "e": 151936, "s": 151668, "text": "> use testDB\nswitched to db testDB\n> db.sample.find()\n{ \"_id\" : \"1001\", \"name\" : \"Ram\", \"age\" : \"26\", \"city\" : \"Hyderabad\" }\n{ \"_id\" : \"1002\", \"name\" : \"Rahim\", \"age\" : 27, \"city\" : \"Bangalore\" }\n{ \"_id\" : \"1003\", \"name\" : \"Robert\", \"age\" : 28, \"city\" : \"Mumbai\" }\n>\n" }, { "code": null, "e": 152023, "s": 151936, "text": "You can also retrieve first document in the collection using the findOne() method as −" }, { "code": null, "e": 152117, "s": 152023, "text": "> db.sample.findOne()\n{ \"_id\" : \"1001\", \"name\" : \"Ram\", \"age\" : \"26\", \"city\" : \"Hyderabad\" }\n" }, { "code": null, "e": 152341, "s": 152117, "text": "The find_One() method of pymongo is used to retrieve a single document based on your query, in case of no matches this method returns nothing and if you doesn’t use any query it returns the first document of the collection." }, { "code": null, "e": 152488, "s": 152341, "text": "This method comes handy whenever you need to retrieve only one document of a result or, if you are sure that your query returns only one document." }, { "code": null, "e": 152555, "s": 152488, "text": "Following python example retrieve first document of a collection −" }, { "code": null, "e": 153353, "s": 152555, "text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['mydatabase']\n\n#Creating a collection\ncoll = db['example']\n\n#Inserting document into a collection\ndata = [\n {\"_id\": \"101\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n {\"_id\": \"102\", \"name\": \"Rahim\", \"age\": \"27\", \"city\": \"Bangalore\"},\n {\"_id\": \"103\", \"name\": \"Robert\", \"age\": \"28\", \"city\": \"Mumbai\"}\n]\nres = coll.insert_many(data)\nprint(\"Data inserted ......\")\nprint(res.inserted_ids)\n\n#Retrieving the first record using the find_one() method\nprint(\"First record of the collection: \")\nprint(coll.find_one())\n\n#Retrieving a record with is 103 using the find_one() method\nprint(\"Record whose id is 103: \")\nprint(coll.find_one({\"_id\": \"103\"}))" }, { "code": null, "e": 153581, "s": 153353, "text": "Data inserted ......\n['101', '102', '103']\nFirst record of the collection:\n{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}\nRecord whose id is 103:\n{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}\n" }, { "code": null, "e": 153863, "s": 153581, "text": "To get multiple documents in a single query (single call od find method), you can use the find() method of the pymongo. If haven’t passed any query, this returns all the documents of a collection and, if you have passed a query to this method, it returns all the matched documents." }, { "code": null, "e": 154571, "s": 153863, "text": "#Getting the database instance\ndb = client['myDB']\n\n#Creating a collection\ncoll = db['example']\n\n#Inserting document into a collection\ndata = [\n {\"_id\": \"101\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n {\"_id\": \"102\", \"name\": \"Rahim\", \"age\": \"27\", \"city\": \"Bangalore\"},\n {\"_id\": \"103\", \"name\": \"Robert\", \"age\": \"28\", \"city\": \"Mumbai\"}\n]\nres = coll.insert_many(data)\nprint(\"Data inserted ......\")\n\n#Retrieving all the records using the find() method\nprint(\"Records of the collection: \")\nfor doc1 in coll.find():\nprint(doc1)\n\n#Retrieving records with age greater than 26 using the find() method\nprint(\"Record whose age is more than 26: \")\nfor doc2 in coll.find({\"age\":{\"$gt\":\"26\"}}):\nprint(doc2)" }, { "code": null, "e": 154978, "s": 154571, "text": "Data inserted ......\nRecords of the collection:\n{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}\n{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}\n{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}\nRecord whose age is more than 26:\n{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}\n{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}\n" }, { "code": null, "e": 155175, "s": 154978, "text": "While retrieving using find() method, you can filter the documents using the query object. You can pass the query specifying the condition for the required documents as a parameter to this method." }, { "code": null, "e": 155242, "s": 155175, "text": "Following is the list of operators used in the queries in MongoDB." }, { "code": null, "e": 155323, "s": 155242, "text": "Following example retrieves the document in a collection whose name is sarmista." }, { "code": null, "e": 156164, "s": 155323, "text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['sdsegf']\n\n#Creating a collection\ncoll = db['example']\n\n#Inserting document into a collection\ndata = [\n {\"_id\": \"1001\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n {\"_id\": \"1002\", \"name\": \"Rahim\", \"age\": \"27\", \"city\": \"Bangalore\"},\n {\"_id\": \"1003\", \"name\": \"Robert\", \"age\": \"28\", \"city\": \"Mumbai\"},\n {\"_id\": \"1004\", \"name\": \"Romeo\", \"age\": \"25\", \"city\": \"Pune\"},\n {\"_id\": \"1005\", \"name\": \"Sarmista\", \"age\": \"23\", \"city\": \"Delhi\"},\n {\"_id\": \"1006\", \"name\": \"Rasajna\", \"age\": \"26\", \"city\": \"Chennai\"}\n]\nres = coll.insert_many(data)\nprint(\"Data inserted ......\")\n\n#Retrieving data\nprint(\"Documents in the collection: \")\n\nfor doc1 in coll.find({\"name\":\"Sarmista\"}):\n print(doc1)" }, { "code": null, "e": 156281, "s": 156164, "text": "Data inserted ......\nDocuments in the collection:\n{'_id': '1005', 'name': 'Sarmista', 'age': '23', 'city': 'Delhi'}\n" }, { "code": null, "e": 156374, "s": 156281, "text": "Following example retrieves the document in a collection whose age value is greater than 26." }, { "code": null, "e": 157212, "s": 156374, "text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['ghhj']\n\n#Creating a collection\ncoll = db['example']\n\n#Inserting document into a collection\ndata = [\n {\"_id\": \"1001\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n {\"_id\": \"1002\", \"name\": \"Rahim\", \"age\": \"27\", \"city\": \"Bangalore\"},\n {\"_id\": \"1003\", \"name\": \"Robert\", \"age\": \"28\", \"city\": \"Mumbai\"},\n {\"_id\": \"1004\", \"name\": \"Romeo\", \"age\": \"25\", \"city\": \"Pune\"},\n {\"_id\": \"1005\", \"name\": \"Sarmista\", \"age\": \"23\", \"city\": \"Delhi\"},\n {\"_id\": \"1006\", \"name\": \"Rasajna\", \"age\": \"26\", \"city\": \"Chennai\"}\n]\nres = coll.insert_many(data)\nprint(\"Data inserted ......\")\n\n#Retrieving data\nprint(\"Documents in the collection: \")\n\nfor doc in coll.find({\"age\":{\"$gt\":\"26\"}}):\n print(doc)" }, { "code": null, "e": 157395, "s": 157212, "text": "Data inserted ......\nDocuments in the collection:\n{'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}\n{'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}\n" }, { "code": null, "e": 157531, "s": 157395, "text": "While retrieving the contents of a collection, you can sort and arrange them in ascending or descending orders using the sort() method." }, { "code": null, "e": 157673, "s": 157531, "text": "To this method, you can pass the field(s) and the sorting order which is 1 or -1. Where, 1 is for ascending order and -1 is descending order." }, { "code": null, "e": 157719, "s": 157673, "text": "Following is the syntax of the sort() method." }, { "code": null, "e": 157761, "s": 157719, "text": ">db.COLLECTION_NAME.find().sort({KEY:1})\n" }, { "code": null, "e": 157847, "s": 157761, "text": "Assume we have created a collection and inserted 5 documents into it as shown below −" }, { "code": null, "e": 158588, "s": 157847, "text": "> use testDB\nswitched to db testDB\n> db.createCollection(\"myColl\")\n{ \"ok\" : 1 }\n> data = [\n ... {\"_id\": \"1001\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n ... {\"_id\": \"1002\", \"name\": \"Rahim\", \"age\": 27, \"city\": \"Bangalore\"},\n ... {\"_id\": \"1003\", \"name\": \"Robert\", \"age\": 28, \"city\": \"Mumbai\"},\n ... {\"_id\": \"1004\", \"name\": \"Romeo\", \"age\": 25, \"city\": \"Pune\"},\n ... {\"_id\": \"1005\", \"name\": \"Sarmista\", \"age\": 23, \"city\": \"Delhi\"},\n ... {\"_id\": \"1006\", \"name\": \"Rasajna\", \"age\": 26, \"city\": \"Chennai\"}\n]\n> db.sample.insert(data)\nBulkWriteResult({\n \"writeErrors\" : [ ],\n \"writeConcernErrors\" : [ ],\n \"nInserted\" : 6,\n \"nUpserted\" : 0,\n \"nMatched\" : 0,\n \"nModified\" : 0,\n \"nRemoved\" : 0,\n \"upserted\" : [ ]\n})" }, { "code": null, "e": 158699, "s": 158588, "text": "Following line retrieves all the documents of the collection which are sorted in ascending order based on age." }, { "code": null, "e": 159151, "s": 158699, "text": "> db.sample.find().sort({age:1})\n{ \"_id\" : \"1005\", \"name\" : \"Sarmista\", \"age\" : 23, \"city\" : \"Delhi\" }\n{ \"_id\" : \"1004\", \"name\" : \"Romeo\", \"age\" : 25, \"city\" : \"Pune\" }\n{ \"_id\" : \"1006\", \"name\" : \"Rasajna\", \"age\" : 26, \"city\" : \"Chennai\" }\n{ \"_id\" : \"1002\", \"name\" : \"Rahim\", \"age\" : 27, \"city\" : \"Bangalore\" }\n{ \"_id\" : \"1003\", \"name\" : \"Robert\", \"age\" : 28, \"city\" : \"Mumbai\" }\n{ \"_id\" : \"1001\", \"name\" : \"Ram\", \"age\" : \"26\", \"city\" : \"Hyderabad\" }\n" }, { "code": null, "e": 159349, "s": 159151, "text": "To sort the results of a query in ascending or, descending order pymongo provides the sort() method. To this method, pass a number value representing the number of documents you need in the result." }, { "code": null, "e": 159518, "s": 159349, "text": "By default, this method sorts the documents in ascending order based on the specified field. If you need to sort in descending order pass -1 along with the field name −" }, { "code": null, "e": 159546, "s": 159518, "text": "coll.find().sort(\"age\",-1)\n" }, { "code": null, "e": 159666, "s": 159546, "text": "Following example retrieves all the documents of a collection arranged according to the age values in ascending order −" }, { "code": null, "e": 160574, "s": 159666, "text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['b_mydb']\n\n#Creating a collection\ncoll = db['myColl']\n\n#Inserting document into a collection\ndata = [\n {\"_id\": \"1001\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n {\"_id\": \"1002\", \"name\": \"Rahim\", \"age\": \"27\", \"city\": \"Bangalore\"},\n {\"_id\": \"1003\", \"name\": \"Robert\", \"age\": \"28\", \"city\": \"Mumbai\"},\n {\"_id\": \"1004\", \"name\": \"Romeo\", \"age\": 25, \"city\": \"Pune\"},\n {\"_id\": \"1005\", \"name\": \"Sarmista\", \"age\": 23, \"city\": \"Delhi\"},\n {\"_id\": \"1006\", \"name\": \"Rasajna\", \"age\": 26, \"city\": \"Chennai\"}\n]\nres = coll.insert_many(data)\nprint(\"Data inserted ......\")\n\n#Retrieving first 3 documents using the find() and limit() methods\nprint(\"List of documents (sorted in ascending order based on age): \")\n\nfor doc1 in coll.find().sort(\"age\"):\n print(doc1)" }, { "code": null, "e": 161042, "s": 160574, "text": "Data inserted ......\nList of documents (sorted in ascending order based on age):\n{'_id': '1005', 'name': 'Sarmista', 'age': 23, 'city': 'Delhi'}\n{'_id': '1004', 'name': 'Romeo', 'age': 25, 'city': 'Pune'}\n{'_id': '1006', 'name': 'Rasajna', 'age': 26, 'city': 'Chennai'}\n{'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}\n{'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}\n{'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}\n" }, { "code": null, "e": 161167, "s": 161042, "text": "You can delete documents in a collection using the remove() method of MongoDB. This method accepts two optional parameters −" }, { "code": null, "e": 161231, "s": 161167, "text": "deletion criteria specifying the condition to delete documents." }, { "code": null, "e": 161295, "s": 161231, "text": "deletion criteria specifying the condition to delete documents." }, { "code": null, "e": 161388, "s": 161295, "text": "just one, if you pass true or 1 as second parameter, then only one document will be deleted." }, { "code": null, "e": 161481, "s": 161388, "text": "just one, if you pass true or 1 as second parameter, then only one document will be deleted." }, { "code": null, "e": 161530, "s": 161481, "text": "Following is the syntax of the remove() method −" }, { "code": null, "e": 161579, "s": 161530, "text": ">db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)\n" }, { "code": null, "e": 161665, "s": 161579, "text": "Assume we have created a collection and inserted 5 documents into it as shown below −" }, { "code": null, "e": 162406, "s": 161665, "text": "> use testDB\nswitched to db testDB\n> db.createCollection(\"myColl\")\n{ \"ok\" : 1 }\n> data = [\n ... {\"_id\": \"1001\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n ... {\"_id\": \"1002\", \"name\": \"Rahim\", \"age\": 27, \"city\": \"Bangalore\"},\n ... {\"_id\": \"1003\", \"name\": \"Robert\", \"age\": 28, \"city\": \"Mumbai\"},\n ... {\"_id\": \"1004\", \"name\": \"Romeo\", \"age\": 25, \"city\": \"Pune\"},\n ... {\"_id\": \"1005\", \"name\": \"Sarmista\", \"age\": 23, \"city\": \"Delhi\"},\n ... {\"_id\": \"1006\", \"name\": \"Rasajna\", \"age\": 26, \"city\": \"Chennai\"}\n]\n> db.sample.insert(data)\nBulkWriteResult({\n \"writeErrors\" : [ ],\n \"writeConcernErrors\" : [ ],\n \"nInserted\" : 6,\n \"nUpserted\" : 0,\n \"nMatched\" : 0,\n \"nModified\" : 0,\n \"nRemoved\" : 0,\n \"upserted\" : [ ]\n})" }, { "code": null, "e": 162499, "s": 162406, "text": "Following query deletes the document(s) of the collection which have name value as Sarmista." }, { "code": null, "e": 162940, "s": 162499, "text": "> db.sample.remove({\"name\": \"Sarmista\"})\nWriteResult({ \"nRemoved\" : 1 })\n> db.sample.find()\n{ \"_id\" : \"1001\", \"name\" : \"Ram\", \"age\" : \"26\", \"city\" : \"Hyderabad\" }\n{ \"_id\" : \"1002\", \"name\" : \"Rahim\", \"age\" : 27, \"city\" : \"Bangalore\" }\n{ \"_id\" : \"1003\", \"name\" : \"Robert\", \"age\" : 28, \"city\" : \"Mumbai\" }\n{ \"_id\" : \"1004\", \"name\" : \"Romeo\", \"age\" : 25, \"city\" : \"Pune\" }\n{ \"_id\" : \"1006\", \"name\" : \"Rasajna\", \"age\" : 26, \"city\" : \"Chennai\" }\n" }, { "code": null, "e": 163058, "s": 162940, "text": "If you invoke remove() method without passing deletion criteria, all the documents in the collection will be deleted." }, { "code": null, "e": 163133, "s": 163058, "text": "> db.sample.remove({})\nWriteResult({ \"nRemoved\" : 5 })\n> db.sample.find()\n" }, { "code": null, "e": 163285, "s": 163133, "text": "To delete documents from a collection of MangoDB, you can delete documents from a collections using the methods delete_one() and delete_many() methods." }, { "code": null, "e": 163370, "s": 163285, "text": "These methods accept a query object specifying the condition for deleting documents." }, { "code": null, "e": 163524, "s": 163370, "text": "The detele_one() method deletes a single document, in case of a match. If no query is specified this method deletes the first document in the collection." }, { "code": null, "e": 163616, "s": 163524, "text": "Following python example deletes the document in the collection which has id value as 1006." }, { "code": null, "e": 164549, "s": 163616, "text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['lpaksgf']\n\n#Creating a collection\ncoll = db['example']\n\n#Inserting document into a collection\ndata = [\n {\"_id\": \"1001\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n {\"_id\": \"1002\", \"name\": \"Rahim\", \"age\": \"27\", \"city\": \"Bangalore\"},\n {\"_id\": \"1003\", \"name\": \"Robert\", \"age\": \"28\", \"city\": \"Mumbai\"},\n {\"_id\": \"1004\", \"name\": \"Romeo\", \"age\": 25, \"city\": \"Pune\"},\n {\"_id\": \"1005\", \"name\": \"Sarmista\", \"age\": 23, \"city\": \"Delhi\"},\n {\"_id\": \"1006\", \"name\": \"Rasajna\", \"age\": 26, \"city\": \"Chennai\"}\n]\nres = coll.insert_many(data)\nprint(\"Data inserted ......\")\n\n#Deleting one document\ncoll.delete_one({\"_id\" : \"1006\"})\n\n#Retrieving all the records using the find() method\nprint(\"Documents in the collection after update operation: \")\n\nfor doc2 in coll.find():\n print(doc2)" }, { "code": null, "e": 164944, "s": 164549, "text": "Data inserted ......\nDocuments in the collection after update operation:\n{'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}\n{'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}\n{'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}\n{'_id': '1004', 'name': 'Romeo', 'age': 25, 'city': 'Pune'}\n{'_id': '1005', 'name': 'Sarmista', 'age': 23, 'city': 'Delhi'}\n" }, { "code": null, "e": 165057, "s": 164944, "text": "Similarly, the delete_many() method of pymongo deletes all the documents that satisfies the specified condition." }, { "code": null, "e": 165156, "s": 165057, "text": "Following example deletes all the documents in the collection whose age value is greater than 26 −" }, { "code": null, "e": 166107, "s": 165156, "text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['sampleDB']\n\n#Creating a collection\ncoll = db['example']\n\n#Inserting document into a collection\ndata = [\n {\"_id\": \"1001\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n {\"_id\": \"1002\", \"name\": \"Rahim\", \"age\": \"27\", \"city\": \"Bangalore\"},\n {\"_id\": \"1003\", \"name\": \"Robert\", \"age\": \"28\", \"city\": \"Mumbai\"},\n {\"_id\": \"1004\", \"name\": \"Romeo\", \"age\": \"25\", \"city\": \"Pune\"},\n {\"_id\": \"1005\", \"name\": \"Sarmista\", \"age\": \"23\", \"city\": \"Delhi\"},\n {\"_id\": \"1006\", \"name\": \"Rasajna\", \"age\": \"26\", \"city\": \"Chennai\"}\n]\nres = coll.insert_many(data)\nprint(\"Data inserted ......\")\n\n#Deleting multiple documents\ncoll.delete_many({\"age\":{\"$gt\":\"26\"}})\n\n#Retrieving all the records using the find() method\nprint(\"Documents in the collection after update operation: \")\n\nfor doc2 in coll.find():\n print(doc2)" }, { "code": null, "e": 166441, "s": 166107, "text": "Data inserted ......\nDocuments in the collection after update operation:\n{'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}\n{'_id': '1004', 'name': 'Romeo', 'age': '25', 'city': 'Pune'}\n{'_id': '1005', 'name': 'Sarmista', 'age': '23', 'city': 'Delhi'}\n{'_id': '1006', 'name': 'Rasajna', 'age': '26', 'city': 'Chennai'}\n" }, { "code": null, "e": 166564, "s": 166441, "text": "If you invoke the delete_many() method without passing any query, this method deletes all the documents in the collection." }, { "code": null, "e": 166586, "s": 166564, "text": "coll.delete_many({})\n" }, { "code": null, "e": 166645, "s": 166586, "text": "You can delete collections using drop() method of MongoDB." }, { "code": null, "e": 166688, "s": 166645, "text": "Following is the syntax of drop() method −" }, { "code": null, "e": 166715, "s": 166688, "text": "db.COLLECTION_NAME.drop()\n" }, { "code": null, "e": 166769, "s": 166715, "text": "Following example drops collection with name sample −" }, { "code": null, "e": 166853, "s": 166769, "text": "> show collections\nmyColl\nsample\n> db.sample.drop()\ntrue\n> show collections\nmyColl\n" }, { "code": null, "e": 166939, "s": 166853, "text": "You can drop/delete a collection from the current database by invoking drop() method." }, { "code": null, "e": 167807, "s": 166939, "text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['example2']\n\n#Creating a collection\ncol1 = db['collection']\ncol1.insert_one({\"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"})\ncol2 = db['coll']\ncol2.insert_one({\"name\": \"Rahim\", \"age\": \"27\", \"city\": \"Bangalore\"})\ncol3 = db['myColl']\ncol3.insert_one({\"name\": \"Robert\", \"age\": \"28\", \"city\": \"Mumbai\"})\ncol4 = db['data']\ncol4.insert_one({\"name\": \"Romeo\", \"age\": \"25\", \"city\": \"Pune\"})\n\n#List of collections\nprint(\"List of collections:\")\ncollections = db.list_collection_names()\nfor coll in collections:\nprint(coll)\n\n#Dropping a collection\ncol1.drop()\ncol4.drop()\nprint(\"List of collections after dropping two of them: \")\n\n#List of collections\ncollections = db.list_collection_names()\n\nfor coll in collections:\n print(coll)" }, { "code": null, "e": 167917, "s": 167807, "text": "List of collections:\ncoll\ndata\ncollection\nmyColl\nList of collections after dropping two of them:\ncoll\nmyColl\n" }, { "code": null, "e": 168014, "s": 167917, "text": "You can update the contents of an existing documents using the update() method or save() method." }, { "code": null, "e": 168136, "s": 168014, "text": "The update method modifies the existing document whereas the save method replaces the existing document with the new one." }, { "code": null, "e": 168208, "s": 168136, "text": "Following is the syntax of the update() and save() methods of MangoDB −" }, { "code": null, "e": 168325, "s": 168208, "text": ">db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)\nOr,\ndb.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})\n" }, { "code": null, "e": 168421, "s": 168325, "text": "Assume we have created a collection in a database and inserted 3 records in it as shown below −" }, { "code": null, "e": 169082, "s": 168421, "text": "> use testdatabase\nswitched to db testdatabase\n> data = [\n ... {\"_id\": \"1001\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n ... {\"_id\": \"1002\", \"name\" : \"Rahim\", \"age\" : 27, \"city\" : \"Bangalore\" },\n ... {\"_id\": \"1003\", \"name\" : \"Robert\", \"age\" : 28, \"city\" : \"Mumbai\" }\n]\n[\n {\n \"_id\" : \"1001\",\n \"name\" : \"Ram\",\n \"age\" : \"26\",\n \"city\" : \"Hyderabad\"\n },\n {\n \"_id\" : \"1002\",\n \"name\" : \"Rahim\",\n \"age\" : 27,\n \"city\" : \"Bangalore\"\n },\n {\n \"_id\" : \"1003\",\n \"name\" : \"Robert\",\n \"age\" : 28,\n \"city\" : \"Mumbai\"\n }\n]\n> db.createCollection(\"sample\")\n{ \"ok\" : 1 }\n> db.sample.insert(data)" }, { "code": null, "e": 169152, "s": 169082, "text": "Following method updates the city value of the document with id 1002." }, { "code": null, "e": 169521, "s": 169152, "text": "> db.sample.update({\"_id\":\"1002\"},{\"$set\":{\"city\":\"Visakhapatnam\"}})\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })\n> db.sample.find()\n{ \"_id\" : \"1001\", \"name\" : \"Ram\", \"age\" : \"26\", \"city\" : \"Hyderabad\" }\n{ \"_id\" : \"1002\", \"name\" : \"Rahim\", \"age\" : 27, \"city\" : \"Visakhapatnam\" }\n{ \"_id\" : \"1003\", \"name\" : \"Robert\", \"age\" : 28, \"city\" : \"Mumbai\" }" }, { "code": null, "e": 169625, "s": 169521, "text": "Similarly you can replace the document with new data by saving it with same id using the save() method." }, { "code": null, "e": 170022, "s": 169625, "text": "> db.sample.save(\n { \"_id\" : \"1001\", \"name\" : \"Ram\", \"age\" : \"26\", \"city\" : \"Vijayawada\" }\n)\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })\n> db.sample.find()\n{ \"_id\" : \"1001\", \"name\" : \"Ram\", \"age\" : \"26\", \"city\" : \"Vijayawada\" }\n{ \"_id\" : \"1002\", \"name\" : \"Rahim\", \"age\" : 27, \"city\" : \"Visakhapatnam\" }\n{ \"_id\" : \"1003\", \"name\" : \"Robert\", \"age\" : 28, \"city\" : \"Mumbai\" }\n" }, { "code": null, "e": 170146, "s": 170022, "text": "Similar to find_one() method which retrieves single document, the update_one() method of pymongo updates a single document." }, { "code": null, "e": 170236, "s": 170146, "text": "This method accepts a query specifying which document to update and the update operation." }, { "code": null, "e": 170319, "s": 170236, "text": "Following python example updates the location value of a document in a collection." }, { "code": null, "e": 171181, "s": 170319, "text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['myDB']\n\n#Creating a collection\ncoll = db['example']\n\n#Inserting document into a collection\ndata = [\n {\"_id\": \"101\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n {\"_id\": \"102\", \"name\": \"Rahim\", \"age\": \"27\", \"city\": \"Bangalore\"},\n {\"_id\": \"103\", \"name\": \"Robert\", \"age\": \"28\", \"city\": \"Mumbai\"}\n]\nres = coll.insert_many(data)\nprint(\"Data inserted ......\")\n\n#Retrieving all the records using the find() method\nprint(\"Documents in the collection: \")\nfor doc1 in coll.find():\nprint(doc1)\ncoll.update_one({\"_id\":\"102\"},{\"$set\":{\"city\":\"Visakhapatnam\"}})\n\n#Retrieving all the records using the find() method\nprint(\"Documents in the collection after update operation: \")\n\nfor doc2 in coll.find():\n print(doc2)" }, { "code": null, "e": 171676, "s": 171181, "text": "Data inserted ......\nDocuments in the collection:\n{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}\n{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}\n{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}\nDocuments in the collection after update operation:\n{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}\n{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Visakhapatnam'}\n{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}\n" }, { "code": null, "e": 171789, "s": 171676, "text": "Similarly, the update_many() method of pymongo updates all the documents that satisfies the specified condition." }, { "code": null, "e": 171891, "s": 171789, "text": "Following example updates the location value in all the documents in a collection (empty condition) −" }, { "code": null, "e": 172743, "s": 171891, "text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['myDB']\n\n#Creating a collection\ncoll = db['example']\n\n#Inserting document into a collection\ndata = [\n {\"_id\": \"101\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n {\"_id\": \"102\", \"name\": \"Rahim\", \"age\": \"27\", \"city\": \"Bangalore\"},\n {\"_id\": \"103\", \"name\": \"Robert\", \"age\": \"28\", \"city\": \"Mumbai\"}\n]\nres = coll.insert_many(data)\nprint(\"Data inserted ......\")\n\n#Retrieving all the records using the find() method\nprint(\"Documents in the collection: \")\nfor doc1 in coll.find():\nprint(doc1)\ncoll.update_many({},{\"$set\":{\"city\":\"Visakhapatnam\"}})\n\n#Retrieving all the records using the find() method\nprint(\"Documents in the collection after update operation: \")\n\nfor doc2 in coll.find():\n print(doc2)" }, { "code": null, "e": 173249, "s": 172743, "text": "Data inserted ......\nDocuments in the collection:\n{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}\n{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}\n{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}\nDocuments in the collection after update operation:\n{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Visakhapatnam'}\n{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Visakhapatnam'}\n{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Visakhapatnam'}\n" }, { "code": null, "e": 173469, "s": 173249, "text": "While retrieving the contents of a collection you can limit the number of documents in the result using the limit() method. This method accepts a number value representing the number of documents you want in the result." }, { "code": null, "e": 173517, "s": 173469, "text": "Following is the syntax of the limit() method −" }, { "code": null, "e": 173559, "s": 173517, "text": ">db.COLLECTION_NAME.find().limit(NUMBER)\n" }, { "code": null, "e": 173645, "s": 173559, "text": "Assume we have created a collection and inserted 5 documents into it as shown below −" }, { "code": null, "e": 174386, "s": 173645, "text": "> use testDB\nswitched to db testDB\n> db.createCollection(\"sample\")\n{ \"ok\" : 1 }\n> data = [\n ... {\"_id\": \"1001\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n ... {\"_id\": \"1002\", \"name\": \"Rahim\", \"age\": 27, \"city\": \"Bangalore\"},\n ... {\"_id\": \"1003\", \"name\": \"Robert\", \"age\": 28, \"city\": \"Mumbai\"},\n ... {\"_id\": \"1004\", \"name\": \"Romeo\", \"age\": 25, \"city\": \"Pune\"},\n ... {\"_id\": \"1005\", \"name\": \"Sarmista\", \"age\": 23, \"city\": \"Delhi\"},\n ... {\"_id\": \"1006\", \"name\": \"Rasajna\", \"age\": 26, \"city\": \"Chennai\"}\n]\n> db.sample.insert(data)\nBulkWriteResult({\n \"writeErrors\" : [ ],\n \"writeConcernErrors\" : [ ],\n \"nInserted\" : 6,\n \"nUpserted\" : 0,\n \"nMatched\" : 0,\n \"nModified\" : 0,\n \"nRemoved\" : 0,\n \"upserted\" : [ ]\n})" }, { "code": null, "e": 174452, "s": 174386, "text": "Following line retrieves the first 3 documents of the collection." }, { "code": null, "e": 174692, "s": 174452, "text": "> db.sample.find().limit(3)\n{ \"_id\" : \"1001\", \"name\" : \"Ram\", \"age\" : \"26\", \"city\" : \"Hyderabad\" }\n{ \"_id\" : \"1002\", \"name\" : \"Rahim\", \"age\" : 27, \"city\" : \"Bangalore\" }\n{ \"_id\" : \"1003\", \"name\" : \"Robert\", \"age\" : 28, \"city\" : \"Mumbai\" }\n" }, { "code": null, "e": 174896, "s": 174692, "text": "To restrict the results of a query to a particular number of documents pymongo provides the limit() method. To this method pass a number value representing the number of documents you need in the result." }, { "code": null, "e": 174963, "s": 174896, "text": "Following example retrieves first three documents in a collection." }, { "code": null, "e": 175840, "s": 174963, "text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['l']\n\n#Creating a collection\ncoll = db['myColl']\n\n#Inserting document into a collection\ndata = [\n {\"_id\": \"1001\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n {\"_id\": \"1002\", \"name\": \"Rahim\", \"age\": \"27\", \"city\": \"Bangalore\"},\n {\"_id\": \"1003\", \"name\": \"Robert\", \"age\": \"28\", \"city\": \"Mumbai\"},\n {\"_id\": \"1004\", \"name\": \"Romeo\", \"age\": 25, \"city\": \"Pune\"},\n {\"_id\": \"1005\", \"name\": \"Sarmista\", \"age\": 23, \"city\": \"Delhi\"},\n {\"_id\": \"1006\", \"name\": \"Rasajna\", \"age\": 26, \"city\": \"Chennai\"}\n]\nres = coll.insert_many(data)\nprint(\"Data inserted ......\")\n\n#Retrieving first 3 documents using the find() and limit() methods\nprint(\"First 3 documents in the collection: \")\n\nfor doc1 in coll.find().limit(3):\n print(doc1)" }, { "code": null, "e": 176096, "s": 175840, "text": "Data inserted ......\nFirst 3 documents in the collection:\n{'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}\n{'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}\n{'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}\n" }, { "code": null, "e": 176133, "s": 176096, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 176149, "s": 176133, "text": " Malhar Lathkar" }, { "code": null, "e": 176182, "s": 176149, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 176201, "s": 176182, "text": " Arnab Chakraborty" }, { "code": null, "e": 176236, "s": 176201, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 176258, "s": 176236, "text": " In28Minutes Official" }, { "code": null, "e": 176292, "s": 176258, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 176320, "s": 176292, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 176355, "s": 176320, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 176369, "s": 176355, "text": " Lets Kode It" }, { "code": null, "e": 176402, "s": 176369, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 176419, "s": 176402, "text": " Abhilash Nelson" }, { "code": null, "e": 176426, "s": 176419, "text": " Print" }, { "code": null, "e": 176437, "s": 176426, "text": " Add Notes" } ]
std::stoul and std::stoull in C++ - GeeksforGeeks
05 Nov, 2019 std::stoul Convert string to unsigned integer. Parses str interpreting its content as an integral number of the specified base, which is returned as an unsigned long value. unsigned long stoul (const string& str, size_t* idx = 0, int base = 10); Parameters : str : String object with the representation of an integral number. idx : Pointer to an object of type size_t, whose value is set by the function to position of the next character in str after the numerical value. This parameter can also be a null pointer, in which case it is not used. base : Numerical base (radix) that determines the valid characters and their interpretation. If this is 0, the base used is determined by the format in the sequence.Notice that by default this argument is 10, not 0. std::stoull Convert string to unsigned long long. Parses str interpreting its content as an integral number of the specified base, which is returned as a value of type unsigned long long. unsigned long long stoull (const string& str, size_t* idx = 0, int base = 10); Parameters : str : String object with the representation of an integral number. idx : Pointer to an object of type size_t, whose value is set by the function to position of the next character in str after the numerical value. This parameter can also be a null pointer, in which case it is not used. base : Numerical base (radix) that determines the valid characters and their interpretation. If this is 0, the base used is determined by the format in the sequence. Notice that by default this argument is 10, not 0. Examples: Input : FF Output : 255 Input : FFFFF Output : // CPP code to convert hexadecimal// string to int#include <bits/stdc++.h>using namespace std; int main(){ // Hexadecimal string string str = "FF"; // Converted integer unsigned long num = stoul(str, nullptr, 16); // Printing the integer cout << num << "\n"; // Hexadecimal string string st = "FFFFFF"; // Converted long long unsigned long long val = stoull(st, nullptr, 16); // Printing the long long cout << val; return 0;} Output: 255 16777215 Another Example : Program to compare two strings containing hexadecimal valuesHere stoul is used, but in cases of numbers exceeding unsigned long value, stoull is used. // CPP code to compare two// hexadecimal string#include <bits/stdc++.h>using namespace std; int main(){ // Hexadecimal string string s1 = "4F"; string s2 = "A0"; // Converted integer unsigned long n1 = stoul(s1, nullptr, 16); unsigned long n2 = stoul(s2, nullptr, 16); // Compare both string if (n1 > n2) cout << s1 << " is greater than " << s2; else if (n2 > n1) cout << s2 << " is greater than " << s1; else cout << "Both " << s1 << " and " << s2 << " are equal"; return 0;} Output: A0 is greater than 4F This article is contributed by Sachin Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nidhi_biet CPP-Library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Iterators in C++ STL Operator Overloading in C++ Friend class and function in C++ Polymorphism in C++ Sorting a vector in C++ Convert string to char array in C++ Inline Functions in C++ List in C++ Standard Template Library (STL) std::string class in C++ new and delete operators in C++ for dynamic memory
[ { "code": null, "e": 24042, "s": 24014, "text": "\n05 Nov, 2019" }, { "code": null, "e": 24053, "s": 24042, "text": "std::stoul" }, { "code": null, "e": 24215, "s": 24053, "text": "Convert string to unsigned integer. Parses str interpreting its content as an integral number of the specified base, which is returned as an unsigned long value." }, { "code": null, "e": 24810, "s": 24215, "text": "unsigned long stoul \n(const string& str, size_t* idx = 0, int base = 10);\nParameters :\nstr : String object with the \nrepresentation of an integral number.\nidx : Pointer to an object of type size_t, \nwhose value is set by the function to position of the \nnext character in str after the numerical value.\nThis parameter can also be a null pointer, in which case\nit is not used.\nbase : Numerical base (radix) that determines\nthe valid characters and their interpretation.\nIf this is 0, the base used is determined by the format in\nthe sequence.Notice that by default this argument is 10, not 0. \n" }, { "code": null, "e": 24822, "s": 24810, "text": "std::stoull" }, { "code": null, "e": 24998, "s": 24822, "text": "Convert string to unsigned long long. Parses str interpreting its content as an integral number of the specified base, which is returned as a value of type unsigned long long." }, { "code": null, "e": 25601, "s": 24998, "text": "unsigned long long stoull \n(const string& str, size_t* idx = 0, int base = 10);\nParameters :\nstr : String object with the representation \nof an integral number.\nidx : Pointer to an object of type size_t,\nwhose value is set by the function to position of the next \ncharacter in str after the numerical value. This parameter can \nalso be a null pointer, in which case it is not used.\nbase : Numerical base (radix) that determines \nthe valid characters and their interpretation.\nIf this is 0, the base used is determined by the format in the\nsequence. Notice that by default this argument is 10, not 0. \n" }, { "code": null, "e": 25611, "s": 25601, "text": "Examples:" }, { "code": null, "e": 25661, "s": 25611, "text": "Input : FF\nOutput : 255\n\nInput : FFFFF\nOutput : \n" }, { "code": "// CPP code to convert hexadecimal// string to int#include <bits/stdc++.h>using namespace std; int main(){ // Hexadecimal string string str = \"FF\"; // Converted integer unsigned long num = stoul(str, nullptr, 16); // Printing the integer cout << num << \"\\n\"; // Hexadecimal string string st = \"FFFFFF\"; // Converted long long unsigned long long val = stoull(st, nullptr, 16); // Printing the long long cout << val; return 0;}", "e": 26137, "s": 25661, "text": null }, { "code": null, "e": 26145, "s": 26137, "text": "Output:" }, { "code": null, "e": 26159, "s": 26145, "text": "255\n16777215\n" }, { "code": null, "e": 26328, "s": 26159, "text": "Another Example : Program to compare two strings containing hexadecimal valuesHere stoul is used, but in cases of numbers exceeding unsigned long value, stoull is used." }, { "code": "// CPP code to compare two// hexadecimal string#include <bits/stdc++.h>using namespace std; int main(){ // Hexadecimal string string s1 = \"4F\"; string s2 = \"A0\"; // Converted integer unsigned long n1 = stoul(s1, nullptr, 16); unsigned long n2 = stoul(s2, nullptr, 16); // Compare both string if (n1 > n2) cout << s1 << \" is greater than \" << s2; else if (n2 > n1) cout << s2 << \" is greater than \" << s1; else cout << \"Both \" << s1 << \" and \" << s2 << \" are equal\"; return 0;}", "e": 26864, "s": 26328, "text": null }, { "code": null, "e": 26872, "s": 26864, "text": "Output:" }, { "code": null, "e": 26895, "s": 26872, "text": "A0 is greater than 4F\n" }, { "code": null, "e": 27195, "s": 26895, "text": "This article is contributed by Sachin Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 27320, "s": 27195, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 27331, "s": 27320, "text": "nidhi_biet" }, { "code": null, "e": 27343, "s": 27331, "text": "CPP-Library" }, { "code": null, "e": 27347, "s": 27343, "text": "STL" }, { "code": null, "e": 27351, "s": 27347, "text": "C++" }, { "code": null, "e": 27355, "s": 27351, "text": "STL" }, { "code": null, "e": 27359, "s": 27355, "text": "CPP" }, { "code": null, "e": 27457, "s": 27359, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27466, "s": 27457, "text": "Comments" }, { "code": null, "e": 27479, "s": 27466, "text": "Old Comments" }, { "code": null, "e": 27500, "s": 27479, "text": "Iterators in C++ STL" }, { "code": null, "e": 27528, "s": 27500, "text": "Operator Overloading in C++" }, { "code": null, "e": 27561, "s": 27528, "text": "Friend class and function in C++" }, { "code": null, "e": 27581, "s": 27561, "text": "Polymorphism in C++" }, { "code": null, "e": 27605, "s": 27581, "text": "Sorting a vector in C++" }, { "code": null, "e": 27641, "s": 27605, "text": "Convert string to char array in C++" }, { "code": null, "e": 27665, "s": 27641, "text": "Inline Functions in C++" }, { "code": null, "e": 27709, "s": 27665, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 27734, "s": 27709, "text": "std::string class in C++" } ]
Visualize and communicate uncertainties clearly with Python and Plotly | by JP Hwang | Towards Data Science
In this article, I want to show how easy it is to effectively visualise and communicate uncertainties and ranges. More importantly, I would like to demonstrate how helpful doing so can be in gaining an intuitive understanding of data and subsequent decision-making. Although most of us are aware of uncertainties in every aspect of life, it is not often that we get to see, or work with them. Information or numbers are typically given in averages (means, or medians if we are lucky). Many of us don’t ever get taught statistics and probabilities, and the few that do are mostly taught them in just awful, tedious, academic ways that prioritise formulae over intuitive understandings. As a result, even if you had a good understanding of uncertainties in data, communicating it to most audiences can be tricky. (Try quoting a standard deviation figure in a meeting and count the blank stares that come back.) Data visualisation can help like no other can in understanding and communicating information related to uncertainties, probabilities and distributions. So, let’s take a look at how uncertainties can be visualised and how to use that data. For reasons that will become clearer, I will use the framework of basketball, and fantasy basketball in particular, for this article. As always, the focus is on the data and analysis methods, not the sport-specific analysis outputs; so you should be fine even if you don’t care about basketball. I include the code and data in my GitLab repo here, so you should be able to easily follow along by downloading/cloning the repo if you wish. I assume you’re familiar with python. Even if you’re relatively new, this tutorial shouldn’t be too tricky, though. You’ll need pandas and plotly. Install each (in your virtual environment) with a simple pip install [PACKAGE_NAME]. You can use any graphics packages, obviously, but I personally prefer the simplicity and power you get with Plotly. Imagine that through some random turn of events, someone has asked you to put together a fantasy basketball team. (You might ask — what is fantasy sports? Simply, in fantasy sports, players compete by forming a team from a pool of all available players in a real league, and these players are assigned points based on their real-life performance.) How would you go about it? One way would be to simply pick the best available players who expect to produce the most points for your team. I have prepared a csv file based on the 2018–2019 NBA season. The data comes from basketball-reference.com, and it was obtained using the basketball_reference_web_scraper library. I have pre-processed it to only include players who played over 1000 minutes, and who had not been traded mid-season. Let’s load the data with: season_tot_df = pd.read_csv('srcdata/bballref_1819_season_tots_1000plus_mins.csv', index_col=0) And take a look at it: season_tot_df.head() The data includes all of the original columns from the site and a handy fan_ppg column which I created based on this formula. What does the data look like? A bar graph of points per game can be plotted as follows: import plotly.express as pxfig = px.bar(season_tot_df, y='fan_ppg', x='name')fig.show() And with some formatting applied (for brevity, I will not show all my formatting code here, please see the repo if you are interested), we get: From James Harden to Bruce Brown, this chart plots all 254 players’ fantasy points. So, when it comes to your turn, would it always be best to simply choose the player with the next highest points per game? I personally don’t think it’s that simple. Here’s why. The bar chart above plots averages — more specifically, the ‘mean’, which is the total points divided by the number of games. But, as anyone who’s watched JR Smith or Nick Young know, not all averages are made the same. Some players are just more consistent than others, while others have inconsistencies that will drive you bonkers with their night to night variations. As an example, let’s compare Khris Middleton with Eric Bledsoe. Both were incidentally on the same team, and have produced nearly identical season average fantasy points: >>> print(season_tot_df[season_tot_df['name'].isin(['Eric Bledsoe', 'Khris Middleton'])].fan_ppg)45 31.90519549 31.351282 But they do so in wildly different manners, as you will see. To do this, let’s load up our data which includes individual game stats for each of our 254 players: with open('srcdata/bballref_1819_pl_box.pickle', 'rb') as f: pl_data_dict = pickle.load(f) The data is in a dictionary form, where the key value is the slug of a player (identifying string for the player as used by basketball-reference). Before doing anything, we need to collect Middleton and Bledsoe’s data with this information into one dataframe: Here, I collect the ‘slugs’ for the two players and use them for the dictionary data for each player. Each player’s data is in a list of dictionaries. They are easily converted into dataframes (temp_df), themselves added to a new list (temp_df_list) and then joined at the matching columns to produce one dataframe (comp_df). And plotting the data as a bar plot, we see: fig = px.bar(comp_df, y='fan_pts', color='player', facet_col='player', labels={'fan_pts': 'Fantasy Points', 'date': 'Date'})fig.update_layout(title='Fantasy performance comparison')fig.show() The entire set from the low end to the upper end in each chart might be referred to as a ‘range of outcomes’. That is, they represent the set of outcomes (I mean, they don’t exactly, but it’s representative, and let’s leave it at that for now). From these bar charts, it looks like Bledsoe’s data might be slightly more uneven than Middleton. There are more high bars, and also some glaring gaps (low bars). It’s hard to tell for certain from these figures, though. That’s where histograms can help. Histograms plot the spread of data points, where the y-values are counts of values that fit into each x ‘bin’. fig = px.histogram( comp_df, x='fan_pts', facet_row='player', color='player', labels={'fan_pts': 'Fantasy Points', 'count': 'Count'}, nbins=30)fig.update_layout(title='Fantasy performance comparison')fig.show() That looks like a resounding yes. These histograms tell us that Bledsoe is clearly more inconsistent than Middleton here for whatever reason. He has higher-scoring games more often, but also lower-scoring games more often. As a result, even though they have the same average, the chance of getting that average score changes drastically with Bledsoe against that for Middleton. Still, it’s not easy to see here just how much more likely it is for Bledsoe to score 40+ fantasy points vs Middleton. Also, what happens if we want to compare more than two players at a time? There are a number of tools that make it easy to see distributions in data. Box plot might be one — where it plots distribution as ‘boxes’, indicating percentile breakdowns of datasets. Try this: fig = px.box(comp_df, x='player', y='fan_pts', color='player', labels={'fan_pts': 'Fantasy Points', 'date': 'Date'})fig.update_layout(title='Fantasy performance comparison')fig.show() The middle lines indicate ‘median’ values, indicating the most likely outcomes, and the box indicates where half of all outcomes fall into, and the lines where most of the outcomes are expected. The dots indicate ‘outliers’ which is statistic-speak for unusual outcomes. Plotly also allows the underlying data to be plotted in point form — so let’s do that for further clarity and illustration: Clearly, having Bledsoe in your team is a high-risk, high-reward strategy. Violin plot is also a good tool that can give you a closer look at the distribution of data: fig = px.violin(comp_df, x='player', y='fan_pts', color='player', labels={'fan_pts': 'Fantasy Points', 'date': 'Date'}, points="all")fig.update_layout(title='Fantasy performance comparison')fig.show() Instead of the simplicity of box plots, where quartiles are marked as lines, violin plots essentially compare histograms, where width of the plot represents how often those values are likely to occur. This is also a limitation of violin plots. Because width is crucial in deciphering a violin plot, they are not as useful when many data points are shown. As each plot is given less and less width, subtle differences in them becomes more difficult. Okay, that was probably enough on that. Let’s go back to our initial question, which was — how could this data help us in choosing players. Let’s say that we have players left whose average fantasy points production is between 35 and 40, any of whom we could get into our team. Who do we choose? As we have done before, we can put them into histograms, or box plots: This code is very similar to what we did above for Middleton and Bledsoe, except now we are collecting slugs of players by the fan_ppg value. We can see here that as the data points increase, the compactness of box plots help it come into its own. Comparing even more players: Someone like Rudy Gobert, Chris Paul, or Khris Middleton (marked in orange) are what we would call ‘low variance’ players. You would be more certain about how they would perform day-to-day. On the other hand, players like John Wall, D’Angelo Russell, or Victor Oladipo (marked in blue) are much more variable. So the question becomes — what is more important to you? Maybe you are playing to get into the top few percent of your league, in which case you might want the high variance players. Or, if your league rewards consistent performance rather than occasional flash performance, the steady players might be better bets. In real life, this may be more like what you might want. Can you imagine having a team of players and never having any idea what you’re getting from them on any given night? How do we find one group or the other? One way to sort the player data to identify relative consistency as such is to use measures called ‘standard deviation’, or ‘variance’. Without getting too mathematical, they basically measure how spread out a distribution is. Eric Bledsoe would have a larger standard deviation than Middleton does in the above example. And to go a step further, we can identify how players of similar average (mean) performance might vary in terms of potential output, by plotting both as a scatter plot as below. Let’s go through the code briefly. Once again, slugs are collected, except that here the loop is simply over all slug values in the season total dataframe (i.e. every player). Then a mean and a standard deviation are calculated for each player, based on which a new dataframe is constructed. Lastly, I produce a ratio of standard deviation to the mean, which is used as the colour variable. (The numbers are rounded for simplicity in display purposes.) (I have put up an interactive version is here) The graph shows a good general correlation between standard deviation and the mean, with a large spread. That is, at the same mean values, a large range of standard deviation values exist. As we discussed previously, there are situations where identifying data points who might have occasional high-output performances are beneficial. Fantasy sports against many players is definitely one of them, where outsized benefits exist for placing towards the top of a large group, than being in the middle of the pack. The large spread here represents significant choice for the person choosing a player, to optimise their selection towards their goal. Take a look at the same graph, with some players’ data highlighted. Karl-Anthony Towns and Paul George in this plot have almost identical means, yet KAT’s standard deviation score is much higher. On the other hand, Jamal Crawford’s standard deviation is higher than George’s despite having a much lower mean. If a player’s “price” in the fantasy league was based solely on their mean production, Crawford might present a good value opportunity in helping to construct a high-ceiling team. This is a personal preference, but I will make one note on presenting statistical data. Depending on my audience, I often prefer plain language if possible, rather than jargon. So I might re-label ‘standard deviation’ to something like ‘variability’. Personally, I found that jargon like ‘mean’ and ‘standard deviation’ often distract (and worse, alienate) the audience sometimes. The statistical significance of a ‘standard deviation’ means nothing in this context. We are simply looking for data points with increased variability, so why not label as such? Take a look at this plot: I think that this conveys the message better than the one above, where the audience is often trying to remember what a standard deviation is — rather than on the substance of the message. Of course, for a specialist or a stat-friendly audience, go full throttle on the jargon 😉. I would like to also talk about the independence of uncertainties. That is when uncertainties stack linearly (and when they don’t, exactly). An intuitive way to think about it is this. Imagine that two variables with some given uncertainties are being analysed. Would one of them being high, or low, or affect the other? If it did, the two would be dependent. Practically, imagine that your entire fantasy basketball team included players from the same teams only. This would preclude many of them having career nights, as one performing well would likely mean reduced opportunities for the others. We can take a look at an example. Let’s compare James Harden’s data with a teammate’s (Chris Paul). I include the code, where we repeat the same thing we did to compare Middleton & Bledsoe’s data. Then, we go on to combine the data into one dataframe so that we can point to them for a scatter plot. And the resulting plot is below: The plot shows a classic, L-shaped inverse correlation between the two people’s scores. What does the data look like if we replace CP3 with a similar player who’s not on the same team? Like this, actually: It is more or less a random distribution. Note also that the highest combined points are higher for the lower plot — as one person’s high score does not preclude the other from doing so. In other words, correlation is important when we deal with uncertainties of multiple variables, and when we might be looking at data which combines them. Ok, let’s wrap it up there. As you might have seen, uncertainties, or ranges, are quite easy to visualise, and a good understanding of them is crucial to be able to make the best of the variability inherent in the world. It’s not the easiest thing to do, but I personally find that sometimes seeing all of the data (as in our scatter plots), and comparing the distributions (through box plots, histograms or violins) really help me to gain a better understanding of them. This article uses an example based on sport, but it is applicable to many other domains also. I’d love to hear about the types of uncertainties in your domain. In one of my upcoming articles, I would like to talk about forecasting (making predictions) and visualising outputs from them. Until then, take it easy! If you liked this, say 👋 / follow on twitter, or follow for updates. I also wrote this article about my favourite data visualisation books, if you haven’t read it before:
[ { "code": null, "e": 438, "s": 172, "text": "In this article, I want to show how easy it is to effectively visualise and communicate uncertainties and ranges. More importantly, I would like to demonstrate how helpful doing so can be in gaining an intuitive understanding of data and subsequent decision-making." }, { "code": null, "e": 1081, "s": 438, "text": "Although most of us are aware of uncertainties in every aspect of life, it is not often that we get to see, or work with them. Information or numbers are typically given in averages (means, or medians if we are lucky). Many of us don’t ever get taught statistics and probabilities, and the few that do are mostly taught them in just awful, tedious, academic ways that prioritise formulae over intuitive understandings. As a result, even if you had a good understanding of uncertainties in data, communicating it to most audiences can be tricky. (Try quoting a standard deviation figure in a meeting and count the blank stares that come back.)" }, { "code": null, "e": 1320, "s": 1081, "text": "Data visualisation can help like no other can in understanding and communicating information related to uncertainties, probabilities and distributions. So, let’s take a look at how uncertainties can be visualised and how to use that data." }, { "code": null, "e": 1616, "s": 1320, "text": "For reasons that will become clearer, I will use the framework of basketball, and fantasy basketball in particular, for this article. As always, the focus is on the data and analysis methods, not the sport-specific analysis outputs; so you should be fine even if you don’t care about basketball." }, { "code": null, "e": 1758, "s": 1616, "text": "I include the code and data in my GitLab repo here, so you should be able to easily follow along by downloading/cloning the repo if you wish." }, { "code": null, "e": 1874, "s": 1758, "text": "I assume you’re familiar with python. Even if you’re relatively new, this tutorial shouldn’t be too tricky, though." }, { "code": null, "e": 1990, "s": 1874, "text": "You’ll need pandas and plotly. Install each (in your virtual environment) with a simple pip install [PACKAGE_NAME]." }, { "code": null, "e": 2106, "s": 1990, "text": "You can use any graphics packages, obviously, but I personally prefer the simplicity and power you get with Plotly." }, { "code": null, "e": 2220, "s": 2106, "text": "Imagine that through some random turn of events, someone has asked you to put together a fantasy basketball team." }, { "code": null, "e": 2454, "s": 2220, "text": "(You might ask — what is fantasy sports? Simply, in fantasy sports, players compete by forming a team from a pool of all available players in a real league, and these players are assigned points based on their real-life performance.)" }, { "code": null, "e": 2593, "s": 2454, "text": "How would you go about it? One way would be to simply pick the best available players who expect to produce the most points for your team." }, { "code": null, "e": 2891, "s": 2593, "text": "I have prepared a csv file based on the 2018–2019 NBA season. The data comes from basketball-reference.com, and it was obtained using the basketball_reference_web_scraper library. I have pre-processed it to only include players who played over 1000 minutes, and who had not been traded mid-season." }, { "code": null, "e": 2917, "s": 2891, "text": "Let’s load the data with:" }, { "code": null, "e": 3013, "s": 2917, "text": "season_tot_df = pd.read_csv('srcdata/bballref_1819_season_tots_1000plus_mins.csv', index_col=0)" }, { "code": null, "e": 3036, "s": 3013, "text": "And take a look at it:" }, { "code": null, "e": 3057, "s": 3036, "text": "season_tot_df.head()" }, { "code": null, "e": 3183, "s": 3057, "text": "The data includes all of the original columns from the site and a handy fan_ppg column which I created based on this formula." }, { "code": null, "e": 3271, "s": 3183, "text": "What does the data look like? A bar graph of points per game can be plotted as follows:" }, { "code": null, "e": 3359, "s": 3271, "text": "import plotly.express as pxfig = px.bar(season_tot_df, y='fan_ppg', x='name')fig.show()" }, { "code": null, "e": 3503, "s": 3359, "text": "And with some formatting applied (for brevity, I will not show all my formatting code here, please see the repo if you are interested), we get:" }, { "code": null, "e": 3710, "s": 3503, "text": "From James Harden to Bruce Brown, this chart plots all 254 players’ fantasy points. So, when it comes to your turn, would it always be best to simply choose the player with the next highest points per game?" }, { "code": null, "e": 3765, "s": 3710, "text": "I personally don’t think it’s that simple. Here’s why." }, { "code": null, "e": 3985, "s": 3765, "text": "The bar chart above plots averages — more specifically, the ‘mean’, which is the total points divided by the number of games. But, as anyone who’s watched JR Smith or Nick Young know, not all averages are made the same." }, { "code": null, "e": 4136, "s": 3985, "text": "Some players are just more consistent than others, while others have inconsistencies that will drive you bonkers with their night to night variations." }, { "code": null, "e": 4307, "s": 4136, "text": "As an example, let’s compare Khris Middleton with Eric Bledsoe. Both were incidentally on the same team, and have produced nearly identical season average fantasy points:" }, { "code": null, "e": 4435, "s": 4307, "text": ">>> print(season_tot_df[season_tot_df['name'].isin(['Eric Bledsoe', 'Khris Middleton'])].fan_ppg)45 31.90519549 31.351282" }, { "code": null, "e": 4597, "s": 4435, "text": "But they do so in wildly different manners, as you will see. To do this, let’s load up our data which includes individual game stats for each of our 254 players:" }, { "code": null, "e": 4691, "s": 4597, "text": "with open('srcdata/bballref_1819_pl_box.pickle', 'rb') as f: pl_data_dict = pickle.load(f)" }, { "code": null, "e": 4838, "s": 4691, "text": "The data is in a dictionary form, where the key value is the slug of a player (identifying string for the player as used by basketball-reference)." }, { "code": null, "e": 4951, "s": 4838, "text": "Before doing anything, we need to collect Middleton and Bledsoe’s data with this information into one dataframe:" }, { "code": null, "e": 5277, "s": 4951, "text": "Here, I collect the ‘slugs’ for the two players and use them for the dictionary data for each player. Each player’s data is in a list of dictionaries. They are easily converted into dataframes (temp_df), themselves added to a new list (temp_df_list) and then joined at the matching columns to produce one dataframe (comp_df)." }, { "code": null, "e": 5322, "s": 5277, "text": "And plotting the data as a bar plot, we see:" }, { "code": null, "e": 5514, "s": 5322, "text": "fig = px.bar(comp_df, y='fan_pts', color='player', facet_col='player', labels={'fan_pts': 'Fantasy Points', 'date': 'Date'})fig.update_layout(title='Fantasy performance comparison')fig.show()" }, { "code": null, "e": 5759, "s": 5514, "text": "The entire set from the low end to the upper end in each chart might be referred to as a ‘range of outcomes’. That is, they represent the set of outcomes (I mean, they don’t exactly, but it’s representative, and let’s leave it at that for now)." }, { "code": null, "e": 6125, "s": 5759, "text": "From these bar charts, it looks like Bledsoe’s data might be slightly more uneven than Middleton. There are more high bars, and also some glaring gaps (low bars). It’s hard to tell for certain from these figures, though. That’s where histograms can help. Histograms plot the spread of data points, where the y-values are counts of values that fit into each x ‘bin’." }, { "code": null, "e": 6342, "s": 6125, "text": "fig = px.histogram( comp_df, x='fan_pts', facet_row='player', color='player', labels={'fan_pts': 'Fantasy Points', 'count': 'Count'}, nbins=30)fig.update_layout(title='Fantasy performance comparison')fig.show()" }, { "code": null, "e": 6376, "s": 6342, "text": "That looks like a resounding yes." }, { "code": null, "e": 6720, "s": 6376, "text": "These histograms tell us that Bledsoe is clearly more inconsistent than Middleton here for whatever reason. He has higher-scoring games more often, but also lower-scoring games more often. As a result, even though they have the same average, the chance of getting that average score changes drastically with Bledsoe against that for Middleton." }, { "code": null, "e": 6913, "s": 6720, "text": "Still, it’s not easy to see here just how much more likely it is for Bledsoe to score 40+ fantasy points vs Middleton. Also, what happens if we want to compare more than two players at a time?" }, { "code": null, "e": 7109, "s": 6913, "text": "There are a number of tools that make it easy to see distributions in data. Box plot might be one — where it plots distribution as ‘boxes’, indicating percentile breakdowns of datasets. Try this:" }, { "code": null, "e": 7293, "s": 7109, "text": "fig = px.box(comp_df, x='player', y='fan_pts', color='player', labels={'fan_pts': 'Fantasy Points', 'date': 'Date'})fig.update_layout(title='Fantasy performance comparison')fig.show()" }, { "code": null, "e": 7564, "s": 7293, "text": "The middle lines indicate ‘median’ values, indicating the most likely outcomes, and the box indicates where half of all outcomes fall into, and the lines where most of the outcomes are expected. The dots indicate ‘outliers’ which is statistic-speak for unusual outcomes." }, { "code": null, "e": 7688, "s": 7564, "text": "Plotly also allows the underlying data to be plotted in point form — so let’s do that for further clarity and illustration:" }, { "code": null, "e": 7763, "s": 7688, "text": "Clearly, having Bledsoe in your team is a high-risk, high-reward strategy." }, { "code": null, "e": 7856, "s": 7763, "text": "Violin plot is also a good tool that can give you a closer look at the distribution of data:" }, { "code": null, "e": 8057, "s": 7856, "text": "fig = px.violin(comp_df, x='player', y='fan_pts', color='player', labels={'fan_pts': 'Fantasy Points', 'date': 'Date'}, points=\"all\")fig.update_layout(title='Fantasy performance comparison')fig.show()" }, { "code": null, "e": 8258, "s": 8057, "text": "Instead of the simplicity of box plots, where quartiles are marked as lines, violin plots essentially compare histograms, where width of the plot represents how often those values are likely to occur." }, { "code": null, "e": 8506, "s": 8258, "text": "This is also a limitation of violin plots. Because width is crucial in deciphering a violin plot, they are not as useful when many data points are shown. As each plot is given less and less width, subtle differences in them becomes more difficult." }, { "code": null, "e": 8546, "s": 8506, "text": "Okay, that was probably enough on that." }, { "code": null, "e": 8646, "s": 8546, "text": "Let’s go back to our initial question, which was — how could this data help us in choosing players." }, { "code": null, "e": 8873, "s": 8646, "text": "Let’s say that we have players left whose average fantasy points production is between 35 and 40, any of whom we could get into our team. Who do we choose? As we have done before, we can put them into histograms, or box plots:" }, { "code": null, "e": 9015, "s": 8873, "text": "This code is very similar to what we did above for Middleton and Bledsoe, except now we are collecting slugs of players by the fan_ppg value." }, { "code": null, "e": 9150, "s": 9015, "text": "We can see here that as the data points increase, the compactness of box plots help it come into its own. Comparing even more players:" }, { "code": null, "e": 9460, "s": 9150, "text": "Someone like Rudy Gobert, Chris Paul, or Khris Middleton (marked in orange) are what we would call ‘low variance’ players. You would be more certain about how they would perform day-to-day. On the other hand, players like John Wall, D’Angelo Russell, or Victor Oladipo (marked in blue) are much more variable." }, { "code": null, "e": 9643, "s": 9460, "text": "So the question becomes — what is more important to you? Maybe you are playing to get into the top few percent of your league, in which case you might want the high variance players." }, { "code": null, "e": 9950, "s": 9643, "text": "Or, if your league rewards consistent performance rather than occasional flash performance, the steady players might be better bets. In real life, this may be more like what you might want. Can you imagine having a team of players and never having any idea what you’re getting from them on any given night?" }, { "code": null, "e": 9989, "s": 9950, "text": "How do we find one group or the other?" }, { "code": null, "e": 10310, "s": 9989, "text": "One way to sort the player data to identify relative consistency as such is to use measures called ‘standard deviation’, or ‘variance’. Without getting too mathematical, they basically measure how spread out a distribution is. Eric Bledsoe would have a larger standard deviation than Middleton does in the above example." }, { "code": null, "e": 10488, "s": 10310, "text": "And to go a step further, we can identify how players of similar average (mean) performance might vary in terms of potential output, by plotting both as a scatter plot as below." }, { "code": null, "e": 10664, "s": 10488, "text": "Let’s go through the code briefly. Once again, slugs are collected, except that here the loop is simply over all slug values in the season total dataframe (i.e. every player)." }, { "code": null, "e": 10879, "s": 10664, "text": "Then a mean and a standard deviation are calculated for each player, based on which a new dataframe is constructed. Lastly, I produce a ratio of standard deviation to the mean, which is used as the colour variable." }, { "code": null, "e": 10941, "s": 10879, "text": "(The numbers are rounded for simplicity in display purposes.)" }, { "code": null, "e": 10988, "s": 10941, "text": "(I have put up an interactive version is here)" }, { "code": null, "e": 11177, "s": 10988, "text": "The graph shows a good general correlation between standard deviation and the mean, with a large spread. That is, at the same mean values, a large range of standard deviation values exist." }, { "code": null, "e": 11500, "s": 11177, "text": "As we discussed previously, there are situations where identifying data points who might have occasional high-output performances are beneficial. Fantasy sports against many players is definitely one of them, where outsized benefits exist for placing towards the top of a large group, than being in the middle of the pack." }, { "code": null, "e": 11634, "s": 11500, "text": "The large spread here represents significant choice for the person choosing a player, to optimise their selection towards their goal." }, { "code": null, "e": 11702, "s": 11634, "text": "Take a look at the same graph, with some players’ data highlighted." }, { "code": null, "e": 11830, "s": 11702, "text": "Karl-Anthony Towns and Paul George in this plot have almost identical means, yet KAT’s standard deviation score is much higher." }, { "code": null, "e": 12123, "s": 11830, "text": "On the other hand, Jamal Crawford’s standard deviation is higher than George’s despite having a much lower mean. If a player’s “price” in the fantasy league was based solely on their mean production, Crawford might present a good value opportunity in helping to construct a high-ceiling team." }, { "code": null, "e": 12374, "s": 12123, "text": "This is a personal preference, but I will make one note on presenting statistical data. Depending on my audience, I often prefer plain language if possible, rather than jargon. So I might re-label ‘standard deviation’ to something like ‘variability’." }, { "code": null, "e": 12708, "s": 12374, "text": "Personally, I found that jargon like ‘mean’ and ‘standard deviation’ often distract (and worse, alienate) the audience sometimes. The statistical significance of a ‘standard deviation’ means nothing in this context. We are simply looking for data points with increased variability, so why not label as such? Take a look at this plot:" }, { "code": null, "e": 12896, "s": 12708, "text": "I think that this conveys the message better than the one above, where the audience is often trying to remember what a standard deviation is — rather than on the substance of the message." }, { "code": null, "e": 12987, "s": 12896, "text": "Of course, for a specialist or a stat-friendly audience, go full throttle on the jargon 😉." }, { "code": null, "e": 13128, "s": 12987, "text": "I would like to also talk about the independence of uncertainties. That is when uncertainties stack linearly (and when they don’t, exactly)." }, { "code": null, "e": 13308, "s": 13128, "text": "An intuitive way to think about it is this. Imagine that two variables with some given uncertainties are being analysed. Would one of them being high, or low, or affect the other?" }, { "code": null, "e": 13586, "s": 13308, "text": "If it did, the two would be dependent. Practically, imagine that your entire fantasy basketball team included players from the same teams only. This would preclude many of them having career nights, as one performing well would likely mean reduced opportunities for the others." }, { "code": null, "e": 13886, "s": 13586, "text": "We can take a look at an example. Let’s compare James Harden’s data with a teammate’s (Chris Paul). I include the code, where we repeat the same thing we did to compare Middleton & Bledsoe’s data. Then, we go on to combine the data into one dataframe so that we can point to them for a scatter plot." }, { "code": null, "e": 13919, "s": 13886, "text": "And the resulting plot is below:" }, { "code": null, "e": 14125, "s": 13919, "text": "The plot shows a classic, L-shaped inverse correlation between the two people’s scores. What does the data look like if we replace CP3 with a similar player who’s not on the same team? Like this, actually:" }, { "code": null, "e": 14312, "s": 14125, "text": "It is more or less a random distribution. Note also that the highest combined points are higher for the lower plot — as one person’s high score does not preclude the other from doing so." }, { "code": null, "e": 14466, "s": 14312, "text": "In other words, correlation is important when we deal with uncertainties of multiple variables, and when we might be looking at data which combines them." }, { "code": null, "e": 14494, "s": 14466, "text": "Ok, let’s wrap it up there." }, { "code": null, "e": 14687, "s": 14494, "text": "As you might have seen, uncertainties, or ranges, are quite easy to visualise, and a good understanding of them is crucial to be able to make the best of the variability inherent in the world." }, { "code": null, "e": 14938, "s": 14687, "text": "It’s not the easiest thing to do, but I personally find that sometimes seeing all of the data (as in our scatter plots), and comparing the distributions (through box plots, histograms or violins) really help me to gain a better understanding of them." }, { "code": null, "e": 15098, "s": 14938, "text": "This article uses an example based on sport, but it is applicable to many other domains also. I’d love to hear about the types of uncertainties in your domain." }, { "code": null, "e": 15251, "s": 15098, "text": "In one of my upcoming articles, I would like to talk about forecasting (making predictions) and visualising outputs from them. Until then, take it easy!" } ]
Java Generics - No instanceOf
Because compiler uses type erasure, the runtime does not keep track of type parameters, so at runtime difference between Box<Integer> and Box<String> cannot be verified using instanceOf operator. Box<Integer> integerBox = new Box<Integer>(); //Compiler Error: //Cannot perform instanceof check against //parameterized type Box<Integer>. //Use the form Box<?> instead since further //generic type information will be erased at runtime if(integerBox instanceof Box<Integer>) { } 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2836, "s": 2640, "text": "Because compiler uses type erasure, the runtime does not keep track of type parameters, so at runtime difference between Box<Integer> and Box<String> cannot be verified using instanceOf operator." }, { "code": null, "e": 3121, "s": 2836, "text": "Box<Integer> integerBox = new Box<Integer>();\n\n//Compiler Error:\n//Cannot perform instanceof check against \n//parameterized type Box<Integer>. \n//Use the form Box<?> instead since further \n//generic type information will be erased at runtime\nif(integerBox instanceof Box<Integer>) { }" }, { "code": null, "e": 3154, "s": 3121, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 3170, "s": 3154, "text": " Malhar Lathkar" }, { "code": null, "e": 3203, "s": 3170, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 3219, "s": 3203, "text": " Malhar Lathkar" }, { "code": null, "e": 3254, "s": 3219, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3268, "s": 3254, "text": " Anadi Sharma" }, { "code": null, "e": 3302, "s": 3268, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 3316, "s": 3302, "text": " Tushar Kale" }, { "code": null, "e": 3353, "s": 3316, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3368, "s": 3353, "text": " Monica Mittal" }, { "code": null, "e": 3401, "s": 3368, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 3420, "s": 3401, "text": " Arnab Chakraborty" }, { "code": null, "e": 3427, "s": 3420, "text": " Print" }, { "code": null, "e": 3438, "s": 3427, "text": " Add Notes" } ]
Are you using Python with APIs? Learn how to use a retry decorator! | by Fabian Bosler | Towards Data Science
People often describe Python as a “glue-language.” The term “glue-language” to me entails that a language helps to connect systems and makes sure that data gets from A to B in a desired structure and format. I have built countless ETL-scripts (Extraction Transformation Load) with Python. All those scripts essentially are functioning according to the same principle. They are pulling data from somewhere, transform the data, and then run a final operation. This last operation would typically mean to upload the data somewhere, but could also be a conditional deletion. An ever-increasing proportion of a typical company’s infrastructure is moving to the cloud. More companies are shifting towards a micro-service approach. These paradigm shifts away from local to cloud-based means that you probably also have faced a situation where you had to pull data from somewhere or write data somewhere that is not your local computer. On a small scale, there rarely are problems around that. If some extraction or writeback fails, you would typically notice that and would be able to remedy the mistake. But, as you move towards larger-scale operations and potentially hundreds of thousands of transactions, you don’t want to get screwed over by a temporary drop of internet-connection, too many concurrent writes, a temporarily unresponsive source system, or god knows what else. I found a very simple retry-decorator to be a saving grace in countless situations like that. Most of my projects, at one point or another, end up having the retry decorator in some util module. In Python, functions are first-class objects. A function is just like any other object. This fact, among other things, means that a function can be dynamically created, passed to a function itself, and even changed. Take a look at the following (albeit silly) example: def my_function(x): print(x)IN:my_function(2)OUT:2IN:my_function.yolo = 'you live only once'print(my_function.yolo)OUT:'you live only once' It is good to know that we can wrap a function with another function to fulfill a particular need. We could, for example, make sure that the function reports to some logging endpoint whenever called, we could print out the arguments, we could implement type checking, preprocessing, or postprocessing to just name a few possibilities. Let’s take a look at a simple example: def first_func(x): return x**2 def second_func(x): return x - 2 Both functions fail when being called with the string '2'. We could throw a type conversion function in the mix and decorate our first_func and second_func with that. def convert_to_numeric(func): # define a function within the outer function def new_func(x): return func(float(x)) # return the newly defined function return new_func This convert_to_numeric wrapper function expects a function as an argument and returns another function. Now, while previously failing, if you wrap the functions and then call them with a string number, all works as expected. IN:new_fist_func = convert_to_numeric(first_func)###############################convert_to_numeric returns this function:def new_func(x): return first_func(float(x))###############################new_fist_func('2')OUT:4.0IN:convert_to_numeric(second_func)('2')OUT:0 So what is going on here? Well, our convert_to_numeric takes a function (A) as an argument and returns a new function (B). The new function (B), when called, calls function (A) but instead of calling it with the passed argument x it calls function (A) with float(x) and therefore solving our previous TypeError problem. To make it a little bit easier for the developer, Python provides a special Syntax. We can also do the following: @convert_to_numericdef first_func(x): return x**2 The above syntax is equivalent to: def first_func(x): return x**2first_func = convert_to_numeric(first_func) This syntax makes a little clearer what exactly is happening, especially when using multiple decorators. Now that we have covered the basics, let’s move to my favorite and heavily used retry-decorator: Wrapping a wrapped function. That is some inception stuff right there. But bear with me, it is not that complicated! Let’s walk through the code step by step: Outmost function retry: This parameterizes our decorator, i.e. what are the exceptions we want to handle, how often do we want to try, how long do we wait between tries, and what is our exponential backoff-factor (i.e. with what number do we multiply the waiting time each time we fail).retry_decorator: This is the parametrized decorator, which is being returned by our retry function. We are decorating the function within the retry_decorator with @wraps. Strictly speaking, this is not necessary when it comes to functionality. This wrapper updates the __name__ and __doc__ of the wrapped function (if we didn't do that our function __name__ would always be func_with_retries)func_with_retries applies the retry logic. This function wraps the function calls in try-except blocks and implements the exponential backoff wait and some logging. Outmost function retry: This parameterizes our decorator, i.e. what are the exceptions we want to handle, how often do we want to try, how long do we wait between tries, and what is our exponential backoff-factor (i.e. with what number do we multiply the waiting time each time we fail). retry_decorator: This is the parametrized decorator, which is being returned by our retry function. We are decorating the function within the retry_decorator with @wraps. Strictly speaking, this is not necessary when it comes to functionality. This wrapper updates the __name__ and __doc__ of the wrapped function (if we didn't do that our function __name__ would always be func_with_retries) func_with_retries applies the retry logic. This function wraps the function calls in try-except blocks and implements the exponential backoff wait and some logging. Alternatively, a little bit more specific: Calling the decorated function and running into errors would then lead to something like this: Here we have nice logging, we print out the args and kwargs and function name, which should make debugging and fixing the problem a breeze (should the error persist event after all the retries are used up). There you have it. You learned how decorators work in Python and how to decorate your mission-critical functions with a simple retry decorator to make sure they will execute even in the face of some uncertainty. If you like what you read and don’t want to miss new stories, subscribe here: medium.com Some further reading about how to speed up your code:
[ { "code": null, "e": 380, "s": 172, "text": "People often describe Python as a “glue-language.” The term “glue-language” to me entails that a language helps to connect systems and makes sure that data gets from A to B in a desired structure and format." }, { "code": null, "e": 743, "s": 380, "text": "I have built countless ETL-scripts (Extraction Transformation Load) with Python. All those scripts essentially are functioning according to the same principle. They are pulling data from somewhere, transform the data, and then run a final operation. This last operation would typically mean to upload the data somewhere, but could also be a conditional deletion." }, { "code": null, "e": 1101, "s": 743, "text": "An ever-increasing proportion of a typical company’s infrastructure is moving to the cloud. More companies are shifting towards a micro-service approach. These paradigm shifts away from local to cloud-based means that you probably also have faced a situation where you had to pull data from somewhere or write data somewhere that is not your local computer." }, { "code": null, "e": 1547, "s": 1101, "text": "On a small scale, there rarely are problems around that. If some extraction or writeback fails, you would typically notice that and would be able to remedy the mistake. But, as you move towards larger-scale operations and potentially hundreds of thousands of transactions, you don’t want to get screwed over by a temporary drop of internet-connection, too many concurrent writes, a temporarily unresponsive source system, or god knows what else." }, { "code": null, "e": 1742, "s": 1547, "text": "I found a very simple retry-decorator to be a saving grace in countless situations like that. Most of my projects, at one point or another, end up having the retry decorator in some util module." }, { "code": null, "e": 2011, "s": 1742, "text": "In Python, functions are first-class objects. A function is just like any other object. This fact, among other things, means that a function can be dynamically created, passed to a function itself, and even changed. Take a look at the following (albeit silly) example:" }, { "code": null, "e": 2154, "s": 2011, "text": "def my_function(x): print(x)IN:my_function(2)OUT:2IN:my_function.yolo = 'you live only once'print(my_function.yolo)OUT:'you live only once'" }, { "code": null, "e": 2528, "s": 2154, "text": "It is good to know that we can wrap a function with another function to fulfill a particular need. We could, for example, make sure that the function reports to some logging endpoint whenever called, we could print out the arguments, we could implement type checking, preprocessing, or postprocessing to just name a few possibilities. Let’s take a look at a simple example:" }, { "code": null, "e": 2601, "s": 2528, "text": "def first_func(x): return x**2 def second_func(x): return x - 2" }, { "code": null, "e": 2768, "s": 2601, "text": "Both functions fail when being called with the string '2'. We could throw a type conversion function in the mix and decorate our first_func and second_func with that." }, { "code": null, "e": 2954, "s": 2768, "text": "def convert_to_numeric(func): # define a function within the outer function def new_func(x): return func(float(x)) # return the newly defined function return new_func" }, { "code": null, "e": 3059, "s": 2954, "text": "This convert_to_numeric wrapper function expects a function as an argument and returns another function." }, { "code": null, "e": 3180, "s": 3059, "text": "Now, while previously failing, if you wrap the functions and then call them with a string number, all works as expected." }, { "code": null, "e": 3449, "s": 3180, "text": "IN:new_fist_func = convert_to_numeric(first_func)###############################convert_to_numeric returns this function:def new_func(x): return first_func(float(x))###############################new_fist_func('2')OUT:4.0IN:convert_to_numeric(second_func)('2')OUT:0" }, { "code": null, "e": 3475, "s": 3449, "text": "So what is going on here?" }, { "code": null, "e": 3769, "s": 3475, "text": "Well, our convert_to_numeric takes a function (A) as an argument and returns a new function (B). The new function (B), when called, calls function (A) but instead of calling it with the passed argument x it calls function (A) with float(x) and therefore solving our previous TypeError problem." }, { "code": null, "e": 3883, "s": 3769, "text": "To make it a little bit easier for the developer, Python provides a special Syntax. We can also do the following:" }, { "code": null, "e": 3936, "s": 3883, "text": "@convert_to_numericdef first_func(x): return x**2" }, { "code": null, "e": 3971, "s": 3936, "text": "The above syntax is equivalent to:" }, { "code": null, "e": 4048, "s": 3971, "text": "def first_func(x): return x**2first_func = convert_to_numeric(first_func)" }, { "code": null, "e": 4153, "s": 4048, "text": "This syntax makes a little clearer what exactly is happening, especially when using multiple decorators." }, { "code": null, "e": 4250, "s": 4153, "text": "Now that we have covered the basics, let’s move to my favorite and heavily used retry-decorator:" }, { "code": null, "e": 4367, "s": 4250, "text": "Wrapping a wrapped function. That is some inception stuff right there. But bear with me, it is not that complicated!" }, { "code": null, "e": 4409, "s": 4367, "text": "Let’s walk through the code step by step:" }, { "code": null, "e": 5253, "s": 4409, "text": "Outmost function retry: This parameterizes our decorator, i.e. what are the exceptions we want to handle, how often do we want to try, how long do we wait between tries, and what is our exponential backoff-factor (i.e. with what number do we multiply the waiting time each time we fail).retry_decorator: This is the parametrized decorator, which is being returned by our retry function. We are decorating the function within the retry_decorator with @wraps. Strictly speaking, this is not necessary when it comes to functionality. This wrapper updates the __name__ and __doc__ of the wrapped function (if we didn't do that our function __name__ would always be func_with_retries)func_with_retries applies the retry logic. This function wraps the function calls in try-except blocks and implements the exponential backoff wait and some logging." }, { "code": null, "e": 5541, "s": 5253, "text": "Outmost function retry: This parameterizes our decorator, i.e. what are the exceptions we want to handle, how often do we want to try, how long do we wait between tries, and what is our exponential backoff-factor (i.e. with what number do we multiply the waiting time each time we fail)." }, { "code": null, "e": 5934, "s": 5541, "text": "retry_decorator: This is the parametrized decorator, which is being returned by our retry function. We are decorating the function within the retry_decorator with @wraps. Strictly speaking, this is not necessary when it comes to functionality. This wrapper updates the __name__ and __doc__ of the wrapped function (if we didn't do that our function __name__ would always be func_with_retries)" }, { "code": null, "e": 6099, "s": 5934, "text": "func_with_retries applies the retry logic. This function wraps the function calls in try-except blocks and implements the exponential backoff wait and some logging." }, { "code": null, "e": 6142, "s": 6099, "text": "Alternatively, a little bit more specific:" }, { "code": null, "e": 6237, "s": 6142, "text": "Calling the decorated function and running into errors would then lead to something like this:" }, { "code": null, "e": 6444, "s": 6237, "text": "Here we have nice logging, we print out the args and kwargs and function name, which should make debugging and fixing the problem a breeze (should the error persist event after all the retries are used up)." }, { "code": null, "e": 6656, "s": 6444, "text": "There you have it. You learned how decorators work in Python and how to decorate your mission-critical functions with a simple retry decorator to make sure they will execute even in the face of some uncertainty." }, { "code": null, "e": 6734, "s": 6656, "text": "If you like what you read and don’t want to miss new stories, subscribe here:" }, { "code": null, "e": 6745, "s": 6734, "text": "medium.com" } ]
Find all the patterns of “1(0+)1” in a given string using Python Regex
In this tutorial, we are going to write a program which finds all the occurrences of the 1(0+1) in a string using the regexes. We have a re module in Python which helps us to work with the regular expressions. Let's see one sample case. Input: string = "Sample 1(0+)1 string with 1(0+)1 unnecessary patterns 1(0+)1" Output: Total number of pattern maches are 3 ['1(0+)1', '1(0+)1', '1(0+)1'] Follow the below steps to write the code for the program. 1. Import the re module. 2. Initialise a string. 3. Create a regex object using regular expression which matches the pattern using the re.compile(). Remember to pass a raw string to the function instead of the usual string. 4. Now, match all the occurrence of the pattern using regex object from the above step and regex_object.findall() method. 5. The above steps return a match object and print the matched patterns using match_object.group() method. Let's see the code. Live Demo # importing the re module import re # initializing the string string = "Sample 1(0+)1 string with 1(0+)1 unnecessary patterns 1(0+)1" # creating a regex object for our patter regex = re.compile(r"\d\(\d\+\)\d") # this regex object will find all the patter ns which are 1(0+)1 # storing all the matches patterns in a variable using regex.findall() method result = regex.findall(string) # result is a match object # printing the frequency of patterns print(f"Total number of pattern maches are {len(result)}") print() # printing the matches from the string using result.group() method print(result) If you run the above code, you will get the following output. Total number of pattern maches are 3 ['1(0+)1', '1(0+)1', '1(0+)1'] If you have any doubts regarding the tutorial, mention them in the comment section.
[ { "code": null, "e": 1272, "s": 1062, "text": "In this tutorial, we are going to write a program which finds all the occurrences of the 1(0+1) in a string using the regexes. We have a re module in Python which helps us to work with the regular expressions." }, { "code": null, "e": 1299, "s": 1272, "text": "Let's see one sample case." }, { "code": null, "e": 1454, "s": 1299, "text": "Input:\nstring = \"Sample 1(0+)1 string with 1(0+)1 unnecessary patterns 1(0+)1\" Output:\nTotal number of pattern maches are 3 ['1(0+)1', '1(0+)1', '1(0+)1']" }, { "code": null, "e": 1512, "s": 1454, "text": "Follow the below steps to write the code for the program." }, { "code": null, "e": 1965, "s": 1512, "text": "1. Import the re module.\n2. Initialise a string.\n3. Create a regex object using regular expression which matches the pattern using the re.compile(). Remember to pass a raw string to the function instead of the usual string.\n4. Now, match all the occurrence of the pattern using regex object from the above step and regex_object.findall() method.\n5. The above steps return a match object and print the matched patterns using match_object.group() method." }, { "code": null, "e": 1985, "s": 1965, "text": "Let's see the code." }, { "code": null, "e": 1996, "s": 1985, "text": " Live Demo" }, { "code": null, "e": 2593, "s": 1996, "text": "# importing the re module\nimport re\n# initializing the string\nstring = \"Sample 1(0+)1 string with 1(0+)1 unnecessary patterns 1(0+)1\"\n# creating a regex object for our patter\nregex = re.compile(r\"\\d\\(\\d\\+\\)\\d\") # this regex object will find all the patter ns which are 1(0+)1\n# storing all the matches patterns in a variable using regex.findall() method\nresult = regex.findall(string) # result is a match object\n# printing the frequency of patterns\nprint(f\"Total number of pattern maches are {len(result)}\")\nprint()\n# printing the matches from the string using result.group() method\nprint(result)" }, { "code": null, "e": 2655, "s": 2593, "text": "If you run the above code, you will get the following output." }, { "code": null, "e": 2723, "s": 2655, "text": "Total number of pattern maches are 3\n['1(0+)1', '1(0+)1', '1(0+)1']" }, { "code": null, "e": 2807, "s": 2723, "text": "If you have any doubts regarding the tutorial, mention them in the comment section." } ]
Program to find largest element in an array in C++
In this tutorial, we will be discussing a program to find the largest element in an array. For this, we will be provided with an array. Our task is to find the largest number from the elements inside the array. Live Demo #include <bits/stdc++.h> using namespace std; //finding largest integer int largest(int arr[], int n){ int i; int max = arr[0]; //traversing other elements for (i = 1; i < n; i++) if (arr[i] > max) max = arr[i]; return max; } int main(){ int arr[] = {10, 324, 45, 90, 9808}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Largest in given array is " << largest(arr, n); return 0; } Largest in given array is 9808
[ { "code": null, "e": 1153, "s": 1062, "text": "In this tutorial, we will be discussing a program to find the largest element in an\narray." }, { "code": null, "e": 1273, "s": 1153, "text": "For this, we will be provided with an array. Our task is to find the largest number from\nthe elements inside the array." }, { "code": null, "e": 1284, "s": 1273, "text": " Live Demo" }, { "code": null, "e": 1702, "s": 1284, "text": "#include <bits/stdc++.h>\nusing namespace std;\n//finding largest integer\nint largest(int arr[], int n){\n int i;\n int max = arr[0];\n //traversing other elements\n for (i = 1; i < n; i++)\n if (arr[i] > max)\n max = arr[i];\n return max;\n}\nint main(){\n int arr[] = {10, 324, 45, 90, 9808};\n int n = sizeof(arr) / sizeof(arr[0]);\n cout << \"Largest in given array is \" << largest(arr, n);\n return 0;\n}" }, { "code": null, "e": 1733, "s": 1702, "text": "Largest in given array is 9808" } ]
Java Program to sort a List in case insensitive order
Let’s say your list is having the following elements − P, W, g, K, H, t, E Therefore, case sensitive order means, capital and small letters will be considered irrespective of case. The output would be − E, g, H, K, P, t, W The following is our array − String[] arr = new String[] { "P", "W", "g", "K", "H", "t", "E" }; Convert the above array to a List − List<String>list = Arrays.asList(arr); Now sort the above list in case insensitive order − Collections.sort(list, String.CASE_INSENSITIVE_ORDER); Live Demo import java.util.Arrays; import java.util.Collections; import java.util.List; public class Demo { public static void main(String[] argv) throws Exception { String[] arr = new String[] { "P", "W", "g", "K", "H", "t", "E" }; List<String>list = Arrays.asList(arr); System.out.println("List = "+list); Collections.sort(list); System.out.println("Case Sensitive Sort = "+list); Collections.sort(list, String.CASE_INSENSITIVE_ORDER); System.out.println("Case Insensitive Sort = "+list); } } List = [P, W, g, K, H, t, E] Case Sensitive Sort = [E, H, K, P, W, g, t] Case Insensitive Sort = [E, g, H, K, P, t, W]
[ { "code": null, "e": 1117, "s": 1062, "text": "Let’s say your list is having the following elements −" }, { "code": null, "e": 1137, "s": 1117, "text": "P, W, g, K, H, t, E" }, { "code": null, "e": 1265, "s": 1137, "text": "Therefore, case sensitive order means, capital and small letters will be considered irrespective of case. The output would be −" }, { "code": null, "e": 1285, "s": 1265, "text": "E, g, H, K, P, t, W" }, { "code": null, "e": 1314, "s": 1285, "text": "The following is our array −" }, { "code": null, "e": 1381, "s": 1314, "text": "String[] arr = new String[] { \"P\", \"W\", \"g\", \"K\", \"H\", \"t\", \"E\" };" }, { "code": null, "e": 1417, "s": 1381, "text": "Convert the above array to a List −" }, { "code": null, "e": 1456, "s": 1417, "text": "List<String>list = Arrays.asList(arr);" }, { "code": null, "e": 1508, "s": 1456, "text": "Now sort the above list in case insensitive order −" }, { "code": null, "e": 1563, "s": 1508, "text": "Collections.sort(list, String.CASE_INSENSITIVE_ORDER);" }, { "code": null, "e": 1574, "s": 1563, "text": " Live Demo" }, { "code": null, "e": 2107, "s": 1574, "text": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\npublic class Demo {\n public static void main(String[] argv) throws Exception {\n String[] arr = new String[] { \"P\", \"W\", \"g\", \"K\", \"H\", \"t\", \"E\" };\n List<String>list = Arrays.asList(arr);\n System.out.println(\"List = \"+list);\n Collections.sort(list);\n System.out.println(\"Case Sensitive Sort = \"+list);\n Collections.sort(list, String.CASE_INSENSITIVE_ORDER);\n System.out.println(\"Case Insensitive Sort = \"+list);\n }\n}" }, { "code": null, "e": 2226, "s": 2107, "text": "List = [P, W, g, K, H, t, E]\nCase Sensitive Sort = [E, H, K, P, W, g, t]\nCase Insensitive Sort = [E, g, H, K, P, t, W]" } ]
Uncovering the Potential of Materials Data using Matminer and Pymatgen | by Joyita Bhattacharya | Towards Data Science
Introduction The usage of different types of devices is an integral part of our everyday life. And these devices are made of myriad combinations of elements forming materials for daily applications. Materials scientists are engaged with the processing of these materials and studying their structures and properties. For example, to develop a new semiconductor, a materials scientist requires to choose the most optimized combination of ingredients from the palette of elements in the Periodic table so that the new semiconductor has the right set of properties. Moreover, performance of a material depends on the trinity of Processing conditions, Structure that spans from electronic scale to macro-scale, and its various structural and functional Properties . Thus, materials scientists have come up with the concept of “Materials Tetrahedron” where the vertices represent Processing, Structure, Properties and Performance, and the lines connecting these vertices denote interrelations between them. These interconnections are also termed as PSPP linkages. A comprehensive library of discovered materials with their PSPP linkages will immensely benefit the materials scientists and engineers who aim to design the next super materials such as a battery more efficient than the existing lithium ion battery or a car lighter and stronger than the new Tesla cars. Hence, extracting meaningful data from these interconnected parameters becomes a crucial step in the design and discovery of high-performance cutting edge materials. The number of parameters can be so diverse that it becomes difficult to extract physics-based cause-effect relations between all these parameters. In such cases, machine learning (ML) can facilitate the development of new knowledge by extracting useful correlations between these parameters. Materials Data The very first and crucial step of ML, regardless of the algorithm used, is importing and preprocessing data. Clean data increase the reliability of training and building a machine learning model for successful deployment. This data is further categorized into input variables (also known as predictors/ descriptors in ML language) and outcome (known as target/ response). Materials data comprise a wide spectrum of descriptors. These include Processing conditions: Compositions with constituent elements, Temperature, Pressure, Heating and Cooling Rates, Relative Humidity, etc. Structural information: Arrangement of atoms or crystal structure, Microstructural and Textural patterns across length scales spanning between few Angstroms (1 Angstrom = 10−10 m) and few hundreds of microns (1 micron = 10−6 m). Physical properties: Density, Viscosity, Refractive index, Thermal and Electrical conductivity and so on. Mechanical properties: Toughness, Hardness, Yield strength, Elastic Stiffness, Fracture toughness, Ductility, Hardness and others. The target or the response is usually the property dictating the overall performance of the material. Mining important features from a given dataset is the most critical and challenging step for developing a robust data-driven model. Otherwise, the model will follow the GIGO (Garbage-In-Garbage-Out) rule. We can show the importance of featurization in materials datasets using a very simple example. Let us consider a dataset containing chemical formulae of several materials and their densities. A chemical formula is represented by a combination of elements and their atomic proportions. For example, the chemical formula (AiBjCkDl) contains four elements A, B, C and D where their corresponding subscripts i, j, k and l represent the number of atoms of each element. For instance, the formula of water is H2O which implies 2 atoms of hydrogen (H is the element symbol) and 1 atom of oxygen (denoted by the symbol O). Now, to understand the correlations between features and design a super-dense material from such data, we need to unearth the contribution of each element on density. These individual elemental contributions become features (descriptors) for the prediction of the target variable — density in this example. Hence, it is required to split the formula into its individual constituents (or elements) along with their corresponding amount. There is no direct way to achieve this task in the conventional ML technique such as encoding. However, thanks to the Python-based materials libraries, Pymatgen and Matminer, which helps in reaching this goal. In this article, I will demonstrate how to import constituent elements and their amount from formulae with the aid of the mentioned materials libraries. A Step-by-Step Guide to Preprocessing Tabulating the descriptor and target variables in comma-delimited (csv) or Excel file (XLSX) is a good way to organize data for machine learning. Once csv/ excel file is ready, we can import the same to any machine learning environment. Here, I will show all the steps, written and run, in Jupyter Notebook. You can also choose Google Colab Notebook for the same purpose. Step 1: Importing libraries The first and foremost step is to import all the required basic libraries such as Pandas, NumPy, Matplotlib. Moreover, exclusive libraries for materials data mining (Matminer) and materials analysis (Pymatgen) are installed and then the necessary modules are imported. Both Matminer and Pymatgen are open-source python libraries. import numpy as npimport pandas as pdfrom matplotlib import pyplot as pltfrom matplotlib.pyplot import figure Step 2: Loading data (Dataset used in here is a subset of the original dataset.) After importing the basic libraries, we need to load and read the csv or excel file containing data using pandas from their file path. In the code snippet below, the first three columns are descriptor variables designated as X, while the last column is the target variable denoted as y. ds_PF_ZT = pd.read_csv('TE/csv/PF_ZT.csv')X = ds_PF_ZT.iloc[:, 0:3]y = ds_PF_ZT.iloc[:, -1]ds_PF_ZT Now, we need to add the individual elements comprising the materials (denoted as Formula in the above Dataframe) as predictors. The synergistic effect of these elemental contributions along with other variables result in the outcome or the response. Here comes the application of Pymatgen and Matminer tools which have featurizers such as core.composition and featurizers.composition to split a given formula into its individual elements. Before proceeding with the coding activity, let me give a preface about Matminer and Pymatgen. Pymatgen and Matminer: Beneficial libraries for materials data preprocessing Both Pymatgen and Matminer are open-source Python libraries employed for materials data mining and analysis. Pymatgen has many modules and sub modules and their respective classes aiding in analysis of structural and functional characteristics of materials. We will be viewing the application of one such module: pymatgen.core.composition and its class: Composition. This class maps each composition in a dataset into individual element and its amount in immutable and hashable form and not as Python dictionary. In Python, there are two types of data: Mutable and Immutable. The values of mutable data can be altered/ mutated while that of immutable cannot. Few examples of mutable data are lists, dictionaries. On the other hand, a tuple is a quintessential example of immutable data. All immutable objects are hashable which means that these objects have unique identification number for easy tracking. Matminer helps in extracting complex materials attributes applying various featurizers. There are almost more than 70 featurizers (matminer.featurizers) that convert materials attributes into numerical descriptors or vectors. We will focus on Composition featurizer and its ElementFraction class to preprocess our dataset. The said class calculates element fraction of individual elements in a composition. Step 3: Installing Pymatgen and Matminer pip install pymatgenpip install matminer Note: Matminer and Pymatgen requires Python version 3.6+. Step 4: Mapping elements and their amount using Pymatgen Composition class of pymatgen splits each and every formula, in the given dataset, into constituent elements and their amount. Let’s take the first formula, Ca0.98Bi0.02Mn0.98Nb0.02O3.0, in column 1, row 1 : from pymatgen.core.composition import Compositionds_PF_ZT['Formula']Comp = []for value in ds_PF_ZT['Formula']: Comp.append(Composition(value))Comp An additional composition column is added to the original dataset containing only the constituent elements corresponding to each composition. ds_PF_ZT['Composition'] = Compds_PF_ZT Step 5: Calculation of atomic fraction using ElementFraction class We now need to add the individual element along with its atomic fraction in the Dataframe to be subjected to machine learning. A class in matminer.featurizers.composition named “ElementFraction” serves the said intent. from matminer.featurizers.composition import ElementFractionef = ElementFraction() We, then, create a Dataframe using the featurize_dataframe function which contains all the elements of the periodic table along with other variables. The dimension of the dataframe increased to 573 X 108 (encircled by orange in the output of the code snippet shown below). ds_PF_ZT = ef.featurize_dataframe(ds_PF_ZT,'Composition')ds_PF_ZT Let me elaborate on element fraction calculation. Let’s consider the very first composition (in the formula column of the given dataset). The composition,Ca0.98Bi0.02Mn0.98Nb0.02O3.0, has five elements: Ca (calcium), Bi (bismuth), Mn (manganese), Nb (niobium), and O (oxygen). The amount of Ca present in the formula is 0.98, and the element fraction of Ca is calculated by taking into account the amount of other elements present in the formula. Hence, element fraction of Ca is 0.196 ((0⋅98)/(0.98+0.02+0.98+0.02+3.0) ). Similarly, element fractions of Bi, Mn, Nb, and O are 0.004, 0.196, 0.004, and 0.6 respectively. The element fraction of the rest of the elements, for this formula, in the periodic table remains zero. Step 6: Reduction in Dimensionality and display of final, clean, preprocessed data Note that above Dataframe contains many columns with only zero value. This is due to the non-existence of such elements in compositions in the given dataset. Hence, these zero columns are omitted from the Dataframe which resulted in dimensionality reduction of the Dataframe from 573 rows X 108 columns to 573 rows X 57 columns. ds_PF_ZT = ds_PF_ZT.loc[:, (ds_PF_ZT != 0).any(axis=0)]ds_PF_ZT The above preprocessed, clean Dataframe is the final form ready for machine learning. It is a good practice to keep the response or target column as the last one in the final Dataframe.The code is published in Github. Concluding Remarks In the contemporary world, “data is the new oil” — a phrase coined by a British mathematician Clive Humby. Hence, mining this treasure to get maximum useful latent information is necessary for technological advancement. From a materials science perspective, numerous materials attributes, processing parameters, and elemental contributions form a complete dataset. These details constitute a part of materials informatics which play an enormous role in the discovery of new high-performance materials. Uncovering the role of constituent elements on material properties is a crucial but tricky job. Matminer and Pymatgen have made this task easier. Here I described the usage of a few relevant modules of these materials libraries to gather elemental information from the original dataset. I hope this article is informative, especially for engineers and scientists working on the design and discovery of new materials. Please feel free to connect if you need any clarifications and do share your feedback and suggestions. Thank you for reading!
[ { "code": null, "e": 185, "s": 172, "text": "Introduction" }, { "code": null, "e": 735, "s": 185, "text": "The usage of different types of devices is an integral part of our everyday life. And these devices are made of myriad combinations of elements forming materials for daily applications. Materials scientists are engaged with the processing of these materials and studying their structures and properties. For example, to develop a new semiconductor, a materials scientist requires to choose the most optimized combination of ingredients from the palette of elements in the Periodic table so that the new semiconductor has the right set of properties." }, { "code": null, "e": 1231, "s": 735, "text": "Moreover, performance of a material depends on the trinity of Processing conditions, Structure that spans from electronic scale to macro-scale, and its various structural and functional Properties . Thus, materials scientists have come up with the concept of “Materials Tetrahedron” where the vertices represent Processing, Structure, Properties and Performance, and the lines connecting these vertices denote interrelations between them. These interconnections are also termed as PSPP linkages." }, { "code": null, "e": 1535, "s": 1231, "text": "A comprehensive library of discovered materials with their PSPP linkages will immensely benefit the materials scientists and engineers who aim to design the next super materials such as a battery more efficient than the existing lithium ion battery or a car lighter and stronger than the new Tesla cars." }, { "code": null, "e": 1993, "s": 1535, "text": "Hence, extracting meaningful data from these interconnected parameters becomes a crucial step in the design and discovery of high-performance cutting edge materials. The number of parameters can be so diverse that it becomes difficult to extract physics-based cause-effect relations between all these parameters. In such cases, machine learning (ML) can facilitate the development of new knowledge by extracting useful correlations between these parameters." }, { "code": null, "e": 2008, "s": 1993, "text": "Materials Data" }, { "code": null, "e": 2381, "s": 2008, "text": "The very first and crucial step of ML, regardless of the algorithm used, is importing and preprocessing data. Clean data increase the reliability of training and building a machine learning model for successful deployment. This data is further categorized into input variables (also known as predictors/ descriptors in ML language) and outcome (known as target/ response)." }, { "code": null, "e": 2451, "s": 2381, "text": "Materials data comprise a wide spectrum of descriptors. These include" }, { "code": null, "e": 2588, "s": 2451, "text": "Processing conditions: Compositions with constituent elements, Temperature, Pressure, Heating and Cooling Rates, Relative Humidity, etc." }, { "code": null, "e": 2817, "s": 2588, "text": "Structural information: Arrangement of atoms or crystal structure, Microstructural and Textural patterns across length scales spanning between few Angstroms (1 Angstrom = 10−10 m) and few hundreds of microns (1 micron = 10−6 m)." }, { "code": null, "e": 2923, "s": 2817, "text": "Physical properties: Density, Viscosity, Refractive index, Thermal and Electrical conductivity and so on." }, { "code": null, "e": 3054, "s": 2923, "text": "Mechanical properties: Toughness, Hardness, Yield strength, Elastic Stiffness, Fracture toughness, Ductility, Hardness and others." }, { "code": null, "e": 3156, "s": 3054, "text": "The target or the response is usually the property dictating the overall performance of the material." }, { "code": null, "e": 3361, "s": 3156, "text": "Mining important features from a given dataset is the most critical and challenging step for developing a robust data-driven model. Otherwise, the model will follow the GIGO (Garbage-In-Garbage-Out) rule." }, { "code": null, "e": 3976, "s": 3361, "text": "We can show the importance of featurization in materials datasets using a very simple example. Let us consider a dataset containing chemical formulae of several materials and their densities. A chemical formula is represented by a combination of elements and their atomic proportions. For example, the chemical formula (AiBjCkDl) contains four elements A, B, C and D where their corresponding subscripts i, j, k and l represent the number of atoms of each element. For instance, the formula of water is H2O which implies 2 atoms of hydrogen (H is the element symbol) and 1 atom of oxygen (denoted by the symbol O)." }, { "code": null, "e": 4622, "s": 3976, "text": "Now, to understand the correlations between features and design a super-dense material from such data, we need to unearth the contribution of each element on density. These individual elemental contributions become features (descriptors) for the prediction of the target variable — density in this example. Hence, it is required to split the formula into its individual constituents (or elements) along with their corresponding amount. There is no direct way to achieve this task in the conventional ML technique such as encoding. However, thanks to the Python-based materials libraries, Pymatgen and Matminer, which helps in reaching this goal." }, { "code": null, "e": 4775, "s": 4622, "text": "In this article, I will demonstrate how to import constituent elements and their amount from formulae with the aid of the mentioned materials libraries." }, { "code": null, "e": 4813, "s": 4775, "text": "A Step-by-Step Guide to Preprocessing" }, { "code": null, "e": 5185, "s": 4813, "text": "Tabulating the descriptor and target variables in comma-delimited (csv) or Excel file (XLSX) is a good way to organize data for machine learning. Once csv/ excel file is ready, we can import the same to any machine learning environment. Here, I will show all the steps, written and run, in Jupyter Notebook. You can also choose Google Colab Notebook for the same purpose." }, { "code": null, "e": 5213, "s": 5185, "text": "Step 1: Importing libraries" }, { "code": null, "e": 5543, "s": 5213, "text": "The first and foremost step is to import all the required basic libraries such as Pandas, NumPy, Matplotlib. Moreover, exclusive libraries for materials data mining (Matminer) and materials analysis (Pymatgen) are installed and then the necessary modules are imported. Both Matminer and Pymatgen are open-source python libraries." }, { "code": null, "e": 5653, "s": 5543, "text": "import numpy as npimport pandas as pdfrom matplotlib import pyplot as pltfrom matplotlib.pyplot import figure" }, { "code": null, "e": 5674, "s": 5653, "text": "Step 2: Loading data" }, { "code": null, "e": 5734, "s": 5674, "text": "(Dataset used in here is a subset of the original dataset.)" }, { "code": null, "e": 6021, "s": 5734, "text": "After importing the basic libraries, we need to load and read the csv or excel file containing data using pandas from their file path. In the code snippet below, the first three columns are descriptor variables designated as X, while the last column is the target variable denoted as y." }, { "code": null, "e": 6121, "s": 6021, "text": "ds_PF_ZT = pd.read_csv('TE/csv/PF_ZT.csv')X = ds_PF_ZT.iloc[:, 0:3]y = ds_PF_ZT.iloc[:, -1]ds_PF_ZT" }, { "code": null, "e": 6655, "s": 6121, "text": "Now, we need to add the individual elements comprising the materials (denoted as Formula in the above Dataframe) as predictors. The synergistic effect of these elemental contributions along with other variables result in the outcome or the response. Here comes the application of Pymatgen and Matminer tools which have featurizers such as core.composition and featurizers.composition to split a given formula into its individual elements. Before proceeding with the coding activity, let me give a preface about Matminer and Pymatgen." }, { "code": null, "e": 6732, "s": 6655, "text": "Pymatgen and Matminer: Beneficial libraries for materials data preprocessing" }, { "code": null, "e": 6841, "s": 6732, "text": "Both Pymatgen and Matminer are open-source Python libraries employed for materials data mining and analysis." }, { "code": null, "e": 7638, "s": 6841, "text": "Pymatgen has many modules and sub modules and their respective classes aiding in analysis of structural and functional characteristics of materials. We will be viewing the application of one such module: pymatgen.core.composition and its class: Composition. This class maps each composition in a dataset into individual element and its amount in immutable and hashable form and not as Python dictionary. In Python, there are two types of data: Mutable and Immutable. The values of mutable data can be altered/ mutated while that of immutable cannot. Few examples of mutable data are lists, dictionaries. On the other hand, a tuple is a quintessential example of immutable data. All immutable objects are hashable which means that these objects have unique identification number for easy tracking." }, { "code": null, "e": 8045, "s": 7638, "text": "Matminer helps in extracting complex materials attributes applying various featurizers. There are almost more than 70 featurizers (matminer.featurizers) that convert materials attributes into numerical descriptors or vectors. We will focus on Composition featurizer and its ElementFraction class to preprocess our dataset. The said class calculates element fraction of individual elements in a composition." }, { "code": null, "e": 8086, "s": 8045, "text": "Step 3: Installing Pymatgen and Matminer" }, { "code": null, "e": 8127, "s": 8086, "text": "pip install pymatgenpip install matminer" }, { "code": null, "e": 8185, "s": 8127, "text": "Note: Matminer and Pymatgen requires Python version 3.6+." }, { "code": null, "e": 8242, "s": 8185, "text": "Step 4: Mapping elements and their amount using Pymatgen" }, { "code": null, "e": 8450, "s": 8242, "text": "Composition class of pymatgen splits each and every formula, in the given dataset, into constituent elements and their amount. Let’s take the first formula, Ca0.98Bi0.02Mn0.98Nb0.02O3.0, in column 1, row 1 :" }, { "code": null, "e": 8598, "s": 8450, "text": "from pymatgen.core.composition import Compositionds_PF_ZT['Formula']Comp = []for value in ds_PF_ZT['Formula']: Comp.append(Composition(value))Comp" }, { "code": null, "e": 8740, "s": 8598, "text": "An additional composition column is added to the original dataset containing only the constituent elements corresponding to each composition." }, { "code": null, "e": 8779, "s": 8740, "text": "ds_PF_ZT['Composition'] = Compds_PF_ZT" }, { "code": null, "e": 8846, "s": 8779, "text": "Step 5: Calculation of atomic fraction using ElementFraction class" }, { "code": null, "e": 9065, "s": 8846, "text": "We now need to add the individual element along with its atomic fraction in the Dataframe to be subjected to machine learning. A class in matminer.featurizers.composition named “ElementFraction” serves the said intent." }, { "code": null, "e": 9148, "s": 9065, "text": "from matminer.featurizers.composition import ElementFractionef = ElementFraction()" }, { "code": null, "e": 9421, "s": 9148, "text": "We, then, create a Dataframe using the featurize_dataframe function which contains all the elements of the periodic table along with other variables. The dimension of the dataframe increased to 573 X 108 (encircled by orange in the output of the code snippet shown below)." }, { "code": null, "e": 9487, "s": 9421, "text": "ds_PF_ZT = ef.featurize_dataframe(ds_PF_ZT,'Composition')ds_PF_ZT" }, { "code": null, "e": 10211, "s": 9487, "text": "Let me elaborate on element fraction calculation. Let’s consider the very first composition (in the formula column of the given dataset). The composition,Ca0.98Bi0.02Mn0.98Nb0.02O3.0, has five elements: Ca (calcium), Bi (bismuth), Mn (manganese), Nb (niobium), and O (oxygen). The amount of Ca present in the formula is 0.98, and the element fraction of Ca is calculated by taking into account the amount of other elements present in the formula. Hence, element fraction of Ca is 0.196 ((0⋅98)/(0.98+0.02+0.98+0.02+3.0) ). Similarly, element fractions of Bi, Mn, Nb, and O are 0.004, 0.196, 0.004, and 0.6 respectively. The element fraction of the rest of the elements, for this formula, in the periodic table remains zero." }, { "code": null, "e": 10294, "s": 10211, "text": "Step 6: Reduction in Dimensionality and display of final, clean, preprocessed data" }, { "code": null, "e": 10623, "s": 10294, "text": "Note that above Dataframe contains many columns with only zero value. This is due to the non-existence of such elements in compositions in the given dataset. Hence, these zero columns are omitted from the Dataframe which resulted in dimensionality reduction of the Dataframe from 573 rows X 108 columns to 573 rows X 57 columns." }, { "code": null, "e": 10687, "s": 10623, "text": "ds_PF_ZT = ds_PF_ZT.loc[:, (ds_PF_ZT != 0).any(axis=0)]ds_PF_ZT" }, { "code": null, "e": 10905, "s": 10687, "text": "The above preprocessed, clean Dataframe is the final form ready for machine learning. It is a good practice to keep the response or target column as the last one in the final Dataframe.The code is published in Github." }, { "code": null, "e": 10924, "s": 10905, "text": "Concluding Remarks" }, { "code": null, "e": 11843, "s": 10924, "text": "In the contemporary world, “data is the new oil” — a phrase coined by a British mathematician Clive Humby. Hence, mining this treasure to get maximum useful latent information is necessary for technological advancement. From a materials science perspective, numerous materials attributes, processing parameters, and elemental contributions form a complete dataset. These details constitute a part of materials informatics which play an enormous role in the discovery of new high-performance materials. Uncovering the role of constituent elements on material properties is a crucial but tricky job. Matminer and Pymatgen have made this task easier. Here I described the usage of a few relevant modules of these materials libraries to gather elemental information from the original dataset. I hope this article is informative, especially for engineers and scientists working on the design and discovery of new materials." }, { "code": null, "e": 11946, "s": 11843, "text": "Please feel free to connect if you need any clarifications and do share your feedback and suggestions." } ]
How to pass entire array as an argument to a function in C language?
The array is a group of related items that store with a common name. Following are the two ways of passing arrays as arguments to functions − sending entire array as argument to function sending individual elements as argument to function To send entire array as argument, just send the array name in the function call. To send entire array as argument, just send the array name in the function call. To receive an array, it must be declared in the function header. To receive an array, it must be declared in the function header. #include<stdio.h> main (){ void display (int a[5]); int a[5], i; clrscr(); printf ("enter 5 elements"); for (i=0; i<5; i++) scanf("%d", &a[i]); display (a); //calling array getch( ); } void display (int a[5]){ int i; printf ("elements of the array are"); for (i=0; i<5; i++) printf("%d ", a[i]); } Enter 5 elements 10 20 30 40 50 Elements of the array are 10 20 30 40 50 Let us consider another example to know more about passing entire array as argument to function − #include<stdio.h> main (){ void number(int a[5]); int a[5], i; printf ("enter 5 elements\n"); for (i=0; i<5; i++) scanf("%d", &a[i]); number(a); //calling array getch( ); } void number(int a[5]){ int i; printf ("elements of the array are\n"); for (i=0; i<5; i++) printf("%d\n" , a[i]); } enter 5 elements 100 200 300 400 500 elements of the array are 100 200 300 400 500
[ { "code": null, "e": 1204, "s": 1062, "text": "The array is a group of related items that store with a common name. Following are the two ways of passing arrays as arguments to functions −" }, { "code": null, "e": 1249, "s": 1204, "text": "sending entire array as argument to function" }, { "code": null, "e": 1301, "s": 1249, "text": "sending individual elements as argument to function" }, { "code": null, "e": 1382, "s": 1301, "text": "To send entire array as argument, just send the array name in the function call." }, { "code": null, "e": 1463, "s": 1382, "text": "To send entire array as argument, just send the array name in the function call." }, { "code": null, "e": 1528, "s": 1463, "text": "To receive an array, it must be declared in the function header." }, { "code": null, "e": 1593, "s": 1528, "text": "To receive an array, it must be declared in the function header." }, { "code": null, "e": 1933, "s": 1593, "text": "#include<stdio.h>\nmain (){\n void display (int a[5]);\n int a[5], i;\n clrscr();\n printf (\"enter 5 elements\");\n for (i=0; i<5; i++)\n scanf(\"%d\", &a[i]);\n display (a); //calling array\n getch( );\n}\nvoid display (int a[5]){\n int i;\n printf (\"elements of the array are\");\n for (i=0; i<5; i++)\n printf(\"%d \", a[i]);\n}" }, { "code": null, "e": 2006, "s": 1933, "text": "Enter 5 elements\n10 20 30 40 50\nElements of the array are\n10 20 30 40 50" }, { "code": null, "e": 2104, "s": 2006, "text": "Let us consider another example to know more about passing entire array as argument to function −" }, { "code": null, "e": 2431, "s": 2104, "text": "#include<stdio.h>\nmain (){\n void number(int a[5]);\n int a[5], i;\n printf (\"enter 5 elements\\n\");\n for (i=0; i<5; i++)\n scanf(\"%d\", &a[i]);\n number(a); //calling array\n getch( );\n}\nvoid number(int a[5]){\n int i;\n printf (\"elements of the array are\\n\");\n for (i=0; i<5; i++)\n printf(\"%d\\n\" , a[i]);\n}" }, { "code": null, "e": 2514, "s": 2431, "text": "enter 5 elements\n100\n200\n300\n400\n500\nelements of the array are\n100\n200\n300\n400\n500" } ]
How to send Attachments and Email using nodemailer in Node.js ?
10 Feb, 2021 For this purpose, we will use a package called nodemailer. It is a module that makes email sending pretty easy. For using it, you will need to install by using the following command: $ npm install nodemailer Features of nodemailer module: It has zero dependencies and heavy security. You can use it hassle free whether its Azure or Windows box. It also comes with Custom Plugin support for manipulating messages. Inorder to send email, create a file named index.js and write down the following code: Filename: index.js javascript var nodemailer = require("nodemailer"); var sender = nodemailer.createTransport({ service: 'gmail', auth: { user: '[email protected]', pass: 'your_password' }}); var mail = { from: "[email protected]", to: "receiver'[email protected]", subject: "Sending Email using Node.js", text: "That was easy!"}; sender.sendMail(mail, function(error, info) { if (error) { console.log(error); } else { console.log("Email sent successfully: " + info.response); }}); Steps to run this program: In order to run this file, just Git Bash into your working directory and type the following command: $ nodemon index.js If you don’t have nodemon installed then just run the following command: $ node index.js To double-check its working you can go to the receiver’s mail and you will get the following mail as shown below: What if you have multiple receiver? Well in that case just add below code in your mail function: to: '[email protected], [email protected]' What if you want to send HTML formatted text to the receiver? Well in that case just add below code in your mail function: html: "<h1>GeeksforGeeks</h1><p>I love geeksforgeeks</p>" What if you want to send an attachment to the receiver? Well in that case just add below code in your mail function: attachments: [ { filename: 'mailtrap.png', path: __dirname + '/mailtrap.png', cid: 'uniq-mailtrap.png' } ] The final index.js file look like this: Filename: index.js javascript var nodemailer = require("nodemailer"); var sender = nodemailer.createTransport({ service: 'gmail', auth: { user: '[email protected]', pass: 'your_password' }}); var mail = { from: '[email protected]', to:'[email protected], [email protected]', subject: 'Sending Email using Node.js', text: 'That was easy!', html:"<h1>GeeksforGeeks</h1><p>I love geeksforgeeks</p>", attachments: [ { filename: 'mailtrap.png', path: __dirname + '/mailtrap.png', cid: 'uniq-mailtrap.png' } ]}; sender.sendMail(mail, function (error, info) { if (error) { console.log(error); } else { console.log('Email sent successfully: ' + info.response); }}); mridulmanochagfg 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 install the previous version of node.js and npm ? Node.js fs.writeFile() Method Difference between promise and async await in Node.js Mongoose | findByIdAndUpdate() Function JWT Authentication with Node.js Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Feb, 2021" }, { "code": null, "e": 213, "s": 28, "text": "For this purpose, we will use a package called nodemailer. It is a module that makes email sending pretty easy. For using it, you will need to install by using the following command: " }, { "code": null, "e": 238, "s": 213, "text": "$ npm install nodemailer" }, { "code": null, "e": 271, "s": 238, "text": "Features of nodemailer module: " }, { "code": null, "e": 316, "s": 271, "text": "It has zero dependencies and heavy security." }, { "code": null, "e": 377, "s": 316, "text": "You can use it hassle free whether its Azure or Windows box." }, { "code": null, "e": 445, "s": 377, "text": "It also comes with Custom Plugin support for manipulating messages." }, { "code": null, "e": 553, "s": 445, "text": "Inorder to send email, create a file named index.js and write down the following code: Filename: index.js " }, { "code": null, "e": 564, "s": 553, "text": "javascript" }, { "code": "var nodemailer = require(\"nodemailer\"); var sender = nodemailer.createTransport({ service: 'gmail', auth: { user: '[email protected]', pass: 'your_password' }}); var mail = { from: \"[email protected]\", to: \"receiver'[email protected]\", subject: \"Sending Email using Node.js\", text: \"That was easy!\"}; sender.sendMail(mail, function(error, info) { if (error) { console.log(error); } else { console.log(\"Email sent successfully: \" + info.response); }});", "e": 1059, "s": 564, "text": null }, { "code": null, "e": 1189, "s": 1059, "text": "Steps to run this program: In order to run this file, just Git Bash into your working directory and type the following command: " }, { "code": null, "e": 1208, "s": 1189, "text": "$ nodemon index.js" }, { "code": null, "e": 1283, "s": 1208, "text": "If you don’t have nodemon installed then just run the following command: " }, { "code": null, "e": 1299, "s": 1283, "text": "$ node index.js" }, { "code": null, "e": 1417, "s": 1301, "text": "To double-check its working you can go to the receiver’s mail and you will get the following mail as shown below: " }, { "code": null, "e": 1516, "s": 1417, "text": "What if you have multiple receiver? Well in that case just add below code in your mail function: " }, { "code": null, "e": 1574, "s": 1516, "text": "to: '[email protected], [email protected]'" }, { "code": null, "e": 1699, "s": 1574, "text": "What if you want to send HTML formatted text to the receiver? Well in that case just add below code in your mail function: " }, { "code": null, "e": 1757, "s": 1699, "text": "html: \"<h1>GeeksforGeeks</h1><p>I love geeksforgeeks</p>\"" }, { "code": null, "e": 1876, "s": 1757, "text": "What if you want to send an attachment to the receiver? Well in that case just add below code in your mail function: " }, { "code": null, "e": 2012, "s": 1876, "text": "attachments: [\n {\n filename: 'mailtrap.png',\n path: __dirname + '/mailtrap.png',\n cid: 'uniq-mailtrap.png' \n }\n ]" }, { "code": null, "e": 2073, "s": 2012, "text": "The final index.js file look like this: Filename: index.js " }, { "code": null, "e": 2084, "s": 2073, "text": "javascript" }, { "code": "var nodemailer = require(\"nodemailer\"); var sender = nodemailer.createTransport({ service: 'gmail', auth: { user: '[email protected]', pass: 'your_password' }}); var mail = { from: '[email protected]', to:'[email protected], [email protected]', subject: 'Sending Email using Node.js', text: 'That was easy!', html:\"<h1>GeeksforGeeks</h1><p>I love geeksforgeeks</p>\", attachments: [ { filename: 'mailtrap.png', path: __dirname + '/mailtrap.png', cid: 'uniq-mailtrap.png' } ]}; sender.sendMail(mail, function (error, info) { if (error) { console.log(error); } else { console.log('Email sent successfully: ' + info.response); }});", "e": 2854, "s": 2084, "text": null }, { "code": null, "e": 2871, "s": 2854, "text": "mridulmanochagfg" }, { "code": null, "e": 2884, "s": 2871, "text": "Node.js-Misc" }, { "code": null, "e": 2892, "s": 2884, "text": "Node.js" }, { "code": null, "e": 2909, "s": 2892, "text": "Web Technologies" }, { "code": null, "e": 3007, "s": 2909, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3064, "s": 3007, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 3094, "s": 3064, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 3148, "s": 3094, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 3188, "s": 3148, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 3220, "s": 3188, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 3282, "s": 3220, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3343, "s": 3282, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3393, "s": 3343, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3436, "s": 3393, "text": "How to fetch data from an API in ReactJS ?" } ]
JavaScript Date toISOString() Method
30 May, 2022 Below is the example of Date toISOString() method. Example: javascript <script> // Here a date has been assigned // while creating Date object var dateobj = new Date('October 15, 1996 05:35:32'); // Contents of above date object is converted // into a string using toISOString() function. var B = dateobj.toISOString(); // Printing the converted string. document.write(B);</script> Output: 1996-10-15T00:05:32.000Z The date.toISOString() method is used to convert the given date object’s contents into a string in ISO format (ISO 8601) i.e, in the form of (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ).The date object is created using date() constructor. Syntax: dateObj.toISOString() Parameters: This method does not take any parameter. It is just used along with a Date object created using Date() constructor. Return Values: It returns the converted string of Date() constructor contents into ISO format (ISO 8601). Note: The DateObj is a valid Date object created using Date()constructor. More codes for the above method are as follows: Program 1: Here nothing as a parameter is passed while creating date object but still toISOString() method return current day name, month name, date, year, and time. javascript <script> // Here nothing has been assigned // while creating Date object var dateobj = new Date(); // Contents of above date object is // converted into a string using toISOString() method. var B = dateobj.toISOString(); // Printing the converted string. document.write(B);</script> Output: 2018-04-23T10:26:00.996Z Program 2: Here we will pass a date object toISOString() method return day name, month name, date, year, and time. javascript <script> // Here nothing has been assigned // while creating Date object var dateobj = new Date('October 13, 1996 05:35:32 GMT-3:00'); // Contents of above date object is // converted into a string using toISOString() method. var B = dateobj.toISOString(); // Printing the converted string. document.write(B);</script> Output: 1996-10-13T08:35:32.000Z Note: Months, Dates, hours, minutes, seconds, milliseconds should all be in their respective range of 0 to 11, 1 to 31, 0 to 23, 0 to 59, 0 to 59, 0 to 999 respectively. Supported Browsers: The browsers supported by JavaScript Date toISOString() method are listed below: Google Chrome 3 and above Edge 12 and above Firefox 1 and above Internet Explorer 9 and above Opera 10.5 and above Safari 5 and above 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. ysachin2314 simmytarika5 javascript-date JavaScript-Methods JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 May, 2022" }, { "code": null, "e": 79, "s": 28, "text": "Below is the example of Date toISOString() method." }, { "code": null, "e": 89, "s": 79, "text": "Example: " }, { "code": null, "e": 100, "s": 89, "text": "javascript" }, { "code": "<script> // Here a date has been assigned // while creating Date object var dateobj = new Date('October 15, 1996 05:35:32'); // Contents of above date object is converted // into a string using toISOString() function. var B = dateobj.toISOString(); // Printing the converted string. document.write(B);</script>", "e": 431, "s": 100, "text": null }, { "code": null, "e": 439, "s": 431, "text": "Output:" }, { "code": null, "e": 464, "s": 439, "text": "1996-10-15T00:05:32.000Z" }, { "code": null, "e": 717, "s": 464, "text": "The date.toISOString() method is used to convert the given date object’s contents into a string in ISO format (ISO 8601) i.e, in the form of (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ).The date object is created using date() constructor. " }, { "code": null, "e": 725, "s": 717, "text": "Syntax:" }, { "code": null, "e": 747, "s": 725, "text": "dateObj.toISOString()" }, { "code": null, "e": 876, "s": 747, "text": "Parameters: This method does not take any parameter. It is just used along with a Date object created using Date() constructor. " }, { "code": null, "e": 983, "s": 876, "text": "Return Values: It returns the converted string of Date() constructor contents into ISO format (ISO 8601). " }, { "code": null, "e": 1106, "s": 983, "text": "Note: The DateObj is a valid Date object created using Date()constructor. More codes for the above method are as follows: " }, { "code": null, "e": 1273, "s": 1106, "text": "Program 1: Here nothing as a parameter is passed while creating date object but still toISOString() method return current day name, month name, date, year, and time. " }, { "code": null, "e": 1284, "s": 1273, "text": "javascript" }, { "code": "<script> // Here nothing has been assigned // while creating Date object var dateobj = new Date(); // Contents of above date object is // converted into a string using toISOString() method. var B = dateobj.toISOString(); // Printing the converted string. document.write(B);</script>", "e": 1585, "s": 1284, "text": null }, { "code": null, "e": 1593, "s": 1585, "text": "Output:" }, { "code": null, "e": 1618, "s": 1593, "text": "2018-04-23T10:26:00.996Z" }, { "code": null, "e": 1734, "s": 1618, "text": "Program 2: Here we will pass a date object toISOString() method return day name, month name, date, year, and time. " }, { "code": null, "e": 1745, "s": 1734, "text": "javascript" }, { "code": "<script> // Here nothing has been assigned // while creating Date object var dateobj = new Date('October 13, 1996 05:35:32 GMT-3:00'); // Contents of above date object is // converted into a string using toISOString() method. var B = dateobj.toISOString(); // Printing the converted string. document.write(B);</script> ", "e": 2112, "s": 1745, "text": null }, { "code": null, "e": 2120, "s": 2112, "text": "Output:" }, { "code": null, "e": 2145, "s": 2120, "text": "1996-10-13T08:35:32.000Z" }, { "code": null, "e": 2316, "s": 2145, "text": "Note: Months, Dates, hours, minutes, seconds, milliseconds should all be in their respective range of 0 to 11, 1 to 31, 0 to 23, 0 to 59, 0 to 59, 0 to 999 respectively. " }, { "code": null, "e": 2417, "s": 2316, "text": "Supported Browsers: The browsers supported by JavaScript Date toISOString() method are listed below:" }, { "code": null, "e": 2443, "s": 2417, "text": "Google Chrome 3 and above" }, { "code": null, "e": 2461, "s": 2443, "text": "Edge 12 and above" }, { "code": null, "e": 2481, "s": 2461, "text": "Firefox 1 and above" }, { "code": null, "e": 2511, "s": 2481, "text": "Internet Explorer 9 and above" }, { "code": null, "e": 2532, "s": 2511, "text": "Opera 10.5 and above" }, { "code": null, "e": 2551, "s": 2532, "text": "Safari 5 and above" }, { "code": null, "e": 2770, "s": 2551, "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": 2782, "s": 2770, "text": "ysachin2314" }, { "code": null, "e": 2795, "s": 2782, "text": "simmytarika5" }, { "code": null, "e": 2811, "s": 2795, "text": "javascript-date" }, { "code": null, "e": 2830, "s": 2811, "text": "JavaScript-Methods" }, { "code": null, "e": 2841, "s": 2830, "text": "JavaScript" }, { "code": null, "e": 2858, "s": 2841, "text": "Web Technologies" } ]
Proof that Hamiltonian Cycle is NP-Complete
18 Jun, 2020 Prerequisite: NP-Completeness, Hamiltonian cycle. Hamiltonian Cycle: A cycle in an undirected graph G =(V, E) which traverses every vertex exactly once. Problem Statement:Given a graph G(V, E), the problem is to determine if the graph contains a Hamiltonian cycle consisting of all the vertices belonging to V.Explanation –An instance of the problem is an input specified to the problem. An instance of the Independent Set problem is a graph G (V, E), and the problem is to check whether the graph can have a Hamiltonian Cycle in G.Since an NP-Complete problem, by definition, is a problem which is both in NP and NP-hard, the proof for the statement that a problem is NP-Complete consists of two parts: The problem itself is in NP class.All other problems in NP class can be polynomial-time reducible to that.(B is polynomial-time reducible to C is denoted as ) The problem itself is in NP class. All other problems in NP class can be polynomial-time reducible to that.(B is polynomial-time reducible to C is denoted as ) If the 2nd condition is only satisfied then the problem is called NP-Hard. But it is not possible to reduce every NP problem into another NP problem to show its NP-Completeness all the time. That is why if we want to show a problem is NP-Complete, we just show that the problem is in NP and if any NP-Complete problem is reducible to that, then we are done, i.e. if B is NP-Complete and for C in NP, then C is NP-Complete. Hamiltonian Cycle is in NPIf any problem is in NP, then, given a ‘certificate’, which is a solution to the problem and an instance of the problem (a graph G and a positive integer k, in this case), we will be able to verify (check whether the solution given is correct or not) the certificate in polynomial time.The certificate is a sequence of vertices forming Hamiltonian Cycle in the graph. We can validate this solution by verifying that all the vertices belong to the graph and each pair of vertices belonging to the solution are adjacent. This can be done in polynomial time, that is O(V +E) using the following strategy for graph G(V, E):flag=true For every pair {u, v} in the subset V’: Check that these two have an edge between them If there is no edge, set flag to false and break If flag is true: Solution is correct Else: Solution is incorrect Hamiltonian Cycle is NP HardIn order to prove the Hamiltonian Cycle is NP-Hard, we will have to reduce a known NP-Hard problem to this problem. We will carry out a reduction from the Hamiltonian Path problem to the Hamiltonian Cycle problem.Every instance of the Hamiltonian Path problem consisting of a graph G =(V, E) as the input can be converted to Hamiltonian Cycle problem consisting of graph G’ = (V’, E’). We will construct the graph G’ in the following way:V’ = Add vertices V of the original graph G and add an additional vertex Vnew such that all the vertices connected of the graph are connected to this vertex. The number of vertices increases by 1, V’ =V+1.E’ = Add edges E of the original graph G and add new edges between the newly added vertex and the original vertices of the graph. The number of edges increases by the number of vertices V, that is, E’=E+V.The new graph G’ can be obtained in polynomial time, by adding new edges to the new vertex, that requires O(V) time. This reduction can be proved by the following two claims:Let us assume that the graph G contains a hamiltonian path covering the V vertices of the graph starting at a random vertex say Vstart and ending at Vend, now since we connected all the vertices to an arbitrary new vertex Vnew in G’.We extend the original Hamiltonian Path to a Hamiltonian Cycle by using the edges Vend to Vnew and Vnew to Vstart respectively. The graph G’ now contains the closed cycle traversing all vertices once.We assume that the graph G’ has a Hamiltonian Cycle passing through all the vertices, inclusive of Vnew. Now to convert it to a Hamiltonian Path, we remove the edges corresponding to the vertex Vnew in the cycle. The resultant path will cover the vertices V of the graph and will cover them exactly once. Hamiltonian Cycle is in NPIf any problem is in NP, then, given a ‘certificate’, which is a solution to the problem and an instance of the problem (a graph G and a positive integer k, in this case), we will be able to verify (check whether the solution given is correct or not) the certificate in polynomial time.The certificate is a sequence of vertices forming Hamiltonian Cycle in the graph. We can validate this solution by verifying that all the vertices belong to the graph and each pair of vertices belonging to the solution are adjacent. This can be done in polynomial time, that is O(V +E) using the following strategy for graph G(V, E):flag=true For every pair {u, v} in the subset V’: Check that these two have an edge between them If there is no edge, set flag to false and break If flag is true: Solution is correct Else: Solution is incorrect flag=true For every pair {u, v} in the subset V’: Check that these two have an edge between them If there is no edge, set flag to false and break If flag is true: Solution is correct Else: Solution is incorrect Hamiltonian Cycle is NP HardIn order to prove the Hamiltonian Cycle is NP-Hard, we will have to reduce a known NP-Hard problem to this problem. We will carry out a reduction from the Hamiltonian Path problem to the Hamiltonian Cycle problem.Every instance of the Hamiltonian Path problem consisting of a graph G =(V, E) as the input can be converted to Hamiltonian Cycle problem consisting of graph G’ = (V’, E’). We will construct the graph G’ in the following way:V’ = Add vertices V of the original graph G and add an additional vertex Vnew such that all the vertices connected of the graph are connected to this vertex. The number of vertices increases by 1, V’ =V+1.E’ = Add edges E of the original graph G and add new edges between the newly added vertex and the original vertices of the graph. The number of edges increases by the number of vertices V, that is, E’=E+V.The new graph G’ can be obtained in polynomial time, by adding new edges to the new vertex, that requires O(V) time. This reduction can be proved by the following two claims:Let us assume that the graph G contains a hamiltonian path covering the V vertices of the graph starting at a random vertex say Vstart and ending at Vend, now since we connected all the vertices to an arbitrary new vertex Vnew in G’.We extend the original Hamiltonian Path to a Hamiltonian Cycle by using the edges Vend to Vnew and Vnew to Vstart respectively. The graph G’ now contains the closed cycle traversing all vertices once.We assume that the graph G’ has a Hamiltonian Cycle passing through all the vertices, inclusive of Vnew. Now to convert it to a Hamiltonian Path, we remove the edges corresponding to the vertex Vnew in the cycle. The resultant path will cover the vertices V of the graph and will cover them exactly once. V’ = Add vertices V of the original graph G and add an additional vertex Vnew such that all the vertices connected of the graph are connected to this vertex. The number of vertices increases by 1, V’ =V+1. E’ = Add edges E of the original graph G and add new edges between the newly added vertex and the original vertices of the graph. The number of edges increases by the number of vertices V, that is, E’=E+V. The new graph G’ can be obtained in polynomial time, by adding new edges to the new vertex, that requires O(V) time. This reduction can be proved by the following two claims: Let us assume that the graph G contains a hamiltonian path covering the V vertices of the graph starting at a random vertex say Vstart and ending at Vend, now since we connected all the vertices to an arbitrary new vertex Vnew in G’.We extend the original Hamiltonian Path to a Hamiltonian Cycle by using the edges Vend to Vnew and Vnew to Vstart respectively. The graph G’ now contains the closed cycle traversing all vertices once. We assume that the graph G’ has a Hamiltonian Cycle passing through all the vertices, inclusive of Vnew. Now to convert it to a Hamiltonian Path, we remove the edges corresponding to the vertex Vnew in the cycle. The resultant path will cover the vertices V of the graph and will cover them exactly once. Thus we can say that the graph G’ contains a Hamiltonian Cycle iff graph G contains a Hamiltonian Path. Therefore, any instance of the Hamiltonian Cycle problem can be reduced to an instance of the Hamiltonian Path problem. Thus, the Hamiltonian Cycle is NP-Hard. Conclusion: Since, the Hamiltonian Cycle is both, a NP-Problem and NP-Hard. Therefore, it is a NP-Complete problem. Algorithms-NP Complete NP Complete NPHard Algorithms Analysis Graph Graph Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n18 Jun, 2020" }, { "code": null, "e": 104, "s": 54, "text": "Prerequisite: NP-Completeness, Hamiltonian cycle." }, { "code": null, "e": 207, "s": 104, "text": "Hamiltonian Cycle: A cycle in an undirected graph G =(V, E) which traverses every vertex exactly once." }, { "code": null, "e": 758, "s": 207, "text": "Problem Statement:Given a graph G(V, E), the problem is to determine if the graph contains a Hamiltonian cycle consisting of all the vertices belonging to V.Explanation –An instance of the problem is an input specified to the problem. An instance of the Independent Set problem is a graph G (V, E), and the problem is to check whether the graph can have a Hamiltonian Cycle in G.Since an NP-Complete problem, by definition, is a problem which is both in NP and NP-hard, the proof for the statement that a problem is NP-Complete consists of two parts:" }, { "code": null, "e": 917, "s": 758, "text": "The problem itself is in NP class.All other problems in NP class can be polynomial-time reducible to that.(B is polynomial-time reducible to C is denoted as )" }, { "code": null, "e": 952, "s": 917, "text": "The problem itself is in NP class." }, { "code": null, "e": 1077, "s": 952, "text": "All other problems in NP class can be polynomial-time reducible to that.(B is polynomial-time reducible to C is denoted as )" }, { "code": null, "e": 1152, "s": 1077, "text": "If the 2nd condition is only satisfied then the problem is called NP-Hard." }, { "code": null, "e": 1501, "s": 1152, "text": "But it is not possible to reduce every NP problem into another NP problem to show its NP-Completeness all the time. That is why if we want to show a problem is NP-Complete, we just show that the problem is in NP and if any NP-Complete problem is reducible to that, then we are done, i.e. if B is NP-Complete and for C in NP, then C is NP-Complete." }, { "code": null, "e": 4161, "s": 1501, "text": "Hamiltonian Cycle is in NPIf any problem is in NP, then, given a ‘certificate’, which is a solution to the problem and an instance of the problem (a graph G and a positive integer k, in this case), we will be able to verify (check whether the solution given is correct or not) the certificate in polynomial time.The certificate is a sequence of vertices forming Hamiltonian Cycle in the graph. We can validate this solution by verifying that all the vertices belong to the graph and each pair of vertices belonging to the solution are adjacent. This can be done in polynomial time, that is O(V +E) using the following strategy for graph G(V, E):flag=true\nFor every pair {u, v} in the subset V’:\n Check that these two have an edge between them\n If there is no edge, set flag to false and break\nIf flag is true:\n Solution is correct\nElse:\n Solution is incorrect\nHamiltonian Cycle is NP HardIn order to prove the Hamiltonian Cycle is NP-Hard, we will have to reduce a known NP-Hard problem to this problem. We will carry out a reduction from the Hamiltonian Path problem to the Hamiltonian Cycle problem.Every instance of the Hamiltonian Path problem consisting of a graph G =(V, E) as the input can be converted to Hamiltonian Cycle problem consisting of graph G’ = (V’, E’). We will construct the graph G’ in the following way:V’ = Add vertices V of the original graph G and add an additional vertex Vnew such that all the vertices connected of the graph are connected to this vertex. The number of vertices increases by 1, V’ =V+1.E’ = Add edges E of the original graph G and add new edges between the newly added vertex and the original vertices of the graph. The number of edges increases by the number of vertices V, that is, E’=E+V.The new graph G’ can be obtained in polynomial time, by adding new edges to the new vertex, that requires O(V) time. This reduction can be proved by the following two claims:Let us assume that the graph G contains a hamiltonian path covering the V vertices of the graph starting at a random vertex say Vstart and ending at Vend, now since we connected all the vertices to an arbitrary new vertex Vnew in G’.We extend the original Hamiltonian Path to a Hamiltonian Cycle by using the edges Vend to Vnew and Vnew to Vstart respectively. The graph G’ now contains the closed cycle traversing all vertices once.We assume that the graph G’ has a Hamiltonian Cycle passing through all the vertices, inclusive of Vnew. Now to convert it to a Hamiltonian Path, we remove the edges corresponding to the vertex Vnew in the cycle. The resultant path will cover the vertices V of the graph and will cover them exactly once." }, { "code": null, "e": 5034, "s": 4161, "text": "Hamiltonian Cycle is in NPIf any problem is in NP, then, given a ‘certificate’, which is a solution to the problem and an instance of the problem (a graph G and a positive integer k, in this case), we will be able to verify (check whether the solution given is correct or not) the certificate in polynomial time.The certificate is a sequence of vertices forming Hamiltonian Cycle in the graph. We can validate this solution by verifying that all the vertices belong to the graph and each pair of vertices belonging to the solution are adjacent. This can be done in polynomial time, that is O(V +E) using the following strategy for graph G(V, E):flag=true\nFor every pair {u, v} in the subset V’:\n Check that these two have an edge between them\n If there is no edge, set flag to false and break\nIf flag is true:\n Solution is correct\nElse:\n Solution is incorrect\n" }, { "code": null, "e": 5262, "s": 5034, "text": "flag=true\nFor every pair {u, v} in the subset V’:\n Check that these two have an edge between them\n If there is no edge, set flag to false and break\nIf flag is true:\n Solution is correct\nElse:\n Solution is incorrect\n" }, { "code": null, "e": 7050, "s": 5262, "text": "Hamiltonian Cycle is NP HardIn order to prove the Hamiltonian Cycle is NP-Hard, we will have to reduce a known NP-Hard problem to this problem. We will carry out a reduction from the Hamiltonian Path problem to the Hamiltonian Cycle problem.Every instance of the Hamiltonian Path problem consisting of a graph G =(V, E) as the input can be converted to Hamiltonian Cycle problem consisting of graph G’ = (V’, E’). We will construct the graph G’ in the following way:V’ = Add vertices V of the original graph G and add an additional vertex Vnew such that all the vertices connected of the graph are connected to this vertex. The number of vertices increases by 1, V’ =V+1.E’ = Add edges E of the original graph G and add new edges between the newly added vertex and the original vertices of the graph. The number of edges increases by the number of vertices V, that is, E’=E+V.The new graph G’ can be obtained in polynomial time, by adding new edges to the new vertex, that requires O(V) time. This reduction can be proved by the following two claims:Let us assume that the graph G contains a hamiltonian path covering the V vertices of the graph starting at a random vertex say Vstart and ending at Vend, now since we connected all the vertices to an arbitrary new vertex Vnew in G’.We extend the original Hamiltonian Path to a Hamiltonian Cycle by using the edges Vend to Vnew and Vnew to Vstart respectively. The graph G’ now contains the closed cycle traversing all vertices once.We assume that the graph G’ has a Hamiltonian Cycle passing through all the vertices, inclusive of Vnew. Now to convert it to a Hamiltonian Path, we remove the edges corresponding to the vertex Vnew in the cycle. The resultant path will cover the vertices V of the graph and will cover them exactly once." }, { "code": null, "e": 7256, "s": 7050, "text": "V’ = Add vertices V of the original graph G and add an additional vertex Vnew such that all the vertices connected of the graph are connected to this vertex. The number of vertices increases by 1, V’ =V+1." }, { "code": null, "e": 7462, "s": 7256, "text": "E’ = Add edges E of the original graph G and add new edges between the newly added vertex and the original vertices of the graph. The number of edges increases by the number of vertices V, that is, E’=E+V." }, { "code": null, "e": 7637, "s": 7462, "text": "The new graph G’ can be obtained in polynomial time, by adding new edges to the new vertex, that requires O(V) time. This reduction can be proved by the following two claims:" }, { "code": null, "e": 8071, "s": 7637, "text": "Let us assume that the graph G contains a hamiltonian path covering the V vertices of the graph starting at a random vertex say Vstart and ending at Vend, now since we connected all the vertices to an arbitrary new vertex Vnew in G’.We extend the original Hamiltonian Path to a Hamiltonian Cycle by using the edges Vend to Vnew and Vnew to Vstart respectively. The graph G’ now contains the closed cycle traversing all vertices once." }, { "code": null, "e": 8376, "s": 8071, "text": "We assume that the graph G’ has a Hamiltonian Cycle passing through all the vertices, inclusive of Vnew. Now to convert it to a Hamiltonian Path, we remove the edges corresponding to the vertex Vnew in the cycle. The resultant path will cover the vertices V of the graph and will cover them exactly once." }, { "code": null, "e": 8640, "s": 8376, "text": "Thus we can say that the graph G’ contains a Hamiltonian Cycle iff graph G contains a Hamiltonian Path. Therefore, any instance of the Hamiltonian Cycle problem can be reduced to an instance of the Hamiltonian Path problem. Thus, the Hamiltonian Cycle is NP-Hard." }, { "code": null, "e": 8756, "s": 8640, "text": "Conclusion: Since, the Hamiltonian Cycle is both, a NP-Problem and NP-Hard. Therefore, it is a NP-Complete problem." }, { "code": null, "e": 8779, "s": 8756, "text": "Algorithms-NP Complete" }, { "code": null, "e": 8791, "s": 8779, "text": "NP Complete" }, { "code": null, "e": 8798, "s": 8791, "text": "NPHard" }, { "code": null, "e": 8809, "s": 8798, "text": "Algorithms" }, { "code": null, "e": 8818, "s": 8809, "text": "Analysis" }, { "code": null, "e": 8824, "s": 8818, "text": "Graph" }, { "code": null, "e": 8830, "s": 8824, "text": "Graph" }, { "code": null, "e": 8841, "s": 8830, "text": "Algorithms" } ]
Python | Find common elements in list of lists
12 Feb, 2019 The problem of finding the common elements in list of 2 lists is quite a common problem and can be dealt with ease and also has been discussed before many times. But sometimes, we require to find the elements that are in common from N lists. Let’s discuss certain ways in which this operation can be performed. Method #1 : Using reduce() + lambda + set()This particular task can be achieved in just a one line using the combination of the above functions. The reduce function can be used to operate the function of “&” operation to all the list. The set function can be used to convert list into a set to remove repetition. # Python3 code to demonstrate # common element extraction form N lists # using reduce() + lambda + set()from functools import reduce # initializing list of liststest_list = [[2, 3, 5, 8], [2, 6, 7, 3], [10, 9, 2, 3]] # printing original listprint ("The original list is : " + str(test_list)) # common element extraction form N lists# using reduce() + lambda + set()res = list(reduce(lambda i, j: i & j, (set(x) for x in test_list))) # printing resultprint ("The common elements from N lists : " + str(res)) The original list is : [[2, 3, 5, 8], [2, 6, 7, 3], [10, 9, 2, 3]] The common elements from N lists : [2, 3] Method #2 : Using map() + intersection()The map function can be used to convert each of the lists to set to be operated by to perform the intersection, using the set.intersection function. This is the most elegant way to perform this particular task. # Python3 code to demonstrate # common element extraction form N lists # using map() + intersection() # initializing list of liststest_list = [[2, 3, 5, 8], [2, 6, 7, 3], [10, 9, 2, 3]] # printing original listprint ("The original list is : " + str(test_list)) # common element extraction form N lists# using map() + intersection()res = list(set.intersection(*map(set, test_list))) # printing resultprint ("The common elements from N lists : " + str(res)) The original list is : [[2, 3, 5, 8], [2, 6, 7, 3], [10, 9, 2, 3]] The common elements from N lists : [2, 3] Python list-programs Python Python Programs 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() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Feb, 2019" }, { "code": null, "e": 339, "s": 28, "text": "The problem of finding the common elements in list of 2 lists is quite a common problem and can be dealt with ease and also has been discussed before many times. But sometimes, we require to find the elements that are in common from N lists. Let’s discuss certain ways in which this operation can be performed." }, { "code": null, "e": 652, "s": 339, "text": "Method #1 : Using reduce() + lambda + set()This particular task can be achieved in just a one line using the combination of the above functions. The reduce function can be used to operate the function of “&” operation to all the list. The set function can be used to convert list into a set to remove repetition." }, { "code": "# Python3 code to demonstrate # common element extraction form N lists # using reduce() + lambda + set()from functools import reduce # initializing list of liststest_list = [[2, 3, 5, 8], [2, 6, 7, 3], [10, 9, 2, 3]] # printing original listprint (\"The original list is : \" + str(test_list)) # common element extraction form N lists# using reduce() + lambda + set()res = list(reduce(lambda i, j: i & j, (set(x) for x in test_list))) # printing resultprint (\"The common elements from N lists : \" + str(res))", "e": 1163, "s": 652, "text": null }, { "code": null, "e": 1273, "s": 1163, "text": "The original list is : [[2, 3, 5, 8], [2, 6, 7, 3], [10, 9, 2, 3]]\nThe common elements from N lists : [2, 3]\n" }, { "code": null, "e": 1525, "s": 1273, "text": " Method #2 : Using map() + intersection()The map function can be used to convert each of the lists to set to be operated by to perform the intersection, using the set.intersection function. This is the most elegant way to perform this particular task." }, { "code": "# Python3 code to demonstrate # common element extraction form N lists # using map() + intersection() # initializing list of liststest_list = [[2, 3, 5, 8], [2, 6, 7, 3], [10, 9, 2, 3]] # printing original listprint (\"The original list is : \" + str(test_list)) # common element extraction form N lists# using map() + intersection()res = list(set.intersection(*map(set, test_list))) # printing resultprint (\"The common elements from N lists : \" + str(res))", "e": 1985, "s": 1525, "text": null }, { "code": null, "e": 2095, "s": 1985, "text": "The original list is : [[2, 3, 5, 8], [2, 6, 7, 3], [10, 9, 2, 3]]\nThe common elements from N lists : [2, 3]\n" }, { "code": null, "e": 2116, "s": 2095, "text": "Python list-programs" }, { "code": null, "e": 2123, "s": 2116, "text": "Python" }, { "code": null, "e": 2139, "s": 2123, "text": "Python Programs" }, { "code": null, "e": 2237, "s": 2139, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2255, "s": 2237, "text": "Python Dictionary" }, { "code": null, "e": 2297, "s": 2255, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2319, "s": 2297, "text": "Enumerate() in Python" }, { "code": null, "e": 2354, "s": 2319, "text": "Read a file line by line in Python" }, { "code": null, "e": 2380, "s": 2354, "text": "Python String | replace()" }, { "code": null, "e": 2423, "s": 2380, "text": "Python program to convert a list to string" }, { "code": null, "e": 2445, "s": 2423, "text": "Defaultdict in Python" }, { "code": null, "e": 2484, "s": 2445, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2522, "s": 2484, "text": "Python | Convert a list to dictionary" } ]
How to specify minimum & maximum number of characters allowed in an input field in HTML ?
28 Feb, 2022 Given an input field and the task is to set the minimum/maximum number of characters allowed in an input field in HTML. To set the maximum character limit in input field, we use <input> maxlength attribute. This attribute is used to specify the maximum number of characters enters into the <input> element. To set the minimum character limit in input field, we use <input> minlength attribute. This attribute is used to specify the minimum number of characters enters into the <input> element. Syntax: <input maxlength="number1"> <input minlength="number2"> Attribute Value: number1: It contains single value number which allows the maximum number of character in <input> element. Its default value is 524288. number2: The minimum number of character required in input fields. Example 1: Set the limit of maximum number of characters allowed in input fields. HTML <!DOCTYPE html><html> <head> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h3> How to specify the maximum number of characters <br>allowed in an input field in HTML? </h3> <form action="#"> Username: <input type="text" name="username" maxlength="12"><br><br> Password: <input type="password" name="password" maxlength="10"><br><br> <input type="submit" value="Submit"> </form></body> </html> Output: Example 2: Set the limit of minimum number of characters allowed in input fields. HTML <!DOCTYPE html><html> <head> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h3> How to specify the minimum number of characters <br>allowed in an input field in HTML? </h3> <form action="#"> Username: <input type="text" name="username" minlength="12"><br><br> Password: <input type="password" name="password" minlength="10"><br><br> <input type="submit" value="Submit"> </form></body> </html> Output: varshagumber28 HTML-Attributes HTML-Questions HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Feb, 2022" }, { "code": null, "e": 148, "s": 28, "text": "Given an input field and the task is to set the minimum/maximum number of characters allowed in an input field in HTML." }, { "code": null, "e": 335, "s": 148, "text": "To set the maximum character limit in input field, we use <input> maxlength attribute. This attribute is used to specify the maximum number of characters enters into the <input> element." }, { "code": null, "e": 522, "s": 335, "text": "To set the minimum character limit in input field, we use <input> minlength attribute. This attribute is used to specify the minimum number of characters enters into the <input> element." }, { "code": null, "e": 531, "s": 522, "text": "Syntax: " }, { "code": null, "e": 588, "s": 531, "text": "<input maxlength=\"number1\">\n<input minlength=\"number2\"> " }, { "code": null, "e": 606, "s": 588, "text": "Attribute Value: " }, { "code": null, "e": 741, "s": 606, "text": "number1: It contains single value number which allows the maximum number of character in <input> element. Its default value is 524288." }, { "code": null, "e": 808, "s": 741, "text": "number2: The minimum number of character required in input fields." }, { "code": null, "e": 890, "s": 808, "text": "Example 1: Set the limit of maximum number of characters allowed in input fields." }, { "code": null, "e": 895, "s": 890, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h3> How to specify the maximum number of characters <br>allowed in an input field in HTML? </h3> <form action=\"#\"> Username: <input type=\"text\" name=\"username\" maxlength=\"12\"><br><br> Password: <input type=\"password\" name=\"password\" maxlength=\"10\"><br><br> <input type=\"submit\" value=\"Submit\"> </form></body> </html>", "e": 1510, "s": 895, "text": null }, { "code": null, "e": 1523, "s": 1514, "text": "Output: " }, { "code": null, "e": 1609, "s": 1527, "text": "Example 2: Set the limit of minimum number of characters allowed in input fields." }, { "code": null, "e": 1616, "s": 1611, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h3> How to specify the minimum number of characters <br>allowed in an input field in HTML? </h3> <form action=\"#\"> Username: <input type=\"text\" name=\"username\" minlength=\"12\"><br><br> Password: <input type=\"password\" name=\"password\" minlength=\"10\"><br><br> <input type=\"submit\" value=\"Submit\"> </form></body> </html>", "e": 2231, "s": 1616, "text": null }, { "code": null, "e": 2239, "s": 2231, "text": "Output:" }, { "code": null, "e": 2254, "s": 2239, "text": "varshagumber28" }, { "code": null, "e": 2270, "s": 2254, "text": "HTML-Attributes" }, { "code": null, "e": 2285, "s": 2270, "text": "HTML-Questions" }, { "code": null, "e": 2290, "s": 2285, "text": "HTML" }, { "code": null, "e": 2307, "s": 2290, "text": "Web Technologies" }, { "code": null, "e": 2312, "s": 2307, "text": "HTML" } ]
Matplotlib.pyplot.vlines() in Python
18 Nov, 2021 Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. matplotlib.pyplot.vlines() is a function used in the plotting of a dataset. In matplotlib.pyplot.vlines(), vlines is the abbreviation for vertical lines.what this function does is very much clear from the expanded form, which says that function deals with the plotting of the vertical lines across the axes. Syntax: vlines(x, ymin, ymax, colors, linestyles) Example 1: Python3 import numpy as npimport matplotlib.pyplot as plt plt.vlines(4, 0, 5, linestyles ="dotted", colors ="k")plt.vlines(3, 0, 5, linestyles ="solid", colors ="k")plt.vlines(5, 0, 5, linestyles ="dashed", colors ="k") plt.xlim(0, 10)plt.ylim(0, 10) plt.show() Output : In the above example, the first argument at the beginning of the vlines() function shows the axis-point at the vertical line is to be generated, the next argument refers to the lower limit of the total length of the vertical line, whereas the third argument refers to the upper limit of the total length of the vertical line. After these three basic arguments, the next argument we can use is linestyles which decides the type of line to be plotted (eg.dotted, solid, dashed, dashdot, etc.), the last argument used is colors which is optional, basically, it is array-like of colors.Example 2: Python3 import matplotlib.pyplot as plt plt.vlines((1, 3, 5,), 0, 10, colors = ("r", "g", "b"), linestyles = ("solid", "dashed", "dotted")) plt.show() Output: kalrap615 Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Nov, 2021" }, { "code": null, "e": 136, "s": 28, "text": "Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. " }, { "code": null, "e": 447, "s": 138, "text": "matplotlib.pyplot.vlines() is a function used in the plotting of a dataset. In matplotlib.pyplot.vlines(), vlines is the abbreviation for vertical lines.what this function does is very much clear from the expanded form, which says that function deals with the plotting of the vertical lines across the axes. " }, { "code": null, "e": 497, "s": 447, "text": "Syntax: vlines(x, ymin, ymax, colors, linestyles)" }, { "code": null, "e": 510, "s": 497, "text": "Example 1: " }, { "code": null, "e": 518, "s": 510, "text": "Python3" }, { "code": "import numpy as npimport matplotlib.pyplot as plt plt.vlines(4, 0, 5, linestyles =\"dotted\", colors =\"k\")plt.vlines(3, 0, 5, linestyles =\"solid\", colors =\"k\")plt.vlines(5, 0, 5, linestyles =\"dashed\", colors =\"k\") plt.xlim(0, 10)plt.ylim(0, 10) plt.show()", "e": 772, "s": 518, "text": null }, { "code": null, "e": 782, "s": 772, "text": "Output : " }, { "code": null, "e": 1376, "s": 782, "text": "In the above example, the first argument at the beginning of the vlines() function shows the axis-point at the vertical line is to be generated, the next argument refers to the lower limit of the total length of the vertical line, whereas the third argument refers to the upper limit of the total length of the vertical line. After these three basic arguments, the next argument we can use is linestyles which decides the type of line to be plotted (eg.dotted, solid, dashed, dashdot, etc.), the last argument used is colors which is optional, basically, it is array-like of colors.Example 2: " }, { "code": null, "e": 1384, "s": 1376, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt plt.vlines((1, 3, 5,), 0, 10, colors = (\"r\", \"g\", \"b\"), linestyles = (\"solid\", \"dashed\", \"dotted\")) plt.show()", "e": 1535, "s": 1384, "text": null }, { "code": null, "e": 1544, "s": 1535, "text": "Output: " }, { "code": null, "e": 1556, "s": 1546, "text": "kalrap615" }, { "code": null, "e": 1574, "s": 1556, "text": "Python-matplotlib" }, { "code": null, "e": 1581, "s": 1574, "text": "Python" } ]
Type.FindInterfaces() Method in C# with Examples
06 May, 2019 Type.FindInterfaces(TypeFilter, Object) Method is used to return an array of Type objects which represents a filtered list of interfaces implemented or inherited by the current Type. All of the interfaces implemented by this class are considered during the search, whether declared by a base class or this class itself.This method searches the base class hierarchy, returning each of the matching interfaces each class implements as well as all the matching interfaces each of those interfaces implements (that is, the transitive closure of the matching interfaces is returned). No duplicate interfaces are returned. Syntax: public virtual Type[] FindInterfaces (System.Reflection.TypeFilter filter, object filterCriteria); Parameters: filter: The delegate which compares the interfaces against filterCriteria. filterCriteria: The search criteria which determines whether an interface should be included in the returned array. Return Value: This method returns an array of Type objects representing a filtered list of the interfaces implemented or inherited by the current Type, or an empty array of type Type if no interfaces matching the filter are implemented or inherited by the current Type. Exception: This method throws ArgumentNullException if filter is null. Below programs illustrate the use of the above-discussed method: Example 1: // C# program to demonstrate the// Type.FindInterfaces(TypeFilter,// Object) Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Creating try-catch block // to handle exceptions try { // Declaring and initializing // object Type Datatype Type type = typeof(System.String); // Declaring and initializing the object // of TypeFilter Datatype which help the // delegate that compares the interfaces // against filterCriteria TypeFilter myFilter = new TypeFilter(MyInterfaceFilter); // Declaring and initializing filterCriteria // object. It is used to search the criteria // that determines whether an interface should // be included in the returned array. object filterCriteria = "System.Collections.IEnumerable"; // Getting the filtered list of interface // using FindInterfaces() method Type[] myInterfaces = type.FindInterfaces(myFilter, filterCriteria); // Display the interfaces for (int j = 0; j < myInterfaces.Length; j++) Console.WriteLine("filtered list of interface : {0}.", myInterfaces[j].ToString()); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } } // Defining MyInterfaceFilter // which helps to fix the certain // condition on which filtration // took place public static bool MyInterfaceFilter(Type typeObj, Object criteriaObj) { if (typeObj.ToString() == criteriaObj.ToString()) return true; else return false; }} filtered list of interface : System.Collections.IEnumerable. Example 2: // C# program to demonstrate the// Type.FindInterfaces(TypeFilter,// Object) Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Creating try-catch block // to handle exceptions try { // Declaring and initializing // object Type Datatype Type type = typeof(System.String); // Declaring and initializing object // of TypeFilter Datatype // which help the delegate that compares // the interfaces against filterCriteria. TypeFilter myFilter = null; // Declaring and initializing filterCriteria // object. It is used to search the criteria // that determines whether an interface should // be included in the returned array. object filterCriteria = "System.Collections.IEnumerable"; // Getting the filtered list of interface // using FindInterfaces() method Type[] myInterfaces = type.FindInterfaces(myFilter, filterCriteria); // Display the interfaces for (int j = 0; j < myInterfaces.Length; j++) Console.WriteLine("filtered list of interface : {0}.", myInterfaces[j].ToString()); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.WriteLine("myFilter should not be null"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} myFilter should not be null Exception Thrown: System.ArgumentNullException Reference: https://docs.microsoft.com/en-us/dotnet/api/system.type.findinterfaces?view=netcore-3.0 CSharp-method CSharp-Type-Class C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework Extension Method in C# C# | List Class C# | .NET Framework (Basic Architecture and Component Stack) HashSet in C# with Examples Lambda Expressions in C# Switch Statement in C# Partial Classes in C# Hello World in C#
[ { "code": null, "e": 28, "s": 0, "text": "\n06 May, 2019" }, { "code": null, "e": 645, "s": 28, "text": "Type.FindInterfaces(TypeFilter, Object) Method is used to return an array of Type objects which represents a filtered list of interfaces implemented or inherited by the current Type. All of the interfaces implemented by this class are considered during the search, whether declared by a base class or this class itself.This method searches the base class hierarchy, returning each of the matching interfaces each class implements as well as all the matching interfaces each of those interfaces implements (that is, the transitive closure of the matching interfaces is returned). No duplicate interfaces are returned." }, { "code": null, "e": 653, "s": 645, "text": "Syntax:" }, { "code": null, "e": 752, "s": 653, "text": "public virtual Type[] FindInterfaces (System.Reflection.TypeFilter filter, object filterCriteria);" }, { "code": null, "e": 764, "s": 752, "text": "Parameters:" }, { "code": null, "e": 839, "s": 764, "text": "filter: The delegate which compares the interfaces against filterCriteria." }, { "code": null, "e": 955, "s": 839, "text": "filterCriteria: The search criteria which determines whether an interface should be included in the returned array." }, { "code": null, "e": 1225, "s": 955, "text": "Return Value: This method returns an array of Type objects representing a filtered list of the interfaces implemented or inherited by the current Type, or an empty array of type Type if no interfaces matching the filter are implemented or inherited by the current Type." }, { "code": null, "e": 1296, "s": 1225, "text": "Exception: This method throws ArgumentNullException if filter is null." }, { "code": null, "e": 1361, "s": 1296, "text": "Below programs illustrate the use of the above-discussed method:" }, { "code": null, "e": 1372, "s": 1361, "text": "Example 1:" }, { "code": "// C# program to demonstrate the// Type.FindInterfaces(TypeFilter,// Object) Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Creating try-catch block // to handle exceptions try { // Declaring and initializing // object Type Datatype Type type = typeof(System.String); // Declaring and initializing the object // of TypeFilter Datatype which help the // delegate that compares the interfaces // against filterCriteria TypeFilter myFilter = new TypeFilter(MyInterfaceFilter); // Declaring and initializing filterCriteria // object. It is used to search the criteria // that determines whether an interface should // be included in the returned array. object filterCriteria = \"System.Collections.IEnumerable\"; // Getting the filtered list of interface // using FindInterfaces() method Type[] myInterfaces = type.FindInterfaces(myFilter, filterCriteria); // Display the interfaces for (int j = 0; j < myInterfaces.Length; j++) Console.WriteLine(\"filtered list of interface : {0}.\", myInterfaces[j].ToString()); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } } // Defining MyInterfaceFilter // which helps to fix the certain // condition on which filtration // took place public static bool MyInterfaceFilter(Type typeObj, Object criteriaObj) { if (typeObj.ToString() == criteriaObj.ToString()) return true; else return false; }}", "e": 3397, "s": 1372, "text": null }, { "code": null, "e": 3459, "s": 3397, "text": "filtered list of interface : System.Collections.IEnumerable.\n" }, { "code": null, "e": 3470, "s": 3459, "text": "Example 2:" }, { "code": "// C# program to demonstrate the// Type.FindInterfaces(TypeFilter,// Object) Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Creating try-catch block // to handle exceptions try { // Declaring and initializing // object Type Datatype Type type = typeof(System.String); // Declaring and initializing object // of TypeFilter Datatype // which help the delegate that compares // the interfaces against filterCriteria. TypeFilter myFilter = null; // Declaring and initializing filterCriteria // object. It is used to search the criteria // that determines whether an interface should // be included in the returned array. object filterCriteria = \"System.Collections.IEnumerable\"; // Getting the filtered list of interface // using FindInterfaces() method Type[] myInterfaces = type.FindInterfaces(myFilter, filterCriteria); // Display the interfaces for (int j = 0; j < myInterfaces.Length; j++) Console.WriteLine(\"filtered list of interface : {0}.\", myInterfaces[j].ToString()); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.WriteLine(\"myFilter should not be null\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}", "e": 5158, "s": 3470, "text": null }, { "code": null, "e": 5234, "s": 5158, "text": "myFilter should not be null\nException Thrown: System.ArgumentNullException\n" }, { "code": null, "e": 5245, "s": 5234, "text": "Reference:" }, { "code": null, "e": 5333, "s": 5245, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.type.findinterfaces?view=netcore-3.0" }, { "code": null, "e": 5347, "s": 5333, "text": "CSharp-method" }, { "code": null, "e": 5365, "s": 5347, "text": "CSharp-Type-Class" }, { "code": null, "e": 5368, "s": 5365, "text": "C#" }, { "code": null, "e": 5466, "s": 5368, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5509, "s": 5466, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 5558, "s": 5509, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 5581, "s": 5558, "text": "Extension Method in C#" }, { "code": null, "e": 5597, "s": 5581, "text": "C# | List Class" }, { "code": null, "e": 5658, "s": 5597, "text": "C# | .NET Framework (Basic Architecture and Component Stack)" }, { "code": null, "e": 5686, "s": 5658, "text": "HashSet in C# with Examples" }, { "code": null, "e": 5711, "s": 5686, "text": "Lambda Expressions in C#" }, { "code": null, "e": 5734, "s": 5711, "text": "Switch Statement in C#" }, { "code": null, "e": 5756, "s": 5734, "text": "Partial Classes in C#" } ]
Program to convert speed in km/hr to m/sec and vice versa
16 Apr, 2021 Convert speed given in km/hr to m/sec and vice versa .Examples: Input : kmph = 72, mps = 10 Output : speed_in_mps = 20 speed_in_kmph = 36 Input : kmph = 54, mps = 15 Output : speed_in_mps = 15 speed_in_kmph = 54 Approach: 1 km = 1000 m and 1 hr = 3600 sec (60 min x 60 sec each). Conversion from Km/h to m/sec- When converting km/hr to m/sec, multiply the speed with 1000 and divide the result with 3600. 1 km/hr = 5/18 m/sec or 0.277778 m/sec Conversion from m/sec to km/h- When Converting m/sec to km/hr, divide the speed with 1000 and multiply the result with 3600. 1 m/sec = 18/5 km/hr or 3.6 km/hr Below is the program implementation: C++ Java Python3 C# PHP Javascript // CPP program to convert // kmph to mps and vice versa#include <bits/stdc++.h>using namespace std; // function to convert speed// in km/hr to m/secfloat kmph_to_mps(float kmph){ return (0.277778 * kmph);} // function to convert speed// in m/sec to km/hrfloat mps_to_kmph(float mps){ return (3.6 * mps);} // driver functionint main(){ // variable to store // speed in kmph float kmph = 72.0; // variable to store // speed in mps float mps = 10.0; cout << "speed_in_mps = " << kmph_to_mps(kmph) << " speed_in_kmph = " << mps_to_kmph(mps); return 0;} // Java program to convert// kmph to mps and vice versaimport java.io.*; class GFG{ // function to convert speed // in km/hr to m/sec static int kmph_to_mps(double kmph) { return(int) (0.277778 * kmph); } // function to convert speed // in m/sec to km/hr static int mps_to_kmph(double mps) { return(int) (3.6 * mps); } // Driver function public static void main (String[] args) { // variable to store // speed in kmph double kmph = 72.0; // variable to store // speed in mps double mps = 10.0; System.out.println("speed_in_mps = " + kmph_to_mps(kmph) + " speed_in_kmph = " +mps_to_kmph(mps)); }} // This code is contributed by vt_m. # Python3 program to convert# kmph to mps and vice versa # Function to convert speed# in km/hr to m/secdef kmph_to_mps(kmph): return (0.277778 * kmph) # Function to convert speed# in m/sec to km/hrdef mps_to_kmph(mps): return (3.6 * mps) # Driver Code # variable to store# speed in kmphkmph = 72.0 # variable to store# speed in mpsmps = 10.0 print("speed_in_mps = ", int(kmph_to_mps(kmph)) , " speed_in_kmph = ", int(mps_to_kmph(mps))) # This code is contributed by Anant Agarwal. // C# program to convert// kmph to mps and vice versausing System; class GFG { // function to convert speed // in km/hr to m/sec static int kmph_to_mps(double kmph) { return (int)(0.277778 * kmph); } // function to convert speed // in m/sec to km/hr static int mps_to_kmph(double mps) { return (int)(3.6 * mps); } // Driver function public static void Main() { // variable to store // speed in kmph double kmph = 72.0; // variable to store // speed in mps double mps = 10.0; Console.WriteLine("speed_in_mps = " + kmph_to_mps(kmph) + " speed_in_kmph = " + mps_to_kmph(mps)); }} // This code is contributed by vt_m. <?php// PHP program to convert// kmph to mps and vice versa // function to convert speed // in km/hr to m/sec function kmph_to_mps($kmph) { return floor(0.277778 * $kmph); } // function to convert speed // in m/sec to km/hr function mps_to_kmph( $mps) { return (3.6 * $mps); } // Driver Code // variable to store // speed in kmph $kmph = 72.0; // variable to store // speed in mps $mps = 10.0; echo "speed_in_mps = " , kmph_to_mps($kmph) ," speed_in_kmph = " , mps_to_kmph($mps); // This code is contributed by anuj_67.?> <script> // javascript program to convert// kmph to mps and vice versa // Function to convert speed// in km/hr to m/secfunction kmph_to_mps(kmph){ return (0.277778 * kmph);} // Function to convert speed// in m/sec to km/hr function mps_to_kmph(mps){ return (3.6 * mps) ;} // Driver Code // variable to store// speed in kmphvar kmph = 72.0 // variable to store// speed in mpsvar mps = 10.0 document.write("speed_in_mps = " + Number(kmph_to_mps(kmph).toFixed(0)) + " speed_in_kmph = " + Number(mps_to_kmph(mps).toFixed(0))) // This code is contributed by bunnyram19.</script> Output: speed_in_mps = 20 speed_in_kmph = 36 vt_m bunnyram19 School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Apr, 2021" }, { "code": null, "e": 94, "s": 28, "text": "Convert speed given in km/hr to m/sec and vice versa .Examples: " }, { "code": null, "e": 263, "s": 94, "text": "Input : kmph = 72, mps = 10\nOutput : speed_in_mps = 20\n speed_in_kmph = 36 \n\nInput : kmph = 54, mps = 15\nOutput : speed_in_mps = 15\n speed_in_kmph = 54 " }, { "code": null, "e": 460, "s": 265, "text": "Approach: 1 km = 1000 m and 1 hr = 3600 sec (60 min x 60 sec each). Conversion from Km/h to m/sec- When converting km/hr to m/sec, multiply the speed with 1000 and divide the result with 3600. " }, { "code": null, "e": 500, "s": 460, "text": "1 km/hr = 5/18 m/sec or 0.277778 m/sec " }, { "code": null, "e": 627, "s": 500, "text": "Conversion from m/sec to km/h- When Converting m/sec to km/hr, divide the speed with 1000 and multiply the result with 3600. " }, { "code": null, "e": 661, "s": 627, "text": "1 m/sec = 18/5 km/hr or 3.6 km/hr" }, { "code": null, "e": 700, "s": 661, "text": "Below is the program implementation: " }, { "code": null, "e": 704, "s": 700, "text": "C++" }, { "code": null, "e": 709, "s": 704, "text": "Java" }, { "code": null, "e": 717, "s": 709, "text": "Python3" }, { "code": null, "e": 720, "s": 717, "text": "C#" }, { "code": null, "e": 724, "s": 720, "text": "PHP" }, { "code": null, "e": 735, "s": 724, "text": "Javascript" }, { "code": "// CPP program to convert // kmph to mps and vice versa#include <bits/stdc++.h>using namespace std; // function to convert speed// in km/hr to m/secfloat kmph_to_mps(float kmph){ return (0.277778 * kmph);} // function to convert speed// in m/sec to km/hrfloat mps_to_kmph(float mps){ return (3.6 * mps);} // driver functionint main(){ // variable to store // speed in kmph float kmph = 72.0; // variable to store // speed in mps float mps = 10.0; cout << \"speed_in_mps = \" << kmph_to_mps(kmph) << \" speed_in_kmph = \" << mps_to_kmph(mps); return 0;}", "e": 1342, "s": 735, "text": null }, { "code": "// Java program to convert// kmph to mps and vice versaimport java.io.*; class GFG{ // function to convert speed // in km/hr to m/sec static int kmph_to_mps(double kmph) { return(int) (0.277778 * kmph); } // function to convert speed // in m/sec to km/hr static int mps_to_kmph(double mps) { return(int) (3.6 * mps); } // Driver function public static void main (String[] args) { // variable to store // speed in kmph double kmph = 72.0; // variable to store // speed in mps double mps = 10.0; System.out.println(\"speed_in_mps = \" + kmph_to_mps(kmph) + \" speed_in_kmph = \" +mps_to_kmph(mps)); }} // This code is contributed by vt_m.", "e": 2138, "s": 1342, "text": null }, { "code": "# Python3 program to convert# kmph to mps and vice versa # Function to convert speed# in km/hr to m/secdef kmph_to_mps(kmph): return (0.277778 * kmph) # Function to convert speed# in m/sec to km/hrdef mps_to_kmph(mps): return (3.6 * mps) # Driver Code # variable to store# speed in kmphkmph = 72.0 # variable to store# speed in mpsmps = 10.0 print(\"speed_in_mps = \", int(kmph_to_mps(kmph)) , \" speed_in_kmph = \", int(mps_to_kmph(mps))) # This code is contributed by Anant Agarwal.", "e": 2648, "s": 2138, "text": null }, { "code": "// C# program to convert// kmph to mps and vice versausing System; class GFG { // function to convert speed // in km/hr to m/sec static int kmph_to_mps(double kmph) { return (int)(0.277778 * kmph); } // function to convert speed // in m/sec to km/hr static int mps_to_kmph(double mps) { return (int)(3.6 * mps); } // Driver function public static void Main() { // variable to store // speed in kmph double kmph = 72.0; // variable to store // speed in mps double mps = 10.0; Console.WriteLine(\"speed_in_mps = \" + kmph_to_mps(kmph) + \" speed_in_kmph = \" + mps_to_kmph(mps)); }} // This code is contributed by vt_m.", "e": 3399, "s": 2648, "text": null }, { "code": "<?php// PHP program to convert// kmph to mps and vice versa // function to convert speed // in km/hr to m/sec function kmph_to_mps($kmph) { return floor(0.277778 * $kmph); } // function to convert speed // in m/sec to km/hr function mps_to_kmph( $mps) { return (3.6 * $mps); } // Driver Code // variable to store // speed in kmph $kmph = 72.0; // variable to store // speed in mps $mps = 10.0; echo \"speed_in_mps = \" , kmph_to_mps($kmph) ,\" speed_in_kmph = \" , mps_to_kmph($mps); // This code is contributed by anuj_67.?>", "e": 4041, "s": 3399, "text": null }, { "code": "<script> // javascript program to convert// kmph to mps and vice versa // Function to convert speed// in km/hr to m/secfunction kmph_to_mps(kmph){ return (0.277778 * kmph);} // Function to convert speed// in m/sec to km/hr function mps_to_kmph(mps){ return (3.6 * mps) ;} // Driver Code // variable to store// speed in kmphvar kmph = 72.0 // variable to store// speed in mpsvar mps = 10.0 document.write(\"speed_in_mps = \" + Number(kmph_to_mps(kmph).toFixed(0)) + \" speed_in_kmph = \" + Number(mps_to_kmph(mps).toFixed(0))) // This code is contributed by bunnyram19.</script> ", "e": 4671, "s": 4041, "text": null }, { "code": null, "e": 4681, "s": 4671, "text": "Output: " }, { "code": null, "e": 4718, "s": 4681, "text": "speed_in_mps = 20 speed_in_kmph = 36" }, { "code": null, "e": 4725, "s": 4720, "text": "vt_m" }, { "code": null, "e": 4736, "s": 4725, "text": "bunnyram19" }, { "code": null, "e": 4755, "s": 4736, "text": "School Programming" } ]
How to Redirect to Another Page After 5 Seconds using jQuery ? - GeeksforGeeks
14 Jul, 2021 In this article, we will learn, how to redirect to another page or URL after a specified time in jQuery. The built-in function used for performing the action is as follows. The setTimeout(callback, delay) function takes two parameters a callback and a time in milliseconds. When this method is called, the callback function will be executed after the specified time. With this method, the callback function is executed only one time after the specified time. Our goal is to redirect to another page after 5 seconds and this will happen only one time. We use jQuery setTimeout() function Example: HTML <!DOCTYPE html><html lang="en"> <head> <!-- using jquery library --> <script src="https://code.jquery.com/jquery-git.js"> </script> </head> <body> <h1 style="color: green;"> Geeksforgeeks </h1> <!-- Creating a button --> <div class="redirect"> <button>Redirect me to GFG</button> </div> <!-- Script which will redirect us to another page --> <script> // click event on button $("button").click(function(){ $(".redirect").text("Redirecting....") // storing url and time let delay = 5000; let url = "https://www.geeksforgeeks.org/"; setTimeout(function(){ location = url; },5000) }) </script></body> </html> Output: After 5 seconds, the “geeksforgeeks” home page will open. jQuery-Methods jQuery-Questions Picked JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show and Hide div elements using radio buttons? How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method jQuery | removeAttr() with Examples How to get the value in an input text box using jQuery ? 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": 26954, "s": 26926, "text": "\n14 Jul, 2021" }, { "code": null, "e": 27413, "s": 26954, "text": "In this article, we will learn, how to redirect to another page or URL after a specified time in jQuery. The built-in function used for performing the action is as follows. The setTimeout(callback, delay) function takes two parameters a callback and a time in milliseconds. When this method is called, the callback function will be executed after the specified time. With this method, the callback function is executed only one time after the specified time." }, { "code": null, "e": 27541, "s": 27413, "text": "Our goal is to redirect to another page after 5 seconds and this will happen only one time. We use jQuery setTimeout() function" }, { "code": null, "e": 27550, "s": 27541, "text": "Example:" }, { "code": null, "e": 27555, "s": 27550, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- using jquery library --> <script src=\"https://code.jquery.com/jquery-git.js\"> </script> </head> <body> <h1 style=\"color: green;\"> Geeksforgeeks </h1> <!-- Creating a button --> <div class=\"redirect\"> <button>Redirect me to GFG</button> </div> <!-- Script which will redirect us to another page --> <script> // click event on button $(\"button\").click(function(){ $(\".redirect\").text(\"Redirecting....\") // storing url and time let delay = 5000; let url = \"https://www.geeksforgeeks.org/\"; setTimeout(function(){ location = url; },5000) }) </script></body> </html>", "e": 28340, "s": 27555, "text": null }, { "code": null, "e": 28406, "s": 28340, "text": "Output: After 5 seconds, the “geeksforgeeks” home page will open." }, { "code": null, "e": 28421, "s": 28406, "text": "jQuery-Methods" }, { "code": null, "e": 28438, "s": 28421, "text": "jQuery-Questions" }, { "code": null, "e": 28445, "s": 28438, "text": "Picked" }, { "code": null, "e": 28452, "s": 28445, "text": "JQuery" }, { "code": null, "e": 28469, "s": 28452, "text": "Web Technologies" }, { "code": null, "e": 28567, "s": 28469, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28622, "s": 28567, "text": "How to Show and Hide div elements using radio buttons?" }, { "code": null, "e": 28695, "s": 28622, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 28718, "s": 28695, "text": "jQuery | ajax() Method" }, { "code": null, "e": 28754, "s": 28718, "text": "jQuery | removeAttr() with Examples" }, { "code": null, "e": 28811, "s": 28754, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 28851, "s": 28811, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28884, "s": 28851, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28929, "s": 28884, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28972, "s": 28929, "text": "How to fetch data from an API in ReactJS ?" } ]
How to change background color according to the mouse location using JavaScript ? - GeeksforGeeks
08 Jun, 2020 The background color can be changed according to the cursor position using the DOM (Document Object Model). In this article, we use the position of the cursor to set the value of the background. Approach: The approach is to use DOM manipulation to change the background according to the cursor position at a particular time. HTML Code: In this section, we have a simple boiler-plate code of HTML with a div tag in it. <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <title> How to change background color according to mouse location using JavaScript? </title></head> <body> <div class="geeks"></div></body> </html> CSS Code: In CSS, we have just set the background color as cover. <style> .geeks { width: 100%; height: 600px; background-size: cover; }</style> Note: You can set a default background. Javascript Code: In JS, first select the div tag using querySelector function and we have offset property to get the position of the cursor on the 2-D plane i.e. the X and Y-axis. Now we set the value of background using the co-ordinates. <script> var div = document.querySelector(".geeks"); div.addEventListener( "mousemove", function (e) { x = e.offsetX; y = e.offsetY; div.style.backgroundColor = `rgb(${x}, ${y}, ${x - y})`; });</script> Complete Code: It is the combination of the above three sections of code. <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title> How to change background color according to mouse location using JavaScript ? </title> <style> .geeks { width: 100%; height: 600px; background-size: cover; } </style></head> <body> <div class="geeks"></div> <script> var div = document.querySelector(".geeks"); div.addEventListener( "mousemove", function (e) { x = e.offsetX; y = e.offsetY; div.style.backgroundColor = `rgb(${x}, ${y}, ${x - y})`; }); </script></body> </html> Output: CSS-Misc HTML-Misc JavaScript-Misc CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to apply style to parent if it has child with CSS? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? Design a web page using HTML and CSS How to Upload Image into Database and Display it using PHP ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 26499, "s": 26471, "text": "\n08 Jun, 2020" }, { "code": null, "e": 26694, "s": 26499, "text": "The background color can be changed according to the cursor position using the DOM (Document Object Model). In this article, we use the position of the cursor to set the value of the background." }, { "code": null, "e": 26824, "s": 26694, "text": "Approach: The approach is to use DOM manipulation to change the background according to the cursor position at a particular time." }, { "code": null, "e": 26917, "s": 26824, "text": "HTML Code: In this section, we have a simple boiler-plate code of HTML with a div tag in it." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <title> How to change background color according to mouse location using JavaScript? </title></head> <body> <div class=\"geeks\"></div></body> </html>", "e": 27262, "s": 26917, "text": null }, { "code": null, "e": 27328, "s": 27262, "text": "CSS Code: In CSS, we have just set the background color as cover." }, { "code": "<style> .geeks { width: 100%; height: 600px; background-size: cover; }</style>", "e": 27434, "s": 27328, "text": null }, { "code": null, "e": 27474, "s": 27434, "text": "Note: You can set a default background." }, { "code": null, "e": 27713, "s": 27474, "text": "Javascript Code: In JS, first select the div tag using querySelector function and we have offset property to get the position of the cursor on the 2-D plane i.e. the X and Y-axis. Now we set the value of background using the co-ordinates." }, { "code": "<script> var div = document.querySelector(\".geeks\"); div.addEventListener( \"mousemove\", function (e) { x = e.offsetX; y = e.offsetY; div.style.backgroundColor = `rgb(${x}, ${y}, ${x - y})`; });</script>", "e": 27975, "s": 27713, "text": null }, { "code": null, "e": 28049, "s": 27975, "text": "Complete Code: It is the combination of the above three sections of code." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title> How to change background color according to mouse location using JavaScript ? </title> <style> .geeks { width: 100%; height: 600px; background-size: cover; } </style></head> <body> <div class=\"geeks\"></div> <script> var div = document.querySelector(\".geeks\"); div.addEventListener( \"mousemove\", function (e) { x = e.offsetX; y = e.offsetY; div.style.backgroundColor = `rgb(${x}, ${y}, ${x - y})`; }); </script></body> </html>", "e": 28851, "s": 28049, "text": null }, { "code": null, "e": 28859, "s": 28851, "text": "Output:" }, { "code": null, "e": 28868, "s": 28859, "text": "CSS-Misc" }, { "code": null, "e": 28878, "s": 28868, "text": "HTML-Misc" }, { "code": null, "e": 28894, "s": 28878, "text": "JavaScript-Misc" }, { "code": null, "e": 28898, "s": 28894, "text": "CSS" }, { "code": null, "e": 28903, "s": 28898, "text": "HTML" }, { "code": null, "e": 28914, "s": 28903, "text": "JavaScript" }, { "code": null, "e": 28931, "s": 28914, "text": "Web Technologies" }, { "code": null, "e": 28958, "s": 28931, "text": "Web technologies Questions" }, { "code": null, "e": 28963, "s": 28958, "text": "HTML" }, { "code": null, "e": 29061, "s": 28963, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29116, "s": 29061, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 29153, "s": 29116, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 29217, "s": 29153, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 29254, "s": 29217, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 29315, "s": 29254, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 29375, "s": 29315, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 29428, "s": 29375, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 29489, "s": 29428, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 29539, "s": 29489, "text": "How to Insert Form Data into Database using PHP ?" } ]
Employee Record System in C using File Handling - GeeksforGeeks
12 Nov, 2021 Employee Record System is software built to handle the primary housekeeping functions of a company. ERS helps companies keep track of all the employees and their records. It is used to manage the company using a computerized system. This software built to handle the records of employees of any company. It will help companies to keep track of all the employees’ records in a file. Aim of the Employee’s Record System: The user will be provided with 5 options: Add a new record. Delete a record. Modify a record. View all the records. Exit. Data of the Employees: Name. Age. Salary. Employee ID. Approach: All the functions will be provided under switch cases. The idea is to use the concepts of File Handling to write the data in a text file and read the written data as well. We need to add a data.txt file in the same folder as well. Approach: The opening frame consists of the name of the application and the developer: It is created using some printf statements and a predefined function called system(). The system() function is a part of the C/C++ standard library. It is used to pass the commands that can be executed in the command processor or the terminal of the operating system and finally returns the command after it has been completed. system(“Color 3F”) will change the color of the console i.e. background (3) and the text on the console i.e. foreground (F). system(“pause”) will pause the screen, so the user will get a message: Press any key to continue . . . gotoxy() function: It will help to set the coordinates of the displayed data. Switch Case: The required function under the switch cases will be executed as per the input of the user. Simple file handling concepts like opening a file, closing a file, writing in a file, and reading the file, etc. are used to develop the code. Below is the C program for the Employee record system: C // C program for the above approach#include <stdio.h>#include <stdlib.h>#include <string.h>#include <windows.h> // Structure of the employeestruct emp { char name[50]; float salary; int age; int id;};struct emp e; // size of the structurelong int size = sizeof(e); // In the start coordinates// will be 0, 0COORD cord = { 0, 0 }; // function to set the// coordinatesvoid gotoxy(int x, int y){ cord.X = x; cord.Y = y; SetConsoleCursorPosition( GetStdHandle(STD_OUTPUT_HANDLE), cord);} FILE *fp, *ft; // Function to add the recordsvoid addrecord(){ system("cls"); fseek(fp, 0, SEEK_END); char another = 'y'; while (another == 'y') { printf("\nEnter Name : "); scanf("%s", e.name); printf("\nEnter Age : "); scanf("%d", &e.age); printf("\nEnter Salary : "); scanf("%f", &e.salary); printf("\nEnter EMP-ID : "); scanf("%d", &e.id); fwrite(&e, size, 1, fp); printf("\nWant to add another" " record (Y/N) : "); fflush(stdin); scanf("%c", &another); }} // Function to delete the recordsvoid deleterecord(){ system("cls"); char empname[50]; char another = 'y'; while (another == 'y') { printf("\nEnter employee " "name to delete : "); scanf("%s", empname); ft = fopen("temp.txt", "wb"); rewind(fp); while (fread(&e, size, 1, fp) == 1) { if (strcmp(e.name, empname) != 0) fwrite(&e, size, 1, ft); } fclose(fp); fclose(ft); remove("data.txt"); rename("temp.txt", "data.txt"); fp = fopen("data.txt", "rb+"); printf("\nWant to delete another" " record (Y/N) :"); fflush(stdin); another = getche(); }} // Function to display the recordvoid displayrecord(){ system("cls"); // sets pointer to start // of the file rewind(fp); printf("\n=========================" "===========================" "======"); printf("\nNAME\t\tAGE\t\tSALARY\t\t" "\tID\n", e.name, e.age, e.salary, e.id); printf("===========================" "===========================" "====\n"); while (fread(&e, size, 1, fp) == 1) printf("\n%s\t\t%d\t\t%.2f\t%10d", e.name, e.age, e.salary, e.id); printf("\n\n\n\t"); system("pause");} // Function to modify the recordvoid modifyrecord(){ system("cls"); char empname[50]; char another = 'y'; while (another == 'y') { printf("\nEnter employee name" " to modify : "); scanf("%s", empname); rewind(fp); // While File is open while (fread(&e, size, 1, fp) == 1) { // Compare the employee name // with ename if (strcmp(e.name, empname) == 0) { printf("\nEnter new name:"); scanf("%s", e.name); printf("\nEnter new age :"); scanf("%d", &e.age); printf("\nEnter new salary :"); scanf("%f", &e.salary); printf("\nEnter new EMP-ID :"); scanf("%d", &e.id); fseek(fp, -size, SEEK_CUR); fwrite(&e, size, 1, fp); break; } } // Ask for modifying another record printf("\nWant to modify another" " record (Y/N) :"); fflush(stdin); scanf("%c", &another); }} // Driver codeint main(){ int choice; // opening the file fp = fopen("data.txt", "rb+"); // showing error if file is // unable to open. if (fp == NULL) { fp = fopen("data.txt", "wb+"); if (fp == NULL) { printf("\nCannot open file..."); exit(1); } } system("Color 3F"); printf("\n\n\n\n\t\t\t\t=============" "=============================" "==========="); printf("\n\t\t\t\t~~~~~~~~~~~~~~~~~~~" "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" "~~~~~"); printf("\n\t\t\t\t===================" "=============================" "====="); printf("\n\t\t\t\t[|:::>:::>:::>::> " "EMPLOYEE RECORD <::<:::<:::" "<:::|]\t"); printf("\n\t\t\t\t===================" "=============================" "====="); printf("\n\t\t\t\t~~~~~~~~~~~~~~~~~~~~" "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" "~~~"); printf("\n\t\t\t\t=====================" "==============================\n"); printf("\n\n\n\t\t\t\t\t\t\t\t\t\t" "Developer : @Sushant_Gaurav" "\n\n\t\t\t\t"); system("pause"); while (1) { // Clearing console and asking the // user for input system("cls"); gotoxy(30, 10); printf("\n1. ADD RECORD\n"); gotoxy(30, 12); printf("\n2. DELETE RECORD\n"); gotoxy(30, 14); printf("\n3. DISPLAY RECORDS\n"); gotoxy(30, 16); printf("\n4. MODIFY RECORD\n"); gotoxy(30, 18); printf("\n5. EXIT\n"); gotoxy(30, 20); printf("\nENTER YOUR CHOICE...\n"); fflush(stdin); scanf("%d", &choice); // Switch Case switch (choice) { case 1: // Add the records addrecord(); break; case 2: // Delete the records deleterecord(); break; case 3: // Display the records displayrecord(); break; case 4: // Modify the records modifyrecord(); break; case 5: fclose(fp); exit(0); break; default: printf("\nINVALID CHOICE...\n"); } } return 0;} Output: First displaying the name of software: Displaying all the options: Adding Records: Displaying Records: Delete a Record: Record After Deletion: Modifying or Editing a record: Record after Modification: kapoorsagar226 C-File Handling File Handling C Language C Programs Project Technical Scripter File Handling Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Multidimensional Arrays in C / C++ Converting Strings to Numbers in C/C++ Left Shift and Right Shift Operators in C/C++ Function Pointer in C Strings in C Arrow operator -> in C/C++ with Examples C Program to read contents of Whole File Header files in C/C++ and its uses Basics of File Handling in C
[ { "code": null, "e": 25821, "s": 25793, "text": "\n12 Nov, 2021" }, { "code": null, "e": 26203, "s": 25821, "text": "Employee Record System is software built to handle the primary housekeeping functions of a company. ERS helps companies keep track of all the employees and their records. It is used to manage the company using a computerized system. This software built to handle the records of employees of any company. It will help companies to keep track of all the employees’ records in a file." }, { "code": null, "e": 26282, "s": 26203, "text": "Aim of the Employee’s Record System: The user will be provided with 5 options:" }, { "code": null, "e": 26300, "s": 26282, "text": "Add a new record." }, { "code": null, "e": 26317, "s": 26300, "text": "Delete a record." }, { "code": null, "e": 26334, "s": 26317, "text": "Modify a record." }, { "code": null, "e": 26356, "s": 26334, "text": "View all the records." }, { "code": null, "e": 26362, "s": 26356, "text": "Exit." }, { "code": null, "e": 26385, "s": 26362, "text": "Data of the Employees:" }, { "code": null, "e": 26391, "s": 26385, "text": "Name." }, { "code": null, "e": 26396, "s": 26391, "text": "Age." }, { "code": null, "e": 26404, "s": 26396, "text": "Salary." }, { "code": null, "e": 26417, "s": 26404, "text": "Employee ID." }, { "code": null, "e": 26658, "s": 26417, "text": "Approach: All the functions will be provided under switch cases. The idea is to use the concepts of File Handling to write the data in a text file and read the written data as well. We need to add a data.txt file in the same folder as well." }, { "code": null, "e": 26668, "s": 26658, "text": "Approach:" }, { "code": null, "e": 27073, "s": 26668, "text": "The opening frame consists of the name of the application and the developer: It is created using some printf statements and a predefined function called system(). The system() function is a part of the C/C++ standard library. It is used to pass the commands that can be executed in the command processor or the terminal of the operating system and finally returns the command after it has been completed." }, { "code": null, "e": 27199, "s": 27073, "text": "system(“Color 3F”) will change the color of the console i.e. background (3) and the text on the console i.e. foreground (F)." }, { "code": null, "e": 27302, "s": 27199, "text": "system(“pause”) will pause the screen, so the user will get a message: Press any key to continue . . ." }, { "code": null, "e": 27380, "s": 27302, "text": "gotoxy() function: It will help to set the coordinates of the displayed data." }, { "code": null, "e": 27628, "s": 27380, "text": "Switch Case: The required function under the switch cases will be executed as per the input of the user. Simple file handling concepts like opening a file, closing a file, writing in a file, and reading the file, etc. are used to develop the code." }, { "code": null, "e": 27683, "s": 27628, "text": "Below is the C program for the Employee record system:" }, { "code": null, "e": 27685, "s": 27683, "text": "C" }, { "code": "// C program for the above approach#include <stdio.h>#include <stdlib.h>#include <string.h>#include <windows.h> // Structure of the employeestruct emp { char name[50]; float salary; int age; int id;};struct emp e; // size of the structurelong int size = sizeof(e); // In the start coordinates// will be 0, 0COORD cord = { 0, 0 }; // function to set the// coordinatesvoid gotoxy(int x, int y){ cord.X = x; cord.Y = y; SetConsoleCursorPosition( GetStdHandle(STD_OUTPUT_HANDLE), cord);} FILE *fp, *ft; // Function to add the recordsvoid addrecord(){ system(\"cls\"); fseek(fp, 0, SEEK_END); char another = 'y'; while (another == 'y') { printf(\"\\nEnter Name : \"); scanf(\"%s\", e.name); printf(\"\\nEnter Age : \"); scanf(\"%d\", &e.age); printf(\"\\nEnter Salary : \"); scanf(\"%f\", &e.salary); printf(\"\\nEnter EMP-ID : \"); scanf(\"%d\", &e.id); fwrite(&e, size, 1, fp); printf(\"\\nWant to add another\" \" record (Y/N) : \"); fflush(stdin); scanf(\"%c\", &another); }} // Function to delete the recordsvoid deleterecord(){ system(\"cls\"); char empname[50]; char another = 'y'; while (another == 'y') { printf(\"\\nEnter employee \" \"name to delete : \"); scanf(\"%s\", empname); ft = fopen(\"temp.txt\", \"wb\"); rewind(fp); while (fread(&e, size, 1, fp) == 1) { if (strcmp(e.name, empname) != 0) fwrite(&e, size, 1, ft); } fclose(fp); fclose(ft); remove(\"data.txt\"); rename(\"temp.txt\", \"data.txt\"); fp = fopen(\"data.txt\", \"rb+\"); printf(\"\\nWant to delete another\" \" record (Y/N) :\"); fflush(stdin); another = getche(); }} // Function to display the recordvoid displayrecord(){ system(\"cls\"); // sets pointer to start // of the file rewind(fp); printf(\"\\n=========================\" \"===========================\" \"======\"); printf(\"\\nNAME\\t\\tAGE\\t\\tSALARY\\t\\t\" \"\\tID\\n\", e.name, e.age, e.salary, e.id); printf(\"===========================\" \"===========================\" \"====\\n\"); while (fread(&e, size, 1, fp) == 1) printf(\"\\n%s\\t\\t%d\\t\\t%.2f\\t%10d\", e.name, e.age, e.salary, e.id); printf(\"\\n\\n\\n\\t\"); system(\"pause\");} // Function to modify the recordvoid modifyrecord(){ system(\"cls\"); char empname[50]; char another = 'y'; while (another == 'y') { printf(\"\\nEnter employee name\" \" to modify : \"); scanf(\"%s\", empname); rewind(fp); // While File is open while (fread(&e, size, 1, fp) == 1) { // Compare the employee name // with ename if (strcmp(e.name, empname) == 0) { printf(\"\\nEnter new name:\"); scanf(\"%s\", e.name); printf(\"\\nEnter new age :\"); scanf(\"%d\", &e.age); printf(\"\\nEnter new salary :\"); scanf(\"%f\", &e.salary); printf(\"\\nEnter new EMP-ID :\"); scanf(\"%d\", &e.id); fseek(fp, -size, SEEK_CUR); fwrite(&e, size, 1, fp); break; } } // Ask for modifying another record printf(\"\\nWant to modify another\" \" record (Y/N) :\"); fflush(stdin); scanf(\"%c\", &another); }} // Driver codeint main(){ int choice; // opening the file fp = fopen(\"data.txt\", \"rb+\"); // showing error if file is // unable to open. if (fp == NULL) { fp = fopen(\"data.txt\", \"wb+\"); if (fp == NULL) { printf(\"\\nCannot open file...\"); exit(1); } } system(\"Color 3F\"); printf(\"\\n\\n\\n\\n\\t\\t\\t\\t=============\" \"=============================\" \"===========\"); printf(\"\\n\\t\\t\\t\\t~~~~~~~~~~~~~~~~~~~\" \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" \"~~~~~\"); printf(\"\\n\\t\\t\\t\\t===================\" \"=============================\" \"=====\"); printf(\"\\n\\t\\t\\t\\t[|:::>:::>:::>::> \" \"EMPLOYEE RECORD <::<:::<:::\" \"<:::|]\\t\"); printf(\"\\n\\t\\t\\t\\t===================\" \"=============================\" \"=====\"); printf(\"\\n\\t\\t\\t\\t~~~~~~~~~~~~~~~~~~~~\" \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" \"~~~\"); printf(\"\\n\\t\\t\\t\\t=====================\" \"==============================\\n\"); printf(\"\\n\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\" \"Developer : @Sushant_Gaurav\" \"\\n\\n\\t\\t\\t\\t\"); system(\"pause\"); while (1) { // Clearing console and asking the // user for input system(\"cls\"); gotoxy(30, 10); printf(\"\\n1. ADD RECORD\\n\"); gotoxy(30, 12); printf(\"\\n2. DELETE RECORD\\n\"); gotoxy(30, 14); printf(\"\\n3. DISPLAY RECORDS\\n\"); gotoxy(30, 16); printf(\"\\n4. MODIFY RECORD\\n\"); gotoxy(30, 18); printf(\"\\n5. EXIT\\n\"); gotoxy(30, 20); printf(\"\\nENTER YOUR CHOICE...\\n\"); fflush(stdin); scanf(\"%d\", &choice); // Switch Case switch (choice) { case 1: // Add the records addrecord(); break; case 2: // Delete the records deleterecord(); break; case 3: // Display the records displayrecord(); break; case 4: // Modify the records modifyrecord(); break; case 5: fclose(fp); exit(0); break; default: printf(\"\\nINVALID CHOICE...\\n\"); } } return 0;}", "e": 33627, "s": 27685, "text": null }, { "code": null, "e": 33635, "s": 33627, "text": "Output:" }, { "code": null, "e": 33674, "s": 33635, "text": "First displaying the name of software:" }, { "code": null, "e": 33702, "s": 33674, "text": "Displaying all the options:" }, { "code": null, "e": 33718, "s": 33702, "text": "Adding Records:" }, { "code": null, "e": 33738, "s": 33718, "text": "Displaying Records:" }, { "code": null, "e": 33755, "s": 33738, "text": "Delete a Record:" }, { "code": null, "e": 33778, "s": 33755, "text": "Record After Deletion:" }, { "code": null, "e": 33809, "s": 33778, "text": "Modifying or Editing a record:" }, { "code": null, "e": 33836, "s": 33809, "text": "Record after Modification:" }, { "code": null, "e": 33851, "s": 33836, "text": "kapoorsagar226" }, { "code": null, "e": 33867, "s": 33851, "text": "C-File Handling" }, { "code": null, "e": 33881, "s": 33867, "text": "File Handling" }, { "code": null, "e": 33892, "s": 33881, "text": "C Language" }, { "code": null, "e": 33903, "s": 33892, "text": "C Programs" }, { "code": null, "e": 33911, "s": 33903, "text": "Project" }, { "code": null, "e": 33930, "s": 33911, "text": "Technical Scripter" }, { "code": null, "e": 33944, "s": 33930, "text": "File Handling" }, { "code": null, "e": 34042, "s": 33944, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34059, "s": 34042, "text": "Substring in C++" }, { "code": null, "e": 34094, "s": 34059, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 34133, "s": 34094, "text": "Converting Strings to Numbers in C/C++" }, { "code": null, "e": 34179, "s": 34133, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 34201, "s": 34179, "text": "Function Pointer in C" }, { "code": null, "e": 34214, "s": 34201, "text": "Strings in C" }, { "code": null, "e": 34255, "s": 34214, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 34296, "s": 34255, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 34331, "s": 34296, "text": "Header files in C/C++ and its uses" } ]
8-bit game using pygame - GeeksforGeeks
02 Sep, 2021 Pygame is a python library that can be used specifically to design and build games. Pygame supports only 2d games that are built using different sprites. Pygame is not particularly best for designing games as it is very complex to use doesn’t have a proper GUI like unity but it definitely builds logic for further complex projects.We’ll be creating a simple game with the following rules:- The player can only move vertically. Other than player block there will be two other blocks. One of them will be the enemy block and one of them will be score block. If the player collides with the enemy block then the game over screen pops up, if the player collides with the score block the score is incremented and it is compulsory to collect all score blocks. We’ll be using various techniques such as the use of functions, random variables, various pygame functions etc. Before initializing pygame library we need to install it. To install it type the below command in the terminal. pip install pygame After installing the pygame library we need to write the following lines to initialize the pygame library:- import pygame pygame.init() These lines are pretty self explanatory. The pygame.init() function initiates the pygame library.Then we need to initialize the screen where we want to place our blocks. This can be done by writing following lines:- res = (720, 720) screen = pygame.display.set_mode(res) The tuple res holds two values that will define the resolution of our game. Then we need to define another variable screen that will actually act as our workbench. This can be done by using pygame.display.set_mode((arg, arg)). The tuple (arg, arg) can be stored into a variable res to reduce processor load.Now we need an actual screen to pop up when we run the code this can be done by a for and while loop in following way:- while True: for ev in pygame.event.get(): if ev.type==pygame.QUIT: pygame.quit() The while loop used here run till the condition is true. We define a variable ev that in pygame.event. Now if the user clicks on the cross button of the window the condition is changed to false and the while loop ends killing the current window.Below is the implementation. Python3 # Python program to demonstrate# 8 bit game import pygameimport sysimport random # initialize the constructorpygame.init()res = (720, 720) # randomly assigns a value to variables# ranging from lower limit to upperc1 = random.randint(125, 255) c2 = random.randint(0, 255)c3 = random.randint(0, 255) screen = pygame.display.set_mode(res)clock = pygame.time.Clock()red = (255, 0, 0)green = (0, 255, 0)blue = (0, 0, 255)color_list = [red, green, blue]colox_c1 = 0colox_c2 = 0colox_c3 = 254colox_c4 = 254 # randomly assigns a colour from color_list# to playerplayer_c = random.choice(color_list) # light shade of menu buttonsstartl = (169, 169, 169) # dark shade of menu buttonsstartd = (100, 100, 100) white = (255, 255, 255)start = (255, 255, 255)width = screen.get_width()height = screen.get_height() # initial X position of playerlead_x = 40 # initial y position of playerlead_y = height / 2x = 300y = 290width1 = 100height1 = 40enemy_size = 50 # defining a fontsmallfont = pygame.font.SysFont('Corbel', 35) # texts to be rendered on screentext = smallfont.render('Start', True, white)text1 = smallfont.render('Options', True, white)exit1 = smallfont.render('Exit', True, white) # game titlecolox = smallfont.render('Colox', True, (c3, c2, c1)) x1 = random.randint(width / 2, width)y1 = random.randint(100, height / 2)x2 = 40y2 = 40speed = 15 # score of the playercount = 0 rgb = random.choice(color_list) # enemy positione_p = [width, random.randint(50, height - 50)] e1_p = [random.randint(width, width + 100), random.randint(50, height - 100)] # function for game_overdef game_over(): while True: # if the player clicks the cross # button for ev in pygame.event.get(): if ev.type == pygame.QUIT: pygame.quit() if ev.type == pygame.MOUSEBUTTONDOWN: if 100 < mouse1[0] < 140 and height - 100 < mouse1[1] \ < height - 80: pygame.quit() if ev.type == pygame.MOUSEBUTTONDOWN: if width - 180 < mouse1[0] < width - 100 and height \ - 100 < mouse1[1] < height - 80: # calling function game game(lead_x, lead_y, speed, count) # fills the screen with specified colour screen.fill((65, 25, 64)) smallfont = pygame.font.SysFont('Corbel', 60) smallfont1 = pygame.font.SysFont('Corbel', 25) game_over = smallfont.render('GAME OVER', True, white) game_exit = smallfont1.render('exit', True, white) restart = smallfont1.render('restart', True, white) mouse1 = pygame.mouse.get_pos() # exit if 100 < mouse1[0] < 140 and height - 100 < mouse1[1] < height - 80: pygame.draw.rect(screen, startl, [100, height - 100, 40,20]) else: pygame.draw.rect(screen, startd, [100, height - 100, 40,20]) # restart if width - 180 < mouse1[0] < width - 100 and height - 100 < mouse1[1] < height - 80: pygame.draw.rect(screen, startl, [width - 180, height- 100, 80, 20]) else: pygame.draw.rect(screen, startd, [width - 180, height- 100, 80, 20]) screen.blit(game_exit, (100, height - 100)) # superimposes one object on other screen.blit(restart, (width - 180, height - 100)) screen.blit(game_over, (width / 2 - 150, 295)) # updates frames of the game pygame.display.update() pygame.draw.rect(screen, startd, [100, height - 100, 40, 20])pygame.draw.rect(screen, startd, [width - 180, height - 100, 40, 50]) # function for body of the gamedef game( lead_y, lead_X, speed, count, ): while True: for ev in pygame.event.get(): if ev.type == pygame.QUIT: pygame.quit() # player control # keeps track of the key pressed keys = pygame.key.get_pressed() if keys[pygame.K_UP]: # if up key is pressed then the players # y pos will decrement by 10 lead_y -= 10 if keys[pygame.K_DOWN]: # if down key is pressed then the y pos # of the player is incremented by 10 lead_y += 10 screen.fill((65, 25, 64)) clock.tick(speed) # draws a rectangle on the screen rect = pygame.draw.rect(screen, player_c, [lead_x, lead_y, 40,40]) pygame.draw.rect(screen, (c1, c2, c3), [0, 0, width, 40]) pygame.draw.rect(screen, (c3, c2, c1), [0, 680, width, 40]) pygame.draw.rect(screen, startd, [width - 100, 0, 100, 40]) smallfont = pygame.font.SysFont('Corbel', 35) exit2 = smallfont.render('Exit', True, white) # exit # gets the X and y position of mouse # pointer and stores them as a tuple mouse = pygame.mouse.get_pos() if width - 100 < mouse[0] < width and 0 < mouse[1] < 40: pygame.draw.rect(screen, startl, [width - 100, 0, 100, 40]) else: pygame.draw.rect(screen, startd, [width - 100, 0, 100, 40]) if width - 100 < mouse[0] < width and 0 < mouse[1] < 40: if ev.type == pygame.MOUSEBUTTONDOWN: pygame.quit() # enemy position if e_p[0] > 0 and e_p[0] <= width: # if the enemy block's X coordinate is between 0 and # the width of the screen the X value gets # decremented by 10 e_p[0] -= 10 else: if e_p[1] <= 40 or e_p[1] >= height - 40: e_p[1] = height / 2 if e1_p[1] <= 40 or e1_p[1] >= height - 40: e1_p[1] = random.randint(40, height - 40) e_p[1] = random.randint(enemy_size, height - enemy_size) e_p[0] = width # game over # collision detection if lead_x <= e_p[0] <= lead_x + 40 and lead_y >= e_p[1] >= lead_y - 40: game_over() # checks if the player block has collided with the enemy block if lead_y <= e_p[1] + enemy_size <= lead_y + 40 and lead_x <= e_p[0] <= lead_x + 40: game_over() pygame.draw.rect(screen, red, [e_p[0], e_p[1], enemy_size,enemy_size]) if e1_p[0] > 0 and e1_p[0] <= width + 100: e1_p[0] -= 10 else: if e1_p[1] <= 40 or e1_p[1] >= height - 40: e1_p[1] = height / 2 e1_p[1] = random.randint(enemy_size, height - 40) e1_p[0] = width + 100 if lead_x <= e1_p[0] <= lead_x + 40 and lead_y >= e1_p[1] >= lead_y - 40: e1_p[0] = width + 100 e1_p[1] = random.randint(40, height - 40) count += 1 speed += 1 if lead_y <= e1_p[1] + enemy_size <= lead_y + 40 and lead_x <= e1_p[0] <= lead_x + 40: e1_p[0] = width + 100 e1_p[1] = random.randint(40, height - 40) # increases the score when blue box is hit count += 1 # increases the speed as score increases speed += 1 if count >= 45: # freezes the game FPS to 60 if # score reaches 45 or more speed = 60 if lead_y <= 38 or lead_y >= height - 38: game_over() if e1_p[0] <= 0: game_over() pygame.draw.rect(screen, blue, [e1_p[0], e1_p[1], enemy_size, enemy_size]) score1 = smallfont.render('Score:', True, white) screen.blit(score1, (width - 120, height - 40)) screen.blit(exit2, (width - 80, 0)) pygame.display.update() # introdef intro( colox_c1, colox_c2, colox, exit1, text1, text, ): intro = True while intro: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() screen.fill((65, 25, 64)) mouse = pygame.mouse.get_pos() # start screen if x < mouse[0] < x + width1 and y < mouse[1] < y + height1: # if mouse is hovered on a button # its colour shade becomes lighter pygame.draw.rect(screen, startl, [x, y, width1, height1]) else: if x < mouse[0] < x + width1 + 40 and y + 70 < mouse[1] < y \ + 70 + height1: pygame.draw.rect(screen, startl, [x, y + 70, width1+40,height1]) else: if x < mouse[0] < width1 + x and y + 140 < mouse[1] < y + 140 + height1: pygame.draw.rect(screen, startl, [x, y + 140,width1,height1]) else: pygame.draw.rect(screen, startd, [x, y, width1,height1]) pygame.draw.rect(screen, startd, [x, y + 70, width1 + 40, height1]) pygame.draw.rect(screen, startd, [x, y + 140,width1, height1]) # start button if event.type == pygame.MOUSEBUTTONDOWN: if x < mouse[0] < x + width1 and y < mouse[1] < y + height1: #music() game(lead_y, lead_x, speed, count) if event.type == pygame.MOUSEBUTTONDOWN: if x < mouse[0] < width1 + x and y + 140 < mouse[1] < y + 140 + height1: pygame.quit() # this handles the colour breezing effect if 0 <= colox_c1 <= 254 or 0 <= colox_c2 <= 254: colox_c1 += 1 colox_c2 += 1 if colox_c1 >= 254 or colox_c2 >= 254: colox_c1 = c3 colox_c2 = c3 pygame.draw.rect(screen, (c2, colox_c1, colox_c2), [0, 0, 40, height]) pygame.draw.rect(screen, (c2, colox_c1, colox_c2), [width - 40, 0, 40, height]) smallfont = pygame.font.SysFont('Corbel', 35) sig = smallfont.render('Designed by :- Antriksh', True, white) text = smallfont.render('Start', True, white) text1 = smallfont.render('Options', True, white) exit1 = smallfont.render('Exit', True, white) colox = smallfont.render('Colox', True, (c1, colox_c1, colox_c2)) screen.blit(colox, (312, 50)) screen.blit(text, (312, 295)) screen.blit(text1, (312, 365)) screen.blit(exit1, (312, 435)) screen.blit(sig, (320, height - 50)) clock.tick(60) pygame.display.update() intro( colox_c1, colox_c2, colox, exit1, text1, text, ) Output: Media error: Format(s) not supported or source(s) not found sagartomar9927 Python-PyGame Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25705, "s": 25677, "text": "\n02 Sep, 2021" }, { "code": null, "e": 26097, "s": 25705, "text": "Pygame is a python library that can be used specifically to design and build games. Pygame supports only 2d games that are built using different sprites. Pygame is not particularly best for designing games as it is very complex to use doesn’t have a proper GUI like unity but it definitely builds logic for further complex projects.We’ll be creating a simple game with the following rules:- " }, { "code": null, "e": 26136, "s": 26097, "text": "The player can only move vertically. " }, { "code": null, "e": 26194, "s": 26136, "text": "Other than player block there will be two other blocks. " }, { "code": null, "e": 26269, "s": 26194, "text": "One of them will be the enemy block and one of them will be score block. " }, { "code": null, "e": 26469, "s": 26269, "text": "If the player collides with the enemy block then the game over screen pops up, if the player collides with the score block the score is incremented and it is compulsory to collect all score blocks. " }, { "code": null, "e": 26582, "s": 26469, "text": "We’ll be using various techniques such as the use of functions, random variables, various pygame functions etc. " }, { "code": null, "e": 26695, "s": 26582, "text": "Before initializing pygame library we need to install it. To install it type the below command in the terminal. " }, { "code": null, "e": 26714, "s": 26695, "text": "pip install pygame" }, { "code": null, "e": 26823, "s": 26714, "text": "After installing the pygame library we need to write the following lines to initialize the pygame library:- " }, { "code": null, "e": 26851, "s": 26823, "text": "import pygame\npygame.init()" }, { "code": null, "e": 27068, "s": 26851, "text": "These lines are pretty self explanatory. The pygame.init() function initiates the pygame library.Then we need to initialize the screen where we want to place our blocks. This can be done by writing following lines:- " }, { "code": null, "e": 27123, "s": 27068, "text": "res = (720, 720)\nscreen = pygame.display.set_mode(res)" }, { "code": null, "e": 27551, "s": 27123, "text": "The tuple res holds two values that will define the resolution of our game. Then we need to define another variable screen that will actually act as our workbench. This can be done by using pygame.display.set_mode((arg, arg)). The tuple (arg, arg) can be stored into a variable res to reduce processor load.Now we need an actual screen to pop up when we run the code this can be done by a for and while loop in following way:- " }, { "code": null, "e": 27632, "s": 27551, "text": "while True:\nfor ev in pygame.event.get():\nif ev.type==pygame.QUIT:\npygame.quit()" }, { "code": null, "e": 27908, "s": 27632, "text": "The while loop used here run till the condition is true. We define a variable ev that in pygame.event. Now if the user clicks on the cross button of the window the condition is changed to false and the while loop ends killing the current window.Below is the implementation. " }, { "code": null, "e": 27916, "s": 27908, "text": "Python3" }, { "code": "# Python program to demonstrate# 8 bit game import pygameimport sysimport random # initialize the constructorpygame.init()res = (720, 720) # randomly assigns a value to variables# ranging from lower limit to upperc1 = random.randint(125, 255) c2 = random.randint(0, 255)c3 = random.randint(0, 255) screen = pygame.display.set_mode(res)clock = pygame.time.Clock()red = (255, 0, 0)green = (0, 255, 0)blue = (0, 0, 255)color_list = [red, green, blue]colox_c1 = 0colox_c2 = 0colox_c3 = 254colox_c4 = 254 # randomly assigns a colour from color_list# to playerplayer_c = random.choice(color_list) # light shade of menu buttonsstartl = (169, 169, 169) # dark shade of menu buttonsstartd = (100, 100, 100) white = (255, 255, 255)start = (255, 255, 255)width = screen.get_width()height = screen.get_height() # initial X position of playerlead_x = 40 # initial y position of playerlead_y = height / 2x = 300y = 290width1 = 100height1 = 40enemy_size = 50 # defining a fontsmallfont = pygame.font.SysFont('Corbel', 35) # texts to be rendered on screentext = smallfont.render('Start', True, white)text1 = smallfont.render('Options', True, white)exit1 = smallfont.render('Exit', True, white) # game titlecolox = smallfont.render('Colox', True, (c3, c2, c1)) x1 = random.randint(width / 2, width)y1 = random.randint(100, height / 2)x2 = 40y2 = 40speed = 15 # score of the playercount = 0 rgb = random.choice(color_list) # enemy positione_p = [width, random.randint(50, height - 50)] e1_p = [random.randint(width, width + 100), random.randint(50, height - 100)] # function for game_overdef game_over(): while True: # if the player clicks the cross # button for ev in pygame.event.get(): if ev.type == pygame.QUIT: pygame.quit() if ev.type == pygame.MOUSEBUTTONDOWN: if 100 < mouse1[0] < 140 and height - 100 < mouse1[1] \\ < height - 80: pygame.quit() if ev.type == pygame.MOUSEBUTTONDOWN: if width - 180 < mouse1[0] < width - 100 and height \\ - 100 < mouse1[1] < height - 80: # calling function game game(lead_x, lead_y, speed, count) # fills the screen with specified colour screen.fill((65, 25, 64)) smallfont = pygame.font.SysFont('Corbel', 60) smallfont1 = pygame.font.SysFont('Corbel', 25) game_over = smallfont.render('GAME OVER', True, white) game_exit = smallfont1.render('exit', True, white) restart = smallfont1.render('restart', True, white) mouse1 = pygame.mouse.get_pos() # exit if 100 < mouse1[0] < 140 and height - 100 < mouse1[1] < height - 80: pygame.draw.rect(screen, startl, [100, height - 100, 40,20]) else: pygame.draw.rect(screen, startd, [100, height - 100, 40,20]) # restart if width - 180 < mouse1[0] < width - 100 and height - 100 < mouse1[1] < height - 80: pygame.draw.rect(screen, startl, [width - 180, height- 100, 80, 20]) else: pygame.draw.rect(screen, startd, [width - 180, height- 100, 80, 20]) screen.blit(game_exit, (100, height - 100)) # superimposes one object on other screen.blit(restart, (width - 180, height - 100)) screen.blit(game_over, (width / 2 - 150, 295)) # updates frames of the game pygame.display.update() pygame.draw.rect(screen, startd, [100, height - 100, 40, 20])pygame.draw.rect(screen, startd, [width - 180, height - 100, 40, 50]) # function for body of the gamedef game( lead_y, lead_X, speed, count, ): while True: for ev in pygame.event.get(): if ev.type == pygame.QUIT: pygame.quit() # player control # keeps track of the key pressed keys = pygame.key.get_pressed() if keys[pygame.K_UP]: # if up key is pressed then the players # y pos will decrement by 10 lead_y -= 10 if keys[pygame.K_DOWN]: # if down key is pressed then the y pos # of the player is incremented by 10 lead_y += 10 screen.fill((65, 25, 64)) clock.tick(speed) # draws a rectangle on the screen rect = pygame.draw.rect(screen, player_c, [lead_x, lead_y, 40,40]) pygame.draw.rect(screen, (c1, c2, c3), [0, 0, width, 40]) pygame.draw.rect(screen, (c3, c2, c1), [0, 680, width, 40]) pygame.draw.rect(screen, startd, [width - 100, 0, 100, 40]) smallfont = pygame.font.SysFont('Corbel', 35) exit2 = smallfont.render('Exit', True, white) # exit # gets the X and y position of mouse # pointer and stores them as a tuple mouse = pygame.mouse.get_pos() if width - 100 < mouse[0] < width and 0 < mouse[1] < 40: pygame.draw.rect(screen, startl, [width - 100, 0, 100, 40]) else: pygame.draw.rect(screen, startd, [width - 100, 0, 100, 40]) if width - 100 < mouse[0] < width and 0 < mouse[1] < 40: if ev.type == pygame.MOUSEBUTTONDOWN: pygame.quit() # enemy position if e_p[0] > 0 and e_p[0] <= width: # if the enemy block's X coordinate is between 0 and # the width of the screen the X value gets # decremented by 10 e_p[0] -= 10 else: if e_p[1] <= 40 or e_p[1] >= height - 40: e_p[1] = height / 2 if e1_p[1] <= 40 or e1_p[1] >= height - 40: e1_p[1] = random.randint(40, height - 40) e_p[1] = random.randint(enemy_size, height - enemy_size) e_p[0] = width # game over # collision detection if lead_x <= e_p[0] <= lead_x + 40 and lead_y >= e_p[1] >= lead_y - 40: game_over() # checks if the player block has collided with the enemy block if lead_y <= e_p[1] + enemy_size <= lead_y + 40 and lead_x <= e_p[0] <= lead_x + 40: game_over() pygame.draw.rect(screen, red, [e_p[0], e_p[1], enemy_size,enemy_size]) if e1_p[0] > 0 and e1_p[0] <= width + 100: e1_p[0] -= 10 else: if e1_p[1] <= 40 or e1_p[1] >= height - 40: e1_p[1] = height / 2 e1_p[1] = random.randint(enemy_size, height - 40) e1_p[0] = width + 100 if lead_x <= e1_p[0] <= lead_x + 40 and lead_y >= e1_p[1] >= lead_y - 40: e1_p[0] = width + 100 e1_p[1] = random.randint(40, height - 40) count += 1 speed += 1 if lead_y <= e1_p[1] + enemy_size <= lead_y + 40 and lead_x <= e1_p[0] <= lead_x + 40: e1_p[0] = width + 100 e1_p[1] = random.randint(40, height - 40) # increases the score when blue box is hit count += 1 # increases the speed as score increases speed += 1 if count >= 45: # freezes the game FPS to 60 if # score reaches 45 or more speed = 60 if lead_y <= 38 or lead_y >= height - 38: game_over() if e1_p[0] <= 0: game_over() pygame.draw.rect(screen, blue, [e1_p[0], e1_p[1], enemy_size, enemy_size]) score1 = smallfont.render('Score:', True, white) screen.blit(score1, (width - 120, height - 40)) screen.blit(exit2, (width - 80, 0)) pygame.display.update() # introdef intro( colox_c1, colox_c2, colox, exit1, text1, text, ): intro = True while intro: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() screen.fill((65, 25, 64)) mouse = pygame.mouse.get_pos() # start screen if x < mouse[0] < x + width1 and y < mouse[1] < y + height1: # if mouse is hovered on a button # its colour shade becomes lighter pygame.draw.rect(screen, startl, [x, y, width1, height1]) else: if x < mouse[0] < x + width1 + 40 and y + 70 < mouse[1] < y \\ + 70 + height1: pygame.draw.rect(screen, startl, [x, y + 70, width1+40,height1]) else: if x < mouse[0] < width1 + x and y + 140 < mouse[1] < y + 140 + height1: pygame.draw.rect(screen, startl, [x, y + 140,width1,height1]) else: pygame.draw.rect(screen, startd, [x, y, width1,height1]) pygame.draw.rect(screen, startd, [x, y + 70, width1 + 40, height1]) pygame.draw.rect(screen, startd, [x, y + 140,width1, height1]) # start button if event.type == pygame.MOUSEBUTTONDOWN: if x < mouse[0] < x + width1 and y < mouse[1] < y + height1: #music() game(lead_y, lead_x, speed, count) if event.type == pygame.MOUSEBUTTONDOWN: if x < mouse[0] < width1 + x and y + 140 < mouse[1] < y + 140 + height1: pygame.quit() # this handles the colour breezing effect if 0 <= colox_c1 <= 254 or 0 <= colox_c2 <= 254: colox_c1 += 1 colox_c2 += 1 if colox_c1 >= 254 or colox_c2 >= 254: colox_c1 = c3 colox_c2 = c3 pygame.draw.rect(screen, (c2, colox_c1, colox_c2), [0, 0, 40, height]) pygame.draw.rect(screen, (c2, colox_c1, colox_c2), [width - 40, 0, 40, height]) smallfont = pygame.font.SysFont('Corbel', 35) sig = smallfont.render('Designed by :- Antriksh', True, white) text = smallfont.render('Start', True, white) text1 = smallfont.render('Options', True, white) exit1 = smallfont.render('Exit', True, white) colox = smallfont.render('Colox', True, (c1, colox_c1, colox_c2)) screen.blit(colox, (312, 50)) screen.blit(text, (312, 295)) screen.blit(text1, (312, 365)) screen.blit(exit1, (312, 435)) screen.blit(sig, (320, height - 50)) clock.tick(60) pygame.display.update() intro( colox_c1, colox_c2, colox, exit1, text1, text, )", "e": 38465, "s": 27916, "text": null }, { "code": null, "e": 38474, "s": 38465, "text": "Output: " }, { "code": null, "e": 38534, "s": 38474, "text": "Media error: Format(s) not supported or source(s) not found" }, { "code": null, "e": 38551, "s": 38536, "text": "sagartomar9927" }, { "code": null, "e": 38565, "s": 38551, "text": "Python-PyGame" }, { "code": null, "e": 38572, "s": 38565, "text": "Python" }, { "code": null, "e": 38670, "s": 38572, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38688, "s": 38670, "text": "Python Dictionary" }, { "code": null, "e": 38723, "s": 38688, "text": "Read a file line by line in Python" }, { "code": null, "e": 38755, "s": 38723, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 38777, "s": 38755, "text": "Enumerate() in Python" }, { "code": null, "e": 38819, "s": 38777, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 38849, "s": 38819, "text": "Iterate over a list in Python" }, { "code": null, "e": 38875, "s": 38849, "text": "Python String | replace()" }, { "code": null, "e": 38904, "s": 38875, "text": "*args and **kwargs in Python" }, { "code": null, "e": 38948, "s": 38904, "text": "Reading and Writing to text files in Python" } ]
Implement Comment on a Particular Blog Functionality in Social Media Android App - GeeksforGeeks
09 Apr, 2021 This is the Part 11 of “Build a Social Media App on Android Studio” tutorial, and we are going to cover the following functionalities in this article: We are going to comment on the blog. Here we are going to write a comment, and then we will be showing the comments and will be updating the comment count. The comment feature is the best feature in any blogging app. It helps in interacting with the user who has written the blog and much more. Step 1: Create a new layout resource file Go to the app > res > layout > Right-click > New > Layout Resource File and name the file as row_comments. Below is the code for the row_comments.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="1dp" android:orientation="vertical" app:cardBackgroundColor="@color/colorWhite" app:contentPadding="2dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <de.hdodenhof.circleimageview.CircleImageView android:id="@+id/loadcomment" android:layout_width="40dp" android:layout_height="40dp" android:layout_marginEnd="5dp" android:layout_marginRight="5dp" android:src="@drawable/profile_image" /> <TextView android:id="@+id/commentname" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_toRightOf="@id/loadcomment" android:text="Anni" android:textColor="@color/colorBlack" android:textSize="16sp" android:textStyle="bold" /> <TextView android:id="@+id/commenttext" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/commentname" android:layout_toEndOf="@id/loadcomment" android:layout_toRightOf="@id/loadcomment" android:text="Actual Comment" android:textColor="@color/colorBlack" /> <TextView android:id="@+id/commenttime" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/commenttext" android:layout_toEndOf="@id/loadcomment" android:layout_toRightOf="@id/loadcomment" android:text="12/06/19" /> </RelativeLayout> </androidx.cardview.widget.CardView> Step 2: Create a new java class and name the class as ModelComment Working with the ModelComment.java file. Created this activity to initialize the key so that we can retrieve the value of the key later. Below is the code for the ModelComment.java file. Java package com.example.socialmediaapp; public class ModelComment { String cId; String comment; String ptime; String udp; public String getcId() { return cId; } public void setcId(String cId) { this.cId = cId; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getPtime() { return ptime; } public void setPtime(String ptime) { this.ptime = ptime; } public String getUdp() { return udp; } public void setUdp(String udp) { this.udp = udp; } public String getUemail() { return uemail; } public void setUemail(String uemail) { this.uemail = uemail; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } String uemail; public ModelComment() { } String uid; public ModelComment(String cId, String comment, String ptime, String udp, String uemail, String uid, String uname) { this.cId = cId; this.comment = comment; this.ptime = ptime; this.udp = udp; this.uemail = uemail; this.uid = uid; this.uname = uname; } String uname;} Step 3: Create another new java class and name the class as AdapterComment Working with the AdapterComment.java file. Below is the code for the AdapterComment.java file. Java package com.example.socialmediaapp; import android.content.Context;import android.text.format.DateFormat;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import java.util.Calendar;import java.util.List;import java.util.Locale; public class AdapterComment extends RecyclerView.Adapter<com.example.socialmediaapp.AdapterComment.MyHolder> { Context context; List<ModelComment> list; public AdapterComment(Context context, List<ModelComment> list, String myuid, String postid) { this.context = context; this.list = list; this.myuid = myuid; this.postid = postid; } String myuid; String postid; @NonNull @Override public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.row_comments, parent, false); return new MyHolder(view); } @Override public void onBindViewHolder(@NonNull MyHolder holder, int position) { final String uid = list.get(position).getUid(); String name = list.get(position).getUname(); String email = list.get(position).getUemail(); String image = list.get(position).getUdp(); final String cid = list.get(position).getcId(); String comment = list.get(position).getComment(); String timestamp = list.get(position).getPtime(); Calendar calendar = Calendar.getInstance(Locale.ENGLISH); calendar.setTimeInMillis(Long.parseLong(timestamp)); String timedate = DateFormat.format("dd/MM/yyyy hh:mm aa", calendar).toString(); holder.name.setText(name); holder.time.setText(timedate); holder.comment.setText(comment); try { Glide.with(context).load(image).into(holder.imagea); } catch (Exception e) { } } @Override public int getItemCount() { return list.size(); } class MyHolder extends RecyclerView.ViewHolder { ImageView imagea; TextView name, comment, time; public MyHolder(@NonNull View itemView) { super(itemView); imagea = itemView.findViewById(R.id.loadcomment); name = itemView.findViewById(R.id.commentname); comment = itemView.findViewById(R.id.commenttext); time = itemView.findViewById(R.id.commenttime); } }} Step 4: Working with the PostDetailsActivity Activity Working with the activity_postdetails.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".PostDetailsActivity"> <androidx.core.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@id/commentsa"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"> <androidx.cardview.widget.CardView android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" app:cardBackgroundColor="@color/colorWhite" app:cardCornerRadius="3dp" app:cardElevation="3dp" app:cardUseCompatPadding="true" app:contentPadding="5dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <LinearLayout android:id="@+id/profilelayoutco" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_vertical" android:orientation="horizontal"> <de.hdodenhof.circleimageview.CircleImageView android:id="@+id/pictureco" android:layout_width="50dp" android:layout_height="50dp" android:scaleType="centerCrop" android:src="@drawable/profile_image" /> <LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="vertical"> <TextView android:id="@+id/unameco" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Name" android:textColor="@color/colorBlack" android:textSize="20sp" /> <TextView android:id="@+id/utimeco" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="33 min" /> </LinearLayout> <ImageButton android:id="@+id/morebtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@null" android:src="@drawable/ic_more" /> </LinearLayout> <TextView android:id="@+id/ptitleco" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Title" android:textSize="16sp" android:textStyle="bold" /> <TextView android:id="@+id/descriptco" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Description" android:textColor="@color/colorBlack" /> <ImageView android:id="@+id/pimagetvco" android:layout_width="match_parent" android:layout_height="200dp" android:background="@color/colorWhite" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/plikebco" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="1.2K Likes" android:textColor="@color/colorPrimary" /> <TextView android:id="@+id/pcommenttv" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="1.2K Comment" android:textAlignment="textEnd" android:textColor="@color/colorPrimary" /> </LinearLayout> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="#F5F0F0" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:orientation="horizontal"> <Button android:id="@+id/like" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:autoLink="all" android:background="@color/colorWhite" android:drawableStart="@drawable/ic_like" android:drawableLeft="@drawable/ic_like" android:padding="5dp" android:text="Like" /> <Button android:id="@+id/share" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:background="@color/colorWhite" android:drawableStart="@drawable/ic_share" android:drawableLeft="@drawable/ic_share" android:padding="5dp" android:text="SHARE" /> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:drawableStart="@drawable/ic_commenting" android:drawableLeft="@drawable/ic_commenting" android:drawablePadding="5dp" android:padding="2dp" android:text="Comments" android:textColor="@color/colorBlack" /> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclecomment" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> </androidx.core.widget.NestedScrollView> <RelativeLayout android:id="@+id/commentsa" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true"> <de.hdodenhof.circleimageview.CircleImageView android:id="@+id/commentimge" android:layout_width="50dp" android:layout_height="50dp" android:src="@drawable/profile_image" /> <EditText android:id="@+id/typecommet" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_toStartOf="@id/sendcomment" android:layout_toEndOf="@id/commentimge" android:layout_weight="1" android:background="@color/colorWhite" android:hint="Enter Comment..." android:inputType="textCapSentences|textMultiLine" android:padding="15dp" /> <ImageButton android:id="@+id/sendcomment" android:layout_width="40dp" android:layout_height="40dp" android:layout_alignParentRight="true" android:background="@color/colorWhite" android:src="@drawable/send_message" /> </RelativeLayout> </RelativeLayout> Working with the PostDetailsActivity.java file Post Comment Using this: DatabaseReference datarf= FirebaseDatabase.getInstance().getReference("Posts").child(postId).child("Comments"); HashMap<String ,Object> hashMap=new HashMap<>(); hashMap.put("cId",timestamp); hashMap.put("comment",commentss); hashMap.put("ptime",timestamp); hashMap.put("uid",myuid); hashMap.put("uemail",myemail); hashMap.put("udp",mydp); hashMap.put("uname",myname); datarf.child(timestamp).setValue(hashMap); Showing Comment like this: DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Posts").child(postId).child("Comments"); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { commentList.clear(); for (DataSnapshot dataSnapshot1:dataSnapshot.getChildren()){ } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); Below is the code for the PostDetailsActivity.java file. Java package com.example.socialmediaapp; import android.app.ProgressDialog;import android.content.Intent;import android.os.Bundle;import android.text.TextUtils;import android.text.format.DateFormat;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.ImageButton;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.ActionBar;import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide;import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.OnSuccessListener;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.Query;import com.google.firebase.database.ValueEventListener; import java.util.ArrayList;import java.util.Calendar;import java.util.HashMap;import java.util.List;import java.util.Locale; public class PostDetailsActivity extends AppCompatActivity { String hisuid, ptime, myuid, myname, myemail, mydp, uimage, postId, plike, hisdp, hisname; ImageView picture, image; TextView name, time, title, description, like, tcomment; ImageButton more; Button likebtn, share; LinearLayout profile; EditText comment; ImageButton sendb; RecyclerView recyclerView; List<ModelComment> commentList; AdapterComment adapterComment; ImageView imagep; boolean mlike = false; ActionBar actionBar; ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_post_details); actionBar = getSupportActionBar(); actionBar.setTitle("Post Details"); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowHomeEnabled(true); postId = getIntent().getStringExtra("pid"); recyclerView = findViewById(R.id.recyclecomment); picture = findViewById(R.id.pictureco); image = findViewById(R.id.pimagetvco); name = findViewById(R.id.unameco); time = findViewById(R.id.utimeco); more = findViewById(R.id.morebtn); title = findViewById(R.id.ptitleco); myemail = FirebaseAuth.getInstance().getCurrentUser().getEmail(); myuid = FirebaseAuth.getInstance().getCurrentUser().getUid(); description = findViewById(R.id.descriptco); tcomment = findViewById(R.id.pcommenttv); like = findViewById(R.id.plikebco); likebtn = findViewById(R.id.like); comment = findViewById(R.id.typecommet); sendb = findViewById(R.id.sendcomment); imagep = findViewById(R.id.commentimge); share = findViewById(R.id.share); profile = findViewById(R.id.profilelayout); progressDialog = new ProgressDialog(this); loadPostInfo(); loadUserInfo(); setLikes(); actionBar.setSubtitle("SignedInAs:" + myemail); loadComments(); sendb.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { postComment(); } }); likebtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { likepost(); } }); like.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(PostDetailsActivity.this, PostLikedByActivity.class); intent.putExtra("pid", postId); startActivity(intent); } }); } private void loadComments() { LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(layoutManager); commentList = new ArrayList<>(); DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts").child(postId).child("Comments"); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { commentList.clear(); for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { ModelComment modelComment = dataSnapshot1.getValue(ModelComment.class); commentList.add(modelComment); adapterComment = new AdapterComment(getApplicationContext(), commentList, myuid, postId); recyclerView.setAdapter(adapterComment); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void setLikes() { final DatabaseReference liekeref = FirebaseDatabase.getInstance().getReference().child("Likes"); liekeref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.child(postId).hasChild(myuid)) { likebtn.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_liked, 0, 0, 0); likebtn.setText("Liked"); } else { likebtn.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_like, 0, 0, 0); likebtn.setText("Like"); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void likepost() { mlike = true; final DatabaseReference liekeref = FirebaseDatabase.getInstance().getReference().child("Likes"); final DatabaseReference postref = FirebaseDatabase.getInstance().getReference().child("Posts"); liekeref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (mlike) { if (dataSnapshot.child(postId).hasChild(myuid)) { postref.child(postId).child("plike").setValue("" + (Integer.parseInt(plike) - 1)); liekeref.child(postId).child(myuid).removeValue(); mlike = false; } else { postref.child(postId).child("plike").setValue("" + (Integer.parseInt(plike) + 1)); liekeref.child(postId).child(myuid).setValue("Liked"); mlike = false; } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void postComment() { progressDialog.setMessage("Adding Comment"); final String commentss = comment.getText().toString().trim(); if (TextUtils.isEmpty(commentss)) { Toast.makeText(PostDetailsActivity.this, "Empty comment", Toast.LENGTH_LONG).show(); return; } progressDialog.show(); String timestamp = String.valueOf(System.currentTimeMillis()); DatabaseReference datarf = FirebaseDatabase.getInstance().getReference("Posts").child(postId).child("Comments"); HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put("cId", timestamp); hashMap.put("comment", commentss); hashMap.put("ptime", timestamp); hashMap.put("uid", myuid); hashMap.put("uemail", myemail); hashMap.put("udp", mydp); hashMap.put("uname", myname); datarf.child(timestamp).setValue(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { progressDialog.dismiss(); Toast.makeText(PostDetailsActivity.this, "Added", Toast.LENGTH_LONG).show(); comment.setText(""); updatecommetcount(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { progressDialog.dismiss(); Toast.makeText(PostDetailsActivity.this, "Failed", Toast.LENGTH_LONG).show(); } }); } boolean count = false; private void updatecommetcount() { count = true; final DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts").child(postId); reference.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (count) { String comments = "" + dataSnapshot.child("pcomments").getValue(); int newcomment = Integer.parseInt(comments) + 1; reference.child("pcomments").setValue("" + newcomment); count = false; } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void loadUserInfo() { Query myref = FirebaseDatabase.getInstance().getReference("Users"); myref.orderByChild("uid").equalTo(myuid).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { myname = dataSnapshot1.child("name").getValue().toString(); mydp = dataSnapshot1.child("image").getValue().toString(); try { Glide.with(PostDetailsActivity.this).load(mydp).into(imagep); } catch (Exception e) { } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void loadPostInfo() { DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Posts"); Query query = databaseReference.orderByChild("ptime").equalTo(postId); query.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { String ptitle = dataSnapshot1.child("title").getValue().toString(); String descriptions = dataSnapshot1.child("description").getValue().toString(); uimage = dataSnapshot1.child("uimage").getValue().toString(); hisdp = dataSnapshot1.child("udp").getValue().toString(); // hisuid = dataSnapshot1.child("uid").getValue().toString(); String uemail = dataSnapshot1.child("uemail").getValue().toString(); hisname = dataSnapshot1.child("uname").getValue().toString(); ptime = dataSnapshot1.child("ptime").getValue().toString(); plike = dataSnapshot1.child("plike").getValue().toString(); String commentcount = dataSnapshot1.child("pcomments").getValue().toString(); Calendar calendar = Calendar.getInstance(Locale.ENGLISH); calendar.setTimeInMillis(Long.parseLong(ptime)); String timedate = DateFormat.format("dd/MM/yyyy hh:mm aa", calendar).toString(); name.setText(hisname); title.setText(ptitle); description.setText(descriptions); like.setText(plike + " Likes"); time.setText(timedate); tcomment.setText(commentcount + " Comments"); if (uimage.equals("noImage")) { image.setVisibility(View.GONE); } else { image.setVisibility(View.VISIBLE); try { Glide.with(PostDetailsActivity.this).load(uimage).into(image); } catch (Exception e) { } } try { Glide.with(PostDetailsActivity.this).load(hisdp).into(picture); } catch (Exception e) { } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return super.onSupportNavigateUp(); } } Output: For all the drawable file used in this article please refer to this link: https://drive.google.com/drive/folders/1M_knOH_ugCuwSP5nkYzeD4dRp-Honzbe?usp=sharing Below is the file structure after performing these operations: Firebase 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? How to Post Data to API using Retrofit in Android? Retrofit with Kotlin Coroutine in Android 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
[ { "code": null, "e": 26381, "s": 26353, "text": "\n09 Apr, 2021" }, { "code": null, "e": 26532, "s": 26381, "text": "This is the Part 11 of “Build a Social Media App on Android Studio” tutorial, and we are going to cover the following functionalities in this article:" }, { "code": null, "e": 26569, "s": 26532, "text": "We are going to comment on the blog." }, { "code": null, "e": 26688, "s": 26569, "text": "Here we are going to write a comment, and then we will be showing the comments and will be updating the comment count." }, { "code": null, "e": 26827, "s": 26688, "text": "The comment feature is the best feature in any blogging app. It helps in interacting with the user who has written the blog and much more." }, { "code": null, "e": 26869, "s": 26827, "text": "Step 1: Create a new layout resource file" }, { "code": null, "e": 27025, "s": 26869, "text": "Go to the app > res > layout > Right-click > New > Layout Resource File and name the file as row_comments. Below is the code for the row_comments.xml file." }, { "code": null, "e": 27029, "s": 27025, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"1dp\" android:orientation=\"vertical\" app:cardBackgroundColor=\"@color/colorWhite\" app:contentPadding=\"2dp\"> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\"> <de.hdodenhof.circleimageview.CircleImageView android:id=\"@+id/loadcomment\" android:layout_width=\"40dp\" android:layout_height=\"40dp\" android:layout_marginEnd=\"5dp\" android:layout_marginRight=\"5dp\" android:src=\"@drawable/profile_image\" /> <TextView android:id=\"@+id/commentname\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_toRightOf=\"@id/loadcomment\" android:text=\"Anni\" android:textColor=\"@color/colorBlack\" android:textSize=\"16sp\" android:textStyle=\"bold\" /> <TextView android:id=\"@+id/commenttext\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/commentname\" android:layout_toEndOf=\"@id/loadcomment\" android:layout_toRightOf=\"@id/loadcomment\" android:text=\"Actual Comment\" android:textColor=\"@color/colorBlack\" /> <TextView android:id=\"@+id/commenttime\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/commenttext\" android:layout_toEndOf=\"@id/loadcomment\" android:layout_toRightOf=\"@id/loadcomment\" android:text=\"12/06/19\" /> </RelativeLayout> </androidx.cardview.widget.CardView>", "e": 29041, "s": 27029, "text": null }, { "code": null, "e": 29108, "s": 29041, "text": "Step 2: Create a new java class and name the class as ModelComment" }, { "code": null, "e": 29295, "s": 29108, "text": "Working with the ModelComment.java file. Created this activity to initialize the key so that we can retrieve the value of the key later. Below is the code for the ModelComment.java file." }, { "code": null, "e": 29300, "s": 29295, "text": "Java" }, { "code": "package com.example.socialmediaapp; public class ModelComment { String cId; String comment; String ptime; String udp; public String getcId() { return cId; } public void setcId(String cId) { this.cId = cId; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getPtime() { return ptime; } public void setPtime(String ptime) { this.ptime = ptime; } public String getUdp() { return udp; } public void setUdp(String udp) { this.udp = udp; } public String getUemail() { return uemail; } public void setUemail(String uemail) { this.uemail = uemail; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } String uemail; public ModelComment() { } String uid; public ModelComment(String cId, String comment, String ptime, String udp, String uemail, String uid, String uname) { this.cId = cId; this.comment = comment; this.ptime = ptime; this.udp = udp; this.uemail = uemail; this.uid = uid; this.uname = uname; } String uname;}", "e": 30754, "s": 29300, "text": null }, { "code": null, "e": 30829, "s": 30754, "text": "Step 3: Create another new java class and name the class as AdapterComment" }, { "code": null, "e": 30924, "s": 30829, "text": "Working with the AdapterComment.java file. Below is the code for the AdapterComment.java file." }, { "code": null, "e": 30929, "s": 30924, "text": "Java" }, { "code": "package com.example.socialmediaapp; import android.content.Context;import android.text.format.DateFormat;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import java.util.Calendar;import java.util.List;import java.util.Locale; public class AdapterComment extends RecyclerView.Adapter<com.example.socialmediaapp.AdapterComment.MyHolder> { Context context; List<ModelComment> list; public AdapterComment(Context context, List<ModelComment> list, String myuid, String postid) { this.context = context; this.list = list; this.myuid = myuid; this.postid = postid; } String myuid; String postid; @NonNull @Override public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.row_comments, parent, false); return new MyHolder(view); } @Override public void onBindViewHolder(@NonNull MyHolder holder, int position) { final String uid = list.get(position).getUid(); String name = list.get(position).getUname(); String email = list.get(position).getUemail(); String image = list.get(position).getUdp(); final String cid = list.get(position).getcId(); String comment = list.get(position).getComment(); String timestamp = list.get(position).getPtime(); Calendar calendar = Calendar.getInstance(Locale.ENGLISH); calendar.setTimeInMillis(Long.parseLong(timestamp)); String timedate = DateFormat.format(\"dd/MM/yyyy hh:mm aa\", calendar).toString(); holder.name.setText(name); holder.time.setText(timedate); holder.comment.setText(comment); try { Glide.with(context).load(image).into(holder.imagea); } catch (Exception e) { } } @Override public int getItemCount() { return list.size(); } class MyHolder extends RecyclerView.ViewHolder { ImageView imagea; TextView name, comment, time; public MyHolder(@NonNull View itemView) { super(itemView); imagea = itemView.findViewById(R.id.loadcomment); name = itemView.findViewById(R.id.commentname); comment = itemView.findViewById(R.id.commenttext); time = itemView.findViewById(R.id.commenttime); } }}", "e": 33499, "s": 30929, "text": null }, { "code": null, "e": 33553, "s": 33499, "text": "Step 4: Working with the PostDetailsActivity Activity" }, { "code": null, "e": 33601, "s": 33553, "text": "Working with the activity_postdetails.xml file." }, { "code": null, "e": 33605, "s": 33601, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".PostDetailsActivity\"> <androidx.core.widget.NestedScrollView android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_above=\"@id/commentsa\"> <LinearLayout android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <androidx.cardview.widget.CardView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\" app:cardBackgroundColor=\"@color/colorWhite\" app:cardCornerRadius=\"3dp\" app:cardElevation=\"3dp\" app:cardUseCompatPadding=\"true\" app:contentPadding=\"5dp\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <LinearLayout android:id=\"@+id/profilelayoutco\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:gravity=\"center_vertical\" android:orientation=\"horizontal\"> <de.hdodenhof.circleimageview.CircleImageView android:id=\"@+id/pictureco\" android:layout_width=\"50dp\" android:layout_height=\"50dp\" android:scaleType=\"centerCrop\" android:src=\"@drawable/profile_image\" /> <LinearLayout android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:orientation=\"vertical\"> <TextView android:id=\"@+id/unameco\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Name\" android:textColor=\"@color/colorBlack\" android:textSize=\"20sp\" /> <TextView android:id=\"@+id/utimeco\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"33 min\" /> </LinearLayout> <ImageButton android:id=\"@+id/morebtn\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:background=\"@null\" android:src=\"@drawable/ic_more\" /> </LinearLayout> <TextView android:id=\"@+id/ptitleco\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Title\" android:textSize=\"16sp\" android:textStyle=\"bold\" /> <TextView android:id=\"@+id/descriptco\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Description\" android:textColor=\"@color/colorBlack\" /> <ImageView android:id=\"@+id/pimagetvco\" android:layout_width=\"match_parent\" android:layout_height=\"200dp\" android:background=\"@color/colorWhite\" /> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\"> <TextView android:id=\"@+id/plikebco\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"1.2K Likes\" android:textColor=\"@color/colorPrimary\" /> <TextView android:id=\"@+id/pcommenttv\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"1.2K Comment\" android:textAlignment=\"textEnd\" android:textColor=\"@color/colorPrimary\" /> </LinearLayout> <View android:layout_width=\"match_parent\" android:layout_height=\"1dp\" android:background=\"#F5F0F0\" /> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:gravity=\"center\" android:orientation=\"horizontal\"> <Button android:id=\"@+id/like\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:autoLink=\"all\" android:background=\"@color/colorWhite\" android:drawableStart=\"@drawable/ic_like\" android:drawableLeft=\"@drawable/ic_like\" android:padding=\"5dp\" android:text=\"Like\" /> <Button android:id=\"@+id/share\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:background=\"@color/colorWhite\" android:drawableStart=\"@drawable/ic_share\" android:drawableLeft=\"@drawable/ic_share\" android:padding=\"5dp\" android:text=\"SHARE\" /> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:drawableStart=\"@drawable/ic_commenting\" android:drawableLeft=\"@drawable/ic_commenting\" android:drawablePadding=\"5dp\" android:padding=\"2dp\" android:text=\"Comments\" android:textColor=\"@color/colorBlack\" /> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/recyclecomment\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" /> </LinearLayout> </androidx.core.widget.NestedScrollView> <RelativeLayout android:id=\"@+id/commentsa\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_alignParentBottom=\"true\"> <de.hdodenhof.circleimageview.CircleImageView android:id=\"@+id/commentimge\" android:layout_width=\"50dp\" android:layout_height=\"50dp\" android:src=\"@drawable/profile_image\" /> <EditText android:id=\"@+id/typecommet\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_toStartOf=\"@id/sendcomment\" android:layout_toEndOf=\"@id/commentimge\" android:layout_weight=\"1\" android:background=\"@color/colorWhite\" android:hint=\"Enter Comment...\" android:inputType=\"textCapSentences|textMultiLine\" android:padding=\"15dp\" /> <ImageButton android:id=\"@+id/sendcomment\" android:layout_width=\"40dp\" android:layout_height=\"40dp\" android:layout_alignParentRight=\"true\" android:background=\"@color/colorWhite\" android:src=\"@drawable/send_message\" /> </RelativeLayout> </RelativeLayout>", "e": 42723, "s": 33605, "text": null }, { "code": null, "e": 42770, "s": 42723, "text": "Working with the PostDetailsActivity.java file" }, { "code": null, "e": 42795, "s": 42770, "text": "Post Comment Using this:" }, { "code": null, "e": 43278, "s": 42795, "text": "DatabaseReference datarf= FirebaseDatabase.getInstance().getReference(\"Posts\").child(postId).child(\"Comments\");\n HashMap<String ,Object> hashMap=new HashMap<>();\n hashMap.put(\"cId\",timestamp);\n hashMap.put(\"comment\",commentss);\n hashMap.put(\"ptime\",timestamp);\n hashMap.put(\"uid\",myuid);\n hashMap.put(\"uemail\",myemail);\n hashMap.put(\"udp\",mydp);\n hashMap.put(\"uname\",myname);\n datarf.child(timestamp).setValue(hashMap);" }, { "code": null, "e": 43305, "s": 43278, "text": "Showing Comment like this:" }, { "code": null, "e": 43872, "s": 43305, "text": "DatabaseReference reference= FirebaseDatabase.getInstance().getReference(\"Posts\").child(postId).child(\"Comments\");\n reference.addValueEventListener(new ValueEventListener() {\n @Override\n public void onDataChange(@NonNull DataSnapshot dataSnapshot) {\n\n commentList.clear();\n for (DataSnapshot dataSnapshot1:dataSnapshot.getChildren()){\n \n }\n }\n\n @Override\n public void onCancelled(@NonNull DatabaseError databaseError) {\n\n }\n });" }, { "code": null, "e": 43929, "s": 43872, "text": "Below is the code for the PostDetailsActivity.java file." }, { "code": null, "e": 43934, "s": 43929, "text": "Java" }, { "code": "package com.example.socialmediaapp; import android.app.ProgressDialog;import android.content.Intent;import android.os.Bundle;import android.text.TextUtils;import android.text.format.DateFormat;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.ImageButton;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.ActionBar;import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide;import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.OnSuccessListener;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.Query;import com.google.firebase.database.ValueEventListener; import java.util.ArrayList;import java.util.Calendar;import java.util.HashMap;import java.util.List;import java.util.Locale; public class PostDetailsActivity extends AppCompatActivity { String hisuid, ptime, myuid, myname, myemail, mydp, uimage, postId, plike, hisdp, hisname; ImageView picture, image; TextView name, time, title, description, like, tcomment; ImageButton more; Button likebtn, share; LinearLayout profile; EditText comment; ImageButton sendb; RecyclerView recyclerView; List<ModelComment> commentList; AdapterComment adapterComment; ImageView imagep; boolean mlike = false; ActionBar actionBar; ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_post_details); actionBar = getSupportActionBar(); actionBar.setTitle(\"Post Details\"); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowHomeEnabled(true); postId = getIntent().getStringExtra(\"pid\"); recyclerView = findViewById(R.id.recyclecomment); picture = findViewById(R.id.pictureco); image = findViewById(R.id.pimagetvco); name = findViewById(R.id.unameco); time = findViewById(R.id.utimeco); more = findViewById(R.id.morebtn); title = findViewById(R.id.ptitleco); myemail = FirebaseAuth.getInstance().getCurrentUser().getEmail(); myuid = FirebaseAuth.getInstance().getCurrentUser().getUid(); description = findViewById(R.id.descriptco); tcomment = findViewById(R.id.pcommenttv); like = findViewById(R.id.plikebco); likebtn = findViewById(R.id.like); comment = findViewById(R.id.typecommet); sendb = findViewById(R.id.sendcomment); imagep = findViewById(R.id.commentimge); share = findViewById(R.id.share); profile = findViewById(R.id.profilelayout); progressDialog = new ProgressDialog(this); loadPostInfo(); loadUserInfo(); setLikes(); actionBar.setSubtitle(\"SignedInAs:\" + myemail); loadComments(); sendb.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { postComment(); } }); likebtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { likepost(); } }); like.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(PostDetailsActivity.this, PostLikedByActivity.class); intent.putExtra(\"pid\", postId); startActivity(intent); } }); } private void loadComments() { LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(layoutManager); commentList = new ArrayList<>(); DatabaseReference reference = FirebaseDatabase.getInstance().getReference(\"Posts\").child(postId).child(\"Comments\"); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { commentList.clear(); for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { ModelComment modelComment = dataSnapshot1.getValue(ModelComment.class); commentList.add(modelComment); adapterComment = new AdapterComment(getApplicationContext(), commentList, myuid, postId); recyclerView.setAdapter(adapterComment); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void setLikes() { final DatabaseReference liekeref = FirebaseDatabase.getInstance().getReference().child(\"Likes\"); liekeref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.child(postId).hasChild(myuid)) { likebtn.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_liked, 0, 0, 0); likebtn.setText(\"Liked\"); } else { likebtn.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_like, 0, 0, 0); likebtn.setText(\"Like\"); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void likepost() { mlike = true; final DatabaseReference liekeref = FirebaseDatabase.getInstance().getReference().child(\"Likes\"); final DatabaseReference postref = FirebaseDatabase.getInstance().getReference().child(\"Posts\"); liekeref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (mlike) { if (dataSnapshot.child(postId).hasChild(myuid)) { postref.child(postId).child(\"plike\").setValue(\"\" + (Integer.parseInt(plike) - 1)); liekeref.child(postId).child(myuid).removeValue(); mlike = false; } else { postref.child(postId).child(\"plike\").setValue(\"\" + (Integer.parseInt(plike) + 1)); liekeref.child(postId).child(myuid).setValue(\"Liked\"); mlike = false; } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void postComment() { progressDialog.setMessage(\"Adding Comment\"); final String commentss = comment.getText().toString().trim(); if (TextUtils.isEmpty(commentss)) { Toast.makeText(PostDetailsActivity.this, \"Empty comment\", Toast.LENGTH_LONG).show(); return; } progressDialog.show(); String timestamp = String.valueOf(System.currentTimeMillis()); DatabaseReference datarf = FirebaseDatabase.getInstance().getReference(\"Posts\").child(postId).child(\"Comments\"); HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put(\"cId\", timestamp); hashMap.put(\"comment\", commentss); hashMap.put(\"ptime\", timestamp); hashMap.put(\"uid\", myuid); hashMap.put(\"uemail\", myemail); hashMap.put(\"udp\", mydp); hashMap.put(\"uname\", myname); datarf.child(timestamp).setValue(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { progressDialog.dismiss(); Toast.makeText(PostDetailsActivity.this, \"Added\", Toast.LENGTH_LONG).show(); comment.setText(\"\"); updatecommetcount(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { progressDialog.dismiss(); Toast.makeText(PostDetailsActivity.this, \"Failed\", Toast.LENGTH_LONG).show(); } }); } boolean count = false; private void updatecommetcount() { count = true; final DatabaseReference reference = FirebaseDatabase.getInstance().getReference(\"Posts\").child(postId); reference.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (count) { String comments = \"\" + dataSnapshot.child(\"pcomments\").getValue(); int newcomment = Integer.parseInt(comments) + 1; reference.child(\"pcomments\").setValue(\"\" + newcomment); count = false; } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void loadUserInfo() { Query myref = FirebaseDatabase.getInstance().getReference(\"Users\"); myref.orderByChild(\"uid\").equalTo(myuid).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { myname = dataSnapshot1.child(\"name\").getValue().toString(); mydp = dataSnapshot1.child(\"image\").getValue().toString(); try { Glide.with(PostDetailsActivity.this).load(mydp).into(imagep); } catch (Exception e) { } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void loadPostInfo() { DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference(\"Posts\"); Query query = databaseReference.orderByChild(\"ptime\").equalTo(postId); query.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { String ptitle = dataSnapshot1.child(\"title\").getValue().toString(); String descriptions = dataSnapshot1.child(\"description\").getValue().toString(); uimage = dataSnapshot1.child(\"uimage\").getValue().toString(); hisdp = dataSnapshot1.child(\"udp\").getValue().toString(); // hisuid = dataSnapshot1.child(\"uid\").getValue().toString(); String uemail = dataSnapshot1.child(\"uemail\").getValue().toString(); hisname = dataSnapshot1.child(\"uname\").getValue().toString(); ptime = dataSnapshot1.child(\"ptime\").getValue().toString(); plike = dataSnapshot1.child(\"plike\").getValue().toString(); String commentcount = dataSnapshot1.child(\"pcomments\").getValue().toString(); Calendar calendar = Calendar.getInstance(Locale.ENGLISH); calendar.setTimeInMillis(Long.parseLong(ptime)); String timedate = DateFormat.format(\"dd/MM/yyyy hh:mm aa\", calendar).toString(); name.setText(hisname); title.setText(ptitle); description.setText(descriptions); like.setText(plike + \" Likes\"); time.setText(timedate); tcomment.setText(commentcount + \" Comments\"); if (uimage.equals(\"noImage\")) { image.setVisibility(View.GONE); } else { image.setVisibility(View.VISIBLE); try { Glide.with(PostDetailsActivity.this).load(uimage).into(image); } catch (Exception e) { } } try { Glide.with(PostDetailsActivity.this).load(hisdp).into(picture); } catch (Exception e) { } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return super.onSupportNavigateUp(); } }", "e": 57033, "s": 43934, "text": null }, { "code": null, "e": 57041, "s": 57033, "text": "Output:" }, { "code": null, "e": 57200, "s": 57041, "text": "For all the drawable file used in this article please refer to this link: https://drive.google.com/drive/folders/1M_knOH_ugCuwSP5nkYzeD4dRp-Honzbe?usp=sharing" }, { "code": null, "e": 57263, "s": 57200, "text": "Below is the file structure after performing these operations:" }, { "code": null, "e": 57272, "s": 57263, "text": "Firebase" }, { "code": null, "e": 57280, "s": 57272, "text": "Android" }, { "code": null, "e": 57285, "s": 57280, "text": "Java" }, { "code": null, "e": 57290, "s": 57285, "text": "Java" }, { "code": null, "e": 57298, "s": 57290, "text": "Android" }, { "code": null, "e": 57396, "s": 57298, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 57434, "s": 57396, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 57473, "s": 57434, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 57523, "s": 57473, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 57574, "s": 57523, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 57616, "s": 57574, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 57631, "s": 57616, "text": "Arrays in Java" }, { "code": null, "e": 57675, "s": 57631, "text": "Split() String method in Java with examples" }, { "code": null, "e": 57697, "s": 57675, "text": "For-each loop in Java" }, { "code": null, "e": 57748, "s": 57697, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
PYGLET – Updating Sprite - GeeksforGeeks
19 Sep, 2021 In this article we will see how we can update the sprite in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a “heavyweight” object occupying operating system resources. Windows may appear as floating regions or can be set to fill an entire screen (fullscreen). A sprite is an instance of an image displayed on-screen. Multiple sprites can display the same image at different positions on the screen. Sprites can also be scaled larger or smaller, rotated at any angle and drawn at a fractional opacity. Image is loaded with the help of image module of pyglet. Updating means to changing the properties of sprite, properties can be size, position etc.We can create a window and sprite object with the help of commands given below # creating a window window = pyglet.window.Window(width, height, title) # creating a sprite object sprite = pyglet.sprite.Sprite(img, x, y) In order to create window we use update method with sprite objectSyntax : sprite.update(x=None, y=None, rotation=None, scale=None, scale_x=None, scale_y=None)Argument : It takes optional argument i.e x, y co-ordinates (int), rotation (float), scale (float), horizontal scale (float), vertical scale (float)Return : It returns None Below is the implementation Python3 # importing pyglet moduleimport pygletimport pyglet.window.key as key # width of windowwidth = 500 # height of windowheight = 500 # caption i.e title of the windowtitle = "Geeksforgeeks" # creating a windowwindow = pyglet.window.Window(width, height, title) # text text = "Welcome to GeeksforGeeks" # creating label with following properties# font = cooper# position = 250, 150# anchor position = centerlabel = pyglet.text.Label(text, font_name ='Cooper', font_size = 16, x = 250, y = 150, anchor_x ='center', anchor_y ='center') # creating a batchbatch = pyglet.graphics.Batch() # loading geeksforgeeks imageimage = pyglet.image.load('gfg.png') # creating sprite object# it is instance of an image displayed on-screensprite = pyglet.sprite.Sprite(image, x = 200, y = 230) # on draw [email protected] on_draw(): # clear the window window.clear() # draw the label label.draw() # draw the image on screen sprite.draw() # key press event @window.eventdef on_key_press(symbol, modifier): # key "C" get press if symbol == key.C: # printing the message print("Key : C is pressed") # image for iconimg = image = pyglet.resource.image("gfg.png") # setting image as iconwindow.set_icon(img) # updating the sprite# x, y = 10, 300# rotation = 45# scale = 2sprite.update(100, 300, 45, 2) # start running the applicationpyglet.app.run() Output : singghakshay anikakapoor Python-gui Python-Pyglet Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25809, "s": 25781, "text": "\n19 Sep, 2021" }, { "code": null, "e": 26645, "s": 25809, "text": "In this article we will see how we can update the sprite in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a “heavyweight” object occupying operating system resources. Windows may appear as floating regions or can be set to fill an entire screen (fullscreen). A sprite is an instance of an image displayed on-screen. Multiple sprites can display the same image at different positions on the screen. Sprites can also be scaled larger or smaller, rotated at any angle and drawn at a fractional opacity. Image is loaded with the help of image module of pyglet. Updating means to changing the properties of sprite, properties can be size, position etc.We can create a window and sprite object with the help of commands given below " }, { "code": null, "e": 26786, "s": 26645, "text": "# creating a window\nwindow = pyglet.window.Window(width, height, title)\n\n# creating a sprite object\nsprite = pyglet.sprite.Sprite(img, x, y)" }, { "code": null, "e": 27121, "s": 26788, "text": "In order to create window we use update method with sprite objectSyntax : sprite.update(x=None, y=None, rotation=None, scale=None, scale_x=None, scale_y=None)Argument : It takes optional argument i.e x, y co-ordinates (int), rotation (float), scale (float), horizontal scale (float), vertical scale (float)Return : It returns None " }, { "code": null, "e": 27151, "s": 27121, "text": "Below is the implementation " }, { "code": null, "e": 27159, "s": 27151, "text": "Python3" }, { "code": "# importing pyglet moduleimport pygletimport pyglet.window.key as key # width of windowwidth = 500 # height of windowheight = 500 # caption i.e title of the windowtitle = \"Geeksforgeeks\" # creating a windowwindow = pyglet.window.Window(width, height, title) # text text = \"Welcome to GeeksforGeeks\" # creating label with following properties# font = cooper# position = 250, 150# anchor position = centerlabel = pyglet.text.Label(text, font_name ='Cooper', font_size = 16, x = 250, y = 150, anchor_x ='center', anchor_y ='center') # creating a batchbatch = pyglet.graphics.Batch() # loading geeksforgeeks imageimage = pyglet.image.load('gfg.png') # creating sprite object# it is instance of an image displayed on-screensprite = pyglet.sprite.Sprite(image, x = 200, y = 230) # on draw [email protected] on_draw(): # clear the window window.clear() # draw the label label.draw() # draw the image on screen sprite.draw() # key press event @window.eventdef on_key_press(symbol, modifier): # key \"C\" get press if symbol == key.C: # printing the message print(\"Key : C is pressed\") # image for iconimg = image = pyglet.resource.image(\"gfg.png\") # setting image as iconwindow.set_icon(img) # updating the sprite# x, y = 10, 300# rotation = 45# scale = 2sprite.update(100, 300, 45, 2) # start running the applicationpyglet.app.run()", "e": 28746, "s": 27159, "text": null }, { "code": null, "e": 28757, "s": 28746, "text": "Output : " }, { "code": null, "e": 28772, "s": 28759, "text": "singghakshay" }, { "code": null, "e": 28784, "s": 28772, "text": "anikakapoor" }, { "code": null, "e": 28795, "s": 28784, "text": "Python-gui" }, { "code": null, "e": 28809, "s": 28795, "text": "Python-Pyglet" }, { "code": null, "e": 28816, "s": 28809, "text": "Python" }, { "code": null, "e": 28914, "s": 28816, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28932, "s": 28914, "text": "Python Dictionary" }, { "code": null, "e": 28967, "s": 28932, "text": "Read a file line by line in Python" }, { "code": null, "e": 28999, "s": 28967, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29021, "s": 28999, "text": "Enumerate() in Python" }, { "code": null, "e": 29063, "s": 29021, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29093, "s": 29063, "text": "Iterate over a list in Python" }, { "code": null, "e": 29119, "s": 29093, "text": "Python String | replace()" }, { "code": null, "e": 29148, "s": 29119, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29192, "s": 29148, "text": "Reading and Writing to text files in Python" } ]
Find the Missing Number in a sorted array - GeeksforGeeks
06 May, 2022 Given a list of n-1 integers and these integers are in the range of 1 to n. There are no duplicates in list. One of the integers is missing in the list. Write an efficient code to find the missing integer. Examples: Input : arr[] = [1, 2, 3, 4, 6, 7, 8]Output : 5 Input : arr[] = [1, 2, 3, 4, 5, 6, 8, 9]Output : 7 Naive approach: One Simple solution is to apply methods discussed for finding the missing element in an unsorted array. Time complexity of this solution is O(n). Efficient approach: It is based on the divide and conquer algorithm that we have seen in binary search, the concept behind this solution is that the elements appearing before the missing element will have ar[i] – i = 1 and those appearing after the missing element will have ar[i] – i = 2. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // A binary search based program to find the// only missing number in a sorted array of// distinct elements within limited range.#include <iostream>using namespace std; int search(int ar[], int size){ // Extreme cases if (ar[0] != 1) return 1; if (ar[size - 1] != (size + 1)) return size + 1; int a = 0, b = size - 1; int mid; while ((b - a) > 1) { mid = (a + b) / 2; if ((ar[a] - a) != (ar[mid] - mid)) b = mid; else if ((ar[b] - b) != (ar[mid] - mid)) a = mid; } return (ar[a] + 1);} int main(){ int ar[] = { 1, 2, 3, 4, 5, 6, 8 }; int size = sizeof(ar) / sizeof(ar[0]); cout << "Missing number:" << search(ar, size);} // This code is contributed by Pushpesh Raj // A binary search based program// to find the only missing number// in a sorted array of distinct// elements within limited range.import java.io.*; class GFG { static int search(int ar[], int size) { // Extreme cases if (ar[0] != 1) return 1; if (ar[size - 1] != (size + 1)) return size + 1; int a = 0, b = size - 1; int mid = 0; while ((b - a) > 1) { mid = (a + b) / 2; if ((ar[a] - a) != (ar[mid] - mid)) b = mid; else if ((ar[b] - b) != (ar[mid] - mid)) a = mid; } return (ar[a] + 1); } // Driver Code public static void main(String[] args) { int ar[] = { 1, 2, 3, 4, 5, 6, 8 }; int size = ar.length; System.out.println("Missing number: " + search(ar, size)); }} // This code is contributed// by inder_verma. # A binary search based program to find# the only missing number in a sorted# in a sorted array of distinct elements# within limited range def search(ar, size): # Extreme cases if(ar[0] != 1): return 1 if(ar[size-1] != (size+1)): return size+1 a = 0 b = size - 1 mid = 0 while b > a + 1: mid = (a + b) // 2 if (ar[a] - a) != (ar[mid] - mid): b = mid elif (ar[b] - b) != (ar[mid] - mid): a = mid return ar[a] + 1 # Driver Codea = [1, 2, 3, 4, 5, 6, 8]n = len(a) print("Missing number:", search(a, n)) # This code is contributed# by Mohit Kumar // A binary search based program// to find the only missing number// in a sorted array of distinct// elements within limited range.using System; class GFG { static int search(int[] ar, int size) { // Extreme cases if (ar[0] != 1) return 1; if (ar[size - 1] != (size + 1)) return size + 1; int a = 0, b = size - 1; int mid = 0; while ((b - a) > 1) { mid = (a + b) / 2; if ((ar[a] - a) != (ar[mid] - mid)) b = mid; else if ((ar[b] - b) != (ar[mid] - mid)) a = mid; } return (ar[a] + 1); } // Driver Code static public void Main(String[] args) { int[] ar = { 1, 2, 3, 4, 5, 6, 8 }; int size = ar.Length; Console.WriteLine("Missing number: " + search(ar, size)); }} // This code is contributed// by Arnab Kundu <?php// A binary search based program to find the// only missing number in a sorted array of// distinct elements within limited range. function search($ar, $size){ //Extreme cases if($ar[0]!=1) return 1; if($ar[$size-1]!=($size+1)) return $size+1; $a = 0; $b = $size - 1; $mid; while (($b - $a) > 1) { $mid = (int)(($a + $b) / 2); if (($ar[$a] - $a) != ($ar[$mid] - $mid)) $b = $mid; else if (($ar[$b] - $b) != ($ar[$mid] - $mid)) $a = $mid; } return ($ar[$a] + 1);} // Driver Code$ar = array(1, 2, 3, 4, 5, 6, 8 );$size = sizeof($ar);echo "Missing number: ", search($ar, $size); // This code is contributed by ajit.?> <script>// A binary search based program// to find the only missing number// in a sorted array of distinct// elements within limited range. function findMissing(arr) { var size = arr.length; //Extreme cases if(ar[0]!=1) return 1; if(ar[size-1]!=(size+1)) return size+1; var low = 0; var high = arr.length; while (low <= high) { var mid = Math.floor((low+high)/2); if ((arr[mid]-mid === 1) && (arr[mid+1]-(mid+1) === 2)) return arr[mid]+1; if (arr[mid]-mid === 1) { low = mid+1; } else { high = mid-1; } } return -1;} // Driver Code let ar = [1, 2, 3, 4, 5, 6, 8];document.write("Missing number: " +findMissing(ar)); // This code is contributed by mohit kumar 29.</script> Missing number:7 Time Complexity: O(log(N)), where N is the length of given arrayAuxiliary Space: O(1) inderDuMCA andrew1234 mohit kumar 29 jit_t ryan1219 hitesh aleriya pushpeshrajdx01 Binary Search limited-range-elements Divide and Conquer Searching Searching Divide and Conquer Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for Tower of Hanoi Divide and Conquer Algorithm | Introduction Median of two sorted arrays of different sizes Write a program to calculate pow(x,n) Count number of occurrences (or frequency) in a sorted array Linear Search K'th Smallest/Largest Element in Unsorted Array | Set 1 Program to find largest element in an array Given an array of size n and a number k, find all elements that appear more than n/k times k largest(or smallest) elements in an array
[ { "code": null, "e": 26759, "s": 26731, "text": "\n06 May, 2022" }, { "code": null, "e": 26966, "s": 26759, "text": "Given a list of n-1 integers and these integers are in the range of 1 to n. There are no duplicates in list. One of the integers is missing in the list. Write an efficient code to find the missing integer. " }, { "code": null, "e": 26977, "s": 26966, "text": "Examples: " }, { "code": null, "e": 27025, "s": 26977, "text": "Input : arr[] = [1, 2, 3, 4, 6, 7, 8]Output : 5" }, { "code": null, "e": 27076, "s": 27025, "text": "Input : arr[] = [1, 2, 3, 4, 5, 6, 8, 9]Output : 7" }, { "code": null, "e": 27238, "s": 27076, "text": "Naive approach: One Simple solution is to apply methods discussed for finding the missing element in an unsorted array. Time complexity of this solution is O(n)." }, { "code": null, "e": 27528, "s": 27238, "text": "Efficient approach: It is based on the divide and conquer algorithm that we have seen in binary search, the concept behind this solution is that the elements appearing before the missing element will have ar[i] – i = 1 and those appearing after the missing element will have ar[i] – i = 2." }, { "code": null, "e": 27579, "s": 27528, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27583, "s": 27579, "text": "C++" }, { "code": null, "e": 27588, "s": 27583, "text": "Java" }, { "code": null, "e": 27596, "s": 27588, "text": "Python3" }, { "code": null, "e": 27599, "s": 27596, "text": "C#" }, { "code": null, "e": 27603, "s": 27599, "text": "PHP" }, { "code": null, "e": 27614, "s": 27603, "text": "Javascript" }, { "code": "// A binary search based program to find the// only missing number in a sorted array of// distinct elements within limited range.#include <iostream>using namespace std; int search(int ar[], int size){ // Extreme cases if (ar[0] != 1) return 1; if (ar[size - 1] != (size + 1)) return size + 1; int a = 0, b = size - 1; int mid; while ((b - a) > 1) { mid = (a + b) / 2; if ((ar[a] - a) != (ar[mid] - mid)) b = mid; else if ((ar[b] - b) != (ar[mid] - mid)) a = mid; } return (ar[a] + 1);} int main(){ int ar[] = { 1, 2, 3, 4, 5, 6, 8 }; int size = sizeof(ar) / sizeof(ar[0]); cout << \"Missing number:\" << search(ar, size);} // This code is contributed by Pushpesh Raj", "e": 28370, "s": 27614, "text": null }, { "code": "// A binary search based program// to find the only missing number// in a sorted array of distinct// elements within limited range.import java.io.*; class GFG { static int search(int ar[], int size) { // Extreme cases if (ar[0] != 1) return 1; if (ar[size - 1] != (size + 1)) return size + 1; int a = 0, b = size - 1; int mid = 0; while ((b - a) > 1) { mid = (a + b) / 2; if ((ar[a] - a) != (ar[mid] - mid)) b = mid; else if ((ar[b] - b) != (ar[mid] - mid)) a = mid; } return (ar[a] + 1); } // Driver Code public static void main(String[] args) { int ar[] = { 1, 2, 3, 4, 5, 6, 8 }; int size = ar.length; System.out.println(\"Missing number: \" + search(ar, size)); }} // This code is contributed// by inder_verma.", "e": 29294, "s": 28370, "text": null }, { "code": "# A binary search based program to find# the only missing number in a sorted# in a sorted array of distinct elements# within limited range def search(ar, size): # Extreme cases if(ar[0] != 1): return 1 if(ar[size-1] != (size+1)): return size+1 a = 0 b = size - 1 mid = 0 while b > a + 1: mid = (a + b) // 2 if (ar[a] - a) != (ar[mid] - mid): b = mid elif (ar[b] - b) != (ar[mid] - mid): a = mid return ar[a] + 1 # Driver Codea = [1, 2, 3, 4, 5, 6, 8]n = len(a) print(\"Missing number:\", search(a, n)) # This code is contributed# by Mohit Kumar", "e": 29920, "s": 29294, "text": null }, { "code": "// A binary search based program// to find the only missing number// in a sorted array of distinct// elements within limited range.using System; class GFG { static int search(int[] ar, int size) { // Extreme cases if (ar[0] != 1) return 1; if (ar[size - 1] != (size + 1)) return size + 1; int a = 0, b = size - 1; int mid = 0; while ((b - a) > 1) { mid = (a + b) / 2; if ((ar[a] - a) != (ar[mid] - mid)) b = mid; else if ((ar[b] - b) != (ar[mid] - mid)) a = mid; } return (ar[a] + 1); } // Driver Code static public void Main(String[] args) { int[] ar = { 1, 2, 3, 4, 5, 6, 8 }; int size = ar.Length; Console.WriteLine(\"Missing number: \" + search(ar, size)); }} // This code is contributed// by Arnab Kundu", "e": 30837, "s": 29920, "text": null }, { "code": "<?php// A binary search based program to find the// only missing number in a sorted array of// distinct elements within limited range. function search($ar, $size){ //Extreme cases if($ar[0]!=1) return 1; if($ar[$size-1]!=($size+1)) return $size+1; $a = 0; $b = $size - 1; $mid; while (($b - $a) > 1) { $mid = (int)(($a + $b) / 2); if (($ar[$a] - $a) != ($ar[$mid] - $mid)) $b = $mid; else if (($ar[$b] - $b) != ($ar[$mid] - $mid)) $a = $mid; } return ($ar[$a] + 1);} // Driver Code$ar = array(1, 2, 3, 4, 5, 6, 8 );$size = sizeof($ar);echo \"Missing number: \", search($ar, $size); // This code is contributed by ajit.?>", "e": 31622, "s": 30837, "text": null }, { "code": "<script>// A binary search based program// to find the only missing number// in a sorted array of distinct// elements within limited range. function findMissing(arr) { var size = arr.length; //Extreme cases if(ar[0]!=1) return 1; if(ar[size-1]!=(size+1)) return size+1; var low = 0; var high = arr.length; while (low <= high) { var mid = Math.floor((low+high)/2); if ((arr[mid]-mid === 1) && (arr[mid+1]-(mid+1) === 2)) return arr[mid]+1; if (arr[mid]-mid === 1) { low = mid+1; } else { high = mid-1; } } return -1;} // Driver Code let ar = [1, 2, 3, 4, 5, 6, 8];document.write(\"Missing number: \" +findMissing(ar)); // This code is contributed by mohit kumar 29.</script>", "e": 32354, "s": 31622, "text": null }, { "code": null, "e": 32371, "s": 32354, "text": "Missing number:7" }, { "code": null, "e": 32457, "s": 32371, "text": "Time Complexity: O(log(N)), where N is the length of given arrayAuxiliary Space: O(1)" }, { "code": null, "e": 32468, "s": 32457, "text": "inderDuMCA" }, { "code": null, "e": 32479, "s": 32468, "text": "andrew1234" }, { "code": null, "e": 32494, "s": 32479, "text": "mohit kumar 29" }, { "code": null, "e": 32500, "s": 32494, "text": "jit_t" }, { "code": null, "e": 32509, "s": 32500, "text": "ryan1219" }, { "code": null, "e": 32524, "s": 32509, "text": "hitesh aleriya" }, { "code": null, "e": 32540, "s": 32524, "text": "pushpeshrajdx01" }, { "code": null, "e": 32554, "s": 32540, "text": "Binary Search" }, { "code": null, "e": 32577, "s": 32554, "text": "limited-range-elements" }, { "code": null, "e": 32596, "s": 32577, "text": "Divide and Conquer" }, { "code": null, "e": 32606, "s": 32596, "text": "Searching" }, { "code": null, "e": 32616, "s": 32606, "text": "Searching" }, { "code": null, "e": 32635, "s": 32616, "text": "Divide and Conquer" }, { "code": null, "e": 32649, "s": 32635, "text": "Binary Search" }, { "code": null, "e": 32747, "s": 32649, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32774, "s": 32747, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 32818, "s": 32774, "text": "Divide and Conquer Algorithm | Introduction" }, { "code": null, "e": 32865, "s": 32818, "text": "Median of two sorted arrays of different sizes" }, { "code": null, "e": 32903, "s": 32865, "text": "Write a program to calculate pow(x,n)" }, { "code": null, "e": 32964, "s": 32903, "text": "Count number of occurrences (or frequency) in a sorted array" }, { "code": null, "e": 32978, "s": 32964, "text": "Linear Search" }, { "code": null, "e": 33034, "s": 32978, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 33078, "s": 33034, "text": "Program to find largest element in an array" }, { "code": null, "e": 33169, "s": 33078, "text": "Given an array of size n and a number k, find all elements that appear more than n/k times" } ]
How to declare the optional function parameters in JavaScript ? - GeeksforGeeks
10 Jun, 2019 To declare optional function parameters in JavaScript, there are two approaches: Using the Logical OR operator (‘||’):In this approach, the optional parameter is Logically ORed with the default value within the body of the function.Note: The optional parameters should always come at the end on the parameter list.Syntax:function myFunc(a,b) { b = b || 0; // b will be set either to b or to 0. } Example 1: In the following program the optional parameter is ‘b’:<script> function check(a, b) { b = b || 0; document.write("Value of a is: " + a + " Value of b is: " + b + "<br>"); } check(5, 3); check(10); </script>Output: Note: The optional parameters should always come at the end on the parameter list. Syntax: function myFunc(a,b) { b = b || 0; // b will be set either to b or to 0. } Example 1: In the following program the optional parameter is ‘b’: <script> function check(a, b) { b = b || 0; document.write("Value of a is: " + a + " Value of b is: " + b + "<br>"); } check(5, 3); check(10); </script> Output: Using the Assignment operator (“=”):In this approach the optional variable is assigned the default value in the declaration statement itself.Note: The optional parameters should always come at the end on the parameter list.Syntax:function myFunc(a, b = 0) { // function body }Example 2: In the following program the optional parameter is ‘b’:<script> function check(a, b = 0) { document.write("Value of a is: " + a + " Value of b is: " + b + "<br>"); } check(9, 10); check(1); </script>Output: Note: The optional parameters should always come at the end on the parameter list. Syntax: function myFunc(a, b = 0) { // function body } Example 2: In the following program the optional parameter is ‘b’: <script> function check(a, b = 0) { document.write("Value of a is: " + a + " Value of b is: " + b + "<br>"); } check(9, 10); check(1); </script> Output: javascript-functions JavaScript-Misc Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Difference Between PUT and PATCH Request 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": 26197, "s": 26169, "text": "\n10 Jun, 2019" }, { "code": null, "e": 26278, "s": 26197, "text": "To declare optional function parameters in JavaScript, there are two approaches:" }, { "code": null, "e": 26893, "s": 26278, "text": "Using the Logical OR operator (‘||’):In this approach, the optional parameter is Logically ORed with the default value within the body of the function.Note: The optional parameters should always come at the end on the parameter list.Syntax:function myFunc(a,b) {\n b = b || 0;\n // b will be set either to b or to 0.\n}\nExample 1: In the following program the optional parameter is ‘b’:<script> function check(a, b) { b = b || 0; document.write(\"Value of a is: \" + a + \" Value of b is: \" + b + \"<br>\"); } check(5, 3); check(10); </script>Output:" }, { "code": null, "e": 26976, "s": 26893, "text": "Note: The optional parameters should always come at the end on the parameter list." }, { "code": null, "e": 26984, "s": 26976, "text": "Syntax:" }, { "code": null, "e": 27064, "s": 26984, "text": "function myFunc(a,b) {\n b = b || 0;\n // b will be set either to b or to 0.\n}\n" }, { "code": null, "e": 27131, "s": 27064, "text": "Example 1: In the following program the optional parameter is ‘b’:" }, { "code": "<script> function check(a, b) { b = b || 0; document.write(\"Value of a is: \" + a + \" Value of b is: \" + b + \"<br>\"); } check(5, 3); check(10); </script>", "e": 27354, "s": 27131, "text": null }, { "code": null, "e": 27362, "s": 27354, "text": "Output:" }, { "code": null, "e": 27924, "s": 27362, "text": "Using the Assignment operator (“=”):In this approach the optional variable is assigned the default value in the declaration statement itself.Note: The optional parameters should always come at the end on the parameter list.Syntax:function myFunc(a, b = 0) {\n // function body\n}Example 2: In the following program the optional parameter is ‘b’:<script> function check(a, b = 0) { document.write(\"Value of a is: \" + a + \" Value of b is: \" + b + \"<br>\"); } check(9, 10); check(1); </script>Output:" }, { "code": null, "e": 28007, "s": 27924, "text": "Note: The optional parameters should always come at the end on the parameter list." }, { "code": null, "e": 28015, "s": 28007, "text": "Syntax:" }, { "code": null, "e": 28065, "s": 28015, "text": "function myFunc(a, b = 0) {\n // function body\n}" }, { "code": null, "e": 28132, "s": 28065, "text": "Example 2: In the following program the optional parameter is ‘b’:" }, { "code": "<script> function check(a, b = 0) { document.write(\"Value of a is: \" + a + \" Value of b is: \" + b + \"<br>\"); } check(9, 10); check(1); </script>", "e": 28342, "s": 28132, "text": null }, { "code": null, "e": 28350, "s": 28342, "text": "Output:" }, { "code": null, "e": 28371, "s": 28350, "text": "javascript-functions" }, { "code": null, "e": 28387, "s": 28371, "text": "JavaScript-Misc" }, { "code": null, "e": 28394, "s": 28387, "text": "Picked" }, { "code": null, "e": 28405, "s": 28394, "text": "JavaScript" }, { "code": null, "e": 28422, "s": 28405, "text": "Web Technologies" }, { "code": null, "e": 28520, "s": 28422, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28560, "s": 28520, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28605, "s": 28560, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28666, "s": 28605, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28738, "s": 28666, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28779, "s": 28738, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28819, "s": 28779, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28852, "s": 28819, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28897, "s": 28852, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28940, "s": 28897, "text": "How to fetch data from an API in ReactJS ?" } ]
Program for sum of arithmetic series - GeeksforGeeks
01 Apr, 2021 A series with same common difference is known as arithmetic series. The first term of series is a and common difference is d. The series is looks like a, a + d, a + 2d, a + 3d, . . . Task is to find the sum of series. Examples: Input : a = 1 d = 2 n = 4 Output : 16 1 + 3 + 5 + 7 = 16 Input : a = 2.5 d = 1.5 n = 20 Output : 335 A simple solution to find sum of arithmetic series. C++ Java Python C# PHP Javascript // CPP Program to find the sum of arithmetic// series.#include<bits/stdc++.h>using namespace std; // Function to find sum of series.float sumOfAP(float a, float d, int n){ float sum = 0; for (int i=0;i<n;i++) { sum = sum + a; a = a + d; } return sum;} // Driver functionint main(){ int n = 20; float a = 2.5, d = 1.5; cout<<sumOfAP(a, d, n); return 0;} // JAVA Program to find the sum of// arithmetic series. class GFG{ // Function to find sum of series. static float sumOfAP(float a, float d, int n) { float sum = 0; for (int i = 0; i < n; i++) { sum = sum + a; a = a + d; } return sum; } // Driver function public static void main(String args[]) { int n = 20; float a = 2.5f, d = 1.5f; System.out.println(sumOfAP(a, d, n)); }} /*This code is contributed by Nikita Tiwari.*/ # Python Program to find the sum of# arithmetic series. # Function to find sum of series.def sumOfAP( a, d,n) : sum = 0 i = 0 while i < n : sum = sum + a a = a + d i = i + 1 return sum # Driver functionn = 20a = 2.5d = 1.5print (sumOfAP(a, d, n)) # This code is contributed by Nikita Tiwari. // C# Program to find the sum of// arithmetic series.using System; class GFG { // Function to find sum of series. static float sumOfAP(float a, float d, int n) { float sum = 0; for (int i = 0; i < n; i++) { sum = sum + a; a = a + d; } return sum; } // Driver function public static void Main() { int n = 20; float a = 2.5f, d = 1.5f; Console.Write(sumOfAP(a, d, n)); }} // This code is contributed by parashar. <?php// PHP Program to find the sum // of arithmetic series. // Function to find sum of series.function sumOfAP($a, $d, $n){ $sum = 0; for ($i = 0; $i < $n; $i++) { $sum = $sum + $a; $a = $a + $d; } return $sum;} // Driver Code$n = 20;$a = 2.5; $d = 1.5;echo(sumOfAP($a, $d, $n)); // This code is contributed by Ajit.?> <script> // Javascript Program to find the sum of arithmetic// series. // Function to find sum of series.function sumOfAP(a, d, n){ let sum = 0; for (let i=0;i<n;i++) { sum = sum + a; a = a + d; } return sum;} // Driver function let n = 20; let a = 2.5, d = 1.5; document.write(sumOfAP(a, d, n)); // This code is contributed by Mayank Tyagi </script> Output: 335 Time Complexity: O(n)An Efficient solution to find the sum of arithmetic series is to use below formula. Sum of arithmetic series = ((n / 2) * (2 * a + (n - 1) * d)) Where a - First term d - Common difference n - No of terms C++ Java Python3 C# PHP Javascript // Efficient solution to find sum of arithmetic series.#include<bits/stdc++.h>using namespace std; float sumOfAP(float a, float d, float n){ float sum = (n / 2) * (2 * a + (n - 1) * d); return sum;} // Driver codeint main(){ float n = 20; float a = 2.5, d = 1.5; cout<<sumOfAP(a, d, n); return 0;} // Java Efficient solution to find// sum of arithmetic series.class GFG{ static float sumOfAP(float a, float d, float n) { float sum = (n / 2) * (2 * a + (n - 1) * d); return sum; } // Driver code public static void main (String[] args) { float n = 20; float a = 2.5f, d = 1.5f; System.out.print(sumOfAP(a, d, n)); }} // This code is contributed by Anant Agarwal. # Python3 Efficient# solution to find sum# of arithmetic series. def sumOfAP(a, d, n): sum = (n / 2) * (2 * a + (n - 1) * d) return sum # Driver code n = 20a = 2.5d = 1.5 print(sumOfAP(a, d, n)) # This code is# contributed by sunnysingh // C# efficient solution to find// sum of arithmetic series.using System; class GFG { static float sumOfAP(float a, float d, float n) { float sum = (n / 2) * (2 * a + (n - 1) * d); return sum; } // Driver code static public void Main () { float n = 20; float a = 2.5f, d = 1.5f; Console.WriteLine(sumOfAP(a, d, n)); }} // This code is contributed by Ajit. <?php// Efficient PHP code to find sum// of arithmetic series. // Function to find sum of series.function sumOfAP($a, $d, $n){ $sum = ($n / 2) * (2 * $a + ($n - 1) * $d); return $sum;} // Driver code$n = 20;$a = 2.5; $d = 1.5;echo(sumOfAP($a, $d, $n)); // This code is contributed by Ajit.?> // Efficient solution to find sum of arithmetic series. function sumOfAP(a, d, n) { let sum = (n / 2) * (2 * a + (n - 1) * d); return sum;} // Driver codelet n = 20;let a = 2.5, d = 1.5;document.write(sumOfAP(a, d, n)); // This code is contributed by Ashok 335 Time Complexity: O(1)How does this formula work? We can prove the formula using mathematical induction. We can easily see that the formula holds true for n = 1 and n = 2. Let this be true for n = k-1. Let the formula be true for n = k-1. Sum of first k - 1 elements of geometric series is = (((k-1))/ 2) * (2 * a + (k - 2) * d)) We know k-th term of arithmetic series is = a + (k - 1)*d Sum of first k elements = = Sum of (k-1) numbers + k-th element = (((k-1)/2)*(2*a + (k-2)*d)) + (a + (k-1)*d) = [((k-1)(2a + (k-2)d) + (2a + 2kd - 2d)]/2 = ((k / 2) * (2 * a + (k - 1) * d)) This article is contributed by Dharmendra kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. parashar jit_t iakashkhanra mayanktyagi1709 AshokJaiswal series Mathematical School Programming Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Sieve of Eratosthenes Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26685, "s": 26657, "text": "\n01 Apr, 2021" }, { "code": null, "e": 26915, "s": 26685, "text": "A series with same common difference is known as arithmetic series. The first term of series is a and common difference is d. The series is looks like a, a + d, a + 2d, a + 3d, . . . Task is to find the sum of series. Examples: " }, { "code": null, "e": 27049, "s": 26915, "text": "Input : a = 1\n d = 2\n n = 4\nOutput : 16\n1 + 3 + 5 + 7 = 16\n\nInput : a = 2.5\n d = 1.5\n n = 20\nOutput : 335" }, { "code": null, "e": 27105, "s": 27051, "text": "A simple solution to find sum of arithmetic series. " }, { "code": null, "e": 27109, "s": 27105, "text": "C++" }, { "code": null, "e": 27114, "s": 27109, "text": "Java" }, { "code": null, "e": 27121, "s": 27114, "text": "Python" }, { "code": null, "e": 27124, "s": 27121, "text": "C#" }, { "code": null, "e": 27128, "s": 27124, "text": "PHP" }, { "code": null, "e": 27139, "s": 27128, "text": "Javascript" }, { "code": "// CPP Program to find the sum of arithmetic// series.#include<bits/stdc++.h>using namespace std; // Function to find sum of series.float sumOfAP(float a, float d, int n){ float sum = 0; for (int i=0;i<n;i++) { sum = sum + a; a = a + d; } return sum;} // Driver functionint main(){ int n = 20; float a = 2.5, d = 1.5; cout<<sumOfAP(a, d, n); return 0;}", "e": 27533, "s": 27139, "text": null }, { "code": "// JAVA Program to find the sum of// arithmetic series. class GFG{ // Function to find sum of series. static float sumOfAP(float a, float d, int n) { float sum = 0; for (int i = 0; i < n; i++) { sum = sum + a; a = a + d; } return sum; } // Driver function public static void main(String args[]) { int n = 20; float a = 2.5f, d = 1.5f; System.out.println(sumOfAP(a, d, n)); }} /*This code is contributed by Nikita Tiwari.*/", "e": 28101, "s": 27533, "text": null }, { "code": "# Python Program to find the sum of# arithmetic series. # Function to find sum of series.def sumOfAP( a, d,n) : sum = 0 i = 0 while i < n : sum = sum + a a = a + d i = i + 1 return sum # Driver functionn = 20a = 2.5d = 1.5print (sumOfAP(a, d, n)) # This code is contributed by Nikita Tiwari.", "e": 28430, "s": 28101, "text": null }, { "code": "// C# Program to find the sum of// arithmetic series.using System; class GFG { // Function to find sum of series. static float sumOfAP(float a, float d, int n) { float sum = 0; for (int i = 0; i < n; i++) { sum = sum + a; a = a + d; } return sum; } // Driver function public static void Main() { int n = 20; float a = 2.5f, d = 1.5f; Console.Write(sumOfAP(a, d, n)); }} // This code is contributed by parashar.", "e": 29006, "s": 28430, "text": null }, { "code": "<?php// PHP Program to find the sum // of arithmetic series. // Function to find sum of series.function sumOfAP($a, $d, $n){ $sum = 0; for ($i = 0; $i < $n; $i++) { $sum = $sum + $a; $a = $a + $d; } return $sum;} // Driver Code$n = 20;$a = 2.5; $d = 1.5;echo(sumOfAP($a, $d, $n)); // This code is contributed by Ajit.?>", "e": 29355, "s": 29006, "text": null }, { "code": "<script> // Javascript Program to find the sum of arithmetic// series. // Function to find sum of series.function sumOfAP(a, d, n){ let sum = 0; for (let i=0;i<n;i++) { sum = sum + a; a = a + d; } return sum;} // Driver function let n = 20; let a = 2.5, d = 1.5; document.write(sumOfAP(a, d, n)); // This code is contributed by Mayank Tyagi </script>", "e": 29750, "s": 29355, "text": null }, { "code": null, "e": 29759, "s": 29750, "text": "Output: " }, { "code": null, "e": 29763, "s": 29759, "text": "335" }, { "code": null, "e": 29870, "s": 29763, "text": "Time Complexity: O(n)An Efficient solution to find the sum of arithmetic series is to use below formula. " }, { "code": null, "e": 30058, "s": 29870, "text": "Sum of arithmetic series \n = ((n / 2) * (2 * a + (n - 1) * d))\n Where\n a - First term\n d - Common difference\n n - No of terms" }, { "code": null, "e": 30064, "s": 30060, "text": "C++" }, { "code": null, "e": 30069, "s": 30064, "text": "Java" }, { "code": null, "e": 30077, "s": 30069, "text": "Python3" }, { "code": null, "e": 30080, "s": 30077, "text": "C#" }, { "code": null, "e": 30084, "s": 30080, "text": "PHP" }, { "code": null, "e": 30095, "s": 30084, "text": "Javascript" }, { "code": "// Efficient solution to find sum of arithmetic series.#include<bits/stdc++.h>using namespace std; float sumOfAP(float a, float d, float n){ float sum = (n / 2) * (2 * a + (n - 1) * d); return sum;} // Driver codeint main(){ float n = 20; float a = 2.5, d = 1.5; cout<<sumOfAP(a, d, n); return 0;}", "e": 30411, "s": 30095, "text": null }, { "code": "// Java Efficient solution to find// sum of arithmetic series.class GFG{ static float sumOfAP(float a, float d, float n) { float sum = (n / 2) * (2 * a + (n - 1) * d); return sum; } // Driver code public static void main (String[] args) { float n = 20; float a = 2.5f, d = 1.5f; System.out.print(sumOfAP(a, d, n)); }} // This code is contributed by Anant Agarwal.", "e": 30832, "s": 30411, "text": null }, { "code": "# Python3 Efficient# solution to find sum# of arithmetic series. def sumOfAP(a, d, n): sum = (n / 2) * (2 * a + (n - 1) * d) return sum # Driver code n = 20a = 2.5d = 1.5 print(sumOfAP(a, d, n)) # This code is# contributed by sunnysingh ", "e": 31086, "s": 30832, "text": null }, { "code": "// C# efficient solution to find// sum of arithmetic series.using System; class GFG { static float sumOfAP(float a, float d, float n) { float sum = (n / 2) * (2 * a + (n - 1) * d); return sum; } // Driver code static public void Main () { float n = 20; float a = 2.5f, d = 1.5f; Console.WriteLine(sumOfAP(a, d, n)); }} // This code is contributed by Ajit.", "e": 31594, "s": 31086, "text": null }, { "code": "<?php// Efficient PHP code to find sum// of arithmetic series. // Function to find sum of series.function sumOfAP($a, $d, $n){ $sum = ($n / 2) * (2 * $a + ($n - 1) * $d); return $sum;} // Driver code$n = 20;$a = 2.5; $d = 1.5;echo(sumOfAP($a, $d, $n)); // This code is contributed by Ajit.?>", "e": 31907, "s": 31594, "text": null }, { "code": "// Efficient solution to find sum of arithmetic series. function sumOfAP(a, d, n) { let sum = (n / 2) * (2 * a + (n - 1) * d); return sum;} // Driver codelet n = 20;let a = 2.5, d = 1.5;document.write(sumOfAP(a, d, n)); // This code is contributed by Ashok", "e": 32170, "s": 31907, "text": null }, { "code": null, "e": 32174, "s": 32170, "text": "335" }, { "code": null, "e": 32377, "s": 32174, "text": "Time Complexity: O(1)How does this formula work? We can prove the formula using mathematical induction. We can easily see that the formula holds true for n = 1 and n = 2. Let this be true for n = k-1. " }, { "code": null, "e": 32795, "s": 32377, "text": "Let the formula be true for n = k-1.\nSum of first k - 1 elements of geometric series is\n = (((k-1))/ 2) * (2 * a + (k - 2) * d))\nWe know k-th term of arithmetic series is\n = a + (k - 1)*d\n\nSum of first k elements = \n = Sum of (k-1) numbers + k-th element\n = (((k-1)/2)*(2*a + (k-2)*d)) + (a + (k-1)*d)\n = [((k-1)(2a + (k-2)d) + (2a + 2kd - 2d)]/2\n = ((k / 2) * (2 * a + (k - 1) * d))" }, { "code": null, "e": 33220, "s": 32795, "text": "This article is contributed by Dharmendra kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 33229, "s": 33220, "text": "parashar" }, { "code": null, "e": 33235, "s": 33229, "text": "jit_t" }, { "code": null, "e": 33248, "s": 33235, "text": "iakashkhanra" }, { "code": null, "e": 33264, "s": 33248, "text": "mayanktyagi1709" }, { "code": null, "e": 33277, "s": 33264, "text": "AshokJaiswal" }, { "code": null, "e": 33284, "s": 33277, "text": "series" }, { "code": null, "e": 33297, "s": 33284, "text": "Mathematical" }, { "code": null, "e": 33316, "s": 33297, "text": "School Programming" }, { "code": null, "e": 33329, "s": 33316, "text": "Mathematical" }, { "code": null, "e": 33336, "s": 33329, "text": "series" }, { "code": null, "e": 33434, "s": 33336, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33458, "s": 33434, "text": "Merge two sorted arrays" }, { "code": null, "e": 33501, "s": 33458, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 33515, "s": 33501, "text": "Prime Numbers" }, { "code": null, "e": 33557, "s": 33515, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 33579, "s": 33557, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 33597, "s": 33579, "text": "Python Dictionary" }, { "code": null, "e": 33613, "s": 33597, "text": "Arrays in C/C++" }, { "code": null, "e": 33632, "s": 33613, "text": "Inheritance in C++" }, { "code": null, "e": 33657, "s": 33632, "text": "Reverse a string in Java" } ]
C++ Program to print Fibonacci Series using Class template - GeeksforGeeks
10 Oct, 2019 Given a number n, the task is to write a program in C++ to print the n-terms of Fibonacci Series using a Class templateThe Fibonacci numbers are the numbers in the following integer sequence. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ........ Examples: Input: n = 2 Output: 0, 1 Input: n = 9 Output: 0, 1, 1, 2, 3, 5, 8, 13, 21 Approach: Create a class for the Fibonacci Series Take the first two terms of the series as public members a and b with values 0 and 1, respectively. Create a generate() method in this class to generate the Fibonacci Series. Create an object of this class and call the generate() method of this class using that object. The Fibonacci Series will get printed. Below is the implementation of the above approach: // C++ Program to print Fibonacci// Series using Class template #include <bits/stdc++.h>using namespace std; // Creating class for Fibonacci.class Fibonacci { // Taking the integers as public.public: int a, b, c; void generate(int);}; void Fibonacci::generate(int n){ a = 0; b = 1; cout << a << " " << b; // Using for loop for continuing // the Fibonacci series. for (int i = 1; i <= n - 2; i++) { // Addition of the previous two terms // to get the next term. c = a + b; cout << " " << c; // Converting the new term // into an old term to get // more new terms in series. a = b; b = c; }} // Driver codeint main(){ int n = 9; Fibonacci fib; fib.generate(n); return 0;} 0 1 1 2 3 5 8 13 21 Fibonacci C++ Programs Fibonacci Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Shallow Copy and Deep Copy in C++ Passing a function as a parameter in C++ cin in C++ CSV file management using C++ C Program to Swap two Numbers Program to implement Singly Linked List in C++ using class C++ Program to check if a given String is Palindrome or not Const keyword in C++ Generics in C++ How to find the minimum and maximum element of a Vector using STL in C++?
[ { "code": null, "e": 26051, "s": 26023, "text": "\n10 Oct, 2019" }, { "code": null, "e": 26243, "s": 26051, "text": "Given a number n, the task is to write a program in C++ to print the n-terms of Fibonacci Series using a Class templateThe Fibonacci numbers are the numbers in the following integer sequence." }, { "code": null, "e": 26298, "s": 26243, "text": "0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ........" }, { "code": null, "e": 26308, "s": 26298, "text": "Examples:" }, { "code": null, "e": 26385, "s": 26308, "text": "Input: n = 2\nOutput: 0, 1\n\nInput: n = 9\nOutput: 0, 1, 1, 2, 3, 5, 8, 13, 21\n" }, { "code": null, "e": 26395, "s": 26385, "text": "Approach:" }, { "code": null, "e": 26435, "s": 26395, "text": "Create a class for the Fibonacci Series" }, { "code": null, "e": 26535, "s": 26435, "text": "Take the first two terms of the series as public members a and b with values 0 and 1, respectively." }, { "code": null, "e": 26610, "s": 26535, "text": "Create a generate() method in this class to generate the Fibonacci Series." }, { "code": null, "e": 26705, "s": 26610, "text": "Create an object of this class and call the generate() method of this class using that object." }, { "code": null, "e": 26744, "s": 26705, "text": "The Fibonacci Series will get printed." }, { "code": null, "e": 26795, "s": 26744, "text": "Below is the implementation of the above approach:" }, { "code": "// C++ Program to print Fibonacci// Series using Class template #include <bits/stdc++.h>using namespace std; // Creating class for Fibonacci.class Fibonacci { // Taking the integers as public.public: int a, b, c; void generate(int);}; void Fibonacci::generate(int n){ a = 0; b = 1; cout << a << \" \" << b; // Using for loop for continuing // the Fibonacci series. for (int i = 1; i <= n - 2; i++) { // Addition of the previous two terms // to get the next term. c = a + b; cout << \" \" << c; // Converting the new term // into an old term to get // more new terms in series. a = b; b = c; }} // Driver codeint main(){ int n = 9; Fibonacci fib; fib.generate(n); return 0;}", "e": 27586, "s": 26795, "text": null }, { "code": null, "e": 27607, "s": 27586, "text": "0 1 1 2 3 5 8 13 21\n" }, { "code": null, "e": 27617, "s": 27607, "text": "Fibonacci" }, { "code": null, "e": 27630, "s": 27617, "text": "C++ Programs" }, { "code": null, "e": 27640, "s": 27630, "text": "Fibonacci" }, { "code": null, "e": 27738, "s": 27640, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27772, "s": 27738, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 27813, "s": 27772, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 27824, "s": 27813, "text": "cin in C++" }, { "code": null, "e": 27854, "s": 27824, "text": "CSV file management using C++" }, { "code": null, "e": 27884, "s": 27854, "text": "C Program to Swap two Numbers" }, { "code": null, "e": 27943, "s": 27884, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 28003, "s": 27943, "text": "C++ Program to check if a given String is Palindrome or not" }, { "code": null, "e": 28024, "s": 28003, "text": "Const keyword in C++" }, { "code": null, "e": 28040, "s": 28024, "text": "Generics in C++" } ]
PYGLET – Unformatted Document - GeeksforGeeks
10 Jun, 2021 In this article we will see how we can create a unformatted document in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a “heavyweight” object occupying operating system resources. Windows may appear as floating regions or can be set to fill an entire screen (fullscreen). Unformatted documents are generally laid out to make copy paste easy without adding structure, such as headings, indentation, font variations. In order words we can say this document contains plain text. We can create a window with the help of command given below # creating a window window = pyglet.window.Window(width, height, title) In order to create window we use pyglet.text.document.UnformattedDocument( methodSyntax : pyglet.text.document.UnformattedDocument(text)Argument : It takes string as argumentReturn : It returns UnformattedDocument object Below is the implementation Python3 # importing pyglet moduleimport pygletimport pyglet.window.key # width of windowwidth = 500 # height of windowheight = 500 # caption i.e title of the windowtitle = "Geeksforgeeks" # creating a windowwindow = pyglet.window.Window(width, height, title) # texttext = "GeeksforGeeks Learn and Grow" # batch objectbatch = pyglet.graphics.Batch() # creating a unformatted document# unlike formatted document it is just plain textdocument = pyglet.text.document.UnformattedDocument(text) # setting style to the documentdocument.set_style(0, len(document.text), dict(font_name ='Arial', font_size = 16, color =(255, 255, 255, 255))) # creating a incremental text layoutlayout = pyglet.text.layout.IncrementalTextLayout(document, 400, 350, batch = batch) # creating a caretcaret = pyglet.text.caret.Caret(layout, color =(150, 255, 150)) # caret to window push handlerswindow.push_handlers(caret) # setting caret stylecaret.set_style(dict(font_name ="Arial")) # on draw [email protected] on_draw(): # clear the window window.clear() # draw the batch batch.draw() # caret to window push handlers window.push_handlers(caret) # key press event @window.eventdef on_key_press(symbol, modifier): # key "C" get press if symbol == pyglet.window.key.C: # closing the window # window.close() pass # image for iconimg = pyglet.resource.image("gfg.png") # setting image as iconwindow.set_icon(img) # start running the applicationpyglet.app.run() Output : anikakapoor Python-gui Python-Pyglet 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 Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n10 Jun, 2021" }, { "code": null, "e": 26120, "s": 25537, "text": "In this article we will see how we can create a unformatted document in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a “heavyweight” object occupying operating system resources. Windows may appear as floating regions or can be set to fill an entire screen (fullscreen). Unformatted documents are generally laid out to make copy paste easy without adding structure, such as headings, indentation, font variations. In order words we can say this document contains plain text." }, { "code": null, "e": 26181, "s": 26120, "text": "We can create a window with the help of command given below " }, { "code": null, "e": 26255, "s": 26181, "text": "# creating a window\nwindow = pyglet.window.Window(width, height, title)\n " }, { "code": null, "e": 26478, "s": 26255, "text": "In order to create window we use pyglet.text.document.UnformattedDocument( methodSyntax : pyglet.text.document.UnformattedDocument(text)Argument : It takes string as argumentReturn : It returns UnformattedDocument object " }, { "code": null, "e": 26508, "s": 26478, "text": "Below is the implementation " }, { "code": null, "e": 26516, "s": 26508, "text": "Python3" }, { "code": "# importing pyglet moduleimport pygletimport pyglet.window.key # width of windowwidth = 500 # height of windowheight = 500 # caption i.e title of the windowtitle = \"Geeksforgeeks\" # creating a windowwindow = pyglet.window.Window(width, height, title) # texttext = \"GeeksforGeeks Learn and Grow\" # batch objectbatch = pyglet.graphics.Batch() # creating a unformatted document# unlike formatted document it is just plain textdocument = pyglet.text.document.UnformattedDocument(text) # setting style to the documentdocument.set_style(0, len(document.text), dict(font_name ='Arial', font_size = 16, color =(255, 255, 255, 255))) # creating a incremental text layoutlayout = pyglet.text.layout.IncrementalTextLayout(document, 400, 350, batch = batch) # creating a caretcaret = pyglet.text.caret.Caret(layout, color =(150, 255, 150)) # caret to window push handlerswindow.push_handlers(caret) # setting caret stylecaret.set_style(dict(font_name =\"Arial\")) # on draw [email protected] on_draw(): # clear the window window.clear() # draw the batch batch.draw() # caret to window push handlers window.push_handlers(caret) # key press event @window.eventdef on_key_press(symbol, modifier): # key \"C\" get press if symbol == pyglet.window.key.C: # closing the window # window.close() pass # image for iconimg = pyglet.resource.image(\"gfg.png\") # setting image as iconwindow.set_icon(img) # start running the applicationpyglet.app.run()", "e": 28051, "s": 26516, "text": null }, { "code": null, "e": 28062, "s": 28051, "text": "Output : " }, { "code": null, "e": 28076, "s": 28064, "text": "anikakapoor" }, { "code": null, "e": 28087, "s": 28076, "text": "Python-gui" }, { "code": null, "e": 28101, "s": 28087, "text": "Python-Pyglet" }, { "code": null, "e": 28108, "s": 28101, "text": "Python" }, { "code": null, "e": 28206, "s": 28108, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28238, "s": 28206, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28280, "s": 28238, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28322, "s": 28280, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28349, "s": 28322, "text": "Python Classes and Objects" }, { "code": null, "e": 28405, "s": 28349, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28427, "s": 28405, "text": "Defaultdict in Python" }, { "code": null, "e": 28466, "s": 28427, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28497, "s": 28466, "text": "Python | os.path.join() method" }, { "code": null, "e": 28526, "s": 28497, "text": "Create a directory in Python" } ]
Python Program to find the Quotient and Remainder of two numbers - GeeksforGeeks
29 Aug, 2020 Given two numbers n and m. The task is to find the quotient and remainder of two numbers by dividing n by m. Examples: Input: n = 10 m = 3 Output: Quotient: 3 Remainder 1 Input n = 99 m = 5 Output: Quotient: 19 Remainder 4 Method 1: Naive approach The naive approach is to find the quotient using the double division (//) operator and remainder using the modulus (%) operator. Example: Python3 # Python program to find the# quotient and remainder def find(n, m): # for quotient q = n//m print("Quotient: ", q) # for remainder r = n%m print("Remainder", r) # Driver Codefind(10, 3)find(99, 5) Output: Quotient: 3 Remainder 1 Quotient: 19 Remainder 4 Method 2: Using divmod() method Divmod() method takes two numbers as parameters and returns the tuple containing both quotient and remainder. Example: Python3 # Python program to find the# quotient and remainder using# divmod() method q, r = divmod(10, 3)print("Quotient: ", q)print("Remainder: ", r) q, r = divmod(99, 5)print("Quotient: ", q)print("Remainder: ", r) Output: Quotient: 3 Remainder 1 Quotient: 19 Remainder 4 Number Divisibility Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25562, "s": 25534, "text": "\n29 Aug, 2020" }, { "code": null, "e": 25671, "s": 25562, "text": "Given two numbers n and m. The task is to find the quotient and remainder of two numbers by dividing n by m." }, { "code": null, "e": 25681, "s": 25671, "text": "Examples:" }, { "code": null, "e": 25789, "s": 25681, "text": "Input:\nn = 10\nm = 3\nOutput:\nQuotient: 3\nRemainder 1\n\nInput\nn = 99\nm = 5\nOutput:\nQuotient: 19\nRemainder 4\n" }, { "code": null, "e": 25814, "s": 25789, "text": "Method 1: Naive approach" }, { "code": null, "e": 25943, "s": 25814, "text": "The naive approach is to find the quotient using the double division (//) operator and remainder using the modulus (%) operator." }, { "code": null, "e": 25952, "s": 25943, "text": "Example:" }, { "code": null, "e": 25960, "s": 25952, "text": "Python3" }, { "code": "# Python program to find the# quotient and remainder def find(n, m): # for quotient q = n//m print(\"Quotient: \", q) # for remainder r = n%m print(\"Remainder\", r) # Driver Codefind(10, 3)find(99, 5)", "e": 26194, "s": 25960, "text": null }, { "code": null, "e": 26202, "s": 26194, "text": "Output:" }, { "code": null, "e": 26254, "s": 26202, "text": "Quotient: 3\nRemainder 1\nQuotient: 19\nRemainder 4\n" }, { "code": null, "e": 26286, "s": 26254, "text": "Method 2: Using divmod() method" }, { "code": null, "e": 26396, "s": 26286, "text": "Divmod() method takes two numbers as parameters and returns the tuple containing both quotient and remainder." }, { "code": null, "e": 26405, "s": 26396, "text": "Example:" }, { "code": null, "e": 26413, "s": 26405, "text": "Python3" }, { "code": "# Python program to find the# quotient and remainder using# divmod() method q, r = divmod(10, 3)print(\"Quotient: \", q)print(\"Remainder: \", r) q, r = divmod(99, 5)print(\"Quotient: \", q)print(\"Remainder: \", r)", "e": 26625, "s": 26413, "text": null }, { "code": null, "e": 26633, "s": 26625, "text": "Output:" }, { "code": null, "e": 26685, "s": 26633, "text": "Quotient: 3\nRemainder 1\nQuotient: 19\nRemainder 4\n" }, { "code": null, "e": 26705, "s": 26685, "text": "Number Divisibility" }, { "code": null, "e": 26712, "s": 26705, "text": "Python" }, { "code": null, "e": 26728, "s": 26712, "text": "Python Programs" }, { "code": null, "e": 26826, "s": 26728, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26858, "s": 26826, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26900, "s": 26858, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26942, "s": 26900, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26969, "s": 26942, "text": "Python Classes and Objects" }, { "code": null, "e": 27025, "s": 26969, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27047, "s": 27025, "text": "Defaultdict in Python" }, { "code": null, "e": 27086, "s": 27047, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27132, "s": 27086, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27170, "s": 27132, "text": "Python | Convert a list to dictionary" } ]
Possible Words using given characters in Python - GeeksforGeeks
13 Jun, 2019 Given a dictionary and a character array, print all valid words that are possible using characters from the array.Note: Repetitions of characters is not allowed.Examples: Input : Dict = ["go","bat","me","eat","goal","boy", "run"] arr = ['e','o','b', 'a','m','g', 'l'] Output : go, me, goal. This problem has existing solution please refer Print all valid words that are possible using Characters of Array link. We will this problem in python very quickly using Dictionary Data Structure. Approach is very simple : Traverse list of given strings one by one and convert them into dictionary using Counter(input) method of collections module.Check if all keys of any string lies within given set of characters that means this word is possible to create. Traverse list of given strings one by one and convert them into dictionary using Counter(input) method of collections module. Check if all keys of any string lies within given set of characters that means this word is possible to create. # Function to print words which can be created# using given set of characters def charCount(word): dict = {} for i in word: dict[i] = dict.get(i, 0) + 1 return dict def possible_words(lwords, charSet): for word in lwords: flag = 1 chars = charCount(word) for key in chars: if key not in charSet: flag = 0 else: if charSet.count(key) != chars[key]: flag = 0 if flag == 1: print(word) if __name__ == "__main__": input = ['goo', 'bat', 'me', 'eat', 'goal', 'boy', 'run'] charSet = ['e', 'o', 'b', 'a', 'm', 'g', 'l'] possible_words(input, charSet) Output: go me goal vijaymaddukuri Python dictionary-programs python-dict Python Strings python-dict Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Longest Common Subsequence | DP-4
[ { "code": null, "e": 26147, "s": 26119, "text": "\n13 Jun, 2019" }, { "code": null, "e": 26318, "s": 26147, "text": "Given a dictionary and a character array, print all valid words that are possible using characters from the array.Note: Repetitions of characters is not allowed.Examples:" }, { "code": null, "e": 26448, "s": 26318, "text": "Input : Dict = [\"go\",\"bat\",\"me\",\"eat\",\"goal\",\"boy\", \"run\"]\n arr = ['e','o','b', 'a','m','g', 'l']\nOutput : go, me, goal. \n" }, { "code": null, "e": 26671, "s": 26448, "text": "This problem has existing solution please refer Print all valid words that are possible using Characters of Array link. We will this problem in python very quickly using Dictionary Data Structure. Approach is very simple :" }, { "code": null, "e": 26908, "s": 26671, "text": "Traverse list of given strings one by one and convert them into dictionary using Counter(input) method of collections module.Check if all keys of any string lies within given set of characters that means this word is possible to create." }, { "code": null, "e": 27034, "s": 26908, "text": "Traverse list of given strings one by one and convert them into dictionary using Counter(input) method of collections module." }, { "code": null, "e": 27146, "s": 27034, "text": "Check if all keys of any string lies within given set of characters that means this word is possible to create." }, { "code": "# Function to print words which can be created# using given set of characters def charCount(word): dict = {} for i in word: dict[i] = dict.get(i, 0) + 1 return dict def possible_words(lwords, charSet): for word in lwords: flag = 1 chars = charCount(word) for key in chars: if key not in charSet: flag = 0 else: if charSet.count(key) != chars[key]: flag = 0 if flag == 1: print(word) if __name__ == \"__main__\": input = ['goo', 'bat', 'me', 'eat', 'goal', 'boy', 'run'] charSet = ['e', 'o', 'b', 'a', 'm', 'g', 'l'] possible_words(input, charSet)", "e": 27838, "s": 27146, "text": null }, { "code": null, "e": 27846, "s": 27838, "text": "Output:" }, { "code": null, "e": 27859, "s": 27846, "text": "go \nme\ngoal\n" }, { "code": null, "e": 27874, "s": 27859, "text": "vijaymaddukuri" }, { "code": null, "e": 27901, "s": 27874, "text": "Python dictionary-programs" }, { "code": null, "e": 27913, "s": 27901, "text": "python-dict" }, { "code": null, "e": 27920, "s": 27913, "text": "Python" }, { "code": null, "e": 27928, "s": 27920, "text": "Strings" }, { "code": null, "e": 27940, "s": 27928, "text": "python-dict" }, { "code": null, "e": 27948, "s": 27940, "text": "Strings" }, { "code": null, "e": 28046, "s": 27948, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28064, "s": 28046, "text": "Python Dictionary" }, { "code": null, "e": 28096, "s": 28064, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28118, "s": 28096, "text": "Enumerate() in Python" }, { "code": null, "e": 28160, "s": 28118, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28186, "s": 28160, "text": "Python String | replace()" }, { "code": null, "e": 28232, "s": 28186, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 28257, "s": 28232, "text": "Reverse a string in Java" }, { "code": null, "e": 28317, "s": 28257, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 28332, "s": 28317, "text": "C++ Data Types" } ]
Arrange given numbers to form the biggest number | Set 1 - GeeksforGeeks
28 Apr, 2022 Given an array of numbers, arrange them in a way that yields the largest value. For example, if the given numbers are {54, 546, 548, 60}, the arrangement 6054854654 gives the largest value. And if the given numbers are {1, 34, 3, 98, 9, 76, 45, 4}, then the arrangement 998764543431 gives the largest value. A simple solution that comes to our mind is to sort all numbers in descending order, but simply sorting doesn’t work. For example, 548 is greater than 60, but in output 60 comes before 548. As a second example, 98 is greater than 9, but 9 comes before 98 in output. So how do we go about it? The idea is to use any comparison based sorting algorithm. In the used sorting algorithm, instead of using the default comparison, write a comparison function myCompare() and use it to sort numbers. For Python, the procedure is explained in largestNumber() function. Given two numbers X and Y, how should myCompare() decide which number to put first – we compare two numbers XY (Y appended at the end of X) and YX (X appended at the end of Y). If XY is larger, then X should come before Y in output, else Y should come before. For example, let X and Y be 542 and 60. To compare X and Y, we compare 54260 and 60542. Since 60542 is greater than 54260, we put Y first. Following is the implementation of the above approach. To keep the code simple, numbers are considered as strings, the vector is used instead of a normal array. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // Given an array of numbers,// program to arrange the numbers// to form the largest number#include <algorithm>#include <iostream>#include <string>#include <vector>using namespace std; // A comparison function which// is used by sort() in// printLargest()int myCompare(string X, string Y){ // first append Y at the end of X string XY = X.append(Y); // then append X at the end of Y string YX = Y.append(X); // Now see which of the two // formed numbers is greater return XY.compare(YX) > 0 ? 1 : 0;} // The main function that prints// the arrangement with the// largest value. The function// accepts a vector of stringsvoid printLargest(vector<string> arr){ // Sort the numbers using // library sort function. The // function uses our comparison // function myCompare() to // compare two strings. See // http://www.cplusplus.com/reference/ // algorithm/sort/ // for details sort(arr.begin(), arr.end(), myCompare); for (int i = 0; i < arr.size(); i++) cout << arr[i];} // Driver codeint main(){ vector<string> arr; // output should be 6054854654 arr.push_back("54"); arr.push_back("546"); arr.push_back("548"); arr.push_back("60"); printLargest(arr); return 0;} // Given an array of numbers, program to// arrange the numbers to form the// largest numberimport java.util.*; class GFG { // The main function that prints the // arrangement with the largest value. // The function accepts a vector of strings static void printLargest(Vector<String> arr) { Collections.sort(arr, new Comparator<String>() { // A comparison function which is used by // sort() in printLargest() @Override public int compare(String X, String Y) { // first append Y at the end of X String XY = X + Y; // then append X at the end of Y String YX = Y + X; // Now see which of the two // formed numbers // is greater return XY.compareTo(YX) > 0 ? -1 : 1; } }); Iterator it = arr.iterator(); while (it.hasNext()) System.out.print(it.next()); } // Driver code public static void main(String[] args) { Vector<String> arr; arr = new Vector<>(); // output should be 6054854654 arr.add("54"); arr.add("546"); arr.add("548"); arr.add("60"); printLargest(arr); }}// This code is contributed by Shubham Juneja def largestNumber(array): #If there is only one element in the list, the element itself is the largest element. #Below if condition checks the same. if len(array)==1: return str(array[0]) #Below lines are code are used to find the largest element possible. #First, we convert a list into a string array that is suitable for concatenation for i in range(len(array)): array[i]=str(array[i]) # [54,546,548,60]=>['54','546','548','60'] #Second, we find the largest element by swapping technique. for i in range(len(array)): for j in range(1+i,len(array)): if array[j]+array[i]>array[i]+array[j]: array[i],array[j]=array[j],array[i] #['60', '548', '546', '54'] #Refer JOIN function in Python result=''.join(array) #Edge Case: If all elements are 0, answer must be 0 if(result=='0'*len(result)): return '0' else: return result if __name__ == "__main__": a = [54, 546, 548, 60] print(largestNumber(a)) // C# program for above approachusing System.Collections.Generic;using System; namespace LargestNumberClass {class LargestNumberClass { // Given a list of non-negative // integers, // arrange them such that they // form the largest number. // Note: The result may be very // large, so you need to // return a string instead // of an integer. public static void LargestNumberMethod(List<int> inputList) { string output = string.Empty; List<string> newList = inputList.ConvertAll<string>( delegate(int i) { return i.ToString(); }); newList.Sort(MyCompare); for (int i = 0; i < inputList.Count; i++) { output = output + newList[i]; } if (output[0] == '0' && output.Length > 1) { Console.Write("0"); } Console.Write(output); } internal static int MyCompare(string X, string Y) { // first append Y at the end of X string XY = X + Y; // then append X at the end of Y string YX = Y + X; // Now see which of the two // formed numbers is greater return XY.CompareTo(YX) > 0 ? -1 : 1; }} class Program { // Driver code static void Main(string[] args) { List<int> inputList = new List<int>() { 54, 546, 548, 60 }; LargestNumberClass.LargestNumberMethod(inputList); }}// This code is contributed by Deepak Kumar Singh} <?php// Given an array of numbers, program// to arrange the numbers to form the// largest number // A comparison function which is used// by sort() in printLargest()function myCompare($X, $Y){ // first append Y at the end of X $XY = $Y.$X; // then append X at the end of Y $YX = $X.$Y; // Now see which of the two formed // numbers is greater return strcmp($XY, $YX) > 0 ? 1: 0;} // The main function that prints the// arrangement with the largest value.// The function accepts a vector of stringsfunction printLargest($arr){ // Sort the numbers using library sort // function. The function uses our // comparison function myCompare() to // compare two strings. // See http://www.cplusplus.com/reference/ // algorithm/sort/ // for details usort($arr, "myCompare"); for ($i = 0; $i < count($arr) ; $i++ ) echo $arr[$i];} // Driver Code$arr = array("54", "546", "548", "60");printLargest($arr); // This code is contributed by// rathbhupendra?> <script>// Given an array of numbers,// program to arrange the numbers// to form the largest number // A comparison function which// is used by sort() function in// printLargest() function myCompare(X, Y){ // // first append Y at the end of X let XY = X + Y; // // then append X at the end of Y let YX = Y + X; // // Now see which of the two // // formed numbers is greater return (YX - XY)} // The main function that prints// the arrangement with the// largest value. The function// accepts a vector of strings function printLargest(arr){ // Sort the numbers using // inbuilt sort function. The // function uses our comparison // function myCompare() to // compare two strings. arr.sort(myCompare); for(let i = 0; i < arr.length; i++) document.write(arr[i]) // join method creates a string out of the array elements. document.write(arr.join(""))} // Driver code let arr = []; // output should be 6054854654arr.push("54");arr.push("546");arr.push("548");arr.push("60");printLargest(arr); // This code is contributed by shinjanpatra</script> 6054854654 In the above solution we are allowed strings inputs but in case strings are restricted then also we can solve above problem using long long int to find biggest arrangement. The only limitation is that we can not store numbers greater than 10^18. In case it exceeds that the above solution will be the only option. C++14 // Given an array of numbers,// program to arrange the numbers// to form the largest number#include <algorithm>#include <iostream>#include <string>#include <vector>using namespace std;typedef long long ll; // A comparison function which// is used by sort() in// printLargest()bool myCompare(ll X,ll Y){ // assign X to XY since XY starts with X first // assign Y to YX since YX starts with Y first ll XY=X,YX=Y,revX=0,revY=0; //reverse X and assign to revX while(X) { revX=revX*10+X%10; X/=10; } //reverse Y and assign to revY while(Y) { revY=revY*10+Y%10; Y/=10; } // first append Y at the end of X while(revY) { XY=XY*10+revY%10; revY/=10; } // then append X at the end of Y while(revX) { YX=YX*10+revX%10; revX/=10; } // Now see which of the two // formed numbers is greater return XY>YX;} // The main function that prints// the arrangement with the// largest value. The function// accepts a vector of stringsvoid printLargest(vector<ll> arr){ // Sort the numbers using // library sort function. The // function uses our comparison // function myCompare() to // compare two strings. See // http://www.cplusplus.com/reference/ // algorithm/sort/ // for details sort(arr.begin(), arr.end(), myCompare); for (int i = 0; i < arr.size(); i++) cout << arr[i];} // Driver codeint main(){ vector<ll> arr; // output should be 6054854654 arr.push_back(54); arr.push_back(546); arr.push_back(548); arr.push_back(60); printLargest(arr); return 0;}// this code is contributed by prophet1999 6054854654 Time Complexity: O(n logn) ,sorting is considered to have running time complexity of O(n logn) and the for loop runs in O(n) time.Auxiliary Space: O(1) Another approach:(using itertools) Using the inbuilt library of the Python, itertools library can be used to perform this task. Python3 # Python3 implementation this is to use itertools.# permutations as coded below: from itertools import permutationsdef largest(l): lst = [] for i in permutations(l, len(l)): # provides all permutations of the list values, # store them in list to find max lst.append("".join(map(str,i))) return max(lst) print(largest([54, 546, 548, 60])) #Output 6054854654 # This code is contributed by Raman Monga 6054854654 Time Complexity: O(n!)Auxiliary Space: O(1). This article is compiled by Ravi Chandra Enaganti and improved by prophet1999. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. SaurabhTewary mongaraman rathbhupendra deepak1210 shubham_singh amit143katiyar Rajput-Ji GauravRajput1 mulchandanimanisha5 yshailendra arjunsodhi7 shinjanpatra prophet1999 abhivk792 Amazon MakeMyTrip Paytm Zoho Arrays Paytm Zoho Amazon MakeMyTrip Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Arrays Linked List vs Array Python | Using 2D arrays/lists the right way Search an element in a sorted and rotated array Array of Strings in C++ (5 Different Ways to Create) Queue | Set 1 (Introduction and Array Implementation) Find the Missing Number Subset Sum Problem | DP-25 K'th Smallest/Largest Element in Unsorted Array | Set 1 Find Second largest element in an array
[ { "code": null, "e": 26763, "s": 26735, "text": "\n28 Apr, 2022" }, { "code": null, "e": 27071, "s": 26763, "text": "Given an array of numbers, arrange them in a way that yields the largest value. For example, if the given numbers are {54, 546, 548, 60}, the arrangement 6054854654 gives the largest value. And if the given numbers are {1, 34, 3, 98, 9, 76, 45, 4}, then the arrangement 998764543431 gives the largest value." }, { "code": null, "e": 27337, "s": 27071, "text": "A simple solution that comes to our mind is to sort all numbers in descending order, but simply sorting doesn’t work. For example, 548 is greater than 60, but in output 60 comes before 548. As a second example, 98 is greater than 9, but 9 comes before 98 in output." }, { "code": null, "e": 27562, "s": 27337, "text": "So how do we go about it? The idea is to use any comparison based sorting algorithm. In the used sorting algorithm, instead of using the default comparison, write a comparison function myCompare() and use it to sort numbers." }, { "code": null, "e": 27630, "s": 27562, "text": "For Python, the procedure is explained in largestNumber() function." }, { "code": null, "e": 28029, "s": 27630, "text": "Given two numbers X and Y, how should myCompare() decide which number to put first – we compare two numbers XY (Y appended at the end of X) and YX (X appended at the end of Y). If XY is larger, then X should come before Y in output, else Y should come before. For example, let X and Y be 542 and 60. To compare X and Y, we compare 54260 and 60542. Since 60542 is greater than 54260, we put Y first." }, { "code": null, "e": 28191, "s": 28029, "text": "Following is the implementation of the above approach. To keep the code simple, numbers are considered as strings, the vector is used instead of a normal array. " }, { "code": null, "e": 28243, "s": 28191, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 28247, "s": 28243, "text": "C++" }, { "code": null, "e": 28252, "s": 28247, "text": "Java" }, { "code": null, "e": 28260, "s": 28252, "text": "Python3" }, { "code": null, "e": 28263, "s": 28260, "text": "C#" }, { "code": null, "e": 28267, "s": 28263, "text": "PHP" }, { "code": null, "e": 28278, "s": 28267, "text": "Javascript" }, { "code": "// Given an array of numbers,// program to arrange the numbers// to form the largest number#include <algorithm>#include <iostream>#include <string>#include <vector>using namespace std; // A comparison function which// is used by sort() in// printLargest()int myCompare(string X, string Y){ // first append Y at the end of X string XY = X.append(Y); // then append X at the end of Y string YX = Y.append(X); // Now see which of the two // formed numbers is greater return XY.compare(YX) > 0 ? 1 : 0;} // The main function that prints// the arrangement with the// largest value. The function// accepts a vector of stringsvoid printLargest(vector<string> arr){ // Sort the numbers using // library sort function. The // function uses our comparison // function myCompare() to // compare two strings. See // http://www.cplusplus.com/reference/ // algorithm/sort/ // for details sort(arr.begin(), arr.end(), myCompare); for (int i = 0; i < arr.size(); i++) cout << arr[i];} // Driver codeint main(){ vector<string> arr; // output should be 6054854654 arr.push_back(\"54\"); arr.push_back(\"546\"); arr.push_back(\"548\"); arr.push_back(\"60\"); printLargest(arr); return 0;}", "e": 29532, "s": 28278, "text": null }, { "code": "// Given an array of numbers, program to// arrange the numbers to form the// largest numberimport java.util.*; class GFG { // The main function that prints the // arrangement with the largest value. // The function accepts a vector of strings static void printLargest(Vector<String> arr) { Collections.sort(arr, new Comparator<String>() { // A comparison function which is used by // sort() in printLargest() @Override public int compare(String X, String Y) { // first append Y at the end of X String XY = X + Y; // then append X at the end of Y String YX = Y + X; // Now see which of the two // formed numbers // is greater return XY.compareTo(YX) > 0 ? -1 : 1; } }); Iterator it = arr.iterator(); while (it.hasNext()) System.out.print(it.next()); } // Driver code public static void main(String[] args) { Vector<String> arr; arr = new Vector<>(); // output should be 6054854654 arr.add(\"54\"); arr.add(\"546\"); arr.add(\"548\"); arr.add(\"60\"); printLargest(arr); }}// This code is contributed by Shubham Juneja", "e": 30858, "s": 29532, "text": null }, { "code": "def largestNumber(array): #If there is only one element in the list, the element itself is the largest element. #Below if condition checks the same. if len(array)==1: return str(array[0]) #Below lines are code are used to find the largest element possible. #First, we convert a list into a string array that is suitable for concatenation for i in range(len(array)): array[i]=str(array[i]) # [54,546,548,60]=>['54','546','548','60'] #Second, we find the largest element by swapping technique. for i in range(len(array)): for j in range(1+i,len(array)): if array[j]+array[i]>array[i]+array[j]: array[i],array[j]=array[j],array[i] #['60', '548', '546', '54'] #Refer JOIN function in Python result=''.join(array) #Edge Case: If all elements are 0, answer must be 0 if(result=='0'*len(result)): return '0' else: return result if __name__ == \"__main__\": a = [54, 546, 548, 60] print(largestNumber(a))", "e": 31886, "s": 30858, "text": null }, { "code": "// C# program for above approachusing System.Collections.Generic;using System; namespace LargestNumberClass {class LargestNumberClass { // Given a list of non-negative // integers, // arrange them such that they // form the largest number. // Note: The result may be very // large, so you need to // return a string instead // of an integer. public static void LargestNumberMethod(List<int> inputList) { string output = string.Empty; List<string> newList = inputList.ConvertAll<string>( delegate(int i) { return i.ToString(); }); newList.Sort(MyCompare); for (int i = 0; i < inputList.Count; i++) { output = output + newList[i]; } if (output[0] == '0' && output.Length > 1) { Console.Write(\"0\"); } Console.Write(output); } internal static int MyCompare(string X, string Y) { // first append Y at the end of X string XY = X + Y; // then append X at the end of Y string YX = Y + X; // Now see which of the two // formed numbers is greater return XY.CompareTo(YX) > 0 ? -1 : 1; }} class Program { // Driver code static void Main(string[] args) { List<int> inputList = new List<int>() { 54, 546, 548, 60 }; LargestNumberClass.LargestNumberMethod(inputList); }}// This code is contributed by Deepak Kumar Singh}", "e": 33337, "s": 31886, "text": null }, { "code": "<?php// Given an array of numbers, program// to arrange the numbers to form the// largest number // A comparison function which is used// by sort() in printLargest()function myCompare($X, $Y){ // first append Y at the end of X $XY = $Y.$X; // then append X at the end of Y $YX = $X.$Y; // Now see which of the two formed // numbers is greater return strcmp($XY, $YX) > 0 ? 1: 0;} // The main function that prints the// arrangement with the largest value.// The function accepts a vector of stringsfunction printLargest($arr){ // Sort the numbers using library sort // function. The function uses our // comparison function myCompare() to // compare two strings. // See http://www.cplusplus.com/reference/ // algorithm/sort/ // for details usort($arr, \"myCompare\"); for ($i = 0; $i < count($arr) ; $i++ ) echo $arr[$i];} // Driver Code$arr = array(\"54\", \"546\", \"548\", \"60\");printLargest($arr); // This code is contributed by// rathbhupendra?>", "e": 34345, "s": 33337, "text": null }, { "code": "<script>// Given an array of numbers,// program to arrange the numbers// to form the largest number // A comparison function which// is used by sort() function in// printLargest() function myCompare(X, Y){ // // first append Y at the end of X let XY = X + Y; // // then append X at the end of Y let YX = Y + X; // // Now see which of the two // // formed numbers is greater return (YX - XY)} // The main function that prints// the arrangement with the// largest value. The function// accepts a vector of strings function printLargest(arr){ // Sort the numbers using // inbuilt sort function. The // function uses our comparison // function myCompare() to // compare two strings. arr.sort(myCompare); for(let i = 0; i < arr.length; i++) document.write(arr[i]) // join method creates a string out of the array elements. document.write(arr.join(\"\"))} // Driver code let arr = []; // output should be 6054854654arr.push(\"54\");arr.push(\"546\");arr.push(\"548\");arr.push(\"60\");printLargest(arr); // This code is contributed by shinjanpatra</script>", "e": 35445, "s": 34345, "text": null }, { "code": null, "e": 35456, "s": 35445, "text": "6054854654" }, { "code": null, "e": 35770, "s": 35456, "text": "In the above solution we are allowed strings inputs but in case strings are restricted then also we can solve above problem using long long int to find biggest arrangement. The only limitation is that we can not store numbers greater than 10^18. In case it exceeds that the above solution will be the only option." }, { "code": null, "e": 35776, "s": 35770, "text": "C++14" }, { "code": "// Given an array of numbers,// program to arrange the numbers// to form the largest number#include <algorithm>#include <iostream>#include <string>#include <vector>using namespace std;typedef long long ll; // A comparison function which// is used by sort() in// printLargest()bool myCompare(ll X,ll Y){ // assign X to XY since XY starts with X first // assign Y to YX since YX starts with Y first ll XY=X,YX=Y,revX=0,revY=0; //reverse X and assign to revX while(X) { revX=revX*10+X%10; X/=10; } //reverse Y and assign to revY while(Y) { revY=revY*10+Y%10; Y/=10; } // first append Y at the end of X while(revY) { XY=XY*10+revY%10; revY/=10; } // then append X at the end of Y while(revX) { YX=YX*10+revX%10; revX/=10; } // Now see which of the two // formed numbers is greater return XY>YX;} // The main function that prints// the arrangement with the// largest value. The function// accepts a vector of stringsvoid printLargest(vector<ll> arr){ // Sort the numbers using // library sort function. The // function uses our comparison // function myCompare() to // compare two strings. See // http://www.cplusplus.com/reference/ // algorithm/sort/ // for details sort(arr.begin(), arr.end(), myCompare); for (int i = 0; i < arr.size(); i++) cout << arr[i];} // Driver codeint main(){ vector<ll> arr; // output should be 6054854654 arr.push_back(54); arr.push_back(546); arr.push_back(548); arr.push_back(60); printLargest(arr); return 0;}// this code is contributed by prophet1999", "e": 37464, "s": 35776, "text": null }, { "code": null, "e": 37475, "s": 37464, "text": "6054854654" }, { "code": null, "e": 37628, "s": 37475, "text": "Time Complexity: O(n logn) ,sorting is considered to have running time complexity of O(n logn) and the for loop runs in O(n) time.Auxiliary Space: O(1)" }, { "code": null, "e": 37664, "s": 37628, "text": "Another approach:(using itertools) " }, { "code": null, "e": 37759, "s": 37664, "text": "Using the inbuilt library of the Python, itertools library can be used to perform this task. " }, { "code": null, "e": 37767, "s": 37759, "text": "Python3" }, { "code": "# Python3 implementation this is to use itertools.# permutations as coded below: from itertools import permutationsdef largest(l): lst = [] for i in permutations(l, len(l)): # provides all permutations of the list values, # store them in list to find max lst.append(\"\".join(map(str,i))) return max(lst) print(largest([54, 546, 548, 60])) #Output 6054854654 # This code is contributed by Raman Monga", "e": 38196, "s": 37767, "text": null }, { "code": null, "e": 38207, "s": 38196, "text": "6054854654" }, { "code": null, "e": 38253, "s": 38207, "text": "Time Complexity: O(n!)Auxiliary Space: O(1)." }, { "code": null, "e": 38457, "s": 38253, "text": "This article is compiled by Ravi Chandra Enaganti and improved by prophet1999. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 38471, "s": 38457, "text": "SaurabhTewary" }, { "code": null, "e": 38482, "s": 38471, "text": "mongaraman" }, { "code": null, "e": 38496, "s": 38482, "text": "rathbhupendra" }, { "code": null, "e": 38507, "s": 38496, "text": "deepak1210" }, { "code": null, "e": 38521, "s": 38507, "text": "shubham_singh" }, { "code": null, "e": 38536, "s": 38521, "text": "amit143katiyar" }, { "code": null, "e": 38546, "s": 38536, "text": "Rajput-Ji" }, { "code": null, "e": 38560, "s": 38546, "text": "GauravRajput1" }, { "code": null, "e": 38580, "s": 38560, "text": "mulchandanimanisha5" }, { "code": null, "e": 38592, "s": 38580, "text": "yshailendra" }, { "code": null, "e": 38604, "s": 38592, "text": "arjunsodhi7" }, { "code": null, "e": 38617, "s": 38604, "text": "shinjanpatra" }, { "code": null, "e": 38629, "s": 38617, "text": "prophet1999" }, { "code": null, "e": 38639, "s": 38629, "text": "abhivk792" }, { "code": null, "e": 38646, "s": 38639, "text": "Amazon" }, { "code": null, "e": 38657, "s": 38646, "text": "MakeMyTrip" }, { "code": null, "e": 38663, "s": 38657, "text": "Paytm" }, { "code": null, "e": 38668, "s": 38663, "text": "Zoho" }, { "code": null, "e": 38675, "s": 38668, "text": "Arrays" }, { "code": null, "e": 38681, "s": 38675, "text": "Paytm" }, { "code": null, "e": 38686, "s": 38681, "text": "Zoho" }, { "code": null, "e": 38693, "s": 38686, "text": "Amazon" }, { "code": null, "e": 38704, "s": 38693, "text": "MakeMyTrip" }, { "code": null, "e": 38711, "s": 38704, "text": "Arrays" }, { "code": null, "e": 38809, "s": 38711, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38832, "s": 38809, "text": "Introduction to Arrays" }, { "code": null, "e": 38853, "s": 38832, "text": "Linked List vs Array" }, { "code": null, "e": 38898, "s": 38853, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 38946, "s": 38898, "text": "Search an element in a sorted and rotated array" }, { "code": null, "e": 38999, "s": 38946, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 39053, "s": 38999, "text": "Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 39077, "s": 39053, "text": "Find the Missing Number" }, { "code": null, "e": 39104, "s": 39077, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 39160, "s": 39104, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" } ]