{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \nOutput:\n875\nMethod 2:\nSyntax: \n$(('
'));\nHTML\n \nOutput:\n1538\nMethod 3:\nSyntax:\n$(('
'));\nHTML\n \nOutput:\n2097\nMethod 4:\nSyntax:\n$(('
'));\nHTML\n \nOutput:\n2037\nFor better understanding, try running benchmarks on JavaScript engines.\nConclusion: The $(document.createElement(‘div’)); is the fastest method, even the benchmarking supports, this is the fastest technique to create an HTML element using jQuery. \nReason: It is because jQuery doesn’t have to identify it as an element and create the element itself.\nAlternate way: Using just document.createElement(‘div’) without jQuery will increase the efficiency a lot and will also append the element to DOM automatically.\njQuery-HTML/CSS\nPicked\nHTML\nJQuery\nWeb Technologies\nHTML\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},"parsed":{"kind":"list like","value":[{"code":null,"e":28,"s":0,"text":"\n05 Mar, 2021"},{"code":null,"e":214,"s":28,"text":"In this article, we will look at 4 jQuery techniques that can be used to create an HTML element, and we will be testing out the code for the creation of an element by different methods."},{"code":null,"e":482,"s":214,"text":"Approach: One of the easier ways is to just use $ (‘
’) which is great for readability but technically the piece of code will create an
element, but it will not add it to your HTML DOM. You need to use some other methods like append(), prepend(), etc."},{"code":null,"e":662,"s":482,"text":"It is recommended to run and test the code below and check out the fastest technique for creating an element, as the time taken by the code varies depending upon the web browser. "},{"code":null,"e":830,"s":662,"text":"For the below code, you must incorporate jQuery into your code. One of the easiest ways to do this is to just copy and paste the jQuery CDN into your HTML header tag. "},{"code":null,"e":845,"s":830,"text":"CDN link used:"},{"code":null,"e":889,"s":845,"text":"https://code.jquery.com/jquery-3.5.1.min.js"},{"code":null,"e":1141,"s":889,"text":"Method 1: In the following example, the document.createElement() method creates the HTML “div” element node. The date.getTime() method is used to return the number of milliseconds since 1 January 1970. Run the code below to find out its performance."},{"code":null,"e":1150,"s":1141,"text":"Syntax: "},{"code":null,"e":1186,"s":1150,"text":"$((document.createElement('div')));"},{"code":null,"e":1191,"s":1186,"text":"HTML"},{"code":" ","e":1765,"s":1191,"text":null},{"code":null,"e":1773,"s":1765,"text":"Output:"},{"code":null,"e":1777,"s":1773,"text":"875"},{"code":null,"e":1787,"s":1777,"text":"Method 2:"},{"code":null,"e":1796,"s":1787,"text":"Syntax: "},{"code":null,"e":1810,"s":1796,"text":"$(('
'));"},{"code":null,"e":1815,"s":1810,"text":"HTML"},{"code":" ","e":2357,"s":1815,"text":null},{"code":null,"e":2365,"s":2357,"text":"Output:"},{"code":null,"e":2370,"s":2365,"text":"1538"},{"code":null,"e":2380,"s":2370,"text":"Method 3:"},{"code":null,"e":2388,"s":2380,"text":"Syntax:"},{"code":null,"e":2408,"s":2388,"text":"$(('
'));"},{"code":null,"e":2413,"s":2408,"text":"HTML"},{"code":" ","e":2957,"s":2413,"text":null},{"code":null,"e":2965,"s":2957,"text":"Output:"},{"code":null,"e":2970,"s":2965,"text":"2097"},{"code":null,"e":2980,"s":2970,"text":"Method 4:"},{"code":null,"e":2988,"s":2980,"text":"Syntax:"},{"code":null,"e":3003,"s":2988,"text":"$(('
'));"},{"code":null,"e":3008,"s":3003,"text":"HTML"},{"code":" ","e":3541,"s":3008,"text":null},{"code":null,"e":3549,"s":3541,"text":"Output:"},{"code":null,"e":3554,"s":3549,"text":"2037"},{"code":null,"e":3626,"s":3554,"text":"For better understanding, try running benchmarks on JavaScript engines."},{"code":null,"e":3802,"s":3626,"text":"Conclusion: The $(document.createElement(‘div’)); is the fastest method, even the benchmarking supports, this is the fastest technique to create an HTML element using jQuery. "},{"code":null,"e":3904,"s":3802,"text":"Reason: It is because jQuery doesn’t have to identify it as an element and create the element itself."},{"code":null,"e":4065,"s":3904,"text":"Alternate way: Using just document.createElement(‘div’) without jQuery will increase the efficiency a lot and will also append the element to DOM automatically."},{"code":null,"e":4081,"s":4065,"text":"jQuery-HTML/CSS"},{"code":null,"e":4088,"s":4081,"text":"Picked"},{"code":null,"e":4093,"s":4088,"text":"HTML"},{"code":null,"e":4100,"s":4093,"text":"JQuery"},{"code":null,"e":4117,"s":4100,"text":"Web Technologies"},{"code":null,"e":4122,"s":4117,"text":"HTML"}],"string":"[\n {\n \"code\": null,\n \"e\": 28,\n \"s\": 0,\n \"text\": \"\\n05 Mar, 2021\"\n },\n {\n \"code\": null,\n \"e\": 214,\n \"s\": 28,\n \"text\": \"In this article, we will look at 4 jQuery techniques that can be used to create an HTML element, and we will be testing out the code for the creation of an element by different methods.\"\n },\n {\n \"code\": null,\n \"e\": 482,\n \"s\": 214,\n \"text\": \"Approach: One of the easier ways is to just use $ (‘
’) which is great for readability but technically the piece of code will create an
element, but it will not add it to your HTML DOM. You need to use some other methods like append(), prepend(), etc.\"\n },\n {\n \"code\": null,\n \"e\": 662,\n \"s\": 482,\n \"text\": \"It is recommended to run and test the code below and check out the fastest technique for creating an element, as the time taken by the code varies depending upon the web browser. \"\n },\n {\n \"code\": null,\n \"e\": 830,\n \"s\": 662,\n \"text\": \"For the below code, you must incorporate jQuery into your code. One of the easiest ways to do this is to just copy and paste the jQuery CDN into your HTML header tag. \"\n },\n {\n \"code\": null,\n \"e\": 845,\n \"s\": 830,\n \"text\": \"CDN link used:\"\n },\n {\n \"code\": null,\n \"e\": 889,\n \"s\": 845,\n \"text\": \"https://code.jquery.com/jquery-3.5.1.min.js\"\n },\n {\n \"code\": null,\n \"e\": 1141,\n \"s\": 889,\n \"text\": \"Method 1: In the following example, the document.createElement() method creates the HTML “div” element node. The date.getTime() method is used to return the number of milliseconds since 1 January 1970. Run the code below to find out its performance.\"\n },\n {\n \"code\": null,\n \"e\": 1150,\n \"s\": 1141,\n \"text\": \"Syntax: \"\n },\n {\n \"code\": null,\n \"e\": 1186,\n \"s\": 1150,\n \"text\": \"$((document.createElement('div')));\"\n },\n {\n \"code\": null,\n \"e\": 1191,\n \"s\": 1186,\n \"text\": \"HTML\"\n },\n {\n \"code\": \" \",\n \"e\": 1765,\n \"s\": 1191,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 1773,\n \"s\": 1765,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 1777,\n \"s\": 1773,\n \"text\": \"875\"\n },\n {\n \"code\": null,\n \"e\": 1787,\n \"s\": 1777,\n \"text\": \"Method 2:\"\n },\n {\n \"code\": null,\n \"e\": 1796,\n \"s\": 1787,\n \"text\": \"Syntax: \"\n },\n {\n \"code\": null,\n \"e\": 1810,\n \"s\": 1796,\n \"text\": \"$(('
'));\"\n },\n {\n \"code\": null,\n \"e\": 1815,\n \"s\": 1810,\n \"text\": \"HTML\"\n },\n {\n \"code\": \" \",\n \"e\": 2357,\n \"s\": 1815,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 2365,\n \"s\": 2357,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 2370,\n \"s\": 2365,\n \"text\": \"1538\"\n },\n {\n \"code\": null,\n \"e\": 2380,\n \"s\": 2370,\n \"text\": \"Method 3:\"\n },\n {\n \"code\": null,\n \"e\": 2388,\n \"s\": 2380,\n \"text\": \"Syntax:\"\n },\n {\n \"code\": null,\n \"e\": 2408,\n \"s\": 2388,\n \"text\": \"$(('
'));\"\n },\n {\n \"code\": null,\n \"e\": 2413,\n \"s\": 2408,\n \"text\": \"HTML\"\n },\n {\n \"code\": \" \",\n \"e\": 2957,\n \"s\": 2413,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 2965,\n \"s\": 2957,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 2970,\n \"s\": 2965,\n \"text\": \"2097\"\n },\n {\n \"code\": null,\n \"e\": 2980,\n \"s\": 2970,\n \"text\": \"Method 4:\"\n },\n {\n \"code\": null,\n \"e\": 2988,\n \"s\": 2980,\n \"text\": \"Syntax:\"\n },\n {\n \"code\": null,\n \"e\": 3003,\n \"s\": 2988,\n \"text\": \"$(('
'));\"\n },\n {\n \"code\": null,\n \"e\": 3008,\n \"s\": 3003,\n \"text\": \"HTML\"\n },\n {\n \"code\": \" \",\n \"e\": 3541,\n \"s\": 3008,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 3549,\n \"s\": 3541,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 3554,\n \"s\": 3549,\n \"text\": \"2037\"\n },\n {\n \"code\": null,\n \"e\": 3626,\n \"s\": 3554,\n \"text\": \"For better understanding, try running benchmarks on JavaScript engines.\"\n },\n {\n \"code\": null,\n \"e\": 3802,\n \"s\": 3626,\n \"text\": \"Conclusion: The $(document.createElement(‘div’)); is the fastest method, even the benchmarking supports, this is the fastest technique to create an HTML element using jQuery. \"\n },\n {\n \"code\": null,\n \"e\": 3904,\n \"s\": 3802,\n \"text\": \"Reason: It is because jQuery doesn’t have to identify it as an element and create the element itself.\"\n },\n {\n \"code\": null,\n \"e\": 4065,\n \"s\": 3904,\n \"text\": \"Alternate way: Using just document.createElement(‘div’) without jQuery will increase the efficiency a lot and will also append the element to DOM automatically.\"\n },\n {\n \"code\": null,\n \"e\": 4081,\n \"s\": 4065,\n \"text\": \"jQuery-HTML/CSS\"\n },\n {\n \"code\": null,\n \"e\": 4088,\n \"s\": 4081,\n \"text\": \"Picked\"\n },\n {\n \"code\": null,\n \"e\": 4093,\n \"s\": 4088,\n \"text\": \"HTML\"\n },\n {\n \"code\": null,\n \"e\": 4100,\n \"s\": 4093,\n \"text\": \"JQuery\"\n },\n {\n \"code\": null,\n \"e\": 4117,\n \"s\": 4100,\n \"text\": \"Web Technologies\"\n },\n {\n \"code\": null,\n \"e\": 4122,\n \"s\": 4117,\n \"text\": \"HTML\"\n }\n]"}}},{"rowIdx":101,"cells":{"title":{"kind":"string","value":"SQL Query to get information of employee where employee Is Not Assigned to the Department"},"text":{"kind":"string","value":"01 Apr, 2021\nIn this article, we will discuss the overview of SQL query and our main focus will be on how to get information of employee where employee Is Not Assigned to the Department in SQL. Let’s discuss it step by step.\nIntroduction :Queries help us to interact with the database for various operations of data retrieval, updating, deletion, and inserting. In this article let us see a query to get the information of an employee where the employee is not assigned to any department. When in a table if any attribute is not assigned with any value it would be the NULL so let us execute the query on a table in the database company.\nStep-1: Creating a database –Creating a database company by using the following SQL query as follows.\nCREATE DATABASE company;\nOutput :\nStep-2: Using the database –Using the database company using the following SQL query as follows.\nUSE company;\nOutput :\nStep-3: Creating a table –Creating a table employee with 5 columns using the following SQL query as follows.\nCREATE TABLE employee\n(\nemp_id varchar(20),\nemp_name varchar(20),\nemp_dept varchar(20),\nemp_age INT,\nemp_sex varchar(8)\n);\nOutput :\nStep-4: Verifying the database –To view the description of the database using the following SQL query as follows.\nDESCRIBE employee;\nOutput :\nStep-5: Inserting data into the table –Inserting rows into employee table using the following SQL query as follows.\n INSERT INTO employee VALUES('E00001','JHONNY','BACKEND DEVELOPER',26,'male');\n INSERT INTO employee VALUES('E00002','DARSHI',NULL,27,'male');\n INSERT INTO employee VALUES('E00003','JASMINE',NULL,37,'female');\n INSERT INTO employee VALUES('E00004','LILLY',NULL,47,'female');\n INSERT INTO employee VALUES('E00005','RONALD','UI DEVELOPER',26,'male'); \nOutput :\nStep-6: Verifying the inserted data –Viewing the table employee after inserting rows by using the following SQL query as follows.\nSELECT* FROM employee;\nOutput :\nQuery to find the employees whose departments are not assigned :Here, we will see how to query to find the employees whose departments are not assigned by using the following SQL query as follows.\nSyntax :\nSELECT*\nFROM table_name\nWHERE column_name IS NULL;\nSelecting Data Query –\n SELECT*\n FROM employee\n WHERE emp_dept IS NULL;\nOutput :In this table, all the employee records whose department is NULL value are obtained. \nQuery to find the employees whose departments are assigned :Here, we will see how to query to find the employees whose departments are assigned using the following SQL as follows.\nSyntax :\nSELECT *\nFROM table_name\nWHERE column_name IS NOT NULL;\nSelecting Query –\nSELECT *\nFROM employee\nWHERE emp_dept IS NOT NULL;\nOutput :All the records of an employee whose department is assigned are obtained.\n \nDBMS-SQL\nPicked\nSQL\nSQL\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},"parsed":{"kind":"list like","value":[{"code":null,"e":54,"s":26,"text":"\n01 Apr, 2021"},{"code":null,"e":266,"s":54,"text":"In this article, we will discuss the overview of SQL query and our main focus will be on how to get information of employee where employee Is Not Assigned to the Department in SQL. Let’s discuss it step by step."},{"code":null,"e":679,"s":266,"text":"Introduction :Queries help us to interact with the database for various operations of data retrieval, updating, deletion, and inserting. In this article let us see a query to get the information of an employee where the employee is not assigned to any department. When in a table if any attribute is not assigned with any value it would be the NULL so let us execute the query on a table in the database company."},{"code":null,"e":781,"s":679,"text":"Step-1: Creating a database –Creating a database company by using the following SQL query as follows."},{"code":null,"e":806,"s":781,"text":"CREATE DATABASE company;"},{"code":null,"e":815,"s":806,"text":"Output :"},{"code":null,"e":912,"s":815,"text":"Step-2: Using the database –Using the database company using the following SQL query as follows."},{"code":null,"e":925,"s":912,"text":"USE company;"},{"code":null,"e":934,"s":925,"text":"Output :"},{"code":null,"e":1043,"s":934,"text":"Step-3: Creating a table –Creating a table employee with 5 columns using the following SQL query as follows."},{"code":null,"e":1166,"s":1043,"text":"CREATE TABLE employee\n(\nemp_id varchar(20),\nemp_name varchar(20),\nemp_dept varchar(20),\nemp_age INT,\nemp_sex varchar(8)\n);"},{"code":null,"e":1175,"s":1166,"text":"Output :"},{"code":null,"e":1289,"s":1175,"text":"Step-4: Verifying the database –To view the description of the database using the following SQL query as follows."},{"code":null,"e":1308,"s":1289,"text":"DESCRIBE employee;"},{"code":null,"e":1317,"s":1308,"text":"Output :"},{"code":null,"e":1433,"s":1317,"text":"Step-5: Inserting data into the table –Inserting rows into employee table using the following SQL query as follows."},{"code":null,"e":1783,"s":1433,"text":" INSERT INTO employee VALUES('E00001','JHONNY','BACKEND DEVELOPER',26,'male');\n INSERT INTO employee VALUES('E00002','DARSHI',NULL,27,'male');\n INSERT INTO employee VALUES('E00003','JASMINE',NULL,37,'female');\n INSERT INTO employee VALUES('E00004','LILLY',NULL,47,'female');\n INSERT INTO employee VALUES('E00005','RONALD','UI DEVELOPER',26,'male'); "},{"code":null,"e":1792,"s":1783,"text":"Output :"},{"code":null,"e":1922,"s":1792,"text":"Step-6: Verifying the inserted data –Viewing the table employee after inserting rows by using the following SQL query as follows."},{"code":null,"e":1945,"s":1922,"text":"SELECT* FROM employee;"},{"code":null,"e":1954,"s":1945,"text":"Output :"},{"code":null,"e":2151,"s":1954,"text":"Query to find the employees whose departments are not assigned :Here, we will see how to query to find the employees whose departments are not assigned by using the following SQL query as follows."},{"code":null,"e":2160,"s":2151,"text":"Syntax :"},{"code":null,"e":2212,"s":2160,"text":"SELECT*\nFROM table_name\nWHERE column_name IS NULL;"},{"code":null,"e":2235,"s":2212,"text":"Selecting Data Query –"},{"code":null,"e":2284,"s":2235,"text":" SELECT*\n FROM employee\n WHERE emp_dept IS NULL;"},{"code":null,"e":2378,"s":2284,"text":"Output :In this table, all the employee records whose department is NULL value are obtained. "},{"code":null,"e":2558,"s":2378,"text":"Query to find the employees whose departments are assigned :Here, we will see how to query to find the employees whose departments are assigned using the following SQL as follows."},{"code":null,"e":2567,"s":2558,"text":"Syntax :"},{"code":null,"e":2623,"s":2567,"text":"SELECT *\nFROM table_name\nWHERE column_name IS NOT NULL;"},{"code":null,"e":2641,"s":2623,"text":"Selecting Query –"},{"code":null,"e":2692,"s":2641,"text":"SELECT *\nFROM employee\nWHERE emp_dept IS NOT NULL;"},{"code":null,"e":2774,"s":2692,"text":"Output :All the records of an employee whose department is assigned are obtained."},{"code":null,"e":2787,"s":2778,"text":"DBMS-SQL"},{"code":null,"e":2794,"s":2787,"text":"Picked"},{"code":null,"e":2798,"s":2794,"text":"SQL"},{"code":null,"e":2802,"s":2798,"text":"SQL"}],"string":"[\n {\n \"code\": null,\n \"e\": 54,\n \"s\": 26,\n \"text\": \"\\n01 Apr, 2021\"\n },\n {\n \"code\": null,\n \"e\": 266,\n \"s\": 54,\n \"text\": \"In this article, we will discuss the overview of SQL query and our main focus will be on how to get information of employee where employee Is Not Assigned to the Department in SQL. Let’s discuss it step by step.\"\n },\n {\n \"code\": null,\n \"e\": 679,\n \"s\": 266,\n \"text\": \"Introduction :Queries help us to interact with the database for various operations of data retrieval, updating, deletion, and inserting. In this article let us see a query to get the information of an employee where the employee is not assigned to any department. When in a table if any attribute is not assigned with any value it would be the NULL so let us execute the query on a table in the database company.\"\n },\n {\n \"code\": null,\n \"e\": 781,\n \"s\": 679,\n \"text\": \"Step-1: Creating a database –Creating a database company by using the following SQL query as follows.\"\n },\n {\n \"code\": null,\n \"e\": 806,\n \"s\": 781,\n \"text\": \"CREATE DATABASE company;\"\n },\n {\n \"code\": null,\n \"e\": 815,\n \"s\": 806,\n \"text\": \"Output :\"\n },\n {\n \"code\": null,\n \"e\": 912,\n \"s\": 815,\n \"text\": \"Step-2: Using the database –Using the database company using the following SQL query as follows.\"\n },\n {\n \"code\": null,\n \"e\": 925,\n \"s\": 912,\n \"text\": \"USE company;\"\n },\n {\n \"code\": null,\n \"e\": 934,\n \"s\": 925,\n \"text\": \"Output :\"\n },\n {\n \"code\": null,\n \"e\": 1043,\n \"s\": 934,\n \"text\": \"Step-3: Creating a table –Creating a table employee with 5 columns using the following SQL query as follows.\"\n },\n {\n \"code\": null,\n \"e\": 1166,\n \"s\": 1043,\n \"text\": \"CREATE TABLE employee\\n(\\nemp_id varchar(20),\\nemp_name varchar(20),\\nemp_dept varchar(20),\\nemp_age INT,\\nemp_sex varchar(8)\\n);\"\n },\n {\n \"code\": null,\n \"e\": 1175,\n \"s\": 1166,\n \"text\": \"Output :\"\n },\n {\n \"code\": null,\n \"e\": 1289,\n \"s\": 1175,\n \"text\": \"Step-4: Verifying the database –To view the description of the database using the following SQL query as follows.\"\n },\n {\n \"code\": null,\n \"e\": 1308,\n \"s\": 1289,\n \"text\": \"DESCRIBE employee;\"\n },\n {\n \"code\": null,\n \"e\": 1317,\n \"s\": 1308,\n \"text\": \"Output :\"\n },\n {\n \"code\": null,\n \"e\": 1433,\n \"s\": 1317,\n \"text\": \"Step-5: Inserting data into the table –Inserting rows into employee table using the following SQL query as follows.\"\n },\n {\n \"code\": null,\n \"e\": 1783,\n \"s\": 1433,\n \"text\": \" INSERT INTO employee VALUES('E00001','JHONNY','BACKEND DEVELOPER',26,'male');\\n INSERT INTO employee VALUES('E00002','DARSHI',NULL,27,'male');\\n INSERT INTO employee VALUES('E00003','JASMINE',NULL,37,'female');\\n INSERT INTO employee VALUES('E00004','LILLY',NULL,47,'female');\\n INSERT INTO employee VALUES('E00005','RONALD','UI DEVELOPER',26,'male'); \"\n },\n {\n \"code\": null,\n \"e\": 1792,\n \"s\": 1783,\n \"text\": \"Output :\"\n },\n {\n \"code\": null,\n \"e\": 1922,\n \"s\": 1792,\n \"text\": \"Step-6: Verifying the inserted data –Viewing the table employee after inserting rows by using the following SQL query as follows.\"\n },\n {\n \"code\": null,\n \"e\": 1945,\n \"s\": 1922,\n \"text\": \"SELECT* FROM employee;\"\n },\n {\n \"code\": null,\n \"e\": 1954,\n \"s\": 1945,\n \"text\": \"Output :\"\n },\n {\n \"code\": null,\n \"e\": 2151,\n \"s\": 1954,\n \"text\": \"Query to find the employees whose departments are not assigned :Here, we will see how to query to find the employees whose departments are not assigned by using the following SQL query as follows.\"\n },\n {\n \"code\": null,\n \"e\": 2160,\n \"s\": 2151,\n \"text\": \"Syntax :\"\n },\n {\n \"code\": null,\n \"e\": 2212,\n \"s\": 2160,\n \"text\": \"SELECT*\\nFROM table_name\\nWHERE column_name IS NULL;\"\n },\n {\n \"code\": null,\n \"e\": 2235,\n \"s\": 2212,\n \"text\": \"Selecting Data Query –\"\n },\n {\n \"code\": null,\n \"e\": 2284,\n \"s\": 2235,\n \"text\": \" SELECT*\\n FROM employee\\n WHERE emp_dept IS NULL;\"\n },\n {\n \"code\": null,\n \"e\": 2378,\n \"s\": 2284,\n \"text\": \"Output :In this table, all the employee records whose department is NULL value are obtained. \"\n },\n {\n \"code\": null,\n \"e\": 2558,\n \"s\": 2378,\n \"text\": \"Query to find the employees whose departments are assigned :Here, we will see how to query to find the employees whose departments are assigned using the following SQL as follows.\"\n },\n {\n \"code\": null,\n \"e\": 2567,\n \"s\": 2558,\n \"text\": \"Syntax :\"\n },\n {\n \"code\": null,\n \"e\": 2623,\n \"s\": 2567,\n \"text\": \"SELECT *\\nFROM table_name\\nWHERE column_name IS NOT NULL;\"\n },\n {\n \"code\": null,\n \"e\": 2641,\n \"s\": 2623,\n \"text\": \"Selecting Query –\"\n },\n {\n \"code\": null,\n \"e\": 2692,\n \"s\": 2641,\n \"text\": \"SELECT *\\nFROM employee\\nWHERE emp_dept IS NOT NULL;\"\n },\n {\n \"code\": null,\n \"e\": 2774,\n \"s\": 2692,\n \"text\": \"Output :All the records of an employee whose department is assigned are obtained.\"\n },\n {\n \"code\": null,\n \"e\": 2787,\n \"s\": 2778,\n \"text\": \"DBMS-SQL\"\n },\n {\n \"code\": null,\n \"e\": 2794,\n \"s\": 2787,\n \"text\": \"Picked\"\n },\n {\n \"code\": null,\n \"e\": 2798,\n \"s\": 2794,\n \"text\": \"SQL\"\n },\n {\n \"code\": null,\n \"e\": 2802,\n \"s\": 2798,\n \"text\": \"SQL\"\n }\n]"}}},{"rowIdx":102,"cells":{"title":{"kind":"string","value":"Getting Started with PyPy. Up-and-running with PyPy, an... | by Ahmed Gad | Towards Data Science"},"text":{"kind":"string","value":"The Python programming language is an interface that can be implemented in many ways. Some examples include CPython which uses the C language, Jython that is implemented using Java, and so on.\nDespite being the most popular, CPython is not the fastest. PyPy is an alternate Python implementation that is both compliant and fast. PyPy depends on just-in-time (JIT) compilation that dramatically reduces the execution time for long-running operations.\nIn this tutorial, PyPy will be introduced for beginners to highlight how it is different from CPython. We’ll also cover its advantages and limitations. Then we’ll take a look at how to download and use PyPy to execute a simple Python script. PyPy supports hundreds of Python libraries, including NumPy.\nSpecifically, this tutorial covers the following:\nA quick overview of CPython\nIntroduction to PyPy and its features\nPyPy limitations\nRunning PyPy on Ubuntu\nExecution time of PyPy vs CPython\nLet’s get started.\nBefore discussing PyPy, it is important to know how CPython works. My previous tutorial titled Boosting Python Scripts With Cython gave a longer introduction to how CPython works, but it won’t hurt to have a quick recap here about the important points. Below you can see a visualization of the execution pipeline of a Python script implemented using CPython.\nGiven a Python .py script, the source code is first compiled using the CPython compiler into bytecode. The bytecode is generated and saved in a file with a .pyc extension. The bytecode is then executed using the CPython interpreter within a virtual environment.\nThere are benefits to using the compiler to convert the source code into bytecode. If no compiler is used, then the interpreter will work directly on the source code by translating it line by line into machine code. The disadvantage of doing this is that some processes have to be applied for translating each line of source code into machine code, and such processes will be repeated for each line. For example, syntax analysis will be applied to each line independently from the other lines, and thus the interpreter takes a lot of time to translate the code. The compiler solves this issue as it is able to process all of the code at once, and thus syntax analysis will be applied only once rather than to each line of code. The generated bytecode from the compiler will thus be interpreted easily. Note that compiling the entire source code might not be helpful in some cases, and we’ll see a clear example of this when discussing PyPy.\nAfter the bytecode is generated, it is executed by the interpreter running in the virtual machine. The virtual environment is beneficial, as it isolates the CPython bytecode from the machine, and thus makes Python cross-platform.\nUnfortunately, just using a compiler to generate the bytecode is not enough to speed up the execution of CPython. The interpreter works by translating the code, each time it is executed, into machine code. Thus, if a line L takes X seconds to be executed, then executing it 10 times will have a cost of X*10 seconds. For long-running operations, this is too costly in its execution time.\nBased on the drawbacks of CPython, let’s now take a look at PyPy.\nPyPy is a Python implementation similar to CPython that is both compliant and fast. “Compliant” means that PyPy is compatible with CPython, as you can use nearly all CPython syntax in PyPy. There are some compatibility differences, as mentioned here. The most powerful advantage of PyPy is its speed. PyPy is much faster than CPython; we’ll see tests later on where PyPy performs about 7 times faster. In some cases it might even be tens or hundreds of times faster than CPython. So how does PyPy achieve its speed?\nPyPy uses a just-in-time (JIT) compiler that is able to dramatically increase the speed of Python scripts. The type of compilation used in CPython is ahead-of-time (AOT), meaning that all of the code will be translated into bytecode before being executed. JIT just translates the code at runtime, only when it is needed.\nThe source code might contain code blocks that are not executed at all, but which are still being translated using the AOT compiler. This leads to slower processing times. When the source code is large and contains thousands of lines, using a JIT makes a big difference. For AOT, the entire source code will be translated and thus take a lot of time. For JIT, just the needed parts of the code will be executed, making it a lot faster.\nAfter PyPy translates a part of the code, it then gets cached. This means the code is translated only once, and then the translation is used later. The CPython interpreter repeats the translation each time the code is executed, an additional cause for its slowness.\nPyPy is not the only way to boost the performance of Python scripts — but it is the easiest way. For example, Cython could be used to increase the speed of assigning C types to the variables. The problem is that Cython asks the developer to manually inspect the source code and optimize it. This is tiresome, and the complexity increases as the code size increases. When PyPy is used, you just run the regular Python code much faster without any effort at all.\nStandard Python uses the C stack. This stack stores the sequence of functions that are called from each other (recursion). Because the stack size is limited, you are limited in the number of function calls.\nPyPy uses Stackless Python, a Python implementation that does not use the C stack. Instead, it stores the function calls in the heap alongside the objects. The heap size is greater than the stack size, and thus you can do more function calls.\nStackless Python also supports microthreads, which are better than regular Python threads. Within the single Stackless Python thread you can run thousands of tasks, called “tasklets,” with all of them running on the same thread.\nUsing tasklets allows running concurrent tasks. Concurrency means that two tasks work simultaneously by sharing the same resources. One task runs for some time, then stops to make room for the second task to be executed. Note that this is different from parallelism, which involves running the two tasks separately but at the same time.\nUsing tasklets reduces the number of threads created, and thus reduces the overhead of managing all these threads by the OS. As a result, speeding up the execution by swapping between two threads is more time-intensive than swapping between two tasklets.\nUsing Stackless Python also opened the door for implementing continuations. Continuations allow us to save the state of a task and restore it later to continue its job. Note that Stackless Python is not different from Standard Python; it just adds more functionalities. Everything available in Standard Python will be available in Stackless Python, too.\nAfter discussing the benefits of PyPy, let’s talk about its limitations in the next section.\nWhile you can use CPython on any machine and any CPU architecture, PyPy has comparably limited support.\nHere are the CPU architectures supported and maintained by PyPy (source):\nx86 (IA-32) and x86_64\nARM platforms (ARMv6 or ARMv7, with VFPv3)\nAArch64\nPowerPC 64bit, both little and big endian\nSystem Z (s390x)\nPyPy cannot work on all Linux distributions, so you have to take care to use one that’s supported. Running PyPy Linux binary on an unsupported distribution will return an error. PyPy only supports one version of Python 2 and Python 3, which are PyPy 2.7 and PyPy 3.6.\nIf the code that is executed in PyPy is pure Python, then the speed offered by PyPy is usually noticeable. But if the code contains C extensions, such as NumPy, then PyPy might actually increase the time. The PyPy project is actively developed and thus may offer better support for C extensions in the future.\nPyPy is not supported by a number of popular Python frameworks, such as Kivy. Kivy allows CPython to run on all platforms, including Android and iOS. This means that PyPy cannot run on mobile devices.\nNow that we’ve seen the benefits and limitations of PyPy, let’s cover how to run PyPy on Ubuntu.\nYou can run PyPy on either Mac, Linux, or Windows, but we are going to discuss running it on Ubuntu. It is very important to mention again that PyPy Linux binaries are only supported on specific Linux distributions. You can check the available PyPy binaries and their supported distributions on this page. For example, PyPy (either Python 2.7 or Python 3.6) is only supported for three versions of Ubuntu: 18.04, 16.04 and 14.04. If you have the newest version of Ubuntu up to this date (19.10), then you cannot run PyPy on it. Trying to run PyPy on an unsupported distribution will return this error:\npypy: error while loading shared libraries ...\nI simply use a virtual machine to run Ubuntu 18.04.\nThe PyPy binaries come as compressed files. All you need to do is to decompress the file you downloaded. Inside the decompressed directory there is a folder named bin, in which the PyPy executable file can be found. I am using Python 3.6 and thus the file is named pypy3. For Python 2.7, it's just called pypy.\nFor CPython, if you would like to run Python 3 from the terminal, you simply enter the command python3. To run PyPy, simply issue the command pypy3.\nEntering the pypy3 command in the terminal might return the Command 'pypy3' not found message, as shown in the next figure. The reason is that the path of PyPy is not added to the PATH environment variable. The command that actually works is ./pypy3, taking into regard that the current path of the terminal is inside the bin directory of PyPy. The dot . refers to the current directory, and / is added to access something within the current directory. Issuing the ./pypy3 command runs Python successfully as given below.\nYou can now work with Python as usual, taking advantage of the benefits of PyPy. For example, we can create a simple Python script that sums 1,000 numbers and execute it using PyPy. The code is as follows.\nnums = range(1000) sum = 0 for k in nums: sum = sum + kprint(\"Sum of 1,000 numbers is : \", sum)\nIf this script is named test.py, then you can simply run it using the following command (assuming that the Python file is located inside the bin folder of PyPy, which is the same location of the pypy3 command).\n./pypy3 test.py\nThe next figure shows the result of executing the previous code.\nTo compare the runtime of PyPy and CPython for summing 1,000 numbers, the code is changed to measure the time as follows.\nimport timet1 = time.time()nums = range(1000)sum = 0for k in nums: sum = sum + kprint(\"Sum of 1,000 numbers is : \", sum)t2 = time.time()t = t2 - t1print(\"Elapsed time is : \", t, \" seconds\")\nFor PyPy the time is nearly 0.00045 seconds, compared to 0.0002 seconds for CPython (I ran the code on my Core i7-6500U machine @ 2.5GHz). In this case CPython takes less time compared to PyPy, which is to be expected since this task is not really a long-running task. If the code is changed to add 1 million numbers, rather than 1 thousand, then PyPy would end up winning. In this case it takes 0.00035 seconds for Pypy and 0.1 seconds for CPython. The benefit of PyPy is now obvious. This should give you an idea of how much slower CPython is for executing long-running tasks.\nThis article was originally published on the Paperspace blog. You can run the code for my tutorials for free on Gradient.\nThis tutorial introduced PyPy, the fastest Python implementation. The major benefit of PyPy is its just-in-time (JIT) compilation, which offers caching of the compiled machine code to avoid executing it again. The limitations of PyPy are also highlighted, the major one being that it works well for pure Python code but is not efficient for C extensions.\nWe also saw how to run PyPy on Ubuntu and compared the runtime of both CPython and PyPy, highlighting PyPy’s efficiency for long-running tasks. Meanwhile, CPython might still beat out PyPy for short-running tasks. In future articles we’ll explore more comparisons between PyPy, CPython, and Cython."},"parsed":{"kind":"list like","value":[{"code":null,"e":365,"s":172,"text":"The Python programming language is an interface that can be implemented in many ways. Some examples include CPython which uses the C language, Jython that is implemented using Java, and so on."},{"code":null,"e":622,"s":365,"text":"Despite being the most popular, CPython is not the fastest. PyPy is an alternate Python implementation that is both compliant and fast. PyPy depends on just-in-time (JIT) compilation that dramatically reduces the execution time for long-running operations."},{"code":null,"e":925,"s":622,"text":"In this tutorial, PyPy will be introduced for beginners to highlight how it is different from CPython. We’ll also cover its advantages and limitations. Then we’ll take a look at how to download and use PyPy to execute a simple Python script. PyPy supports hundreds of Python libraries, including NumPy."},{"code":null,"e":975,"s":925,"text":"Specifically, this tutorial covers the following:"},{"code":null,"e":1003,"s":975,"text":"A quick overview of CPython"},{"code":null,"e":1041,"s":1003,"text":"Introduction to PyPy and its features"},{"code":null,"e":1058,"s":1041,"text":"PyPy limitations"},{"code":null,"e":1081,"s":1058,"text":"Running PyPy on Ubuntu"},{"code":null,"e":1115,"s":1081,"text":"Execution time of PyPy vs CPython"},{"code":null,"e":1134,"s":1115,"text":"Let’s get started."},{"code":null,"e":1493,"s":1134,"text":"Before discussing PyPy, it is important to know how CPython works. My previous tutorial titled Boosting Python Scripts With Cython gave a longer introduction to how CPython works, but it won’t hurt to have a quick recap here about the important points. Below you can see a visualization of the execution pipeline of a Python script implemented using CPython."},{"code":null,"e":1755,"s":1493,"text":"Given a Python .py script, the source code is first compiled using the CPython compiler into bytecode. The bytecode is generated and saved in a file with a .pyc extension. The bytecode is then executed using the CPython interpreter within a virtual environment."},{"code":null,"e":2696,"s":1755,"text":"There are benefits to using the compiler to convert the source code into bytecode. If no compiler is used, then the interpreter will work directly on the source code by translating it line by line into machine code. The disadvantage of doing this is that some processes have to be applied for translating each line of source code into machine code, and such processes will be repeated for each line. For example, syntax analysis will be applied to each line independently from the other lines, and thus the interpreter takes a lot of time to translate the code. The compiler solves this issue as it is able to process all of the code at once, and thus syntax analysis will be applied only once rather than to each line of code. The generated bytecode from the compiler will thus be interpreted easily. Note that compiling the entire source code might not be helpful in some cases, and we’ll see a clear example of this when discussing PyPy."},{"code":null,"e":2926,"s":2696,"text":"After the bytecode is generated, it is executed by the interpreter running in the virtual machine. The virtual environment is beneficial, as it isolates the CPython bytecode from the machine, and thus makes Python cross-platform."},{"code":null,"e":3314,"s":2926,"text":"Unfortunately, just using a compiler to generate the bytecode is not enough to speed up the execution of CPython. The interpreter works by translating the code, each time it is executed, into machine code. Thus, if a line L takes X seconds to be executed, then executing it 10 times will have a cost of X*10 seconds. For long-running operations, this is too costly in its execution time."},{"code":null,"e":3380,"s":3314,"text":"Based on the drawbacks of CPython, let’s now take a look at PyPy."},{"code":null,"e":3896,"s":3380,"text":"PyPy is a Python implementation similar to CPython that is both compliant and fast. “Compliant” means that PyPy is compatible with CPython, as you can use nearly all CPython syntax in PyPy. There are some compatibility differences, as mentioned here. The most powerful advantage of PyPy is its speed. PyPy is much faster than CPython; we’ll see tests later on where PyPy performs about 7 times faster. In some cases it might even be tens or hundreds of times faster than CPython. So how does PyPy achieve its speed?"},{"code":null,"e":4217,"s":3896,"text":"PyPy uses a just-in-time (JIT) compiler that is able to dramatically increase the speed of Python scripts. The type of compilation used in CPython is ahead-of-time (AOT), meaning that all of the code will be translated into bytecode before being executed. JIT just translates the code at runtime, only when it is needed."},{"code":null,"e":4653,"s":4217,"text":"The source code might contain code blocks that are not executed at all, but which are still being translated using the AOT compiler. This leads to slower processing times. When the source code is large and contains thousands of lines, using a JIT makes a big difference. For AOT, the entire source code will be translated and thus take a lot of time. For JIT, just the needed parts of the code will be executed, making it a lot faster."},{"code":null,"e":4919,"s":4653,"text":"After PyPy translates a part of the code, it then gets cached. This means the code is translated only once, and then the translation is used later. The CPython interpreter repeats the translation each time the code is executed, an additional cause for its slowness."},{"code":null,"e":5380,"s":4919,"text":"PyPy is not the only way to boost the performance of Python scripts — but it is the easiest way. For example, Cython could be used to increase the speed of assigning C types to the variables. The problem is that Cython asks the developer to manually inspect the source code and optimize it. This is tiresome, and the complexity increases as the code size increases. When PyPy is used, you just run the regular Python code much faster without any effort at all."},{"code":null,"e":5587,"s":5380,"text":"Standard Python uses the C stack. This stack stores the sequence of functions that are called from each other (recursion). Because the stack size is limited, you are limited in the number of function calls."},{"code":null,"e":5830,"s":5587,"text":"PyPy uses Stackless Python, a Python implementation that does not use the C stack. Instead, it stores the function calls in the heap alongside the objects. The heap size is greater than the stack size, and thus you can do more function calls."},{"code":null,"e":6059,"s":5830,"text":"Stackless Python also supports microthreads, which are better than regular Python threads. Within the single Stackless Python thread you can run thousands of tasks, called “tasklets,” with all of them running on the same thread."},{"code":null,"e":6396,"s":6059,"text":"Using tasklets allows running concurrent tasks. Concurrency means that two tasks work simultaneously by sharing the same resources. One task runs for some time, then stops to make room for the second task to be executed. Note that this is different from parallelism, which involves running the two tasks separately but at the same time."},{"code":null,"e":6651,"s":6396,"text":"Using tasklets reduces the number of threads created, and thus reduces the overhead of managing all these threads by the OS. As a result, speeding up the execution by swapping between two threads is more time-intensive than swapping between two tasklets."},{"code":null,"e":7005,"s":6651,"text":"Using Stackless Python also opened the door for implementing continuations. Continuations allow us to save the state of a task and restore it later to continue its job. Note that Stackless Python is not different from Standard Python; it just adds more functionalities. Everything available in Standard Python will be available in Stackless Python, too."},{"code":null,"e":7098,"s":7005,"text":"After discussing the benefits of PyPy, let’s talk about its limitations in the next section."},{"code":null,"e":7202,"s":7098,"text":"While you can use CPython on any machine and any CPU architecture, PyPy has comparably limited support."},{"code":null,"e":7276,"s":7202,"text":"Here are the CPU architectures supported and maintained by PyPy (source):"},{"code":null,"e":7299,"s":7276,"text":"x86 (IA-32) and x86_64"},{"code":null,"e":7342,"s":7299,"text":"ARM platforms (ARMv6 or ARMv7, with VFPv3)"},{"code":null,"e":7350,"s":7342,"text":"AArch64"},{"code":null,"e":7392,"s":7350,"text":"PowerPC 64bit, both little and big endian"},{"code":null,"e":7409,"s":7392,"text":"System Z (s390x)"},{"code":null,"e":7677,"s":7409,"text":"PyPy cannot work on all Linux distributions, so you have to take care to use one that’s supported. Running PyPy Linux binary on an unsupported distribution will return an error. PyPy only supports one version of Python 2 and Python 3, which are PyPy 2.7 and PyPy 3.6."},{"code":null,"e":7987,"s":7677,"text":"If the code that is executed in PyPy is pure Python, then the speed offered by PyPy is usually noticeable. But if the code contains C extensions, such as NumPy, then PyPy might actually increase the time. The PyPy project is actively developed and thus may offer better support for C extensions in the future."},{"code":null,"e":8188,"s":7987,"text":"PyPy is not supported by a number of popular Python frameworks, such as Kivy. Kivy allows CPython to run on all platforms, including Android and iOS. This means that PyPy cannot run on mobile devices."},{"code":null,"e":8285,"s":8188,"text":"Now that we’ve seen the benefits and limitations of PyPy, let’s cover how to run PyPy on Ubuntu."},{"code":null,"e":8887,"s":8285,"text":"You can run PyPy on either Mac, Linux, or Windows, but we are going to discuss running it on Ubuntu. It is very important to mention again that PyPy Linux binaries are only supported on specific Linux distributions. You can check the available PyPy binaries and their supported distributions on this page. For example, PyPy (either Python 2.7 or Python 3.6) is only supported for three versions of Ubuntu: 18.04, 16.04 and 14.04. If you have the newest version of Ubuntu up to this date (19.10), then you cannot run PyPy on it. Trying to run PyPy on an unsupported distribution will return this error:"},{"code":null,"e":8934,"s":8887,"text":"pypy: error while loading shared libraries ..."},{"code":null,"e":8986,"s":8934,"text":"I simply use a virtual machine to run Ubuntu 18.04."},{"code":null,"e":9297,"s":8986,"text":"The PyPy binaries come as compressed files. All you need to do is to decompress the file you downloaded. Inside the decompressed directory there is a folder named bin, in which the PyPy executable file can be found. I am using Python 3.6 and thus the file is named pypy3. For Python 2.7, it's just called pypy."},{"code":null,"e":9446,"s":9297,"text":"For CPython, if you would like to run Python 3 from the terminal, you simply enter the command python3. To run PyPy, simply issue the command pypy3."},{"code":null,"e":9968,"s":9446,"text":"Entering the pypy3 command in the terminal might return the Command 'pypy3' not found message, as shown in the next figure. The reason is that the path of PyPy is not added to the PATH environment variable. The command that actually works is ./pypy3, taking into regard that the current path of the terminal is inside the bin directory of PyPy. The dot . refers to the current directory, and / is added to access something within the current directory. Issuing the ./pypy3 command runs Python successfully as given below."},{"code":null,"e":10174,"s":9968,"text":"You can now work with Python as usual, taking advantage of the benefits of PyPy. For example, we can create a simple Python script that sums 1,000 numbers and execute it using PyPy. The code is as follows."},{"code":null,"e":10273,"s":10174,"text":"nums = range(1000) sum = 0 for k in nums: sum = sum + kprint(\"Sum of 1,000 numbers is : \", sum)"},{"code":null,"e":10484,"s":10273,"text":"If this script is named test.py, then you can simply run it using the following command (assuming that the Python file is located inside the bin folder of PyPy, which is the same location of the pypy3 command)."},{"code":null,"e":10500,"s":10484,"text":"./pypy3 test.py"},{"code":null,"e":10565,"s":10500,"text":"The next figure shows the result of executing the previous code."},{"code":null,"e":10687,"s":10565,"text":"To compare the runtime of PyPy and CPython for summing 1,000 numbers, the code is changed to measure the time as follows."},{"code":null,"e":10880,"s":10687,"text":"import timet1 = time.time()nums = range(1000)sum = 0for k in nums: sum = sum + kprint(\"Sum of 1,000 numbers is : \", sum)t2 = time.time()t = t2 - t1print(\"Elapsed time is : \", t, \" seconds\")"},{"code":null,"e":11459,"s":10880,"text":"For PyPy the time is nearly 0.00045 seconds, compared to 0.0002 seconds for CPython (I ran the code on my Core i7-6500U machine @ 2.5GHz). In this case CPython takes less time compared to PyPy, which is to be expected since this task is not really a long-running task. If the code is changed to add 1 million numbers, rather than 1 thousand, then PyPy would end up winning. In this case it takes 0.00035 seconds for Pypy and 0.1 seconds for CPython. The benefit of PyPy is now obvious. This should give you an idea of how much slower CPython is for executing long-running tasks."},{"code":null,"e":11581,"s":11459,"text":"This article was originally published on the Paperspace blog. You can run the code for my tutorials for free on Gradient."},{"code":null,"e":11936,"s":11581,"text":"This tutorial introduced PyPy, the fastest Python implementation. The major benefit of PyPy is its just-in-time (JIT) compilation, which offers caching of the compiled machine code to avoid executing it again. The limitations of PyPy are also highlighted, the major one being that it works well for pure Python code but is not efficient for C extensions."}],"string":"[\n {\n \"code\": null,\n \"e\": 365,\n \"s\": 172,\n \"text\": \"The Python programming language is an interface that can be implemented in many ways. Some examples include CPython which uses the C language, Jython that is implemented using Java, and so on.\"\n },\n {\n \"code\": null,\n \"e\": 622,\n \"s\": 365,\n \"text\": \"Despite being the most popular, CPython is not the fastest. PyPy is an alternate Python implementation that is both compliant and fast. PyPy depends on just-in-time (JIT) compilation that dramatically reduces the execution time for long-running operations.\"\n },\n {\n \"code\": null,\n \"e\": 925,\n \"s\": 622,\n \"text\": \"In this tutorial, PyPy will be introduced for beginners to highlight how it is different from CPython. We’ll also cover its advantages and limitations. Then we’ll take a look at how to download and use PyPy to execute a simple Python script. PyPy supports hundreds of Python libraries, including NumPy.\"\n },\n {\n \"code\": null,\n \"e\": 975,\n \"s\": 925,\n \"text\": \"Specifically, this tutorial covers the following:\"\n },\n {\n \"code\": null,\n \"e\": 1003,\n \"s\": 975,\n \"text\": \"A quick overview of CPython\"\n },\n {\n \"code\": null,\n \"e\": 1041,\n \"s\": 1003,\n \"text\": \"Introduction to PyPy and its features\"\n },\n {\n \"code\": null,\n \"e\": 1058,\n \"s\": 1041,\n \"text\": \"PyPy limitations\"\n },\n {\n \"code\": null,\n \"e\": 1081,\n \"s\": 1058,\n \"text\": \"Running PyPy on Ubuntu\"\n },\n {\n \"code\": null,\n \"e\": 1115,\n \"s\": 1081,\n \"text\": \"Execution time of PyPy vs CPython\"\n },\n {\n \"code\": null,\n \"e\": 1134,\n \"s\": 1115,\n \"text\": \"Let’s get started.\"\n },\n {\n \"code\": null,\n \"e\": 1493,\n \"s\": 1134,\n \"text\": \"Before discussing PyPy, it is important to know how CPython works. My previous tutorial titled Boosting Python Scripts With Cython gave a longer introduction to how CPython works, but it won’t hurt to have a quick recap here about the important points. Below you can see a visualization of the execution pipeline of a Python script implemented using CPython.\"\n },\n {\n \"code\": null,\n \"e\": 1755,\n \"s\": 1493,\n \"text\": \"Given a Python .py script, the source code is first compiled using the CPython compiler into bytecode. The bytecode is generated and saved in a file with a .pyc extension. The bytecode is then executed using the CPython interpreter within a virtual environment.\"\n },\n {\n \"code\": null,\n \"e\": 2696,\n \"s\": 1755,\n \"text\": \"There are benefits to using the compiler to convert the source code into bytecode. If no compiler is used, then the interpreter will work directly on the source code by translating it line by line into machine code. The disadvantage of doing this is that some processes have to be applied for translating each line of source code into machine code, and such processes will be repeated for each line. For example, syntax analysis will be applied to each line independently from the other lines, and thus the interpreter takes a lot of time to translate the code. The compiler solves this issue as it is able to process all of the code at once, and thus syntax analysis will be applied only once rather than to each line of code. The generated bytecode from the compiler will thus be interpreted easily. Note that compiling the entire source code might not be helpful in some cases, and we’ll see a clear example of this when discussing PyPy.\"\n },\n {\n \"code\": null,\n \"e\": 2926,\n \"s\": 2696,\n \"text\": \"After the bytecode is generated, it is executed by the interpreter running in the virtual machine. The virtual environment is beneficial, as it isolates the CPython bytecode from the machine, and thus makes Python cross-platform.\"\n },\n {\n \"code\": null,\n \"e\": 3314,\n \"s\": 2926,\n \"text\": \"Unfortunately, just using a compiler to generate the bytecode is not enough to speed up the execution of CPython. The interpreter works by translating the code, each time it is executed, into machine code. Thus, if a line L takes X seconds to be executed, then executing it 10 times will have a cost of X*10 seconds. For long-running operations, this is too costly in its execution time.\"\n },\n {\n \"code\": null,\n \"e\": 3380,\n \"s\": 3314,\n \"text\": \"Based on the drawbacks of CPython, let’s now take a look at PyPy.\"\n },\n {\n \"code\": null,\n \"e\": 3896,\n \"s\": 3380,\n \"text\": \"PyPy is a Python implementation similar to CPython that is both compliant and fast. “Compliant” means that PyPy is compatible with CPython, as you can use nearly all CPython syntax in PyPy. There are some compatibility differences, as mentioned here. The most powerful advantage of PyPy is its speed. PyPy is much faster than CPython; we’ll see tests later on where PyPy performs about 7 times faster. In some cases it might even be tens or hundreds of times faster than CPython. So how does PyPy achieve its speed?\"\n },\n {\n \"code\": null,\n \"e\": 4217,\n \"s\": 3896,\n \"text\": \"PyPy uses a just-in-time (JIT) compiler that is able to dramatically increase the speed of Python scripts. The type of compilation used in CPython is ahead-of-time (AOT), meaning that all of the code will be translated into bytecode before being executed. JIT just translates the code at runtime, only when it is needed.\"\n },\n {\n \"code\": null,\n \"e\": 4653,\n \"s\": 4217,\n \"text\": \"The source code might contain code blocks that are not executed at all, but which are still being translated using the AOT compiler. This leads to slower processing times. When the source code is large and contains thousands of lines, using a JIT makes a big difference. For AOT, the entire source code will be translated and thus take a lot of time. For JIT, just the needed parts of the code will be executed, making it a lot faster.\"\n },\n {\n \"code\": null,\n \"e\": 4919,\n \"s\": 4653,\n \"text\": \"After PyPy translates a part of the code, it then gets cached. This means the code is translated only once, and then the translation is used later. The CPython interpreter repeats the translation each time the code is executed, an additional cause for its slowness.\"\n },\n {\n \"code\": null,\n \"e\": 5380,\n \"s\": 4919,\n \"text\": \"PyPy is not the only way to boost the performance of Python scripts — but it is the easiest way. For example, Cython could be used to increase the speed of assigning C types to the variables. The problem is that Cython asks the developer to manually inspect the source code and optimize it. This is tiresome, and the complexity increases as the code size increases. When PyPy is used, you just run the regular Python code much faster without any effort at all.\"\n },\n {\n \"code\": null,\n \"e\": 5587,\n \"s\": 5380,\n \"text\": \"Standard Python uses the C stack. This stack stores the sequence of functions that are called from each other (recursion). Because the stack size is limited, you are limited in the number of function calls.\"\n },\n {\n \"code\": null,\n \"e\": 5830,\n \"s\": 5587,\n \"text\": \"PyPy uses Stackless Python, a Python implementation that does not use the C stack. Instead, it stores the function calls in the heap alongside the objects. The heap size is greater than the stack size, and thus you can do more function calls.\"\n },\n {\n \"code\": null,\n \"e\": 6059,\n \"s\": 5830,\n \"text\": \"Stackless Python also supports microthreads, which are better than regular Python threads. Within the single Stackless Python thread you can run thousands of tasks, called “tasklets,” with all of them running on the same thread.\"\n },\n {\n \"code\": null,\n \"e\": 6396,\n \"s\": 6059,\n \"text\": \"Using tasklets allows running concurrent tasks. Concurrency means that two tasks work simultaneously by sharing the same resources. One task runs for some time, then stops to make room for the second task to be executed. Note that this is different from parallelism, which involves running the two tasks separately but at the same time.\"\n },\n {\n \"code\": null,\n \"e\": 6651,\n \"s\": 6396,\n \"text\": \"Using tasklets reduces the number of threads created, and thus reduces the overhead of managing all these threads by the OS. As a result, speeding up the execution by swapping between two threads is more time-intensive than swapping between two tasklets.\"\n },\n {\n \"code\": null,\n \"e\": 7005,\n \"s\": 6651,\n \"text\": \"Using Stackless Python also opened the door for implementing continuations. Continuations allow us to save the state of a task and restore it later to continue its job. Note that Stackless Python is not different from Standard Python; it just adds more functionalities. Everything available in Standard Python will be available in Stackless Python, too.\"\n },\n {\n \"code\": null,\n \"e\": 7098,\n \"s\": 7005,\n \"text\": \"After discussing the benefits of PyPy, let’s talk about its limitations in the next section.\"\n },\n {\n \"code\": null,\n \"e\": 7202,\n \"s\": 7098,\n \"text\": \"While you can use CPython on any machine and any CPU architecture, PyPy has comparably limited support.\"\n },\n {\n \"code\": null,\n \"e\": 7276,\n \"s\": 7202,\n \"text\": \"Here are the CPU architectures supported and maintained by PyPy (source):\"\n },\n {\n \"code\": null,\n \"e\": 7299,\n \"s\": 7276,\n \"text\": \"x86 (IA-32) and x86_64\"\n },\n {\n \"code\": null,\n \"e\": 7342,\n \"s\": 7299,\n \"text\": \"ARM platforms (ARMv6 or ARMv7, with VFPv3)\"\n },\n {\n \"code\": null,\n \"e\": 7350,\n \"s\": 7342,\n \"text\": \"AArch64\"\n },\n {\n \"code\": null,\n \"e\": 7392,\n \"s\": 7350,\n \"text\": \"PowerPC 64bit, both little and big endian\"\n },\n {\n \"code\": null,\n \"e\": 7409,\n \"s\": 7392,\n \"text\": \"System Z (s390x)\"\n },\n {\n \"code\": null,\n \"e\": 7677,\n \"s\": 7409,\n \"text\": \"PyPy cannot work on all Linux distributions, so you have to take care to use one that’s supported. Running PyPy Linux binary on an unsupported distribution will return an error. PyPy only supports one version of Python 2 and Python 3, which are PyPy 2.7 and PyPy 3.6.\"\n },\n {\n \"code\": null,\n \"e\": 7987,\n \"s\": 7677,\n \"text\": \"If the code that is executed in PyPy is pure Python, then the speed offered by PyPy is usually noticeable. But if the code contains C extensions, such as NumPy, then PyPy might actually increase the time. The PyPy project is actively developed and thus may offer better support for C extensions in the future.\"\n },\n {\n \"code\": null,\n \"e\": 8188,\n \"s\": 7987,\n \"text\": \"PyPy is not supported by a number of popular Python frameworks, such as Kivy. Kivy allows CPython to run on all platforms, including Android and iOS. This means that PyPy cannot run on mobile devices.\"\n },\n {\n \"code\": null,\n \"e\": 8285,\n \"s\": 8188,\n \"text\": \"Now that we’ve seen the benefits and limitations of PyPy, let’s cover how to run PyPy on Ubuntu.\"\n },\n {\n \"code\": null,\n \"e\": 8887,\n \"s\": 8285,\n \"text\": \"You can run PyPy on either Mac, Linux, or Windows, but we are going to discuss running it on Ubuntu. It is very important to mention again that PyPy Linux binaries are only supported on specific Linux distributions. You can check the available PyPy binaries and their supported distributions on this page. For example, PyPy (either Python 2.7 or Python 3.6) is only supported for three versions of Ubuntu: 18.04, 16.04 and 14.04. If you have the newest version of Ubuntu up to this date (19.10), then you cannot run PyPy on it. Trying to run PyPy on an unsupported distribution will return this error:\"\n },\n {\n \"code\": null,\n \"e\": 8934,\n \"s\": 8887,\n \"text\": \"pypy: error while loading shared libraries ...\"\n },\n {\n \"code\": null,\n \"e\": 8986,\n \"s\": 8934,\n \"text\": \"I simply use a virtual machine to run Ubuntu 18.04.\"\n },\n {\n \"code\": null,\n \"e\": 9297,\n \"s\": 8986,\n \"text\": \"The PyPy binaries come as compressed files. All you need to do is to decompress the file you downloaded. Inside the decompressed directory there is a folder named bin, in which the PyPy executable file can be found. I am using Python 3.6 and thus the file is named pypy3. For Python 2.7, it's just called pypy.\"\n },\n {\n \"code\": null,\n \"e\": 9446,\n \"s\": 9297,\n \"text\": \"For CPython, if you would like to run Python 3 from the terminal, you simply enter the command python3. To run PyPy, simply issue the command pypy3.\"\n },\n {\n \"code\": null,\n \"e\": 9968,\n \"s\": 9446,\n \"text\": \"Entering the pypy3 command in the terminal might return the Command 'pypy3' not found message, as shown in the next figure. The reason is that the path of PyPy is not added to the PATH environment variable. The command that actually works is ./pypy3, taking into regard that the current path of the terminal is inside the bin directory of PyPy. The dot . refers to the current directory, and / is added to access something within the current directory. Issuing the ./pypy3 command runs Python successfully as given below.\"\n },\n {\n \"code\": null,\n \"e\": 10174,\n \"s\": 9968,\n \"text\": \"You can now work with Python as usual, taking advantage of the benefits of PyPy. For example, we can create a simple Python script that sums 1,000 numbers and execute it using PyPy. The code is as follows.\"\n },\n {\n \"code\": null,\n \"e\": 10273,\n \"s\": 10174,\n \"text\": \"nums = range(1000) sum = 0 for k in nums: sum = sum + kprint(\\\"Sum of 1,000 numbers is : \\\", sum)\"\n },\n {\n \"code\": null,\n \"e\": 10484,\n \"s\": 10273,\n \"text\": \"If this script is named test.py, then you can simply run it using the following command (assuming that the Python file is located inside the bin folder of PyPy, which is the same location of the pypy3 command).\"\n },\n {\n \"code\": null,\n \"e\": 10500,\n \"s\": 10484,\n \"text\": \"./pypy3 test.py\"\n },\n {\n \"code\": null,\n \"e\": 10565,\n \"s\": 10500,\n \"text\": \"The next figure shows the result of executing the previous code.\"\n },\n {\n \"code\": null,\n \"e\": 10687,\n \"s\": 10565,\n \"text\": \"To compare the runtime of PyPy and CPython for summing 1,000 numbers, the code is changed to measure the time as follows.\"\n },\n {\n \"code\": null,\n \"e\": 10880,\n \"s\": 10687,\n \"text\": \"import timet1 = time.time()nums = range(1000)sum = 0for k in nums: sum = sum + kprint(\\\"Sum of 1,000 numbers is : \\\", sum)t2 = time.time()t = t2 - t1print(\\\"Elapsed time is : \\\", t, \\\" seconds\\\")\"\n },\n {\n \"code\": null,\n \"e\": 11459,\n \"s\": 10880,\n \"text\": \"For PyPy the time is nearly 0.00045 seconds, compared to 0.0002 seconds for CPython (I ran the code on my Core i7-6500U machine @ 2.5GHz). In this case CPython takes less time compared to PyPy, which is to be expected since this task is not really a long-running task. If the code is changed to add 1 million numbers, rather than 1 thousand, then PyPy would end up winning. In this case it takes 0.00035 seconds for Pypy and 0.1 seconds for CPython. The benefit of PyPy is now obvious. This should give you an idea of how much slower CPython is for executing long-running tasks.\"\n },\n {\n \"code\": null,\n \"e\": 11581,\n \"s\": 11459,\n \"text\": \"This article was originally published on the Paperspace blog. You can run the code for my tutorials for free on Gradient.\"\n },\n {\n \"code\": null,\n \"e\": 11936,\n \"s\": 11581,\n \"text\": \"This tutorial introduced PyPy, the fastest Python implementation. The major benefit of PyPy is its just-in-time (JIT) compilation, which offers caching of the compiled machine code to avoid executing it again. The limitations of PyPy are also highlighted, the major one being that it works well for pure Python code but is not efficient for C extensions.\"\n }\n]"}}},{"rowIdx":103,"cells":{"title":{"kind":"string","value":"Difference between Private and Protected in C++ with Example - GeeksforGeeks"},"text":{"kind":"string","value":"03 Jan, 2022\nProtected\nProtected access modifier is similar to that of private access modifiers, the difference is that the class member declared as Protected are inaccessible outside the class but they can be accessed by any subclass(derived class) of that class.Example: \nCPP\n// C++ program to demonstrate// protected access modifier #include using namespace std; // base classclass Parent { // protected data membersprotected: int id_protected;}; // sub class or derived classclass Child : public Parent { public: void setId(int id) { // Child class is able to access the inherited // protected data members of the base class id_protected = id; } void displayId() { cout << \"id_protected is: \" << id_protected << endl; }}; // main functionint main(){ Child obj1; // member function of the derived class can // access the protected data members of the base class obj1.setId(81); obj1.displayId(); return 0;}\nid_protected is: 81\n \nPrivate\nThe class members declared as private can be accessed only by the functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of a class.Example: \nCPP\n// C++ program to demonstrate private// access modifier #include using namespace std; class Circle { // private data memberprivate: double radius; // public member functionpublic: void compute_area(double r) { // member function can access private // data member radius radius = r; double area = 3.14 * radius * radius; cout << \"Radius is: \" << radius << endl; cout << \"Area is: \" << area; }}; // main functionint main(){ // creating object of the class Circle obj; // trying to access private data member // directly outside the class obj.compute_area(1.5); return 0;}\nRadius is: 1.5\nArea is: 7.065\n \nDifference between Private and Protected\nitskawal2000\naccess modifiers\nC++\nCPP\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nComments\nOld Comments\nMap in C++ Standard Template Library (STL)\nBitwise Operators in C/C++\nSocket Programming in C/C++\nOperator Overloading in C++\nMultidimensional Arrays in C / C++\nTemplates in C++ with Examples\nvector erase() and clear() in C++\nrand() and srand() in C/C++\nunordered_map in C++ STL\nObject Oriented Programming in C++"},"parsed":{"kind":"list like","value":[{"code":null,"e":23792,"s":23764,"text":"\n03 Jan, 2022"},{"code":null,"e":23802,"s":23792,"text":"Protected"},{"code":null,"e":24054,"s":23802,"text":"Protected access modifier is similar to that of private access modifiers, the difference is that the class member declared as Protected are inaccessible outside the class but they can be accessed by any subclass(derived class) of that class.Example: "},{"code":null,"e":24058,"s":24054,"text":"CPP"},{"code":"// C++ program to demonstrate// protected access modifier #include using namespace std; // base classclass Parent { // protected data membersprotected: int id_protected;}; // sub class or derived classclass Child : public Parent { public: void setId(int id) { // Child class is able to access the inherited // protected data members of the base class id_protected = id; } void displayId() { cout << \"id_protected is: \" << id_protected << endl; }}; // main functionint main(){ Child obj1; // member function of the derived class can // access the protected data members of the base class obj1.setId(81); obj1.displayId(); return 0;}","e":24794,"s":24058,"text":null},{"code":null,"e":24814,"s":24794,"text":"id_protected is: 81"},{"code":null,"e":24824,"s":24816,"text":"Private"},{"code":null,"e":25126,"s":24824,"text":"The class members declared as private can be accessed only by the functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of a class.Example: "},{"code":null,"e":25130,"s":25126,"text":"CPP"},{"code":"// C++ program to demonstrate private// access modifier #include using namespace std; class Circle { // private data memberprivate: double radius; // public member functionpublic: void compute_area(double r) { // member function can access private // data member radius radius = r; double area = 3.14 * radius * radius; cout << \"Radius is: \" << radius << endl; cout << \"Area is: \" << area; }}; // main functionint main(){ // creating object of the class Circle obj; // trying to access private data member // directly outside the class obj.compute_area(1.5); return 0;}","e":25794,"s":25130,"text":null},{"code":null,"e":25824,"s":25794,"text":"Radius is: 1.5\nArea is: 7.065"},{"code":null,"e":25867,"s":25826,"text":"Difference between Private and Protected"},{"code":null,"e":25880,"s":25867,"text":"itskawal2000"},{"code":null,"e":25897,"s":25880,"text":"access modifiers"},{"code":null,"e":25901,"s":25897,"text":"C++"},{"code":null,"e":25905,"s":25901,"text":"CPP"},{"code":null,"e":26003,"s":25905,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":26012,"s":26003,"text":"Comments"},{"code":null,"e":26025,"s":26012,"text":"Old Comments"},{"code":null,"e":26068,"s":26025,"text":"Map in C++ Standard Template Library (STL)"},{"code":null,"e":26095,"s":26068,"text":"Bitwise Operators in C/C++"},{"code":null,"e":26123,"s":26095,"text":"Socket Programming in C/C++"},{"code":null,"e":26151,"s":26123,"text":"Operator Overloading in C++"},{"code":null,"e":26186,"s":26151,"text":"Multidimensional Arrays in C / C++"},{"code":null,"e":26217,"s":26186,"text":"Templates in C++ with Examples"},{"code":null,"e":26251,"s":26217,"text":"vector erase() and clear() in C++"},{"code":null,"e":26279,"s":26251,"text":"rand() and srand() in C/C++"},{"code":null,"e":26304,"s":26279,"text":"unordered_map in C++ STL"}],"string":"[\n {\n \"code\": null,\n \"e\": 23792,\n \"s\": 23764,\n \"text\": \"\\n03 Jan, 2022\"\n },\n {\n \"code\": null,\n \"e\": 23802,\n \"s\": 23792,\n \"text\": \"Protected\"\n },\n {\n \"code\": null,\n \"e\": 24054,\n \"s\": 23802,\n \"text\": \"Protected access modifier is similar to that of private access modifiers, the difference is that the class member declared as Protected are inaccessible outside the class but they can be accessed by any subclass(derived class) of that class.Example: \"\n },\n {\n \"code\": null,\n \"e\": 24058,\n \"s\": 24054,\n \"text\": \"CPP\"\n },\n {\n \"code\": \"// C++ program to demonstrate// protected access modifier #include using namespace std; // base classclass Parent { // protected data membersprotected: int id_protected;}; // sub class or derived classclass Child : public Parent { public: void setId(int id) { // Child class is able to access the inherited // protected data members of the base class id_protected = id; } void displayId() { cout << \\\"id_protected is: \\\" << id_protected << endl; }}; // main functionint main(){ Child obj1; // member function of the derived class can // access the protected data members of the base class obj1.setId(81); obj1.displayId(); return 0;}\",\n \"e\": 24794,\n \"s\": 24058,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 24814,\n \"s\": 24794,\n \"text\": \"id_protected is: 81\"\n },\n {\n \"code\": null,\n \"e\": 24824,\n \"s\": 24816,\n \"text\": \"Private\"\n },\n {\n \"code\": null,\n \"e\": 25126,\n \"s\": 24824,\n \"text\": \"The class members declared as private can be accessed only by the functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of a class.Example: \"\n },\n {\n \"code\": null,\n \"e\": 25130,\n \"s\": 25126,\n \"text\": \"CPP\"\n },\n {\n \"code\": \"// C++ program to demonstrate private// access modifier #include using namespace std; class Circle { // private data memberprivate: double radius; // public member functionpublic: void compute_area(double r) { // member function can access private // data member radius radius = r; double area = 3.14 * radius * radius; cout << \\\"Radius is: \\\" << radius << endl; cout << \\\"Area is: \\\" << area; }}; // main functionint main(){ // creating object of the class Circle obj; // trying to access private data member // directly outside the class obj.compute_area(1.5); return 0;}\",\n \"e\": 25794,\n \"s\": 25130,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 25824,\n \"s\": 25794,\n \"text\": \"Radius is: 1.5\\nArea is: 7.065\"\n },\n {\n \"code\": null,\n \"e\": 25867,\n \"s\": 25826,\n \"text\": \"Difference between Private and Protected\"\n },\n {\n \"code\": null,\n \"e\": 25880,\n \"s\": 25867,\n \"text\": \"itskawal2000\"\n },\n {\n \"code\": null,\n \"e\": 25897,\n \"s\": 25880,\n \"text\": \"access modifiers\"\n },\n {\n \"code\": null,\n \"e\": 25901,\n \"s\": 25897,\n \"text\": \"C++\"\n },\n {\n \"code\": null,\n \"e\": 25905,\n \"s\": 25901,\n \"text\": \"CPP\"\n },\n {\n \"code\": null,\n \"e\": 26003,\n \"s\": 25905,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 26012,\n \"s\": 26003,\n \"text\": \"Comments\"\n },\n {\n \"code\": null,\n \"e\": 26025,\n \"s\": 26012,\n \"text\": \"Old Comments\"\n },\n {\n \"code\": null,\n \"e\": 26068,\n \"s\": 26025,\n \"text\": \"Map in C++ Standard Template Library (STL)\"\n },\n {\n \"code\": null,\n \"e\": 26095,\n \"s\": 26068,\n \"text\": \"Bitwise Operators in C/C++\"\n },\n {\n \"code\": null,\n \"e\": 26123,\n \"s\": 26095,\n \"text\": \"Socket Programming in C/C++\"\n },\n {\n \"code\": null,\n \"e\": 26151,\n \"s\": 26123,\n \"text\": \"Operator Overloading in C++\"\n },\n {\n \"code\": null,\n \"e\": 26186,\n \"s\": 26151,\n \"text\": \"Multidimensional Arrays in C / C++\"\n },\n {\n \"code\": null,\n \"e\": 26217,\n \"s\": 26186,\n \"text\": \"Templates in C++ with Examples\"\n },\n {\n \"code\": null,\n \"e\": 26251,\n \"s\": 26217,\n \"text\": \"vector erase() and clear() in C++\"\n },\n {\n \"code\": null,\n \"e\": 26279,\n \"s\": 26251,\n \"text\": \"rand() and srand() in C/C++\"\n },\n {\n \"code\": null,\n \"e\": 26304,\n \"s\": 26279,\n \"text\": \"unordered_map in C++ STL\"\n }\n]"}}},{"rowIdx":104,"cells":{"title":{"kind":"string","value":"Should you learn Julia?. Is the high performing lovechild of... | by Alexander Bailey | Towards Data Science"},"text":{"kind":"string","value":"Julia is the newest ‘it’ language of the moment, so I thought I’d give it a try. The question is, is it something worth adding to a data scientist's arsenal?\nThe first thing to know about Julia is that it was easy to download and use (on Mac anyway, good luck Windows users). It was also a breeze to install the kernel to allow it to work within Jupyter notebooks.\nJulia isn’t an object-oriented language like Python, so to get writing we need to let go of some (but not all) of those tidy ‘Pythonic’ ways of doing things.\nClasses don’t exist in Julia, so we have to make do with structures like we would with MATLAB. Again, like MATLAB, Julia adopts excellent syntax for linear algebra, which is built natively into the language. This replaces the need for modules like NumPy, in favour of more intuitive syntax like A*x , x' and ./ for multiplication, complex conjugate and pointwise division.\nThe other thing that users should be wary of, and have to get used to with Julia, is ending functions and loops with theend keyword. However, you’ll be pleased to hear that the reason for this is because Julia isn’t a whitespace sensitive language so you’ll never see an “inconsistent use of tabs and spaces in indentation” error again!\nJulia is still technically a dynamically typed language, meaning that you don’t need to tell it which variable has which type — similar to how Python works.\nHowever, Julia does support typing which can enforce a variable to be a specific type, unlike Python. This is pretty handy for two reasons:\nIt allows Julia code to run faster than a fully dynamic language, if a variable is typed then it doesn’t need to check what type it is before performing the calculation.Debugging is easier when dealing with typed variables, as variables can’t be accidentally assigned to a different type without you explicitly doing it. To get the same effect in Python you have to spend a lot of time implementing assert statements on each function input and even then, things can still go wrong!\nIt allows Julia code to run faster than a fully dynamic language, if a variable is typed then it doesn’t need to check what type it is before performing the calculation.\nDebugging is easier when dealing with typed variables, as variables can’t be accidentally assigned to a different type without you explicitly doing it. To get the same effect in Python you have to spend a lot of time implementing assert statements on each function input and even then, things can still go wrong!\nThis is one of Julia’s niftiest features...\nWhen implementing mathematical expressions in MATLAB or Python, we can often be met with variables like x_hat or sigma . However, in Julia, we can use the Unicode characters as variables instead of giving us x̂, and σ!\n“Well how am I supposed to remember the keyboard combination for x̂and σ? I’m not googling it every time I want to use it!”\nIt’s a valid concern, but not to fear as the core developers of Julia are one step ahead of us. For x̂, just write x\\hat ⇥ and forσ , write\\sigma ⇥ , similar to how you would in LaTex.\nWhilst the cynics may think this is a gimmicky feature, I think it allows for much more readable code and as the Zen of Python says, “Readability counts”.\nIn my last article, we implemented a logistic regression model from scratch but what does that look like in Julia?\nfunction σ(x::Array{Float64,2}) return 1.0 ./ (1.0 .+ exp.(-x))endfunction fit( X::Array{Float64,2}, y::Array{Float64,1}, epochs::Int64=100, μ::Float64=0.0001 ) ε::Float64 = 0.00001 loss = [] X = vcat(X, ones(1,size(X)[end])) dims, n_data_points = size(X) w = randn(1,dims) for i in 1:epochs X̂ = w*X ŷ = σ(X̂) cost = -sum(y'.*log.(ŷ .+ ε) .+ (1 .- y').*log.(1 .- ŷ .+ ε)) dc_dw = -sum((y' .- ŷ).*X,dims=2)' w = w .- dc_dw * μ append!(loss,cost) end return w,lossendfunction predict(X::Array{Float64,2},w::Array{Float64,1}) X = vcat(X, ones(1,size(X)[end])) X̂ = w*X ŷ = σ(X̂) return ŷend\nIn this implementation, we can see a perfect example of how Julia’s Unicode characters can make code more readable. The native linear algebra support further simplifies the code by removing np. every time we want to perform multiplication or summation. We have also typed the function inputs to ensure that both the type and dimensionality of the inputs are valid.\nJulia’s C based pedigree and typing allow for some pretty nice speed improvements over its sluggish Python parent. This can all be done without making any major improvements to the efficiency of the code.\nLet’s calculate the first 10,000 prime numbers with this simple Python function:\ndef n_primes(n:int)->list: primes = [] i = 2 while len(primes) < n: prime_bool = True for j in range(2,i//2+1): if i%j == 0: prime_bool = False if prime_bool == True: primes.append(i) i += 1 return primes\nWhich takes 2 min 42s. Let’s compare that to Julia when we use typing:\nfunction n_primes(n::Int64) primes = Int64[] i::Int64 = 2 while size(primes)[1] < n prime_bool::Bool = true for j = 2:i÷2 if i%j == 0 prime_bool = false end end if prime_bool == true append!(primes,i) end i += 1 end return primesend>> @time n_primes(10000)\nThis took just 7.55 seconds!\nFor the intrepid amongst us who want to deploy code in the wild, then compiling to a binary is a useful tool to have.\nPython developers are no strangers with the issue of defining dependencies, and wrestling with pip to ensure all packages remain interoperable. Julia’s nifty solution to this is to compile to a single binary. Not only does this mean that deployment can be as simple as putting that binary in a Docker container and launching your service, but it also means that this comes with the same security improvements that come with using languages like Go.\nThen don’t let Julia stop you, there is a Python interpreter built directly into Julia so using Python is as simple as using Pycall.\nusing Pycallpackagename = pyimport(“packagename”)\nIt really is as easy as that! Pycall allows the use of all built-in Python namespace functions and feature (even use context managers).\nDebugging isn’t quite as easy as it is in Python; this could be that I’m just familiar with Python’s traceback errors, or that Python just has a more descriptive way of telling you where your mistake is.\nHere’s a quick example to try and illustrate in Python:\n... and in Julia:\nI think one of these is a lot clearer than the other...\nThe only other issue with Julia is the lack of support for machine learning libraries. This may be a product of its relative youth, but it remains a frustrating feature. Julia has wrappers for Pandas, TensorFlow and Sklearn but this doesn’t help us if we want to grab a pre-trained ResNet 50 or a Bert model as the chances are they will be written in Python.\nHaving said that, the Julia community is growing and more native libraries are being built on an almost daily basis like Lathe and MLJ, so there’s hope for us yet!\nThe lack of class-based objects in Julia can also make using some of those libraries somewhat unwieldy when used outside of Python. For example Pandas’ df.loc[] becomesloc!(df, ).\nFinally, there are too many functions in the basis namespace of Julia. In some ways, this is convenient and allows for a MATLAB-like level of usability and ease of writing code. However, it makes the readability of Julia code worse, with it often being hard to tell if a function is there by default, if it’s user-defined or if it’s been imported from another module.\nI say yes! What’s the harm anyway? Writing production code in Julia is going to be tough at the moment given the lack of supported libraries available. But, Julia does offer easy to learn syntax, blazing fast code execution, a built-in Python interpreter and host of other potential improvements to a data scientist’s workflow. Given its growing popularity, there might just be a reason to switch over in the future or, maybe your next project has some pretty tough performance constraints? Julia might just be the answer."},"parsed":{"kind":"list like","value":[{"code":null,"e":330,"s":172,"text":"Julia is the newest ‘it’ language of the moment, so I thought I’d give it a try. The question is, is it something worth adding to a data scientist's arsenal?"},{"code":null,"e":537,"s":330,"text":"The first thing to know about Julia is that it was easy to download and use (on Mac anyway, good luck Windows users). It was also a breeze to install the kernel to allow it to work within Jupyter notebooks."},{"code":null,"e":695,"s":537,"text":"Julia isn’t an object-oriented language like Python, so to get writing we need to let go of some (but not all) of those tidy ‘Pythonic’ ways of doing things."},{"code":null,"e":1068,"s":695,"text":"Classes don’t exist in Julia, so we have to make do with structures like we would with MATLAB. Again, like MATLAB, Julia adopts excellent syntax for linear algebra, which is built natively into the language. This replaces the need for modules like NumPy, in favour of more intuitive syntax like A*x , x' and ./ for multiplication, complex conjugate and pointwise division."},{"code":null,"e":1405,"s":1068,"text":"The other thing that users should be wary of, and have to get used to with Julia, is ending functions and loops with theend keyword. However, you’ll be pleased to hear that the reason for this is because Julia isn’t a whitespace sensitive language so you’ll never see an “inconsistent use of tabs and spaces in indentation” error again!"},{"code":null,"e":1562,"s":1405,"text":"Julia is still technically a dynamically typed language, meaning that you don’t need to tell it which variable has which type — similar to how Python works."},{"code":null,"e":1702,"s":1562,"text":"However, Julia does support typing which can enforce a variable to be a specific type, unlike Python. This is pretty handy for two reasons:"},{"code":null,"e":2184,"s":1702,"text":"It allows Julia code to run faster than a fully dynamic language, if a variable is typed then it doesn’t need to check what type it is before performing the calculation.Debugging is easier when dealing with typed variables, as variables can’t be accidentally assigned to a different type without you explicitly doing it. To get the same effect in Python you have to spend a lot of time implementing assert statements on each function input and even then, things can still go wrong!"},{"code":null,"e":2354,"s":2184,"text":"It allows Julia code to run faster than a fully dynamic language, if a variable is typed then it doesn’t need to check what type it is before performing the calculation."},{"code":null,"e":2667,"s":2354,"text":"Debugging is easier when dealing with typed variables, as variables can’t be accidentally assigned to a different type without you explicitly doing it. To get the same effect in Python you have to spend a lot of time implementing assert statements on each function input and even then, things can still go wrong!"},{"code":null,"e":2711,"s":2667,"text":"This is one of Julia’s niftiest features..."},{"code":null,"e":2930,"s":2711,"text":"When implementing mathematical expressions in MATLAB or Python, we can often be met with variables like x_hat or sigma . However, in Julia, we can use the Unicode characters as variables instead of giving us x̂, and σ!"},{"code":null,"e":3054,"s":2930,"text":"“Well how am I supposed to remember the keyboard combination for x̂and σ? I’m not googling it every time I want to use it!”"},{"code":null,"e":3239,"s":3054,"text":"It’s a valid concern, but not to fear as the core developers of Julia are one step ahead of us. For x̂, just write x\\hat ⇥ and forσ , write\\sigma ⇥ , similar to how you would in LaTex."},{"code":null,"e":3394,"s":3239,"text":"Whilst the cynics may think this is a gimmicky feature, I think it allows for much more readable code and as the Zen of Python says, “Readability counts”."},{"code":null,"e":3509,"s":3394,"text":"In my last article, we implemented a logistic regression model from scratch but what does that look like in Julia?"},{"code":null,"e":4236,"s":3509,"text":"function σ(x::Array{Float64,2}) return 1.0 ./ (1.0 .+ exp.(-x))endfunction fit( X::Array{Float64,2}, y::Array{Float64,1}, epochs::Int64=100, μ::Float64=0.0001 ) ε::Float64 = 0.00001 loss = [] X = vcat(X, ones(1,size(X)[end])) dims, n_data_points = size(X) w = randn(1,dims) for i in 1:epochs X̂ = w*X ŷ = σ(X̂) cost = -sum(y'.*log.(ŷ .+ ε) .+ (1 .- y').*log.(1 .- ŷ .+ ε)) dc_dw = -sum((y' .- ŷ).*X,dims=2)' w = w .- dc_dw * μ append!(loss,cost) end return w,lossendfunction predict(X::Array{Float64,2},w::Array{Float64,1}) X = vcat(X, ones(1,size(X)[end])) X̂ = w*X ŷ = σ(X̂) return ŷend"},{"code":null,"e":4601,"s":4236,"text":"In this implementation, we can see a perfect example of how Julia’s Unicode characters can make code more readable. The native linear algebra support further simplifies the code by removing np. every time we want to perform multiplication or summation. We have also typed the function inputs to ensure that both the type and dimensionality of the inputs are valid."},{"code":null,"e":4806,"s":4601,"text":"Julia’s C based pedigree and typing allow for some pretty nice speed improvements over its sluggish Python parent. This can all be done without making any major improvements to the efficiency of the code."},{"code":null,"e":4887,"s":4806,"text":"Let’s calculate the first 10,000 prime numbers with this simple Python function:"},{"code":null,"e":5171,"s":4887,"text":"def n_primes(n:int)->list: primes = [] i = 2 while len(primes) < n: prime_bool = True for j in range(2,i//2+1): if i%j == 0: prime_bool = False if prime_bool == True: primes.append(i) i += 1 return primes"},{"code":null,"e":5242,"s":5171,"text":"Which takes 2 min 42s. Let’s compare that to Julia when we use typing:"},{"code":null,"e":5606,"s":5242,"text":"function n_primes(n::Int64) primes = Int64[] i::Int64 = 2 while size(primes)[1] < n prime_bool::Bool = true for j = 2:i÷2 if i%j == 0 prime_bool = false end end if prime_bool == true append!(primes,i) end i += 1 end return primesend>> @time n_primes(10000)"},{"code":null,"e":5635,"s":5606,"text":"This took just 7.55 seconds!"},{"code":null,"e":5753,"s":5635,"text":"For the intrepid amongst us who want to deploy code in the wild, then compiling to a binary is a useful tool to have."},{"code":null,"e":6202,"s":5753,"text":"Python developers are no strangers with the issue of defining dependencies, and wrestling with pip to ensure all packages remain interoperable. Julia’s nifty solution to this is to compile to a single binary. Not only does this mean that deployment can be as simple as putting that binary in a Docker container and launching your service, but it also means that this comes with the same security improvements that come with using languages like Go."},{"code":null,"e":6335,"s":6202,"text":"Then don’t let Julia stop you, there is a Python interpreter built directly into Julia so using Python is as simple as using Pycall."},{"code":null,"e":6385,"s":6335,"text":"using Pycallpackagename = pyimport(“packagename”)"},{"code":null,"e":6521,"s":6385,"text":"It really is as easy as that! Pycall allows the use of all built-in Python namespace functions and feature (even use context managers)."},{"code":null,"e":6725,"s":6521,"text":"Debugging isn’t quite as easy as it is in Python; this could be that I’m just familiar with Python’s traceback errors, or that Python just has a more descriptive way of telling you where your mistake is."},{"code":null,"e":6781,"s":6725,"text":"Here’s a quick example to try and illustrate in Python:"},{"code":null,"e":6799,"s":6781,"text":"... and in Julia:"},{"code":null,"e":6855,"s":6799,"text":"I think one of these is a lot clearer than the other..."},{"code":null,"e":7214,"s":6855,"text":"The only other issue with Julia is the lack of support for machine learning libraries. This may be a product of its relative youth, but it remains a frustrating feature. Julia has wrappers for Pandas, TensorFlow and Sklearn but this doesn’t help us if we want to grab a pre-trained ResNet 50 or a Bert model as the chances are they will be written in Python."},{"code":null,"e":7378,"s":7214,"text":"Having said that, the Julia community is growing and more native libraries are being built on an almost daily basis like Lathe and MLJ, so there’s hope for us yet!"},{"code":null,"e":7558,"s":7378,"text":"The lack of class-based objects in Julia can also make using some of those libraries somewhat unwieldy when used outside of Python. For example Pandas’ df.loc[] becomesloc!(df, )."},{"code":null,"e":7926,"s":7558,"text":"Finally, there are too many functions in the basis namespace of Julia. In some ways, this is convenient and allows for a MATLAB-like level of usability and ease of writing code. However, it makes the readability of Julia code worse, with it often being hard to tell if a function is there by default, if it’s user-defined or if it’s been imported from another module."}],"string":"[\n {\n \"code\": null,\n \"e\": 330,\n \"s\": 172,\n \"text\": \"Julia is the newest ‘it’ language of the moment, so I thought I’d give it a try. The question is, is it something worth adding to a data scientist's arsenal?\"\n },\n {\n \"code\": null,\n \"e\": 537,\n \"s\": 330,\n \"text\": \"The first thing to know about Julia is that it was easy to download and use (on Mac anyway, good luck Windows users). It was also a breeze to install the kernel to allow it to work within Jupyter notebooks.\"\n },\n {\n \"code\": null,\n \"e\": 695,\n \"s\": 537,\n \"text\": \"Julia isn’t an object-oriented language like Python, so to get writing we need to let go of some (but not all) of those tidy ‘Pythonic’ ways of doing things.\"\n },\n {\n \"code\": null,\n \"e\": 1068,\n \"s\": 695,\n \"text\": \"Classes don’t exist in Julia, so we have to make do with structures like we would with MATLAB. Again, like MATLAB, Julia adopts excellent syntax for linear algebra, which is built natively into the language. This replaces the need for modules like NumPy, in favour of more intuitive syntax like A*x , x' and ./ for multiplication, complex conjugate and pointwise division.\"\n },\n {\n \"code\": null,\n \"e\": 1405,\n \"s\": 1068,\n \"text\": \"The other thing that users should be wary of, and have to get used to with Julia, is ending functions and loops with theend keyword. However, you’ll be pleased to hear that the reason for this is because Julia isn’t a whitespace sensitive language so you’ll never see an “inconsistent use of tabs and spaces in indentation” error again!\"\n },\n {\n \"code\": null,\n \"e\": 1562,\n \"s\": 1405,\n \"text\": \"Julia is still technically a dynamically typed language, meaning that you don’t need to tell it which variable has which type — similar to how Python works.\"\n },\n {\n \"code\": null,\n \"e\": 1702,\n \"s\": 1562,\n \"text\": \"However, Julia does support typing which can enforce a variable to be a specific type, unlike Python. This is pretty handy for two reasons:\"\n },\n {\n \"code\": null,\n \"e\": 2184,\n \"s\": 1702,\n \"text\": \"It allows Julia code to run faster than a fully dynamic language, if a variable is typed then it doesn’t need to check what type it is before performing the calculation.Debugging is easier when dealing with typed variables, as variables can’t be accidentally assigned to a different type without you explicitly doing it. To get the same effect in Python you have to spend a lot of time implementing assert statements on each function input and even then, things can still go wrong!\"\n },\n {\n \"code\": null,\n \"e\": 2354,\n \"s\": 2184,\n \"text\": \"It allows Julia code to run faster than a fully dynamic language, if a variable is typed then it doesn’t need to check what type it is before performing the calculation.\"\n },\n {\n \"code\": null,\n \"e\": 2667,\n \"s\": 2354,\n \"text\": \"Debugging is easier when dealing with typed variables, as variables can’t be accidentally assigned to a different type without you explicitly doing it. To get the same effect in Python you have to spend a lot of time implementing assert statements on each function input and even then, things can still go wrong!\"\n },\n {\n \"code\": null,\n \"e\": 2711,\n \"s\": 2667,\n \"text\": \"This is one of Julia’s niftiest features...\"\n },\n {\n \"code\": null,\n \"e\": 2930,\n \"s\": 2711,\n \"text\": \"When implementing mathematical expressions in MATLAB or Python, we can often be met with variables like x_hat or sigma . However, in Julia, we can use the Unicode characters as variables instead of giving us x̂, and σ!\"\n },\n {\n \"code\": null,\n \"e\": 3054,\n \"s\": 2930,\n \"text\": \"“Well how am I supposed to remember the keyboard combination for x̂and σ? I’m not googling it every time I want to use it!”\"\n },\n {\n \"code\": null,\n \"e\": 3239,\n \"s\": 3054,\n \"text\": \"It’s a valid concern, but not to fear as the core developers of Julia are one step ahead of us. For x̂, just write x\\\\hat ⇥ and forσ , write\\\\sigma ⇥ , similar to how you would in LaTex.\"\n },\n {\n \"code\": null,\n \"e\": 3394,\n \"s\": 3239,\n \"text\": \"Whilst the cynics may think this is a gimmicky feature, I think it allows for much more readable code and as the Zen of Python says, “Readability counts”.\"\n },\n {\n \"code\": null,\n \"e\": 3509,\n \"s\": 3394,\n \"text\": \"In my last article, we implemented a logistic regression model from scratch but what does that look like in Julia?\"\n },\n {\n \"code\": null,\n \"e\": 4236,\n \"s\": 3509,\n \"text\": \"function σ(x::Array{Float64,2}) return 1.0 ./ (1.0 .+ exp.(-x))endfunction fit( X::Array{Float64,2}, y::Array{Float64,1}, epochs::Int64=100, μ::Float64=0.0001 ) ε::Float64 = 0.00001 loss = [] X = vcat(X, ones(1,size(X)[end])) dims, n_data_points = size(X) w = randn(1,dims) for i in 1:epochs X̂ = w*X ŷ = σ(X̂) cost = -sum(y'.*log.(ŷ .+ ε) .+ (1 .- y').*log.(1 .- ŷ .+ ε)) dc_dw = -sum((y' .- ŷ).*X,dims=2)' w = w .- dc_dw * μ append!(loss,cost) end return w,lossendfunction predict(X::Array{Float64,2},w::Array{Float64,1}) X = vcat(X, ones(1,size(X)[end])) X̂ = w*X ŷ = σ(X̂) return ŷend\"\n },\n {\n \"code\": null,\n \"e\": 4601,\n \"s\": 4236,\n \"text\": \"In this implementation, we can see a perfect example of how Julia’s Unicode characters can make code more readable. The native linear algebra support further simplifies the code by removing np. every time we want to perform multiplication or summation. We have also typed the function inputs to ensure that both the type and dimensionality of the inputs are valid.\"\n },\n {\n \"code\": null,\n \"e\": 4806,\n \"s\": 4601,\n \"text\": \"Julia’s C based pedigree and typing allow for some pretty nice speed improvements over its sluggish Python parent. This can all be done without making any major improvements to the efficiency of the code.\"\n },\n {\n \"code\": null,\n \"e\": 4887,\n \"s\": 4806,\n \"text\": \"Let’s calculate the first 10,000 prime numbers with this simple Python function:\"\n },\n {\n \"code\": null,\n \"e\": 5171,\n \"s\": 4887,\n \"text\": \"def n_primes(n:int)->list: primes = [] i = 2 while len(primes) < n: prime_bool = True for j in range(2,i//2+1): if i%j == 0: prime_bool = False if prime_bool == True: primes.append(i) i += 1 return primes\"\n },\n {\n \"code\": null,\n \"e\": 5242,\n \"s\": 5171,\n \"text\": \"Which takes 2 min 42s. Let’s compare that to Julia when we use typing:\"\n },\n {\n \"code\": null,\n \"e\": 5606,\n \"s\": 5242,\n \"text\": \"function n_primes(n::Int64) primes = Int64[] i::Int64 = 2 while size(primes)[1] < n prime_bool::Bool = true for j = 2:i÷2 if i%j == 0 prime_bool = false end end if prime_bool == true append!(primes,i) end i += 1 end return primesend>> @time n_primes(10000)\"\n },\n {\n \"code\": null,\n \"e\": 5635,\n \"s\": 5606,\n \"text\": \"This took just 7.55 seconds!\"\n },\n {\n \"code\": null,\n \"e\": 5753,\n \"s\": 5635,\n \"text\": \"For the intrepid amongst us who want to deploy code in the wild, then compiling to a binary is a useful tool to have.\"\n },\n {\n \"code\": null,\n \"e\": 6202,\n \"s\": 5753,\n \"text\": \"Python developers are no strangers with the issue of defining dependencies, and wrestling with pip to ensure all packages remain interoperable. Julia’s nifty solution to this is to compile to a single binary. Not only does this mean that deployment can be as simple as putting that binary in a Docker container and launching your service, but it also means that this comes with the same security improvements that come with using languages like Go.\"\n },\n {\n \"code\": null,\n \"e\": 6335,\n \"s\": 6202,\n \"text\": \"Then don’t let Julia stop you, there is a Python interpreter built directly into Julia so using Python is as simple as using Pycall.\"\n },\n {\n \"code\": null,\n \"e\": 6385,\n \"s\": 6335,\n \"text\": \"using Pycallpackagename = pyimport(“packagename”)\"\n },\n {\n \"code\": null,\n \"e\": 6521,\n \"s\": 6385,\n \"text\": \"It really is as easy as that! Pycall allows the use of all built-in Python namespace functions and feature (even use context managers).\"\n },\n {\n \"code\": null,\n \"e\": 6725,\n \"s\": 6521,\n \"text\": \"Debugging isn’t quite as easy as it is in Python; this could be that I’m just familiar with Python’s traceback errors, or that Python just has a more descriptive way of telling you where your mistake is.\"\n },\n {\n \"code\": null,\n \"e\": 6781,\n \"s\": 6725,\n \"text\": \"Here’s a quick example to try and illustrate in Python:\"\n },\n {\n \"code\": null,\n \"e\": 6799,\n \"s\": 6781,\n \"text\": \"... and in Julia:\"\n },\n {\n \"code\": null,\n \"e\": 6855,\n \"s\": 6799,\n \"text\": \"I think one of these is a lot clearer than the other...\"\n },\n {\n \"code\": null,\n \"e\": 7214,\n \"s\": 6855,\n \"text\": \"The only other issue with Julia is the lack of support for machine learning libraries. This may be a product of its relative youth, but it remains a frustrating feature. Julia has wrappers for Pandas, TensorFlow and Sklearn but this doesn’t help us if we want to grab a pre-trained ResNet 50 or a Bert model as the chances are they will be written in Python.\"\n },\n {\n \"code\": null,\n \"e\": 7378,\n \"s\": 7214,\n \"text\": \"Having said that, the Julia community is growing and more native libraries are being built on an almost daily basis like Lathe and MLJ, so there’s hope for us yet!\"\n },\n {\n \"code\": null,\n \"e\": 7558,\n \"s\": 7378,\n \"text\": \"The lack of class-based objects in Julia can also make using some of those libraries somewhat unwieldy when used outside of Python. For example Pandas’ df.loc[] becomesloc!(df, ).\"\n },\n {\n \"code\": null,\n \"e\": 7926,\n \"s\": 7558,\n \"text\": \"Finally, there are too many functions in the basis namespace of Julia. In some ways, this is convenient and allows for a MATLAB-like level of usability and ease of writing code. However, it makes the readability of Julia code worse, with it often being hard to tell if a function is there by default, if it’s user-defined or if it’s been imported from another module.\"\n }\n]"}}},{"rowIdx":105,"cells":{"title":{"kind":"string","value":"How to multiply only one column in an R data frame with a number?"},"text":{"kind":"string","value":"To multiply only one column with a number, we can simply use the multiplication operator * but need to replace the original column with the new values. For example, if we have a data frame called df that contains three columns x1, x2, and x3, and we want to multiply the second column x2 with 2 then it can be done as dfx2<−dfx2*2.\n Live Demo\nConsider the below data frame −\nset.seed(212)\nx1<−rpois(20,2)\nx2<−rpois(20,5)\nx3<−rpois(20,2)\ndf1<−data.frame(x1,x2,x3)\ndf1\nx1 x2 x3\n1 1 5 3\n2 3 5 1\n3 3 6 4\n4 1 0 2\n5 0 3 1\n6 0 7 4\n7 4 10 4\n8 4 8 3\n9 1 7 0\n10 2 2 0\n11 2 1 1\n12 2 7 1\n13 3 2 1\n14 1 3 3\n15 1 3 2\n16 3 5 2\n17 3 2 1\n18 1 4 1\n19 2 5 2\n20 4 6 2\nReplacing the column x2 by multiplying the values in it with 2 −\ndf1$x2<−df1$x2*2\ndf1\nx1 x2 x3\n1 1 10 3\n2 3 10 1\n3 3 12 4\n4 1 0 2\n5 0 6 1\n6 0 14 4\n7 4 20 4\n8 4 16 3\n9 1 14 0\n10 2 4 0\n11 2 2 1\n12 2 14 1\n13 3 4 1\n14 1 6 3\n15 1 6 2\n16 3 10 2\n17 3 4 1\n18 1 8 1\n19 2 10 2\n20 4 12 2\n Live Demo\ny1<−rnorm(20)\ny2<−rnorm(20)\ny3<−rnorm(20)\ny4<−rnorm(20)\ndf2<−data.frame(y1,y2,y3,y4)\ndf2\ny1 y2 y3 y4\n1 0.17051839 −1.07371818 0.717652086 −0.6692174\n2 0.26654381 −0.82881794 1.144774784 1.0708255\n3 1.17587680 −0.03197159 −0.257318856 −0.2734330\n4 0.79978274 1.14677652 −1.052941918 0.8212265\n5 0.36352605 0.95455643 0.002662389 0.8991729\n6 −0.52918622 −1.19824723 1.121770768 −0.1345990\n7 −1.30278723 0.90339625 −1.637918585 −0.3986243\n8 −2.01380274 −0.61700004 1.319289169 1.4223520\n9 −0.10499300 −0.99640769 1.508072921 −0.8711021\n10 −0.57019817 0.23396114 0.371342290 −0.5071846\n11 −0.92964644 −2.82593133 −0.191162636 0.2482026\n12 −0.62824719 1.39458991 −0.250602510 −0.5094344\n13 −1.16899182 0.48402510 0.849597620 0.5386604\n14 −0.12800221 −1.01570468 −1.370769300 0.3641254\n15 1.60649960 1.00993852 −0.181644717 0.7057080\n16 −0.09581029 −0.40099838 0.392519844 −1.6369244\n17 −0.43375271 −0.29316467 −0.233208374 0.1270293\n18 −0.96182839 0.54334525 1.550101688 2.0853380\n19 −1.50775746 −0.89573880 0.366389303 0.3372866\n20 1.90255916 −1.41836692 0.428073142 −0.1576013\nReplacing the column y1 by multiplying the values in it with *1 −\ndf2$y1<−df2$y1*(−1)\ndf2\ny1 y2 y3 y4\n1 −0.17051839 −1.07371818 0.717652086 −0.6692174\n2 −0.26654381 −0.82881794 1.144774784 1.0708255\n3 −1.17587680 −0.03197159 −0.257318856 −0.2734330\n4 −0.79978274 1.14677652 −1.052941918 0.8212265\n5 −0.36352605 0.95455643 0.002662389 0.8991729\n6 0.52918622 −1.19824723 1.121770768 −0.1345990\n7 1.30278723 0.90339625 −1.637918585 −0.3986243\n8 2.01380274 −0.61700004 1.319289169 1.4223520\n9 0.10499300 −0.99640769 1.508072921 −0.8711021\n10 0.57019817 0.23396114 0.371342290 −0.5071846\n11 0.92964644 −2.82593133 −0.191162636 0.2482026\n12 0.62824719 1.39458991 −0.250602510 −0.5094344\n13 1.16899182 0.48402510 0.849597620 0.5386604\n14 0.12800221 −1.01570468 −1.370769300 0.3641254\n15 −1.60649960 1.00993852 −0.181644717 0.7057080\n16 0.09581029 −0.40099838 0.392519844 −1.6369244\n17 0.43375271 −0.29316467 −0.233208374 0.1270293\n18 0.96182839 0.54334525 1.550101688 2.0853380\n19 1.50775746 −0.89573880 0.366389303 0.3372866\n20 −1.90255916 −1.41836692 0.428073142 −0.1576013"},"parsed":{"kind":"list like","value":[{"code":null,"e":1394,"s":1062,"text":"To multiply only one column with a number, we can simply use the multiplication operator * but need to replace the original column with the new values. For example, if we have a data frame called df that contains three columns x1, x2, and x3, and we want to multiply the second column x2 with 2 then it can be done as dfx2<−dfx2*2."},{"code":null,"e":1405,"s":1394,"text":" Live Demo"},{"code":null,"e":1437,"s":1405,"text":"Consider the below data frame −"},{"code":null,"e":1529,"s":1437,"text":"set.seed(212)\nx1<−rpois(20,2)\nx2<−rpois(20,5)\nx3<−rpois(20,2)\ndf1<−data.frame(x1,x2,x3)\ndf1"},{"code":null,"e":1710,"s":1529,"text":"x1 x2 x3\n1 1 5 3\n2 3 5 1\n3 3 6 4\n4 1 0 2\n5 0 3 1\n6 0 7 4\n7 4 10 4\n8 4 8 3\n9 1 7 0\n10 2 2 0\n11 2 1 1\n12 2 7 1\n13 3 2 1\n14 1 3 3\n15 1 3 2\n16 3 5 2\n17 3 2 1\n18 1 4 1\n19 2 5 2\n20 4 6 2"},{"code":null,"e":1775,"s":1710,"text":"Replacing the column x2 by multiplying the values in it with 2 −"},{"code":null,"e":1796,"s":1775,"text":"df1$x2<−df1$x2*2\ndf1"},{"code":null,"e":1987,"s":1796,"text":"x1 x2 x3\n1 1 10 3\n2 3 10 1\n3 3 12 4\n4 1 0 2\n5 0 6 1\n6 0 14 4\n7 4 20 4\n8 4 16 3\n9 1 14 0\n10 2 4 0\n11 2 2 1\n12 2 14 1\n13 3 4 1\n14 1 6 3\n15 1 6 2\n16 3 10 2\n17 3 4 1\n18 1 8 1\n19 2 10 2\n20 4 12 2"},{"code":null,"e":1998,"s":1987,"text":" Live Demo"},{"code":null,"e":2087,"s":1998,"text":"y1<−rnorm(20)\ny2<−rnorm(20)\ny3<−rnorm(20)\ny4<−rnorm(20)\ndf2<−data.frame(y1,y2,y3,y4)\ndf2"},{"code":null,"e":3072,"s":2087,"text":"y1 y2 y3 y4\n1 0.17051839 −1.07371818 0.717652086 −0.6692174\n2 0.26654381 −0.82881794 1.144774784 1.0708255\n3 1.17587680 −0.03197159 −0.257318856 −0.2734330\n4 0.79978274 1.14677652 −1.052941918 0.8212265\n5 0.36352605 0.95455643 0.002662389 0.8991729\n6 −0.52918622 −1.19824723 1.121770768 −0.1345990\n7 −1.30278723 0.90339625 −1.637918585 −0.3986243\n8 −2.01380274 −0.61700004 1.319289169 1.4223520\n9 −0.10499300 −0.99640769 1.508072921 −0.8711021\n10 −0.57019817 0.23396114 0.371342290 −0.5071846\n11 −0.92964644 −2.82593133 −0.191162636 0.2482026\n12 −0.62824719 1.39458991 −0.250602510 −0.5094344\n13 −1.16899182 0.48402510 0.849597620 0.5386604\n14 −0.12800221 −1.01570468 −1.370769300 0.3641254\n15 1.60649960 1.00993852 −0.181644717 0.7057080\n16 −0.09581029 −0.40099838 0.392519844 −1.6369244\n17 −0.43375271 −0.29316467 −0.233208374 0.1270293\n18 −0.96182839 0.54334525 1.550101688 2.0853380\n19 −1.50775746 −0.89573880 0.366389303 0.3372866\n20 1.90255916 −1.41836692 0.428073142 −0.1576013"},{"code":null,"e":3138,"s":3072,"text":"Replacing the column y1 by multiplying the values in it with *1 −"},{"code":null,"e":3162,"s":3138,"text":"df2$y1<−df2$y1*(−1)\ndf2"},{"code":null,"e":4141,"s":3162,"text":"y1 y2 y3 y4\n1 −0.17051839 −1.07371818 0.717652086 −0.6692174\n2 −0.26654381 −0.82881794 1.144774784 1.0708255\n3 −1.17587680 −0.03197159 −0.257318856 −0.2734330\n4 −0.79978274 1.14677652 −1.052941918 0.8212265\n5 −0.36352605 0.95455643 0.002662389 0.8991729\n6 0.52918622 −1.19824723 1.121770768 −0.1345990\n7 1.30278723 0.90339625 −1.637918585 −0.3986243\n8 2.01380274 −0.61700004 1.319289169 1.4223520\n9 0.10499300 −0.99640769 1.508072921 −0.8711021\n10 0.57019817 0.23396114 0.371342290 −0.5071846\n11 0.92964644 −2.82593133 −0.191162636 0.2482026\n12 0.62824719 1.39458991 −0.250602510 −0.5094344\n13 1.16899182 0.48402510 0.849597620 0.5386604\n14 0.12800221 −1.01570468 −1.370769300 0.3641254\n15 −1.60649960 1.00993852 −0.181644717 0.7057080\n16 0.09581029 −0.40099838 0.392519844 −1.6369244\n17 0.43375271 −0.29316467 −0.233208374 0.1270293\n18 0.96182839 0.54334525 1.550101688 2.0853380\n19 1.50775746 −0.89573880 0.366389303 0.3372866\n20 −1.90255916 −1.41836692 0.428073142 −0.1576013"}],"string":"[\n {\n \"code\": null,\n \"e\": 1394,\n \"s\": 1062,\n \"text\": \"To multiply only one column with a number, we can simply use the multiplication operator * but need to replace the original column with the new values. For example, if we have a data frame called df that contains three columns x1, x2, and x3, and we want to multiply the second column x2 with 2 then it can be done as dfx2<−dfx2*2.\"\n },\n {\n \"code\": null,\n \"e\": 1405,\n \"s\": 1394,\n \"text\": \" Live Demo\"\n },\n {\n \"code\": null,\n \"e\": 1437,\n \"s\": 1405,\n \"text\": \"Consider the below data frame −\"\n },\n {\n \"code\": null,\n \"e\": 1529,\n \"s\": 1437,\n \"text\": \"set.seed(212)\\nx1<−rpois(20,2)\\nx2<−rpois(20,5)\\nx3<−rpois(20,2)\\ndf1<−data.frame(x1,x2,x3)\\ndf1\"\n },\n {\n \"code\": null,\n \"e\": 1710,\n \"s\": 1529,\n \"text\": \"x1 x2 x3\\n1 1 5 3\\n2 3 5 1\\n3 3 6 4\\n4 1 0 2\\n5 0 3 1\\n6 0 7 4\\n7 4 10 4\\n8 4 8 3\\n9 1 7 0\\n10 2 2 0\\n11 2 1 1\\n12 2 7 1\\n13 3 2 1\\n14 1 3 3\\n15 1 3 2\\n16 3 5 2\\n17 3 2 1\\n18 1 4 1\\n19 2 5 2\\n20 4 6 2\"\n },\n {\n \"code\": null,\n \"e\": 1775,\n \"s\": 1710,\n \"text\": \"Replacing the column x2 by multiplying the values in it with 2 −\"\n },\n {\n \"code\": null,\n \"e\": 1796,\n \"s\": 1775,\n \"text\": \"df1$x2<−df1$x2*2\\ndf1\"\n },\n {\n \"code\": null,\n \"e\": 1987,\n \"s\": 1796,\n \"text\": \"x1 x2 x3\\n1 1 10 3\\n2 3 10 1\\n3 3 12 4\\n4 1 0 2\\n5 0 6 1\\n6 0 14 4\\n7 4 20 4\\n8 4 16 3\\n9 1 14 0\\n10 2 4 0\\n11 2 2 1\\n12 2 14 1\\n13 3 4 1\\n14 1 6 3\\n15 1 6 2\\n16 3 10 2\\n17 3 4 1\\n18 1 8 1\\n19 2 10 2\\n20 4 12 2\"\n },\n {\n \"code\": null,\n \"e\": 1998,\n \"s\": 1987,\n \"text\": \" Live Demo\"\n },\n {\n \"code\": null,\n \"e\": 2087,\n \"s\": 1998,\n \"text\": \"y1<−rnorm(20)\\ny2<−rnorm(20)\\ny3<−rnorm(20)\\ny4<−rnorm(20)\\ndf2<−data.frame(y1,y2,y3,y4)\\ndf2\"\n },\n {\n \"code\": null,\n \"e\": 3072,\n \"s\": 2087,\n \"text\": \"y1 y2 y3 y4\\n1 0.17051839 −1.07371818 0.717652086 −0.6692174\\n2 0.26654381 −0.82881794 1.144774784 1.0708255\\n3 1.17587680 −0.03197159 −0.257318856 −0.2734330\\n4 0.79978274 1.14677652 −1.052941918 0.8212265\\n5 0.36352605 0.95455643 0.002662389 0.8991729\\n6 −0.52918622 −1.19824723 1.121770768 −0.1345990\\n7 −1.30278723 0.90339625 −1.637918585 −0.3986243\\n8 −2.01380274 −0.61700004 1.319289169 1.4223520\\n9 −0.10499300 −0.99640769 1.508072921 −0.8711021\\n10 −0.57019817 0.23396114 0.371342290 −0.5071846\\n11 −0.92964644 −2.82593133 −0.191162636 0.2482026\\n12 −0.62824719 1.39458991 −0.250602510 −0.5094344\\n13 −1.16899182 0.48402510 0.849597620 0.5386604\\n14 −0.12800221 −1.01570468 −1.370769300 0.3641254\\n15 1.60649960 1.00993852 −0.181644717 0.7057080\\n16 −0.09581029 −0.40099838 0.392519844 −1.6369244\\n17 −0.43375271 −0.29316467 −0.233208374 0.1270293\\n18 −0.96182839 0.54334525 1.550101688 2.0853380\\n19 −1.50775746 −0.89573880 0.366389303 0.3372866\\n20 1.90255916 −1.41836692 0.428073142 −0.1576013\"\n },\n {\n \"code\": null,\n \"e\": 3138,\n \"s\": 3072,\n \"text\": \"Replacing the column y1 by multiplying the values in it with *1 −\"\n },\n {\n \"code\": null,\n \"e\": 3162,\n \"s\": 3138,\n \"text\": \"df2$y1<−df2$y1*(−1)\\ndf2\"\n },\n {\n \"code\": null,\n \"e\": 4141,\n \"s\": 3162,\n \"text\": \"y1 y2 y3 y4\\n1 −0.17051839 −1.07371818 0.717652086 −0.6692174\\n2 −0.26654381 −0.82881794 1.144774784 1.0708255\\n3 −1.17587680 −0.03197159 −0.257318856 −0.2734330\\n4 −0.79978274 1.14677652 −1.052941918 0.8212265\\n5 −0.36352605 0.95455643 0.002662389 0.8991729\\n6 0.52918622 −1.19824723 1.121770768 −0.1345990\\n7 1.30278723 0.90339625 −1.637918585 −0.3986243\\n8 2.01380274 −0.61700004 1.319289169 1.4223520\\n9 0.10499300 −0.99640769 1.508072921 −0.8711021\\n10 0.57019817 0.23396114 0.371342290 −0.5071846\\n11 0.92964644 −2.82593133 −0.191162636 0.2482026\\n12 0.62824719 1.39458991 −0.250602510 −0.5094344\\n13 1.16899182 0.48402510 0.849597620 0.5386604\\n14 0.12800221 −1.01570468 −1.370769300 0.3641254\\n15 −1.60649960 1.00993852 −0.181644717 0.7057080\\n16 0.09581029 −0.40099838 0.392519844 −1.6369244\\n17 0.43375271 −0.29316467 −0.233208374 0.1270293\\n18 0.96182839 0.54334525 1.550101688 2.0853380\\n19 1.50775746 −0.89573880 0.366389303 0.3372866\\n20 −1.90255916 −1.41836692 0.428073142 −0.1576013\"\n }\n]"}}},{"rowIdx":106,"cells":{"title":{"kind":"string","value":"C# Program to make a copy of an existing file"},"text":{"kind":"string","value":"Use File.Copy method to make copy of an existing file.\nAdd the path of the file you want to copy.\nString myPath = @\"D:\\one.txt\";\nNow copy the above file to the following file −\nString myPath = @\"D:\\one.txt\";\nUse the File.Copy method with both the source and destination file.\nFile.Copy(myPath,newpath);\nusing System;\nusing System.IO;\npublic class Program {\n public static void Main() {\n String myPath = @\"D:\\one.txt\";\n // the file will get copied here\n String newpath = @\"D:\\two.txt\";\n // copying file\n File.Copy(myPath,newpath);\n }\n}"},"parsed":{"kind":"list like","value":[{"code":null,"e":1117,"s":1062,"text":"Use File.Copy method to make copy of an existing file."},{"code":null,"e":1160,"s":1117,"text":"Add the path of the file you want to copy."},{"code":null,"e":1191,"s":1160,"text":"String myPath = @\"D:\\one.txt\";"},{"code":null,"e":1239,"s":1191,"text":"Now copy the above file to the following file −"},{"code":null,"e":1270,"s":1239,"text":"String myPath = @\"D:\\one.txt\";"},{"code":null,"e":1338,"s":1270,"text":"Use the File.Copy method with both the source and destination file."},{"code":null,"e":1365,"s":1338,"text":"File.Copy(myPath,newpath);"},{"code":null,"e":1626,"s":1365,"text":"using System;\nusing System.IO;\npublic class Program {\n public static void Main() {\n String myPath = @\"D:\\one.txt\";\n // the file will get copied here\n String newpath = @\"D:\\two.txt\";\n // copying file\n File.Copy(myPath,newpath);\n }\n}"}],"string":"[\n {\n \"code\": null,\n \"e\": 1117,\n \"s\": 1062,\n \"text\": \"Use File.Copy method to make copy of an existing file.\"\n },\n {\n \"code\": null,\n \"e\": 1160,\n \"s\": 1117,\n \"text\": \"Add the path of the file you want to copy.\"\n },\n {\n \"code\": null,\n \"e\": 1191,\n \"s\": 1160,\n \"text\": \"String myPath = @\\\"D:\\\\one.txt\\\";\"\n },\n {\n \"code\": null,\n \"e\": 1239,\n \"s\": 1191,\n \"text\": \"Now copy the above file to the following file −\"\n },\n {\n \"code\": null,\n \"e\": 1270,\n \"s\": 1239,\n \"text\": \"String myPath = @\\\"D:\\\\one.txt\\\";\"\n },\n {\n \"code\": null,\n \"e\": 1338,\n \"s\": 1270,\n \"text\": \"Use the File.Copy method with both the source and destination file.\"\n },\n {\n \"code\": null,\n \"e\": 1365,\n \"s\": 1338,\n \"text\": \"File.Copy(myPath,newpath);\"\n },\n {\n \"code\": null,\n \"e\": 1626,\n \"s\": 1365,\n \"text\": \"using System;\\nusing System.IO;\\npublic class Program {\\n public static void Main() {\\n String myPath = @\\\"D:\\\\one.txt\\\";\\n // the file will get copied here\\n String newpath = @\\\"D:\\\\two.txt\\\";\\n // copying file\\n File.Copy(myPath,newpath);\\n }\\n}\"\n }\n]"}}},{"rowIdx":107,"cells":{"title":{"kind":"string","value":"Descriptive Statistics: Expectations vs. Reality (Exploratory Data Analysis) | by Gonçalo Guimarães Gomes | Towards Data Science"},"text":{"kind":"string","value":"An easy descriptive statistics approach to summarize the numeric and categoric data variables through the Measures of Central Tendency and Measures of Spread for every Exploratory Data Analysis process.\nEDA is the first step in the data analysis process. It allows us to understand the data we are dealing with by describing and summarizing the dataset’s main characteristics, often through visual methods like bar and pie charts, histograms, boxplots, scatterplots, heatmaps, and many more.\nMaximize insight into a dataset (be able to listen to your data)\nUncover underlying structure/patterns\nDetect outliers and anomalies\nExtract and select important variables\nIncrease computational effenciency\nTest underlying assumptions (e.g. business intuiton)\nMoreover, to be capable of exploring and explain the dataset’s features with all its attributes getting insights and efficient numeric summaries of the data, we need help from Descriptive Statistics.\nStatistics is divided into two major areas:\nDescriptive statistics: describe and summarize data;\nInferential statistics: methods for using sample data to make general conclusions (inferences) about populations.\nThis tutorial focuses on descriptive statistics of both numerical and categorical variables and is divided into two parts:\nMeasures of central tendency;\nMeasures of spread.\nAlso named Univariate Analysis (one feature analysis at a time), descriptive statistics, in short, help describe and understand the features of a specific dataset, by giving short numeric summaries about the sample and measures of the data.\nDescriptive statistics are mere exploration as they do not allows us to make conclusions beyond the data we have analysed or reach conclusions regarding any hypotheses we might have made.\nNumerical and categorical variables, as we will see shortly, have different descriptive statistics approaches.\nLet’s review the type of variables:\nNumerical continuous: The values are not countable and have an infinite number of possibilities (Someone’s age: 25 years, 4 days, 11 hours, 24 minutes, 5 seconds and so on to the infinite).\nNumerical discrete: The values are countable and have an finite number of possibilities (It is impossible to count 27.52 countries in the EU).\nCategorical ordinal: There is an order implied in the levels (January comes always before February and after December).\nCategorical nominal: There is no order implied in the levels (Female/male, or the wind direction: north, south, east, west).\nMeasures of central tendency: Mean, median\nMeasures of spread: Standard deviation, variance, percentiles, maximum, minimum, skewness, kurtosis\nOthers: Size, unique, number of uniques\nOne approach to display the data is through a boxplot. It gives you the 5-basic-stats, such as the minimum, the 1st quartile (25th percentile), the median, the 3rd quartile (75th percentile), and the maximum.\nMeasures of central tendency: Mode (most common)\nMeasures of spread: Number of uniques\nOthers: Size, % Highest unique\nUnderstanding:\nMean (average): The total sum of values divided by the total observations. The mean is highly sensitive to the outliers.\nMedian (center value): The total count of an ordered sequence of numbers divided by 2. The median is not affected by the outliers.\nMode (most common): The values most frequently observed. There can be more than one modal value in the same variable.\nVariance (variability from the mean): The square of the standard deviation. It is also affected by outliers.\nStandard deviation (concentrated around the mean): The standard amount of deviation (distance) from the mean. The std is affected by the outliers. It is the square root of the variance.\nPercentiles: The value below which a percentage of data falls. The 0th percentile is the minimum value, the 100th is the maximum, the 50th is the median.\nMinimum: The smallest or lowest value.\nMaximum: The greatest or highest value.\nThe number of uniques (total distinct): The total amount of distinct observations.\nUniques (distinct): The distinct values or groups of values observed.\nSkewness (symmetric): How much a distribution derives from the normal distribution. >> Explained Skew concept in the next section.\nKurtosis (volume of outliers): How long are the tails and how sharp is the peak of the distribution.>> Explained Kurtosis concept in the next section.\nCount (size): The total sum of observations. Counting is also necessary for calculating the mean, median, and mode.\n% highest unique (relativity): The proportion of the highest unique observation regarding all the unique values or group of values.\nIn a perfect world, the data’s distribution assumes the form of a bell curve (Gaussian or normally distributed), but in the real world, data distributions usually are not symmetric (= skewed).\nTherefore, the skewness indicates how much our distribution derives from the normal distribution (with the skewness value of zero or very close).\nThere are three generic types of distributions:\nSymmetrical [median = mean]: In a normal distribution, the mean (average) divides the data symmetrically at the median value or close.\nPositive skew [median < mean]: The distribution is asymmetrical, the tail is skewed/longer towards the right-hand side of the curve. In this type, the majority of the observations are concentrated on the left tail, and the value of skewness is positive.\nNegative skew [median > mean]: The distribution is asymmetrical and the tail is skewed/longer towards the left-hand side of the curve. In this type of distribution, the majority of the observations are concentrated on the right tail, and the value of skewness is negative.\nRule of thumbs:\nSymmetric distribution: values between -0.5 to 0.5.\nModerate skew: values between -1 and -0.5 and 0.5 and 1.\nHigh skew: values <-1 or >1.\nkurtosis is another useful tool when it comes to quantify the shape of a distribution. It measures both how long are the tails, but most important, and how sharp is the peak of the distributions.\nIf the distribution has a sharper and taller peak and shorter tails, then it has a higher kurtosis while a low kurtosis can be observed when the peak of the distribution is flatter with thinner tails. There are three types of kurtosis:\nLeptokurtic: The distribution is tall and thin. The value of a leptokurtic must be > 3.\nMesokurtic: This distribution looks the same or very similar to a normal distribution. The value of a “normal” mesokurtic is = 3.\nPlatykurtic: The distributions have a flatter and wider peak and thinner tails, meaning that the data is moderately spread out. The value of a platykurtic must be < 3.\nKurtosis is calculated by raising the average of the standardized data to the fourth power. If we raise any standardized number (less than 1) to the 4th power, the result would be a very small number, somewhere close to zero. Such a small value would not contribute much to the kurtosis. The conclusion is that the values that would make a difference to the kurtosis would be the ones far away from the region of the peak, put it in other words, the outliers.\nIn this section, we will be giving short numeric stats summaries concerning the different measures of central tendency and dispersion of the dataset.\nlet’s work on some practical examples through a descriptive statistics environment in Pandas.\n> Repo code here.\nStart by importing the required libraries:\nimport pandas as pdimport numpy as npimport scipyimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inline\nLoad the dataset:df = pd.read_csv(\"sample.csv\", sep=\";\")\nPrint the data:df.head()\nBefore any stats calculus, let’s just take a quick look at the data:df.info\nThe dataset consists of 310 observations and 2 columns. One of the attributes is numerical, and the other categorical. Both columns have no missing values.\nThe numerical variable we are going to analyze is age. First step is to visually observe the variable. So let's plot an histogram and a boxplot.\nplt.hist(df.age, bins=20)plt.xlabel(“Age”)plt.ylabel(“Absolute Frequency”)plt.show()\nsns.boxplot(x=age, data=df, orient=\"h\").set(xlabel=\"Age\", title=\"Numeric variable 'Age'\");\nIt is also possible to visually observe the variable with both a histogram and a boxplot combined. I find it a useful graphical combination and use it a lot in my reports.\nage = df.agef, (ax_box, ax_hist) = plt.subplots(2, sharex=True, gridspec_kw= {\"height_ratios\": (0.8, 1.2)})mean=np.array(age).mean()median=np.median(age)sns.boxplot(age, ax=ax_box)ax_box.axvline(mean, color='r', linestyle='--')ax_box.axvline(median, color='g', linestyle='-')sns.distplot(age, ax=ax_hist)ax_hist.axvline(mean, color='r', linestyle='--')ax_hist.axvline(median, color='g', linestyle='-')plt.legend({'Mean':mean,'Median':median})plt.title(\"'Age' histogram + boxplot\")ax_box.set(xlabel='')plt.show()\n1. Mean:df.age.mean()\n35.564516129032256\n2. Median:df.age.median()\n32.0\n3. Standard deviation:df.age.std()\n18.824363618000913\n4. Variance:df.age.var()\n354.3566656227164\n5. a) Percentiles 25%:df.age.quantile(0.25)\n23.0\nb) Percentile 75%:df.age.quantile(0.75)\n45.0\nc) In one go:df.age.quantile(q=[.25, .75)\n0.25 23.00.75 45.0Name: age, dtype: float64\n6. Minimum and maximum:df.age.min(), df.age.max()\n(3, 98)\n7. Skewness (with scipy):scipy.stats.skew(df.age)\n0.9085582496839909\n8. Kurtosis (with scipy):scipy.stats.kurtosis(df.age)\n0.7254158742250474\n9. Size (number of rows):df.age.count()\n310\n10. Number of uniques (total distinct)df.age.nunique()\n74\n11. Uniques (distinct):df.age.unique()\narray([46, 22, 54, 33, 69, 35, 11, 97, 50, 34, 67, 43, 21, 12, 23, 45, 89, 76, 5, 55, 65, 24, 27, 57, 38, 28, 36, 60, 56, 53, 26, 25, 42, 83, 16, 51, 90, 10, 70, 44, 20, 31, 47, 30, 91, 7, 6, 41, 66, 61, 96, 32, 58, 17, 52, 29, 75, 86, 98, 48, 40, 13, 4, 68, 62, 9, 18, 39, 15, 19, 8, 71, 3, 37])\nThe categorical variable we are going to analyze is city. Let’s plot a bar chart and get a visual observation of the variable.\ndf.city.value_counts().plot.bar()plt.xlabel(\"City\")plt.ylabel(\"Absolute Frequency\")plt.title(\"Categoric variable 'City'\")plt.show()\n1. Mode:df.city.mode()[0]\n'Paris'\n2. Number of uniques:df.city.nunique()\n6\n3. Uniques (distinct):df.city.unique()\narray(['Lisbon', 'Paris', 'Madrid', 'London', 'Luxembourg', 'Berlin'], dtype=object)\n4. Most frequent unique (value count):df.city.value_counts().head(1)\nParis 67Name: city, dtype: int64\n5. Size (number of rows):df.city.count()\n310\n6. % of the highest unique (fraction of the most common unique in regards to all the others):p = df.city.value_counts(normalize=True)[0] print(f\"{p:.1%}\")\n21.6%\nThe describe() method shows the descriptive statistics gathered in one table. By default, stats for numeric data. The result is represented as a pandas dataframe.df.describe()\nAdding other non-standard values, for instance, the ‘variance’.describe_var = data.describe()describe_var.append(pd.Series(data.var(), name='variance'))\nDisplaying categorical data.df.describe(include=[\"O\"])<=> df.describe(exclude=['float64','int64'])<=> df.describe(include=[np.object])\nBy passing the parameter include='all', displays both numeric and categoric variables at once.df.describe(include='all')\nThese are the basics of descriptive statistics when developing an exploratory data analysis project with the help of Pandas, Numpy, Scipy, Matplolib and/or Seaborn. When well performed, these stats help us to understand and transform the data for further processing.\nRemember always be a skeptic. Look at the data with your own eyes (don’t fully rely on statistics), and graphically visualize the variables (use and abuse of the visuals).\n> Repo code here.\nCheck out other articles you might also like to read:\ntowardsdatascience.com\ntowardsdatascience.com\ntowardsdatascience.com\nLinkedin\nTwitter\nMedium\nGitHub\nKaggle\nEmail\nGood readings, great codings!"},"parsed":{"kind":"list like","value":[{"code":null,"e":374,"s":171,"text":"An easy descriptive statistics approach to summarize the numeric and categoric data variables through the Measures of Central Tendency and Measures of Spread for every Exploratory Data Analysis process."},{"code":null,"e":663,"s":374,"text":"EDA is the first step in the data analysis process. It allows us to understand the data we are dealing with by describing and summarizing the dataset’s main characteristics, often through visual methods like bar and pie charts, histograms, boxplots, scatterplots, heatmaps, and many more."},{"code":null,"e":728,"s":663,"text":"Maximize insight into a dataset (be able to listen to your data)"},{"code":null,"e":766,"s":728,"text":"Uncover underlying structure/patterns"},{"code":null,"e":796,"s":766,"text":"Detect outliers and anomalies"},{"code":null,"e":835,"s":796,"text":"Extract and select important variables"},{"code":null,"e":870,"s":835,"text":"Increase computational effenciency"},{"code":null,"e":923,"s":870,"text":"Test underlying assumptions (e.g. business intuiton)"},{"code":null,"e":1123,"s":923,"text":"Moreover, to be capable of exploring and explain the dataset’s features with all its attributes getting insights and efficient numeric summaries of the data, we need help from Descriptive Statistics."},{"code":null,"e":1167,"s":1123,"text":"Statistics is divided into two major areas:"},{"code":null,"e":1220,"s":1167,"text":"Descriptive statistics: describe and summarize data;"},{"code":null,"e":1334,"s":1220,"text":"Inferential statistics: methods for using sample data to make general conclusions (inferences) about populations."},{"code":null,"e":1457,"s":1334,"text":"This tutorial focuses on descriptive statistics of both numerical and categorical variables and is divided into two parts:"},{"code":null,"e":1487,"s":1457,"text":"Measures of central tendency;"},{"code":null,"e":1507,"s":1487,"text":"Measures of spread."},{"code":null,"e":1748,"s":1507,"text":"Also named Univariate Analysis (one feature analysis at a time), descriptive statistics, in short, help describe and understand the features of a specific dataset, by giving short numeric summaries about the sample and measures of the data."},{"code":null,"e":1936,"s":1748,"text":"Descriptive statistics are mere exploration as they do not allows us to make conclusions beyond the data we have analysed or reach conclusions regarding any hypotheses we might have made."},{"code":null,"e":2047,"s":1936,"text":"Numerical and categorical variables, as we will see shortly, have different descriptive statistics approaches."},{"code":null,"e":2083,"s":2047,"text":"Let’s review the type of variables:"},{"code":null,"e":2273,"s":2083,"text":"Numerical continuous: The values are not countable and have an infinite number of possibilities (Someone’s age: 25 years, 4 days, 11 hours, 24 minutes, 5 seconds and so on to the infinite)."},{"code":null,"e":2416,"s":2273,"text":"Numerical discrete: The values are countable and have an finite number of possibilities (It is impossible to count 27.52 countries in the EU)."},{"code":null,"e":2536,"s":2416,"text":"Categorical ordinal: There is an order implied in the levels (January comes always before February and after December)."},{"code":null,"e":2661,"s":2536,"text":"Categorical nominal: There is no order implied in the levels (Female/male, or the wind direction: north, south, east, west)."},{"code":null,"e":2704,"s":2661,"text":"Measures of central tendency: Mean, median"},{"code":null,"e":2804,"s":2704,"text":"Measures of spread: Standard deviation, variance, percentiles, maximum, minimum, skewness, kurtosis"},{"code":null,"e":2844,"s":2804,"text":"Others: Size, unique, number of uniques"},{"code":null,"e":3053,"s":2844,"text":"One approach to display the data is through a boxplot. It gives you the 5-basic-stats, such as the minimum, the 1st quartile (25th percentile), the median, the 3rd quartile (75th percentile), and the maximum."},{"code":null,"e":3102,"s":3053,"text":"Measures of central tendency: Mode (most common)"},{"code":null,"e":3140,"s":3102,"text":"Measures of spread: Number of uniques"},{"code":null,"e":3171,"s":3140,"text":"Others: Size, % Highest unique"},{"code":null,"e":3186,"s":3171,"text":"Understanding:"},{"code":null,"e":3307,"s":3186,"text":"Mean (average): The total sum of values divided by the total observations. The mean is highly sensitive to the outliers."},{"code":null,"e":3438,"s":3307,"text":"Median (center value): The total count of an ordered sequence of numbers divided by 2. The median is not affected by the outliers."},{"code":null,"e":3556,"s":3438,"text":"Mode (most common): The values most frequently observed. There can be more than one modal value in the same variable."},{"code":null,"e":3665,"s":3556,"text":"Variance (variability from the mean): The square of the standard deviation. It is also affected by outliers."},{"code":null,"e":3851,"s":3665,"text":"Standard deviation (concentrated around the mean): The standard amount of deviation (distance) from the mean. The std is affected by the outliers. It is the square root of the variance."},{"code":null,"e":4005,"s":3851,"text":"Percentiles: The value below which a percentage of data falls. The 0th percentile is the minimum value, the 100th is the maximum, the 50th is the median."},{"code":null,"e":4044,"s":4005,"text":"Minimum: The smallest or lowest value."},{"code":null,"e":4084,"s":4044,"text":"Maximum: The greatest or highest value."},{"code":null,"e":4167,"s":4084,"text":"The number of uniques (total distinct): The total amount of distinct observations."},{"code":null,"e":4237,"s":4167,"text":"Uniques (distinct): The distinct values or groups of values observed."},{"code":null,"e":4368,"s":4237,"text":"Skewness (symmetric): How much a distribution derives from the normal distribution. >> Explained Skew concept in the next section."},{"code":null,"e":4519,"s":4368,"text":"Kurtosis (volume of outliers): How long are the tails and how sharp is the peak of the distribution.>> Explained Kurtosis concept in the next section."},{"code":null,"e":4635,"s":4519,"text":"Count (size): The total sum of observations. Counting is also necessary for calculating the mean, median, and mode."},{"code":null,"e":4767,"s":4635,"text":"% highest unique (relativity): The proportion of the highest unique observation regarding all the unique values or group of values."},{"code":null,"e":4960,"s":4767,"text":"In a perfect world, the data’s distribution assumes the form of a bell curve (Gaussian or normally distributed), but in the real world, data distributions usually are not symmetric (= skewed)."},{"code":null,"e":5106,"s":4960,"text":"Therefore, the skewness indicates how much our distribution derives from the normal distribution (with the skewness value of zero or very close)."},{"code":null,"e":5154,"s":5106,"text":"There are three generic types of distributions:"},{"code":null,"e":5289,"s":5154,"text":"Symmetrical [median = mean]: In a normal distribution, the mean (average) divides the data symmetrically at the median value or close."},{"code":null,"e":5543,"s":5289,"text":"Positive skew [median < mean]: The distribution is asymmetrical, the tail is skewed/longer towards the right-hand side of the curve. In this type, the majority of the observations are concentrated on the left tail, and the value of skewness is positive."},{"code":null,"e":5816,"s":5543,"text":"Negative skew [median > mean]: The distribution is asymmetrical and the tail is skewed/longer towards the left-hand side of the curve. In this type of distribution, the majority of the observations are concentrated on the right tail, and the value of skewness is negative."},{"code":null,"e":5832,"s":5816,"text":"Rule of thumbs:"},{"code":null,"e":5884,"s":5832,"text":"Symmetric distribution: values between -0.5 to 0.5."},{"code":null,"e":5941,"s":5884,"text":"Moderate skew: values between -1 and -0.5 and 0.5 and 1."},{"code":null,"e":5970,"s":5941,"text":"High skew: values <-1 or >1."},{"code":null,"e":6166,"s":5970,"text":"kurtosis is another useful tool when it comes to quantify the shape of a distribution. It measures both how long are the tails, but most important, and how sharp is the peak of the distributions."},{"code":null,"e":6402,"s":6166,"text":"If the distribution has a sharper and taller peak and shorter tails, then it has a higher kurtosis while a low kurtosis can be observed when the peak of the distribution is flatter with thinner tails. There are three types of kurtosis:"},{"code":null,"e":6490,"s":6402,"text":"Leptokurtic: The distribution is tall and thin. The value of a leptokurtic must be > 3."},{"code":null,"e":6620,"s":6490,"text":"Mesokurtic: This distribution looks the same or very similar to a normal distribution. The value of a “normal” mesokurtic is = 3."},{"code":null,"e":6788,"s":6620,"text":"Platykurtic: The distributions have a flatter and wider peak and thinner tails, meaning that the data is moderately spread out. The value of a platykurtic must be < 3."},{"code":null,"e":7248,"s":6788,"text":"Kurtosis is calculated by raising the average of the standardized data to the fourth power. If we raise any standardized number (less than 1) to the 4th power, the result would be a very small number, somewhere close to zero. Such a small value would not contribute much to the kurtosis. The conclusion is that the values that would make a difference to the kurtosis would be the ones far away from the region of the peak, put it in other words, the outliers."},{"code":null,"e":7398,"s":7248,"text":"In this section, we will be giving short numeric stats summaries concerning the different measures of central tendency and dispersion of the dataset."},{"code":null,"e":7492,"s":7398,"text":"let’s work on some practical examples through a descriptive statistics environment in Pandas."},{"code":null,"e":7510,"s":7492,"text":"> Repo code here."},{"code":null,"e":7553,"s":7510,"text":"Start by importing the required libraries:"},{"code":null,"e":7673,"s":7553,"text":"import pandas as pdimport numpy as npimport scipyimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inline"},{"code":null,"e":7730,"s":7673,"text":"Load the dataset:df = pd.read_csv(\"sample.csv\", sep=\";\")"},{"code":null,"e":7755,"s":7730,"text":"Print the data:df.head()"},{"code":null,"e":7831,"s":7755,"text":"Before any stats calculus, let’s just take a quick look at the data:df.info"},{"code":null,"e":7987,"s":7831,"text":"The dataset consists of 310 observations and 2 columns. One of the attributes is numerical, and the other categorical. Both columns have no missing values."},{"code":null,"e":8132,"s":7987,"text":"The numerical variable we are going to analyze is age. First step is to visually observe the variable. So let's plot an histogram and a boxplot."},{"code":null,"e":8217,"s":8132,"text":"plt.hist(df.age, bins=20)plt.xlabel(“Age”)plt.ylabel(“Absolute Frequency”)plt.show()"},{"code":null,"e":8308,"s":8217,"text":"sns.boxplot(x=age, data=df, orient=\"h\").set(xlabel=\"Age\", title=\"Numeric variable 'Age'\");"},{"code":null,"e":8480,"s":8308,"text":"It is also possible to visually observe the variable with both a histogram and a boxplot combined. I find it a useful graphical combination and use it a lot in my reports."},{"code":null,"e":8992,"s":8480,"text":"age = df.agef, (ax_box, ax_hist) = plt.subplots(2, sharex=True, gridspec_kw= {\"height_ratios\": (0.8, 1.2)})mean=np.array(age).mean()median=np.median(age)sns.boxplot(age, ax=ax_box)ax_box.axvline(mean, color='r', linestyle='--')ax_box.axvline(median, color='g', linestyle='-')sns.distplot(age, ax=ax_hist)ax_hist.axvline(mean, color='r', linestyle='--')ax_hist.axvline(median, color='g', linestyle='-')plt.legend({'Mean':mean,'Median':median})plt.title(\"'Age' histogram + boxplot\")ax_box.set(xlabel='')plt.show()"},{"code":null,"e":9014,"s":8992,"text":"1. Mean:df.age.mean()"},{"code":null,"e":9033,"s":9014,"text":"35.564516129032256"},{"code":null,"e":9059,"s":9033,"text":"2. Median:df.age.median()"},{"code":null,"e":9064,"s":9059,"text":"32.0"},{"code":null,"e":9099,"s":9064,"text":"3. Standard deviation:df.age.std()"},{"code":null,"e":9118,"s":9099,"text":"18.824363618000913"},{"code":null,"e":9143,"s":9118,"text":"4. Variance:df.age.var()"},{"code":null,"e":9161,"s":9143,"text":"354.3566656227164"},{"code":null,"e":9205,"s":9161,"text":"5. a) Percentiles 25%:df.age.quantile(0.25)"},{"code":null,"e":9210,"s":9205,"text":"23.0"},{"code":null,"e":9250,"s":9210,"text":"b) Percentile 75%:df.age.quantile(0.75)"},{"code":null,"e":9255,"s":9250,"text":"45.0"},{"code":null,"e":9297,"s":9255,"text":"c) In one go:df.age.quantile(q=[.25, .75)"},{"code":null,"e":9347,"s":9297,"text":"0.25 23.00.75 45.0Name: age, dtype: float64"},{"code":null,"e":9397,"s":9347,"text":"6. Minimum and maximum:df.age.min(), df.age.max()"},{"code":null,"e":9405,"s":9397,"text":"(3, 98)"},{"code":null,"e":9455,"s":9405,"text":"7. Skewness (with scipy):scipy.stats.skew(df.age)"},{"code":null,"e":9474,"s":9455,"text":"0.9085582496839909"},{"code":null,"e":9528,"s":9474,"text":"8. Kurtosis (with scipy):scipy.stats.kurtosis(df.age)"},{"code":null,"e":9547,"s":9528,"text":"0.7254158742250474"},{"code":null,"e":9587,"s":9547,"text":"9. Size (number of rows):df.age.count()"},{"code":null,"e":9591,"s":9587,"text":"310"},{"code":null,"e":9646,"s":9591,"text":"10. Number of uniques (total distinct)df.age.nunique()"},{"code":null,"e":9649,"s":9646,"text":"74"},{"code":null,"e":9688,"s":9649,"text":"11. Uniques (distinct):df.age.unique()"},{"code":null,"e":9986,"s":9688,"text":"array([46, 22, 54, 33, 69, 35, 11, 97, 50, 34, 67, 43, 21, 12, 23, 45, 89, 76, 5, 55, 65, 24, 27, 57, 38, 28, 36, 60, 56, 53, 26, 25, 42, 83, 16, 51, 90, 10, 70, 44, 20, 31, 47, 30, 91, 7, 6, 41, 66, 61, 96, 32, 58, 17, 52, 29, 75, 86, 98, 48, 40, 13, 4, 68, 62, 9, 18, 39, 15, 19, 8, 71, 3, 37])"},{"code":null,"e":10113,"s":9986,"text":"The categorical variable we are going to analyze is city. Let’s plot a bar chart and get a visual observation of the variable."},{"code":null,"e":10245,"s":10113,"text":"df.city.value_counts().plot.bar()plt.xlabel(\"City\")plt.ylabel(\"Absolute Frequency\")plt.title(\"Categoric variable 'City'\")plt.show()"},{"code":null,"e":10271,"s":10245,"text":"1. Mode:df.city.mode()[0]"},{"code":null,"e":10279,"s":10271,"text":"'Paris'"},{"code":null,"e":10318,"s":10279,"text":"2. Number of uniques:df.city.nunique()"},{"code":null,"e":10320,"s":10318,"text":"6"},{"code":null,"e":10359,"s":10320,"text":"3. Uniques (distinct):df.city.unique()"},{"code":null,"e":10444,"s":10359,"text":"array(['Lisbon', 'Paris', 'Madrid', 'London', 'Luxembourg', 'Berlin'], dtype=object)"},{"code":null,"e":10513,"s":10444,"text":"4. Most frequent unique (value count):df.city.value_counts().head(1)"},{"code":null,"e":10550,"s":10513,"text":"Paris 67Name: city, dtype: int64"},{"code":null,"e":10591,"s":10550,"text":"5. Size (number of rows):df.city.count()"},{"code":null,"e":10595,"s":10591,"text":"310"},{"code":null,"e":10750,"s":10595,"text":"6. % of the highest unique (fraction of the most common unique in regards to all the others):p = df.city.value_counts(normalize=True)[0] print(f\"{p:.1%}\")"},{"code":null,"e":10756,"s":10750,"text":"21.6%"},{"code":null,"e":10932,"s":10756,"text":"The describe() method shows the descriptive statistics gathered in one table. By default, stats for numeric data. The result is represented as a pandas dataframe.df.describe()"},{"code":null,"e":11085,"s":10932,"text":"Adding other non-standard values, for instance, the ‘variance’.describe_var = data.describe()describe_var.append(pd.Series(data.var(), name='variance'))"},{"code":null,"e":11220,"s":11085,"text":"Displaying categorical data.df.describe(include=[\"O\"])<=> df.describe(exclude=['float64','int64'])<=> df.describe(include=[np.object])"},{"code":null,"e":11341,"s":11220,"text":"By passing the parameter include='all', displays both numeric and categoric variables at once.df.describe(include='all')"},{"code":null,"e":11608,"s":11341,"text":"These are the basics of descriptive statistics when developing an exploratory data analysis project with the help of Pandas, Numpy, Scipy, Matplolib and/or Seaborn. When well performed, these stats help us to understand and transform the data for further processing."},{"code":null,"e":11780,"s":11608,"text":"Remember always be a skeptic. Look at the data with your own eyes (don’t fully rely on statistics), and graphically visualize the variables (use and abuse of the visuals)."},{"code":null,"e":11798,"s":11780,"text":"> Repo code here."},{"code":null,"e":11852,"s":11798,"text":"Check out other articles you might also like to read:"},{"code":null,"e":11875,"s":11852,"text":"towardsdatascience.com"},{"code":null,"e":11898,"s":11875,"text":"towardsdatascience.com"},{"code":null,"e":11921,"s":11898,"text":"towardsdatascience.com"},{"code":null,"e":11930,"s":11921,"text":"Linkedin"},{"code":null,"e":11938,"s":11930,"text":"Twitter"},{"code":null,"e":11945,"s":11938,"text":"Medium"},{"code":null,"e":11952,"s":11945,"text":"GitHub"},{"code":null,"e":11959,"s":11952,"text":"Kaggle"},{"code":null,"e":11965,"s":11959,"text":"Email"}],"string":"[\n {\n \"code\": null,\n \"e\": 374,\n \"s\": 171,\n \"text\": \"An easy descriptive statistics approach to summarize the numeric and categoric data variables through the Measures of Central Tendency and Measures of Spread for every Exploratory Data Analysis process.\"\n },\n {\n \"code\": null,\n \"e\": 663,\n \"s\": 374,\n \"text\": \"EDA is the first step in the data analysis process. It allows us to understand the data we are dealing with by describing and summarizing the dataset’s main characteristics, often through visual methods like bar and pie charts, histograms, boxplots, scatterplots, heatmaps, and many more.\"\n },\n {\n \"code\": null,\n \"e\": 728,\n \"s\": 663,\n \"text\": \"Maximize insight into a dataset (be able to listen to your data)\"\n },\n {\n \"code\": null,\n \"e\": 766,\n \"s\": 728,\n \"text\": \"Uncover underlying structure/patterns\"\n },\n {\n \"code\": null,\n \"e\": 796,\n \"s\": 766,\n \"text\": \"Detect outliers and anomalies\"\n },\n {\n \"code\": null,\n \"e\": 835,\n \"s\": 796,\n \"text\": \"Extract and select important variables\"\n },\n {\n \"code\": null,\n \"e\": 870,\n \"s\": 835,\n \"text\": \"Increase computational effenciency\"\n },\n {\n \"code\": null,\n \"e\": 923,\n \"s\": 870,\n \"text\": \"Test underlying assumptions (e.g. business intuiton)\"\n },\n {\n \"code\": null,\n \"e\": 1123,\n \"s\": 923,\n \"text\": \"Moreover, to be capable of exploring and explain the dataset’s features with all its attributes getting insights and efficient numeric summaries of the data, we need help from Descriptive Statistics.\"\n },\n {\n \"code\": null,\n \"e\": 1167,\n \"s\": 1123,\n \"text\": \"Statistics is divided into two major areas:\"\n },\n {\n \"code\": null,\n \"e\": 1220,\n \"s\": 1167,\n \"text\": \"Descriptive statistics: describe and summarize data;\"\n },\n {\n \"code\": null,\n \"e\": 1334,\n \"s\": 1220,\n \"text\": \"Inferential statistics: methods for using sample data to make general conclusions (inferences) about populations.\"\n },\n {\n \"code\": null,\n \"e\": 1457,\n \"s\": 1334,\n \"text\": \"This tutorial focuses on descriptive statistics of both numerical and categorical variables and is divided into two parts:\"\n },\n {\n \"code\": null,\n \"e\": 1487,\n \"s\": 1457,\n \"text\": \"Measures of central tendency;\"\n },\n {\n \"code\": null,\n \"e\": 1507,\n \"s\": 1487,\n \"text\": \"Measures of spread.\"\n },\n {\n \"code\": null,\n \"e\": 1748,\n \"s\": 1507,\n \"text\": \"Also named Univariate Analysis (one feature analysis at a time), descriptive statistics, in short, help describe and understand the features of a specific dataset, by giving short numeric summaries about the sample and measures of the data.\"\n },\n {\n \"code\": null,\n \"e\": 1936,\n \"s\": 1748,\n \"text\": \"Descriptive statistics are mere exploration as they do not allows us to make conclusions beyond the data we have analysed or reach conclusions regarding any hypotheses we might have made.\"\n },\n {\n \"code\": null,\n \"e\": 2047,\n \"s\": 1936,\n \"text\": \"Numerical and categorical variables, as we will see shortly, have different descriptive statistics approaches.\"\n },\n {\n \"code\": null,\n \"e\": 2083,\n \"s\": 2047,\n \"text\": \"Let’s review the type of variables:\"\n },\n {\n \"code\": null,\n \"e\": 2273,\n \"s\": 2083,\n \"text\": \"Numerical continuous: The values are not countable and have an infinite number of possibilities (Someone’s age: 25 years, 4 days, 11 hours, 24 minutes, 5 seconds and so on to the infinite).\"\n },\n {\n \"code\": null,\n \"e\": 2416,\n \"s\": 2273,\n \"text\": \"Numerical discrete: The values are countable and have an finite number of possibilities (It is impossible to count 27.52 countries in the EU).\"\n },\n {\n \"code\": null,\n \"e\": 2536,\n \"s\": 2416,\n \"text\": \"Categorical ordinal: There is an order implied in the levels (January comes always before February and after December).\"\n },\n {\n \"code\": null,\n \"e\": 2661,\n \"s\": 2536,\n \"text\": \"Categorical nominal: There is no order implied in the levels (Female/male, or the wind direction: north, south, east, west).\"\n },\n {\n \"code\": null,\n \"e\": 2704,\n \"s\": 2661,\n \"text\": \"Measures of central tendency: Mean, median\"\n },\n {\n \"code\": null,\n \"e\": 2804,\n \"s\": 2704,\n \"text\": \"Measures of spread: Standard deviation, variance, percentiles, maximum, minimum, skewness, kurtosis\"\n },\n {\n \"code\": null,\n \"e\": 2844,\n \"s\": 2804,\n \"text\": \"Others: Size, unique, number of uniques\"\n },\n {\n \"code\": null,\n \"e\": 3053,\n \"s\": 2844,\n \"text\": \"One approach to display the data is through a boxplot. It gives you the 5-basic-stats, such as the minimum, the 1st quartile (25th percentile), the median, the 3rd quartile (75th percentile), and the maximum.\"\n },\n {\n \"code\": null,\n \"e\": 3102,\n \"s\": 3053,\n \"text\": \"Measures of central tendency: Mode (most common)\"\n },\n {\n \"code\": null,\n \"e\": 3140,\n \"s\": 3102,\n \"text\": \"Measures of spread: Number of uniques\"\n },\n {\n \"code\": null,\n \"e\": 3171,\n \"s\": 3140,\n \"text\": \"Others: Size, % Highest unique\"\n },\n {\n \"code\": null,\n \"e\": 3186,\n \"s\": 3171,\n \"text\": \"Understanding:\"\n },\n {\n \"code\": null,\n \"e\": 3307,\n \"s\": 3186,\n \"text\": \"Mean (average): The total sum of values divided by the total observations. The mean is highly sensitive to the outliers.\"\n },\n {\n \"code\": null,\n \"e\": 3438,\n \"s\": 3307,\n \"text\": \"Median (center value): The total count of an ordered sequence of numbers divided by 2. The median is not affected by the outliers.\"\n },\n {\n \"code\": null,\n \"e\": 3556,\n \"s\": 3438,\n \"text\": \"Mode (most common): The values most frequently observed. There can be more than one modal value in the same variable.\"\n },\n {\n \"code\": null,\n \"e\": 3665,\n \"s\": 3556,\n \"text\": \"Variance (variability from the mean): The square of the standard deviation. It is also affected by outliers.\"\n },\n {\n \"code\": null,\n \"e\": 3851,\n \"s\": 3665,\n \"text\": \"Standard deviation (concentrated around the mean): The standard amount of deviation (distance) from the mean. The std is affected by the outliers. It is the square root of the variance.\"\n },\n {\n \"code\": null,\n \"e\": 4005,\n \"s\": 3851,\n \"text\": \"Percentiles: The value below which a percentage of data falls. The 0th percentile is the minimum value, the 100th is the maximum, the 50th is the median.\"\n },\n {\n \"code\": null,\n \"e\": 4044,\n \"s\": 4005,\n \"text\": \"Minimum: The smallest or lowest value.\"\n },\n {\n \"code\": null,\n \"e\": 4084,\n \"s\": 4044,\n \"text\": \"Maximum: The greatest or highest value.\"\n },\n {\n \"code\": null,\n \"e\": 4167,\n \"s\": 4084,\n \"text\": \"The number of uniques (total distinct): The total amount of distinct observations.\"\n },\n {\n \"code\": null,\n \"e\": 4237,\n \"s\": 4167,\n \"text\": \"Uniques (distinct): The distinct values or groups of values observed.\"\n },\n {\n \"code\": null,\n \"e\": 4368,\n \"s\": 4237,\n \"text\": \"Skewness (symmetric): How much a distribution derives from the normal distribution. >> Explained Skew concept in the next section.\"\n },\n {\n \"code\": null,\n \"e\": 4519,\n \"s\": 4368,\n \"text\": \"Kurtosis (volume of outliers): How long are the tails and how sharp is the peak of the distribution.>> Explained Kurtosis concept in the next section.\"\n },\n {\n \"code\": null,\n \"e\": 4635,\n \"s\": 4519,\n \"text\": \"Count (size): The total sum of observations. Counting is also necessary for calculating the mean, median, and mode.\"\n },\n {\n \"code\": null,\n \"e\": 4767,\n \"s\": 4635,\n \"text\": \"% highest unique (relativity): The proportion of the highest unique observation regarding all the unique values or group of values.\"\n },\n {\n \"code\": null,\n \"e\": 4960,\n \"s\": 4767,\n \"text\": \"In a perfect world, the data’s distribution assumes the form of a bell curve (Gaussian or normally distributed), but in the real world, data distributions usually are not symmetric (= skewed).\"\n },\n {\n \"code\": null,\n \"e\": 5106,\n \"s\": 4960,\n \"text\": \"Therefore, the skewness indicates how much our distribution derives from the normal distribution (with the skewness value of zero or very close).\"\n },\n {\n \"code\": null,\n \"e\": 5154,\n \"s\": 5106,\n \"text\": \"There are three generic types of distributions:\"\n },\n {\n \"code\": null,\n \"e\": 5289,\n \"s\": 5154,\n \"text\": \"Symmetrical [median = mean]: In a normal distribution, the mean (average) divides the data symmetrically at the median value or close.\"\n },\n {\n \"code\": null,\n \"e\": 5543,\n \"s\": 5289,\n \"text\": \"Positive skew [median < mean]: The distribution is asymmetrical, the tail is skewed/longer towards the right-hand side of the curve. In this type, the majority of the observations are concentrated on the left tail, and the value of skewness is positive.\"\n },\n {\n \"code\": null,\n \"e\": 5816,\n \"s\": 5543,\n \"text\": \"Negative skew [median > mean]: The distribution is asymmetrical and the tail is skewed/longer towards the left-hand side of the curve. In this type of distribution, the majority of the observations are concentrated on the right tail, and the value of skewness is negative.\"\n },\n {\n \"code\": null,\n \"e\": 5832,\n \"s\": 5816,\n \"text\": \"Rule of thumbs:\"\n },\n {\n \"code\": null,\n \"e\": 5884,\n \"s\": 5832,\n \"text\": \"Symmetric distribution: values between -0.5 to 0.5.\"\n },\n {\n \"code\": null,\n \"e\": 5941,\n \"s\": 5884,\n \"text\": \"Moderate skew: values between -1 and -0.5 and 0.5 and 1.\"\n },\n {\n \"code\": null,\n \"e\": 5970,\n \"s\": 5941,\n \"text\": \"High skew: values <-1 or >1.\"\n },\n {\n \"code\": null,\n \"e\": 6166,\n \"s\": 5970,\n \"text\": \"kurtosis is another useful tool when it comes to quantify the shape of a distribution. It measures both how long are the tails, but most important, and how sharp is the peak of the distributions.\"\n },\n {\n \"code\": null,\n \"e\": 6402,\n \"s\": 6166,\n \"text\": \"If the distribution has a sharper and taller peak and shorter tails, then it has a higher kurtosis while a low kurtosis can be observed when the peak of the distribution is flatter with thinner tails. There are three types of kurtosis:\"\n },\n {\n \"code\": null,\n \"e\": 6490,\n \"s\": 6402,\n \"text\": \"Leptokurtic: The distribution is tall and thin. The value of a leptokurtic must be > 3.\"\n },\n {\n \"code\": null,\n \"e\": 6620,\n \"s\": 6490,\n \"text\": \"Mesokurtic: This distribution looks the same or very similar to a normal distribution. The value of a “normal” mesokurtic is = 3.\"\n },\n {\n \"code\": null,\n \"e\": 6788,\n \"s\": 6620,\n \"text\": \"Platykurtic: The distributions have a flatter and wider peak and thinner tails, meaning that the data is moderately spread out. The value of a platykurtic must be < 3.\"\n },\n {\n \"code\": null,\n \"e\": 7248,\n \"s\": 6788,\n \"text\": \"Kurtosis is calculated by raising the average of the standardized data to the fourth power. If we raise any standardized number (less than 1) to the 4th power, the result would be a very small number, somewhere close to zero. Such a small value would not contribute much to the kurtosis. The conclusion is that the values that would make a difference to the kurtosis would be the ones far away from the region of the peak, put it in other words, the outliers.\"\n },\n {\n \"code\": null,\n \"e\": 7398,\n \"s\": 7248,\n \"text\": \"In this section, we will be giving short numeric stats summaries concerning the different measures of central tendency and dispersion of the dataset.\"\n },\n {\n \"code\": null,\n \"e\": 7492,\n \"s\": 7398,\n \"text\": \"let’s work on some practical examples through a descriptive statistics environment in Pandas.\"\n },\n {\n \"code\": null,\n \"e\": 7510,\n \"s\": 7492,\n \"text\": \"> Repo code here.\"\n },\n {\n \"code\": null,\n \"e\": 7553,\n \"s\": 7510,\n \"text\": \"Start by importing the required libraries:\"\n },\n {\n \"code\": null,\n \"e\": 7673,\n \"s\": 7553,\n \"text\": \"import pandas as pdimport numpy as npimport scipyimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inline\"\n },\n {\n \"code\": null,\n \"e\": 7730,\n \"s\": 7673,\n \"text\": \"Load the dataset:df = pd.read_csv(\\\"sample.csv\\\", sep=\\\";\\\")\"\n },\n {\n \"code\": null,\n \"e\": 7755,\n \"s\": 7730,\n \"text\": \"Print the data:df.head()\"\n },\n {\n \"code\": null,\n \"e\": 7831,\n \"s\": 7755,\n \"text\": \"Before any stats calculus, let’s just take a quick look at the data:df.info\"\n },\n {\n \"code\": null,\n \"e\": 7987,\n \"s\": 7831,\n \"text\": \"The dataset consists of 310 observations and 2 columns. One of the attributes is numerical, and the other categorical. Both columns have no missing values.\"\n },\n {\n \"code\": null,\n \"e\": 8132,\n \"s\": 7987,\n \"text\": \"The numerical variable we are going to analyze is age. First step is to visually observe the variable. So let's plot an histogram and a boxplot.\"\n },\n {\n \"code\": null,\n \"e\": 8217,\n \"s\": 8132,\n \"text\": \"plt.hist(df.age, bins=20)plt.xlabel(“Age”)plt.ylabel(“Absolute Frequency”)plt.show()\"\n },\n {\n \"code\": null,\n \"e\": 8308,\n \"s\": 8217,\n \"text\": \"sns.boxplot(x=age, data=df, orient=\\\"h\\\").set(xlabel=\\\"Age\\\", title=\\\"Numeric variable 'Age'\\\");\"\n },\n {\n \"code\": null,\n \"e\": 8480,\n \"s\": 8308,\n \"text\": \"It is also possible to visually observe the variable with both a histogram and a boxplot combined. I find it a useful graphical combination and use it a lot in my reports.\"\n },\n {\n \"code\": null,\n \"e\": 8992,\n \"s\": 8480,\n \"text\": \"age = df.agef, (ax_box, ax_hist) = plt.subplots(2, sharex=True, gridspec_kw= {\\\"height_ratios\\\": (0.8, 1.2)})mean=np.array(age).mean()median=np.median(age)sns.boxplot(age, ax=ax_box)ax_box.axvline(mean, color='r', linestyle='--')ax_box.axvline(median, color='g', linestyle='-')sns.distplot(age, ax=ax_hist)ax_hist.axvline(mean, color='r', linestyle='--')ax_hist.axvline(median, color='g', linestyle='-')plt.legend({'Mean':mean,'Median':median})plt.title(\\\"'Age' histogram + boxplot\\\")ax_box.set(xlabel='')plt.show()\"\n },\n {\n \"code\": null,\n \"e\": 9014,\n \"s\": 8992,\n \"text\": \"1. Mean:df.age.mean()\"\n },\n {\n \"code\": null,\n \"e\": 9033,\n \"s\": 9014,\n \"text\": \"35.564516129032256\"\n },\n {\n \"code\": null,\n \"e\": 9059,\n \"s\": 9033,\n \"text\": \"2. Median:df.age.median()\"\n },\n {\n \"code\": null,\n \"e\": 9064,\n \"s\": 9059,\n \"text\": \"32.0\"\n },\n {\n \"code\": null,\n \"e\": 9099,\n \"s\": 9064,\n \"text\": \"3. Standard deviation:df.age.std()\"\n },\n {\n \"code\": null,\n \"e\": 9118,\n \"s\": 9099,\n \"text\": \"18.824363618000913\"\n },\n {\n \"code\": null,\n \"e\": 9143,\n \"s\": 9118,\n \"text\": \"4. Variance:df.age.var()\"\n },\n {\n \"code\": null,\n \"e\": 9161,\n \"s\": 9143,\n \"text\": \"354.3566656227164\"\n },\n {\n \"code\": null,\n \"e\": 9205,\n \"s\": 9161,\n \"text\": \"5. a) Percentiles 25%:df.age.quantile(0.25)\"\n },\n {\n \"code\": null,\n \"e\": 9210,\n \"s\": 9205,\n \"text\": \"23.0\"\n },\n {\n \"code\": null,\n \"e\": 9250,\n \"s\": 9210,\n \"text\": \"b) Percentile 75%:df.age.quantile(0.75)\"\n },\n {\n \"code\": null,\n \"e\": 9255,\n \"s\": 9250,\n \"text\": \"45.0\"\n },\n {\n \"code\": null,\n \"e\": 9297,\n \"s\": 9255,\n \"text\": \"c) In one go:df.age.quantile(q=[.25, .75)\"\n },\n {\n \"code\": null,\n \"e\": 9347,\n \"s\": 9297,\n \"text\": \"0.25 23.00.75 45.0Name: age, dtype: float64\"\n },\n {\n \"code\": null,\n \"e\": 9397,\n \"s\": 9347,\n \"text\": \"6. Minimum and maximum:df.age.min(), df.age.max()\"\n },\n {\n \"code\": null,\n \"e\": 9405,\n \"s\": 9397,\n \"text\": \"(3, 98)\"\n },\n {\n \"code\": null,\n \"e\": 9455,\n \"s\": 9405,\n \"text\": \"7. Skewness (with scipy):scipy.stats.skew(df.age)\"\n },\n {\n \"code\": null,\n \"e\": 9474,\n \"s\": 9455,\n \"text\": \"0.9085582496839909\"\n },\n {\n \"code\": null,\n \"e\": 9528,\n \"s\": 9474,\n \"text\": \"8. Kurtosis (with scipy):scipy.stats.kurtosis(df.age)\"\n },\n {\n \"code\": null,\n \"e\": 9547,\n \"s\": 9528,\n \"text\": \"0.7254158742250474\"\n },\n {\n \"code\": null,\n \"e\": 9587,\n \"s\": 9547,\n \"text\": \"9. Size (number of rows):df.age.count()\"\n },\n {\n \"code\": null,\n \"e\": 9591,\n \"s\": 9587,\n \"text\": \"310\"\n },\n {\n \"code\": null,\n \"e\": 9646,\n \"s\": 9591,\n \"text\": \"10. Number of uniques (total distinct)df.age.nunique()\"\n },\n {\n \"code\": null,\n \"e\": 9649,\n \"s\": 9646,\n \"text\": \"74\"\n },\n {\n \"code\": null,\n \"e\": 9688,\n \"s\": 9649,\n \"text\": \"11. Uniques (distinct):df.age.unique()\"\n },\n {\n \"code\": null,\n \"e\": 9986,\n \"s\": 9688,\n \"text\": \"array([46, 22, 54, 33, 69, 35, 11, 97, 50, 34, 67, 43, 21, 12, 23, 45, 89, 76, 5, 55, 65, 24, 27, 57, 38, 28, 36, 60, 56, 53, 26, 25, 42, 83, 16, 51, 90, 10, 70, 44, 20, 31, 47, 30, 91, 7, 6, 41, 66, 61, 96, 32, 58, 17, 52, 29, 75, 86, 98, 48, 40, 13, 4, 68, 62, 9, 18, 39, 15, 19, 8, 71, 3, 37])\"\n },\n {\n \"code\": null,\n \"e\": 10113,\n \"s\": 9986,\n \"text\": \"The categorical variable we are going to analyze is city. Let’s plot a bar chart and get a visual observation of the variable.\"\n },\n {\n \"code\": null,\n \"e\": 10245,\n \"s\": 10113,\n \"text\": \"df.city.value_counts().plot.bar()plt.xlabel(\\\"City\\\")plt.ylabel(\\\"Absolute Frequency\\\")plt.title(\\\"Categoric variable 'City'\\\")plt.show()\"\n },\n {\n \"code\": null,\n \"e\": 10271,\n \"s\": 10245,\n \"text\": \"1. Mode:df.city.mode()[0]\"\n },\n {\n \"code\": null,\n \"e\": 10279,\n \"s\": 10271,\n \"text\": \"'Paris'\"\n },\n {\n \"code\": null,\n \"e\": 10318,\n \"s\": 10279,\n \"text\": \"2. Number of uniques:df.city.nunique()\"\n },\n {\n \"code\": null,\n \"e\": 10320,\n \"s\": 10318,\n \"text\": \"6\"\n },\n {\n \"code\": null,\n \"e\": 10359,\n \"s\": 10320,\n \"text\": \"3. Uniques (distinct):df.city.unique()\"\n },\n {\n \"code\": null,\n \"e\": 10444,\n \"s\": 10359,\n \"text\": \"array(['Lisbon', 'Paris', 'Madrid', 'London', 'Luxembourg', 'Berlin'], dtype=object)\"\n },\n {\n \"code\": null,\n \"e\": 10513,\n \"s\": 10444,\n \"text\": \"4. Most frequent unique (value count):df.city.value_counts().head(1)\"\n },\n {\n \"code\": null,\n \"e\": 10550,\n \"s\": 10513,\n \"text\": \"Paris 67Name: city, dtype: int64\"\n },\n {\n \"code\": null,\n \"e\": 10591,\n \"s\": 10550,\n \"text\": \"5. Size (number of rows):df.city.count()\"\n },\n {\n \"code\": null,\n \"e\": 10595,\n \"s\": 10591,\n \"text\": \"310\"\n },\n {\n \"code\": null,\n \"e\": 10750,\n \"s\": 10595,\n \"text\": \"6. % of the highest unique (fraction of the most common unique in regards to all the others):p = df.city.value_counts(normalize=True)[0] print(f\\\"{p:.1%}\\\")\"\n },\n {\n \"code\": null,\n \"e\": 10756,\n \"s\": 10750,\n \"text\": \"21.6%\"\n },\n {\n \"code\": null,\n \"e\": 10932,\n \"s\": 10756,\n \"text\": \"The describe() method shows the descriptive statistics gathered in one table. By default, stats for numeric data. The result is represented as a pandas dataframe.df.describe()\"\n },\n {\n \"code\": null,\n \"e\": 11085,\n \"s\": 10932,\n \"text\": \"Adding other non-standard values, for instance, the ‘variance’.describe_var = data.describe()describe_var.append(pd.Series(data.var(), name='variance'))\"\n },\n {\n \"code\": null,\n \"e\": 11220,\n \"s\": 11085,\n \"text\": \"Displaying categorical data.df.describe(include=[\\\"O\\\"])<=> df.describe(exclude=['float64','int64'])<=> df.describe(include=[np.object])\"\n },\n {\n \"code\": null,\n \"e\": 11341,\n \"s\": 11220,\n \"text\": \"By passing the parameter include='all', displays both numeric and categoric variables at once.df.describe(include='all')\"\n },\n {\n \"code\": null,\n \"e\": 11608,\n \"s\": 11341,\n \"text\": \"These are the basics of descriptive statistics when developing an exploratory data analysis project with the help of Pandas, Numpy, Scipy, Matplolib and/or Seaborn. When well performed, these stats help us to understand and transform the data for further processing.\"\n },\n {\n \"code\": null,\n \"e\": 11780,\n \"s\": 11608,\n \"text\": \"Remember always be a skeptic. Look at the data with your own eyes (don’t fully rely on statistics), and graphically visualize the variables (use and abuse of the visuals).\"\n },\n {\n \"code\": null,\n \"e\": 11798,\n \"s\": 11780,\n \"text\": \"> Repo code here.\"\n },\n {\n \"code\": null,\n \"e\": 11852,\n \"s\": 11798,\n \"text\": \"Check out other articles you might also like to read:\"\n },\n {\n \"code\": null,\n \"e\": 11875,\n \"s\": 11852,\n \"text\": \"towardsdatascience.com\"\n },\n {\n \"code\": null,\n \"e\": 11898,\n \"s\": 11875,\n \"text\": \"towardsdatascience.com\"\n },\n {\n \"code\": null,\n \"e\": 11921,\n \"s\": 11898,\n \"text\": \"towardsdatascience.com\"\n },\n {\n \"code\": null,\n \"e\": 11930,\n \"s\": 11921,\n \"text\": \"Linkedin\"\n },\n {\n \"code\": null,\n \"e\": 11938,\n \"s\": 11930,\n \"text\": \"Twitter\"\n },\n {\n \"code\": null,\n \"e\": 11945,\n \"s\": 11938,\n \"text\": \"Medium\"\n },\n {\n \"code\": null,\n \"e\": 11952,\n \"s\": 11945,\n \"text\": \"GitHub\"\n },\n {\n \"code\": null,\n \"e\": 11959,\n \"s\": 11952,\n \"text\": \"Kaggle\"\n },\n {\n \"code\": null,\n \"e\": 11965,\n \"s\": 11959,\n \"text\": \"Email\"\n }\n]"}}},{"rowIdx":108,"cells":{"title":{"kind":"string","value":"Sum of subset differences - GeeksforGeeks"},"text":{"kind":"string","value":"28 May, 2018\nGiven a set S consisting of n numbers, find the sum of difference between last and first element of each subset. We find first and last element of every subset by keeping them in same order as they appear in input set S.\ni.e., sumSetDiff(S) = ∑ (last(s) – first(s)),where sum goes over all subsets s of S.\nNote: Elements in the subset should be in the same order as in the set S.\nExamples:\nS = {5, 2, 9, 6}, n = 4\n\nSubsets are:\n{5}, last(s)-first(s) = 0.\n{2}, last(s)-first(s) = 0.\n{9}, last(s)-first(s) = 0.\n{6}, last(s)-first(s) = 0.\n{5,2}, last(s)-first(s) = -3.\n{5,9}, last(s)-first(s) = 4.\n{5,6}, last(s)-first(s) = 1.\n{2,9}, last(s)-first(s) = 7.\n{2,6}, last(s)-first(s) = 4.\n{9,6}, last(s)-first(s) = -3.\n{5,2,9}, last(s)-first(s) = 4.\n{5,2,6}, last(s)-first(s) = 1.\n{5,9,6}, last(s)-first(s) = 1.\n{2,9,6}, last(s)-first(s) = 4.\n{5,2,9,6}, last(s)-first(s) = 1.\n\nOutput = -3+4+1+7+4-3+4+1+1+4+1\n = 21.\n\nA simple solution for this problem is to find the difference between the last and first element for each subset s of set S and output the sum of ll these differences. Time complexity for this approach is O(2n).\nAn efficient solution to solve the problem in linear time complexity.We are given a set S consisting of n numbers, and we need to compute the sum of difference between last and first element of each subset of S, i.e.,sumSetDiff(S) = ∑ (last(s) – first(s)), where sum goes over all subsets s of S.Equivalently,sumSetDiff(S) = ∑ (last(s)) – ∑ (first(s)),In other words, we can compute the sum of last element of each subset, and the sum of first element of each subset separately, and then compute their difference.\nLet us say that the elements of S are {a1, a2, a3,..., an}. Note the following observation:\nSubsets containing element a1 as the first element can be obtained by taking any subset of {a2, a3,..., an} and then including a1 into it. Number of such subsets will be 2n-1.Subsets containing element a2 as the first element can be obtained by taking any subset of {a3, a4,..., an} and then including a2 into it. Number of such subsets will be 2n-2.Subsets containing element ai as the first element can be obtained by taking any subset of {ai, a(i+1),..., an} and then including ai into it. Number of such subsets will be 2n-i.Therefore, the sum of first element of all subsets will be:SumF = a1.2n-1 + a2.2n-2 +...+ an.1In a similar way we can compute the sum of last element of all subsets of S (Taking at every step ai as last element instead of first element and then obtaining all the subsets).SumL = a1.1 + a2.2 +...+ an.2n-1Finally, the answer of our problem will be SumL – SumF.Implementation:C++JavaPython3C#PHPC++// A C++ program to find sum of difference between// last and first element of each subset#include // Returns the sum of first elements of all subsetsint SumF(int S[], int n){ int sum = 0; // Compute the SumF as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, n-i-1)); return sum;} // Returns the sum of last elements of all subsetsint SumL(int S[], int n){ int sum = 0; // Compute the SumL as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, i)); return sum;} // Returns the difference between sum of last elements of// each subset and the sum of first elements of each subsetint sumSetDiff(int S[], int n){ return SumL(S, n) - SumF(S, n);} // Driver program to test above functionint main(){ int n = 4; int S[] = {5, 2, 9, 6}; printf(\"%d\\n\", sumSetDiff(S, n)); return 0;}Java// A Java program to find sum of difference // between last and first element of each // subsetclass GFG { // Returns the sum of first elements // of all subsets static int SumF(int S[], int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int S[], int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int S[], int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void main(String arg[]) { int n = 4; int S[] = { 5, 2, 9, 6 }; System.out.println(sumSetDiff(S, n)); }} // This code is contributed by Anant Agarwal.Python3# Python3 program to find sum of# difference between last and # first element of each subset # Returns the sum of first# elements of all subsetsdef SumF(S, n): sum = 0 # Compute the SumF as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, n - i - 1)) return sum # Returns the sum of last# elements of all subsetsdef SumL(S, n): sum = 0 # Compute the SumL as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, i)) return sum # Returns the difference between sum# of last elements of each subset and# the sum of first elements of each subsetdef sumSetDiff(S, n): return SumL(S, n) - SumF(S, n) # Driver programn = 4S = [5, 2, 9, 6]print(sumSetDiff(S, n)) # This code is contributed by Anant Agarwal.C#// A C# program to find sum of difference // between last and first element of each // subsetusing System;class GFG { // Returns the sum of first elements // of all subsets static int SumF(int []S, int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int []S, int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int []S, int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void Main() { int n = 4; int []S = { 5, 2, 9, 6 }; Console.Write(sumSetDiff(S, n)); }} // This code is contributed by nitin mittal.PHPOutput:21\nTime Complexity : O(n)This article is contributed by Akash Aggarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave\nSubsets containing element a1 as the first element can be obtained by taking any subset of {a2, a3,..., an} and then including a1 into it. Number of such subsets will be 2n-1.\nSubsets containing element a2 as the first element can be obtained by taking any subset of {a3, a4,..., an} and then including a2 into it. Number of such subsets will be 2n-2.\nSubsets containing element ai as the first element can be obtained by taking any subset of {ai, a(i+1),..., an} and then including ai into it. Number of such subsets will be 2n-i.Therefore, the sum of first element of all subsets will be:SumF = a1.2n-1 + a2.2n-2 +...+ an.1In a similar way we can compute the sum of last element of all subsets of S (Taking at every step ai as last element instead of first element and then obtaining all the subsets).SumL = a1.1 + a2.2 +...+ an.2n-1Finally, the answer of our problem will be SumL – SumF.Implementation:C++JavaPython3C#PHPC++// A C++ program to find sum of difference between// last and first element of each subset#include // Returns the sum of first elements of all subsetsint SumF(int S[], int n){ int sum = 0; // Compute the SumF as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, n-i-1)); return sum;} // Returns the sum of last elements of all subsetsint SumL(int S[], int n){ int sum = 0; // Compute the SumL as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, i)); return sum;} // Returns the difference between sum of last elements of// each subset and the sum of first elements of each subsetint sumSetDiff(int S[], int n){ return SumL(S, n) - SumF(S, n);} // Driver program to test above functionint main(){ int n = 4; int S[] = {5, 2, 9, 6}; printf(\"%d\\n\", sumSetDiff(S, n)); return 0;}Java// A Java program to find sum of difference // between last and first element of each // subsetclass GFG { // Returns the sum of first elements // of all subsets static int SumF(int S[], int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int S[], int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int S[], int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void main(String arg[]) { int n = 4; int S[] = { 5, 2, 9, 6 }; System.out.println(sumSetDiff(S, n)); }} // This code is contributed by Anant Agarwal.Python3# Python3 program to find sum of# difference between last and # first element of each subset # Returns the sum of first# elements of all subsetsdef SumF(S, n): sum = 0 # Compute the SumF as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, n - i - 1)) return sum # Returns the sum of last# elements of all subsetsdef SumL(S, n): sum = 0 # Compute the SumL as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, i)) return sum # Returns the difference between sum# of last elements of each subset and# the sum of first elements of each subsetdef sumSetDiff(S, n): return SumL(S, n) - SumF(S, n) # Driver programn = 4S = [5, 2, 9, 6]print(sumSetDiff(S, n)) # This code is contributed by Anant Agarwal.C#// A C# program to find sum of difference // between last and first element of each // subsetusing System;class GFG { // Returns the sum of first elements // of all subsets static int SumF(int []S, int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int []S, int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int []S, int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void Main() { int n = 4; int []S = { 5, 2, 9, 6 }; Console.Write(sumSetDiff(S, n)); }} // This code is contributed by nitin mittal.PHPOutput:21\nTime Complexity : O(n)This article is contributed by Akash Aggarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave\nTherefore, the sum of first element of all subsets will be:SumF = a1.2n-1 + a2.2n-2 +...+ an.1\nIn a similar way we can compute the sum of last element of all subsets of S (Taking at every step ai as last element instead of first element and then obtaining all the subsets).SumL = a1.1 + a2.2 +...+ an.2n-1\nFinally, the answer of our problem will be SumL – SumF.\nImplementation:\nC++\nJava\nPython3\nC#\nPHP\n// A C++ program to find sum of difference between// last and first element of each subset#include // Returns the sum of first elements of all subsetsint SumF(int S[], int n){ int sum = 0; // Compute the SumF as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, n-i-1)); return sum;} // Returns the sum of last elements of all subsetsint SumL(int S[], int n){ int sum = 0; // Compute the SumL as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, i)); return sum;} // Returns the difference between sum of last elements of// each subset and the sum of first elements of each subsetint sumSetDiff(int S[], int n){ return SumL(S, n) - SumF(S, n);} // Driver program to test above functionint main(){ int n = 4; int S[] = {5, 2, 9, 6}; printf(\"%d\\n\", sumSetDiff(S, n)); return 0;}\n// A Java program to find sum of difference // between last and first element of each // subsetclass GFG { // Returns the sum of first elements // of all subsets static int SumF(int S[], int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int S[], int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int S[], int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void main(String arg[]) { int n = 4; int S[] = { 5, 2, 9, 6 }; System.out.println(sumSetDiff(S, n)); }} // This code is contributed by Anant Agarwal.\n# Python3 program to find sum of# difference between last and # first element of each subset # Returns the sum of first# elements of all subsetsdef SumF(S, n): sum = 0 # Compute the SumF as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, n - i - 1)) return sum # Returns the sum of last# elements of all subsetsdef SumL(S, n): sum = 0 # Compute the SumL as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, i)) return sum # Returns the difference between sum# of last elements of each subset and# the sum of first elements of each subsetdef sumSetDiff(S, n): return SumL(S, n) - SumF(S, n) # Driver programn = 4S = [5, 2, 9, 6]print(sumSetDiff(S, n)) # This code is contributed by Anant Agarwal.\n// A C# program to find sum of difference // between last and first element of each // subsetusing System;class GFG { // Returns the sum of first elements // of all subsets static int SumF(int []S, int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int []S, int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int []S, int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void Main() { int n = 4; int []S = { 5, 2, 9, 6 }; Console.Write(sumSetDiff(S, n)); }} // This code is contributed by nitin mittal.\n\n21\n\nTime Complexity : O(n)\nThis article is contributed by Akash Aggarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.\nPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above.\nnitin mittal\nvt_m\nArrays\nArrays\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nComments\nOld Comments\nStack Data Structure (Introduction and Program)\nTop 50 Array Coding Problems for Interviews\nIntroduction to Arrays\nMultidimensional Arrays in Java\nLinear Search\nLinked List vs Array\nPython | Using 2D arrays/lists the right way\nGiven an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)\nMaximum and minimum of an array using minimum number of comparisons\nQueue | Set 1 (Introduction and Array Implementation)"},"parsed":{"kind":"list like","value":[{"code":null,"e":24469,"s":24441,"text":"\n28 May, 2018"},{"code":null,"e":24690,"s":24469,"text":"Given a set S consisting of n numbers, find the sum of difference between last and first element of each subset. We find first and last element of every subset by keeping them in same order as they appear in input set S."},{"code":null,"e":24775,"s":24690,"text":"i.e., sumSetDiff(S) = ∑ (last(s) – first(s)),where sum goes over all subsets s of S."},{"code":null,"e":24849,"s":24775,"text":"Note: Elements in the subset should be in the same order as in the set S."},{"code":null,"e":24859,"s":24849,"text":"Examples:"},{"code":null,"e":25387,"s":24859,"text":"S = {5, 2, 9, 6}, n = 4\n\nSubsets are:\n{5}, last(s)-first(s) = 0.\n{2}, last(s)-first(s) = 0.\n{9}, last(s)-first(s) = 0.\n{6}, last(s)-first(s) = 0.\n{5,2}, last(s)-first(s) = -3.\n{5,9}, last(s)-first(s) = 4.\n{5,6}, last(s)-first(s) = 1.\n{2,9}, last(s)-first(s) = 7.\n{2,6}, last(s)-first(s) = 4.\n{9,6}, last(s)-first(s) = -3.\n{5,2,9}, last(s)-first(s) = 4.\n{5,2,6}, last(s)-first(s) = 1.\n{5,9,6}, last(s)-first(s) = 1.\n{2,9,6}, last(s)-first(s) = 4.\n{5,2,9,6}, last(s)-first(s) = 1.\n\nOutput = -3+4+1+7+4-3+4+1+1+4+1\n = 21.\n"},{"code":null,"e":25598,"s":25387,"text":"A simple solution for this problem is to find the difference between the last and first element for each subset s of set S and output the sum of ll these differences. Time complexity for this approach is O(2n)."},{"code":null,"e":26112,"s":25598,"text":"An efficient solution to solve the problem in linear time complexity.We are given a set S consisting of n numbers, and we need to compute the sum of difference between last and first element of each subset of S, i.e.,sumSetDiff(S) = ∑ (last(s) – first(s)), where sum goes over all subsets s of S.Equivalently,sumSetDiff(S) = ∑ (last(s)) – ∑ (first(s)),In other words, we can compute the sum of last element of each subset, and the sum of first element of each subset separately, and then compute their difference."},{"code":null,"e":26204,"s":26112,"text":"Let us say that the elements of S are {a1, a2, a3,..., an}. Note the following observation:"},{"code":null,"e":32868,"s":26204,"text":"Subsets containing element a1 as the first element can be obtained by taking any subset of {a2, a3,..., an} and then including a1 into it. Number of such subsets will be 2n-1.Subsets containing element a2 as the first element can be obtained by taking any subset of {a3, a4,..., an} and then including a2 into it. Number of such subsets will be 2n-2.Subsets containing element ai as the first element can be obtained by taking any subset of {ai, a(i+1),..., an} and then including ai into it. Number of such subsets will be 2n-i.Therefore, the sum of first element of all subsets will be:SumF = a1.2n-1 + a2.2n-2 +...+ an.1In a similar way we can compute the sum of last element of all subsets of S (Taking at every step ai as last element instead of first element and then obtaining all the subsets).SumL = a1.1 + a2.2 +...+ an.2n-1Finally, the answer of our problem will be SumL – SumF.Implementation:C++JavaPython3C#PHPC++// A C++ program to find sum of difference between// last and first element of each subset#include // Returns the sum of first elements of all subsetsint SumF(int S[], int n){ int sum = 0; // Compute the SumF as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, n-i-1)); return sum;} // Returns the sum of last elements of all subsetsint SumL(int S[], int n){ int sum = 0; // Compute the SumL as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, i)); return sum;} // Returns the difference between sum of last elements of// each subset and the sum of first elements of each subsetint sumSetDiff(int S[], int n){ return SumL(S, n) - SumF(S, n);} // Driver program to test above functionint main(){ int n = 4; int S[] = {5, 2, 9, 6}; printf(\"%d\\n\", sumSetDiff(S, n)); return 0;}Java// A Java program to find sum of difference // between last and first element of each // subsetclass GFG { // Returns the sum of first elements // of all subsets static int SumF(int S[], int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int S[], int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int S[], int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void main(String arg[]) { int n = 4; int S[] = { 5, 2, 9, 6 }; System.out.println(sumSetDiff(S, n)); }} // This code is contributed by Anant Agarwal.Python3# Python3 program to find sum of# difference between last and # first element of each subset # Returns the sum of first# elements of all subsetsdef SumF(S, n): sum = 0 # Compute the SumF as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, n - i - 1)) return sum # Returns the sum of last# elements of all subsetsdef SumL(S, n): sum = 0 # Compute the SumL as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, i)) return sum # Returns the difference between sum# of last elements of each subset and# the sum of first elements of each subsetdef sumSetDiff(S, n): return SumL(S, n) - SumF(S, n) # Driver programn = 4S = [5, 2, 9, 6]print(sumSetDiff(S, n)) # This code is contributed by Anant Agarwal.C#// A C# program to find sum of difference // between last and first element of each // subsetusing System;class GFG { // Returns the sum of first elements // of all subsets static int SumF(int []S, int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int []S, int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int []S, int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void Main() { int n = 4; int []S = { 5, 2, 9, 6 }; Console.Write(sumSetDiff(S, n)); }} // This code is contributed by nitin mittal.PHPOutput:21\nTime Complexity : O(n)This article is contributed by Akash Aggarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave"},{"code":null,"e":33044,"s":32868,"text":"Subsets containing element a1 as the first element can be obtained by taking any subset of {a2, a3,..., an} and then including a1 into it. Number of such subsets will be 2n-1."},{"code":null,"e":33220,"s":33044,"text":"Subsets containing element a2 as the first element can be obtained by taking any subset of {a3, a4,..., an} and then including a2 into it. Number of such subsets will be 2n-2."},{"code":null,"e":39534,"s":33220,"text":"Subsets containing element ai as the first element can be obtained by taking any subset of {ai, a(i+1),..., an} and then including ai into it. Number of such subsets will be 2n-i.Therefore, the sum of first element of all subsets will be:SumF = a1.2n-1 + a2.2n-2 +...+ an.1In a similar way we can compute the sum of last element of all subsets of S (Taking at every step ai as last element instead of first element and then obtaining all the subsets).SumL = a1.1 + a2.2 +...+ an.2n-1Finally, the answer of our problem will be SumL – SumF.Implementation:C++JavaPython3C#PHPC++// A C++ program to find sum of difference between// last and first element of each subset#include // Returns the sum of first elements of all subsetsint SumF(int S[], int n){ int sum = 0; // Compute the SumF as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, n-i-1)); return sum;} // Returns the sum of last elements of all subsetsint SumL(int S[], int n){ int sum = 0; // Compute the SumL as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, i)); return sum;} // Returns the difference between sum of last elements of// each subset and the sum of first elements of each subsetint sumSetDiff(int S[], int n){ return SumL(S, n) - SumF(S, n);} // Driver program to test above functionint main(){ int n = 4; int S[] = {5, 2, 9, 6}; printf(\"%d\\n\", sumSetDiff(S, n)); return 0;}Java// A Java program to find sum of difference // between last and first element of each // subsetclass GFG { // Returns the sum of first elements // of all subsets static int SumF(int S[], int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int S[], int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int S[], int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void main(String arg[]) { int n = 4; int S[] = { 5, 2, 9, 6 }; System.out.println(sumSetDiff(S, n)); }} // This code is contributed by Anant Agarwal.Python3# Python3 program to find sum of# difference between last and # first element of each subset # Returns the sum of first# elements of all subsetsdef SumF(S, n): sum = 0 # Compute the SumF as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, n - i - 1)) return sum # Returns the sum of last# elements of all subsetsdef SumL(S, n): sum = 0 # Compute the SumL as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, i)) return sum # Returns the difference between sum# of last elements of each subset and# the sum of first elements of each subsetdef sumSetDiff(S, n): return SumL(S, n) - SumF(S, n) # Driver programn = 4S = [5, 2, 9, 6]print(sumSetDiff(S, n)) # This code is contributed by Anant Agarwal.C#// A C# program to find sum of difference // between last and first element of each // subsetusing System;class GFG { // Returns the sum of first elements // of all subsets static int SumF(int []S, int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int []S, int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int []S, int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void Main() { int n = 4; int []S = { 5, 2, 9, 6 }; Console.Write(sumSetDiff(S, n)); }} // This code is contributed by nitin mittal.PHPOutput:21\nTime Complexity : O(n)This article is contributed by Akash Aggarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave"},{"code":null,"e":39629,"s":39534,"text":"Therefore, the sum of first element of all subsets will be:SumF = a1.2n-1 + a2.2n-2 +...+ an.1"},{"code":null,"e":39840,"s":39629,"text":"In a similar way we can compute the sum of last element of all subsets of S (Taking at every step ai as last element instead of first element and then obtaining all the subsets).SumL = a1.1 + a2.2 +...+ an.2n-1"},{"code":null,"e":39896,"s":39840,"text":"Finally, the answer of our problem will be SumL – SumF."},{"code":null,"e":39912,"s":39896,"text":"Implementation:"},{"code":null,"e":39916,"s":39912,"text":"C++"},{"code":null,"e":39921,"s":39916,"text":"Java"},{"code":null,"e":39929,"s":39921,"text":"Python3"},{"code":null,"e":39932,"s":39929,"text":"C#"},{"code":null,"e":39936,"s":39932,"text":"PHP"},{"code":"// A C++ program to find sum of difference between// last and first element of each subset#include // Returns the sum of first elements of all subsetsint SumF(int S[], int n){ int sum = 0; // Compute the SumF as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, n-i-1)); return sum;} // Returns the sum of last elements of all subsetsint SumL(int S[], int n){ int sum = 0; // Compute the SumL as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, i)); return sum;} // Returns the difference between sum of last elements of// each subset and the sum of first elements of each subsetint sumSetDiff(int S[], int n){ return SumL(S, n) - SumF(S, n);} // Driver program to test above functionint main(){ int n = 4; int S[] = {5, 2, 9, 6}; printf(\"%d\\n\", sumSetDiff(S, n)); return 0;}","e":40861,"s":39936,"text":null},{"code":"// A Java program to find sum of difference // between last and first element of each // subsetclass GFG { // Returns the sum of first elements // of all subsets static int SumF(int S[], int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int S[], int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int S[], int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void main(String arg[]) { int n = 4; int S[] = { 5, 2, 9, 6 }; System.out.println(sumSetDiff(S, n)); }} // This code is contributed by Anant Agarwal.","e":42125,"s":40861,"text":null},{"code":"# Python3 program to find sum of# difference between last and # first element of each subset # Returns the sum of first# elements of all subsetsdef SumF(S, n): sum = 0 # Compute the SumF as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, n - i - 1)) return sum # Returns the sum of last# elements of all subsetsdef SumL(S, n): sum = 0 # Compute the SumL as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, i)) return sum # Returns the difference between sum# of last elements of each subset and# the sum of first elements of each subsetdef sumSetDiff(S, n): return SumL(S, n) - SumF(S, n) # Driver programn = 4S = [5, 2, 9, 6]print(sumSetDiff(S, n)) # This code is contributed by Anant Agarwal.","e":42945,"s":42125,"text":null},{"code":"// A C# program to find sum of difference // between last and first element of each // subsetusing System;class GFG { // Returns the sum of first elements // of all subsets static int SumF(int []S, int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int []S, int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int []S, int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void Main() { int n = 4; int []S = { 5, 2, 9, 6 }; Console.Write(sumSetDiff(S, n)); }} // This code is contributed by nitin mittal.","e":44211,"s":42945,"text":null},{"code":"","e":45175,"s":44211,"text":null},{"code":null,"e":45179,"s":45175,"text":"21\n"},{"code":null,"e":45202,"s":45179,"text":"Time Complexity : O(n)"},{"code":null,"e":45500,"s":45202,"text":"This article is contributed by Akash Aggarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."},{"code":null,"e":45625,"s":45500,"text":"Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."},{"code":null,"e":45638,"s":45625,"text":"nitin mittal"},{"code":null,"e":45643,"s":45638,"text":"vt_m"},{"code":null,"e":45650,"s":45643,"text":"Arrays"},{"code":null,"e":45657,"s":45650,"text":"Arrays"},{"code":null,"e":45755,"s":45657,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":45764,"s":45755,"text":"Comments"},{"code":null,"e":45777,"s":45764,"text":"Old Comments"},{"code":null,"e":45825,"s":45777,"text":"Stack Data Structure (Introduction and Program)"},{"code":null,"e":45869,"s":45825,"text":"Top 50 Array Coding Problems for Interviews"},{"code":null,"e":45892,"s":45869,"text":"Introduction to Arrays"},{"code":null,"e":45924,"s":45892,"text":"Multidimensional Arrays in Java"},{"code":null,"e":45938,"s":45924,"text":"Linear Search"},{"code":null,"e":45959,"s":45938,"text":"Linked List vs Array"},{"code":null,"e":46004,"s":45959,"text":"Python | Using 2D arrays/lists the right way"},{"code":null,"e":46089,"s":46004,"text":"Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"},{"code":null,"e":46157,"s":46089,"text":"Maximum and minimum of an array using minimum number of comparisons"}],"string":"[\n {\n \"code\": null,\n \"e\": 24469,\n \"s\": 24441,\n \"text\": \"\\n28 May, 2018\"\n },\n {\n \"code\": null,\n \"e\": 24690,\n \"s\": 24469,\n \"text\": \"Given a set S consisting of n numbers, find the sum of difference between last and first element of each subset. We find first and last element of every subset by keeping them in same order as they appear in input set S.\"\n },\n {\n \"code\": null,\n \"e\": 24775,\n \"s\": 24690,\n \"text\": \"i.e., sumSetDiff(S) = ∑ (last(s) – first(s)),where sum goes over all subsets s of S.\"\n },\n {\n \"code\": null,\n \"e\": 24849,\n \"s\": 24775,\n \"text\": \"Note: Elements in the subset should be in the same order as in the set S.\"\n },\n {\n \"code\": null,\n \"e\": 24859,\n \"s\": 24849,\n \"text\": \"Examples:\"\n },\n {\n \"code\": null,\n \"e\": 25387,\n \"s\": 24859,\n \"text\": \"S = {5, 2, 9, 6}, n = 4\\n\\nSubsets are:\\n{5}, last(s)-first(s) = 0.\\n{2}, last(s)-first(s) = 0.\\n{9}, last(s)-first(s) = 0.\\n{6}, last(s)-first(s) = 0.\\n{5,2}, last(s)-first(s) = -3.\\n{5,9}, last(s)-first(s) = 4.\\n{5,6}, last(s)-first(s) = 1.\\n{2,9}, last(s)-first(s) = 7.\\n{2,6}, last(s)-first(s) = 4.\\n{9,6}, last(s)-first(s) = -3.\\n{5,2,9}, last(s)-first(s) = 4.\\n{5,2,6}, last(s)-first(s) = 1.\\n{5,9,6}, last(s)-first(s) = 1.\\n{2,9,6}, last(s)-first(s) = 4.\\n{5,2,9,6}, last(s)-first(s) = 1.\\n\\nOutput = -3+4+1+7+4-3+4+1+1+4+1\\n = 21.\\n\"\n },\n {\n \"code\": null,\n \"e\": 25598,\n \"s\": 25387,\n \"text\": \"A simple solution for this problem is to find the difference between the last and first element for each subset s of set S and output the sum of ll these differences. Time complexity for this approach is O(2n).\"\n },\n {\n \"code\": null,\n \"e\": 26112,\n \"s\": 25598,\n \"text\": \"An efficient solution to solve the problem in linear time complexity.We are given a set S consisting of n numbers, and we need to compute the sum of difference between last and first element of each subset of S, i.e.,sumSetDiff(S) = ∑ (last(s) – first(s)), where sum goes over all subsets s of S.Equivalently,sumSetDiff(S) = ∑ (last(s)) – ∑ (first(s)),In other words, we can compute the sum of last element of each subset, and the sum of first element of each subset separately, and then compute their difference.\"\n },\n {\n \"code\": null,\n \"e\": 26204,\n \"s\": 26112,\n \"text\": \"Let us say that the elements of S are {a1, a2, a3,..., an}. Note the following observation:\"\n },\n {\n \"code\": null,\n \"e\": 32868,\n \"s\": 26204,\n \"text\": \"Subsets containing element a1 as the first element can be obtained by taking any subset of {a2, a3,..., an} and then including a1 into it. Number of such subsets will be 2n-1.Subsets containing element a2 as the first element can be obtained by taking any subset of {a3, a4,..., an} and then including a2 into it. Number of such subsets will be 2n-2.Subsets containing element ai as the first element can be obtained by taking any subset of {ai, a(i+1),..., an} and then including ai into it. Number of such subsets will be 2n-i.Therefore, the sum of first element of all subsets will be:SumF = a1.2n-1 + a2.2n-2 +...+ an.1In a similar way we can compute the sum of last element of all subsets of S (Taking at every step ai as last element instead of first element and then obtaining all the subsets).SumL = a1.1 + a2.2 +...+ an.2n-1Finally, the answer of our problem will be SumL – SumF.Implementation:C++JavaPython3C#PHPC++// A C++ program to find sum of difference between// last and first element of each subset#include // Returns the sum of first elements of all subsetsint SumF(int S[], int n){ int sum = 0; // Compute the SumF as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, n-i-1)); return sum;} // Returns the sum of last elements of all subsetsint SumL(int S[], int n){ int sum = 0; // Compute the SumL as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, i)); return sum;} // Returns the difference between sum of last elements of// each subset and the sum of first elements of each subsetint sumSetDiff(int S[], int n){ return SumL(S, n) - SumF(S, n);} // Driver program to test above functionint main(){ int n = 4; int S[] = {5, 2, 9, 6}; printf(\\\"%d\\\\n\\\", sumSetDiff(S, n)); return 0;}Java// A Java program to find sum of difference // between last and first element of each // subsetclass GFG { // Returns the sum of first elements // of all subsets static int SumF(int S[], int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int S[], int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int S[], int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void main(String arg[]) { int n = 4; int S[] = { 5, 2, 9, 6 }; System.out.println(sumSetDiff(S, n)); }} // This code is contributed by Anant Agarwal.Python3# Python3 program to find sum of# difference between last and # first element of each subset # Returns the sum of first# elements of all subsetsdef SumF(S, n): sum = 0 # Compute the SumF as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, n - i - 1)) return sum # Returns the sum of last# elements of all subsetsdef SumL(S, n): sum = 0 # Compute the SumL as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, i)) return sum # Returns the difference between sum# of last elements of each subset and# the sum of first elements of each subsetdef sumSetDiff(S, n): return SumL(S, n) - SumF(S, n) # Driver programn = 4S = [5, 2, 9, 6]print(sumSetDiff(S, n)) # This code is contributed by Anant Agarwal.C#// A C# program to find sum of difference // between last and first element of each // subsetusing System;class GFG { // Returns the sum of first elements // of all subsets static int SumF(int []S, int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int []S, int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int []S, int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void Main() { int n = 4; int []S = { 5, 2, 9, 6 }; Console.Write(sumSetDiff(S, n)); }} // This code is contributed by nitin mittal.PHPOutput:21\\nTime Complexity : O(n)This article is contributed by Akash Aggarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\\narrow_drop_upSave\"\n },\n {\n \"code\": null,\n \"e\": 33044,\n \"s\": 32868,\n \"text\": \"Subsets containing element a1 as the first element can be obtained by taking any subset of {a2, a3,..., an} and then including a1 into it. Number of such subsets will be 2n-1.\"\n },\n {\n \"code\": null,\n \"e\": 33220,\n \"s\": 33044,\n \"text\": \"Subsets containing element a2 as the first element can be obtained by taking any subset of {a3, a4,..., an} and then including a2 into it. Number of such subsets will be 2n-2.\"\n },\n {\n \"code\": null,\n \"e\": 39534,\n \"s\": 33220,\n \"text\": \"Subsets containing element ai as the first element can be obtained by taking any subset of {ai, a(i+1),..., an} and then including ai into it. Number of such subsets will be 2n-i.Therefore, the sum of first element of all subsets will be:SumF = a1.2n-1 + a2.2n-2 +...+ an.1In a similar way we can compute the sum of last element of all subsets of S (Taking at every step ai as last element instead of first element and then obtaining all the subsets).SumL = a1.1 + a2.2 +...+ an.2n-1Finally, the answer of our problem will be SumL – SumF.Implementation:C++JavaPython3C#PHPC++// A C++ program to find sum of difference between// last and first element of each subset#include // Returns the sum of first elements of all subsetsint SumF(int S[], int n){ int sum = 0; // Compute the SumF as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, n-i-1)); return sum;} // Returns the sum of last elements of all subsetsint SumL(int S[], int n){ int sum = 0; // Compute the SumL as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, i)); return sum;} // Returns the difference between sum of last elements of// each subset and the sum of first elements of each subsetint sumSetDiff(int S[], int n){ return SumL(S, n) - SumF(S, n);} // Driver program to test above functionint main(){ int n = 4; int S[] = {5, 2, 9, 6}; printf(\\\"%d\\\\n\\\", sumSetDiff(S, n)); return 0;}Java// A Java program to find sum of difference // between last and first element of each // subsetclass GFG { // Returns the sum of first elements // of all subsets static int SumF(int S[], int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int S[], int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int S[], int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void main(String arg[]) { int n = 4; int S[] = { 5, 2, 9, 6 }; System.out.println(sumSetDiff(S, n)); }} // This code is contributed by Anant Agarwal.Python3# Python3 program to find sum of# difference between last and # first element of each subset # Returns the sum of first# elements of all subsetsdef SumF(S, n): sum = 0 # Compute the SumF as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, n - i - 1)) return sum # Returns the sum of last# elements of all subsetsdef SumL(S, n): sum = 0 # Compute the SumL as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, i)) return sum # Returns the difference between sum# of last elements of each subset and# the sum of first elements of each subsetdef sumSetDiff(S, n): return SumL(S, n) - SumF(S, n) # Driver programn = 4S = [5, 2, 9, 6]print(sumSetDiff(S, n)) # This code is contributed by Anant Agarwal.C#// A C# program to find sum of difference // between last and first element of each // subsetusing System;class GFG { // Returns the sum of first elements // of all subsets static int SumF(int []S, int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int []S, int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int []S, int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void Main() { int n = 4; int []S = { 5, 2, 9, 6 }; Console.Write(sumSetDiff(S, n)); }} // This code is contributed by nitin mittal.PHPOutput:21\\nTime Complexity : O(n)This article is contributed by Akash Aggarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\\narrow_drop_upSave\"\n },\n {\n \"code\": null,\n \"e\": 39629,\n \"s\": 39534,\n \"text\": \"Therefore, the sum of first element of all subsets will be:SumF = a1.2n-1 + a2.2n-2 +...+ an.1\"\n },\n {\n \"code\": null,\n \"e\": 39840,\n \"s\": 39629,\n \"text\": \"In a similar way we can compute the sum of last element of all subsets of S (Taking at every step ai as last element instead of first element and then obtaining all the subsets).SumL = a1.1 + a2.2 +...+ an.2n-1\"\n },\n {\n \"code\": null,\n \"e\": 39896,\n \"s\": 39840,\n \"text\": \"Finally, the answer of our problem will be SumL – SumF.\"\n },\n {\n \"code\": null,\n \"e\": 39912,\n \"s\": 39896,\n \"text\": \"Implementation:\"\n },\n {\n \"code\": null,\n \"e\": 39916,\n \"s\": 39912,\n \"text\": \"C++\"\n },\n {\n \"code\": null,\n \"e\": 39921,\n \"s\": 39916,\n \"text\": \"Java\"\n },\n {\n \"code\": null,\n \"e\": 39929,\n \"s\": 39921,\n \"text\": \"Python3\"\n },\n {\n \"code\": null,\n \"e\": 39932,\n \"s\": 39929,\n \"text\": \"C#\"\n },\n {\n \"code\": null,\n \"e\": 39936,\n \"s\": 39932,\n \"text\": \"PHP\"\n },\n {\n \"code\": \"// A C++ program to find sum of difference between// last and first element of each subset#include // Returns the sum of first elements of all subsetsint SumF(int S[], int n){ int sum = 0; // Compute the SumF as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, n-i-1)); return sum;} // Returns the sum of last elements of all subsetsint SumL(int S[], int n){ int sum = 0; // Compute the SumL as given in the above explanation for (int i = 0; i < n; i++) sum = sum + (S[i] * pow(2, i)); return sum;} // Returns the difference between sum of last elements of// each subset and the sum of first elements of each subsetint sumSetDiff(int S[], int n){ return SumL(S, n) - SumF(S, n);} // Driver program to test above functionint main(){ int n = 4; int S[] = {5, 2, 9, 6}; printf(\\\"%d\\\\n\\\", sumSetDiff(S, n)); return 0;}\",\n \"e\": 40861,\n \"s\": 39936,\n \"text\": null\n },\n {\n \"code\": \"// A Java program to find sum of difference // between last and first element of each // subsetclass GFG { // Returns the sum of first elements // of all subsets static int SumF(int S[], int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int S[], int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int S[], int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void main(String arg[]) { int n = 4; int S[] = { 5, 2, 9, 6 }; System.out.println(sumSetDiff(S, n)); }} // This code is contributed by Anant Agarwal.\",\n \"e\": 42125,\n \"s\": 40861,\n \"text\": null\n },\n {\n \"code\": \"# Python3 program to find sum of# difference between last and # first element of each subset # Returns the sum of first# elements of all subsetsdef SumF(S, n): sum = 0 # Compute the SumF as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, n - i - 1)) return sum # Returns the sum of last# elements of all subsetsdef SumL(S, n): sum = 0 # Compute the SumL as given # in the above explanation for i in range(n): sum = sum + (S[i] * pow(2, i)) return sum # Returns the difference between sum# of last elements of each subset and# the sum of first elements of each subsetdef sumSetDiff(S, n): return SumL(S, n) - SumF(S, n) # Driver programn = 4S = [5, 2, 9, 6]print(sumSetDiff(S, n)) # This code is contributed by Anant Agarwal.\",\n \"e\": 42945,\n \"s\": 42125,\n \"text\": null\n },\n {\n \"code\": \"// A C# program to find sum of difference // between last and first element of each // subsetusing System;class GFG { // Returns the sum of first elements // of all subsets static int SumF(int []S, int n) { int sum = 0; // Compute the SumF as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, n - i - 1)); return sum; } // Returns the sum of last elements // of all subsets static int SumL(int []S, int n) { int sum = 0; // Compute the SumL as given in // the above explanation for (int i = 0; i < n; i++) sum = sum + (int)(S[i] * Math.Pow(2, i)); return sum; } // Returns the difference between sum // of last elements of each subset and // the sum of first elements of each // subset static int sumSetDiff(int []S, int n) { return SumL(S, n) - SumF(S, n); } // Driver program public static void Main() { int n = 4; int []S = { 5, 2, 9, 6 }; Console.Write(sumSetDiff(S, n)); }} // This code is contributed by nitin mittal.\",\n \"e\": 44211,\n \"s\": 42945,\n \"text\": null\n },\n {\n \"code\": \"\",\n \"e\": 45175,\n \"s\": 44211,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 45179,\n \"s\": 45175,\n \"text\": \"21\\n\"\n },\n {\n \"code\": null,\n \"e\": 45202,\n \"s\": 45179,\n \"text\": \"Time Complexity : O(n)\"\n },\n {\n \"code\": null,\n \"e\": 45500,\n \"s\": 45202,\n \"text\": \"This article is contributed by Akash Aggarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.\"\n },\n {\n \"code\": null,\n \"e\": 45625,\n \"s\": 45500,\n \"text\": \"Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.\"\n },\n {\n \"code\": null,\n \"e\": 45638,\n \"s\": 45625,\n \"text\": \"nitin mittal\"\n },\n {\n \"code\": null,\n \"e\": 45643,\n \"s\": 45638,\n \"text\": \"vt_m\"\n },\n {\n \"code\": null,\n \"e\": 45650,\n \"s\": 45643,\n \"text\": \"Arrays\"\n },\n {\n \"code\": null,\n \"e\": 45657,\n \"s\": 45650,\n \"text\": \"Arrays\"\n },\n {\n \"code\": null,\n \"e\": 45755,\n \"s\": 45657,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 45764,\n \"s\": 45755,\n \"text\": \"Comments\"\n },\n {\n \"code\": null,\n \"e\": 45777,\n \"s\": 45764,\n \"text\": \"Old Comments\"\n },\n {\n \"code\": null,\n \"e\": 45825,\n \"s\": 45777,\n \"text\": \"Stack Data Structure (Introduction and Program)\"\n },\n {\n \"code\": null,\n \"e\": 45869,\n \"s\": 45825,\n \"text\": \"Top 50 Array Coding Problems for Interviews\"\n },\n {\n \"code\": null,\n \"e\": 45892,\n \"s\": 45869,\n \"text\": \"Introduction to Arrays\"\n },\n {\n \"code\": null,\n \"e\": 45924,\n \"s\": 45892,\n \"text\": \"Multidimensional Arrays in Java\"\n },\n {\n \"code\": null,\n \"e\": 45938,\n \"s\": 45924,\n \"text\": \"Linear Search\"\n },\n {\n \"code\": null,\n \"e\": 45959,\n \"s\": 45938,\n \"text\": \"Linked List vs Array\"\n },\n {\n \"code\": null,\n \"e\": 46004,\n \"s\": 45959,\n \"text\": \"Python | Using 2D arrays/lists the right way\"\n },\n {\n \"code\": null,\n \"e\": 46089,\n \"s\": 46004,\n \"text\": \"Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)\"\n },\n {\n \"code\": null,\n \"e\": 46157,\n \"s\": 46089,\n \"text\": \"Maximum and minimum of an array using minimum number of comparisons\"\n }\n]"}}},{"rowIdx":109,"cells":{"title":{"kind":"string","value":"How to create responsive image gallery using HTML, CSS, jQuery and Bootstrap? - GeeksforGeeks"},"text":{"kind":"string","value":"22 Dec, 2021\nWith the advent of new frameworks in web technologies, it has become quite easy to design and implement feature-rich and responsive web pages. Here, we are going to design a responsive image gallery using HTML, CSS, jQuery and Bootstrap.\nFeatures or Functionalities to implement:\nResponsive images\nResponsive Grid System\nImage viewer\nPrerequisites: Basic knowledge of HTML, CSS, JavaScript, jQuery, and Bootstrap. Also, the user should be aware of how the grid system in Bootstrap works.\nWe will divide the complete solution into three different sections in the first section we will create the structure for the gallery. In the second section, we will design the gallery by using CSS. And in the last section will make it available to respond to the user’s interactions.\nCreating structure: Initialize HTML layout and responsive images, but we will attach the images by jQuery, in an array format.\nHTML Code:

GeeksforGeeks

Responsive image gallery


Designing structure: We’ll be adding CSS properties as per the requirement in the project.CSS Code:Bootstrap code: We will use a bootstrap modal as image viewer and modify it according to our requirements accordingly. We will render all unnecessary components of modal transparent. Remember, we are appending the image in the modal, so we need to use on() method to attach functionalities for such selectors.Respond section: In this section we will attach all the images for the responsive gallery, make them responsive to the user. Below is the grid arrangement we’ll be using for displaying images in the image gallery. Since classes used col-sm-6 col-md-2. The logic is 2-grids for medium screen break-point and 6-grids for large breakpoints. They also divide further whenever content overlaps thereby presenting as a single grid.jQuery code: Below is the script for appending in this manner. We’ll be supposing that we are getting the images from the server (as an array of image URLs in JavaScript). Now we will append the image accordingly in the content panel of our page. Below is the implementation for the sameFinal Solution: This is the combination of the above three-section, this is the complete responsive image gallery code.Code:

GeeksforGeeks

Responsive image gallery


Output:Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes\narrow_drop_upSave\n

GeeksforGeeks

Responsive image gallery


\nDesigning structure: We’ll be adding CSS properties as per the requirement in the project.\nCSS Code:\n\nBootstrap code: We will use a bootstrap modal as image viewer and modify it according to our requirements accordingly. We will render all unnecessary components of modal transparent. Remember, we are appending the image in the modal, so we need to use on() method to attach functionalities for such selectors.\n\nRespond section: In this section we will attach all the images for the responsive gallery, make them responsive to the user. Below is the grid arrangement we’ll be using for displaying images in the image gallery. Since classes used col-sm-6 col-md-2. The logic is 2-grids for medium screen break-point and 6-grids for large breakpoints. They also divide further whenever content overlaps thereby presenting as a single grid.\njQuery code: Below is the script for appending in this manner. We’ll be supposing that we are getting the images from the server (as an array of image URLs in JavaScript). Now we will append the image accordingly in the content panel of our page. Below is the implementation for the same\n\nFinal Solution: This is the combination of the above three-section, this is the complete responsive image gallery code.\nCode:

GeeksforGeeks

Responsive image gallery


\n

GeeksforGeeks

Responsive image gallery


\nOutput:\nAttention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.\narorakashish0911\nCSS-Misc\nHTML-Misc\nJavaScript-Misc\nTechnical Scripter 2019\nBootstrap\nCSS\nHTML\nJQuery\nWeb Technologies\nWeb technologies Questions\nHTML\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nHow to pass data into a bootstrap modal?\nHow to Show Images on Click using HTML ?\nHow to set Bootstrap Timepicker using datetimepicker library ?\nHow to change the background color of the active nav-item?\nHow to Use Bootstrap with React?\nTop 10 Projects For Beginners To Practice HTML and CSS Skills\nHow to insert spaces/tabs in text using HTML/CSS?\nHow to create footer to stay at the bottom of a Web page?\nHow to update Node.js and NPM to next version ?\nCSS to put icon inside an input element in a form"},"parsed":{"kind":"list like","value":[{"code":null,"e":24461,"s":24433,"text":"\n22 Dec, 2021"},{"code":null,"e":24699,"s":24461,"text":"With the advent of new frameworks in web technologies, it has become quite easy to design and implement feature-rich and responsive web pages. Here, we are going to design a responsive image gallery using HTML, CSS, jQuery and Bootstrap."},{"code":null,"e":24741,"s":24699,"text":"Features or Functionalities to implement:"},{"code":null,"e":24759,"s":24741,"text":"Responsive images"},{"code":null,"e":24782,"s":24759,"text":"Responsive Grid System"},{"code":null,"e":24795,"s":24782,"text":"Image viewer"},{"code":null,"e":24949,"s":24795,"text":"Prerequisites: Basic knowledge of HTML, CSS, JavaScript, jQuery, and Bootstrap. Also, the user should be aware of how the grid system in Bootstrap works."},{"code":null,"e":25233,"s":24949,"text":"We will divide the complete solution into three different sections in the first section we will create the structure for the gallery. In the second section, we will design the gallery by using CSS. And in the last section will make it available to respond to the user’s interactions."},{"code":null,"e":25360,"s":25233,"text":"Creating structure: Initialize HTML layout and responsive images, but we will attach the images by jQuery, in an array format."},{"code":null,"e":34342,"s":25360,"text":"HTML Code:

GeeksforGeeks

Responsive image gallery


Designing structure: We’ll be adding CSS properties as per the requirement in the project.CSS Code:Bootstrap code: We will use a bootstrap modal as image viewer and modify it according to our requirements accordingly. We will render all unnecessary components of modal transparent. Remember, we are appending the image in the modal, so we need to use on() method to attach functionalities for such selectors.Respond section: In this section we will attach all the images for the responsive gallery, make them responsive to the user. Below is the grid arrangement we’ll be using for displaying images in the image gallery. Since classes used col-sm-6 col-md-2. The logic is 2-grids for medium screen break-point and 6-grids for large breakpoints. They also divide further whenever content overlaps thereby presenting as a single grid.jQuery code: Below is the script for appending in this manner. We’ll be supposing that we are getting the images from the server (as an array of image URLs in JavaScript). Now we will append the image accordingly in the content panel of our page. Below is the implementation for the sameFinal Solution: This is the combination of the above three-section, this is the complete responsive image gallery code.Code:

GeeksforGeeks

Responsive image gallery


Output:Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes\narrow_drop_upSave"},{"code":"

GeeksforGeeks

Responsive image gallery


","e":35736,"s":34342,"text":null},{"code":null,"e":35827,"s":35736,"text":"Designing structure: We’ll be adding CSS properties as per the requirement in the project."},{"code":null,"e":36060,"s":35827,"text":"CSS Code:"},{"code":"","e":36284,"s":36060,"text":null},{"code":null,"e":37314,"s":36284,"text":"Bootstrap code: We will use a bootstrap modal as image viewer and modify it according to our requirements accordingly. We will render all unnecessary components of modal transparent. Remember, we are appending the image in the modal, so we need to use on() method to attach functionalities for such selectors."},{"code":"","e":38035,"s":37314,"text":null},{"code":null,"e":38461,"s":38035,"text":"Respond section: In this section we will attach all the images for the responsive gallery, make them responsive to the user. Below is the grid arrangement we’ll be using for displaying images in the image gallery. Since classes used col-sm-6 col-md-2. The logic is 2-grids for medium screen break-point and 6-grids for large breakpoints. They also divide further whenever content overlaps thereby presenting as a single grid."},{"code":null,"e":40192,"s":38461,"text":"jQuery code: Below is the script for appending in this manner. We’ll be supposing that we are getting the images from the server (as an array of image URLs in JavaScript). Now we will append the image accordingly in the content panel of our page. Below is the implementation for the same"},{"code":"","e":41636,"s":40192,"text":null},{"code":null,"e":41756,"s":41636,"text":"Final Solution: This is the combination of the above three-section, this is the complete responsive image gallery code."},{"code":null,"e":45532,"s":41756,"text":"Code:

GeeksforGeeks

Responsive image gallery


"},{"code":"

GeeksforGeeks

Responsive image gallery


","e":49303,"s":45532,"text":null},{"code":null,"e":49311,"s":49303,"text":"Output:"},{"code":null,"e":49448,"s":49311,"text":"Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."},{"code":null,"e":49465,"s":49448,"text":"arorakashish0911"},{"code":null,"e":49474,"s":49465,"text":"CSS-Misc"},{"code":null,"e":49484,"s":49474,"text":"HTML-Misc"},{"code":null,"e":49500,"s":49484,"text":"JavaScript-Misc"},{"code":null,"e":49524,"s":49500,"text":"Technical Scripter 2019"},{"code":null,"e":49534,"s":49524,"text":"Bootstrap"},{"code":null,"e":49538,"s":49534,"text":"CSS"},{"code":null,"e":49543,"s":49538,"text":"HTML"},{"code":null,"e":49550,"s":49543,"text":"JQuery"},{"code":null,"e":49567,"s":49550,"text":"Web Technologies"},{"code":null,"e":49594,"s":49567,"text":"Web technologies Questions"},{"code":null,"e":49599,"s":49594,"text":"HTML"},{"code":null,"e":49697,"s":49599,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":49738,"s":49697,"text":"How to pass data into a bootstrap modal?"},{"code":null,"e":49779,"s":49738,"text":"How to Show Images on Click using HTML ?"},{"code":null,"e":49842,"s":49779,"text":"How to set Bootstrap Timepicker using datetimepicker library ?"},{"code":null,"e":49901,"s":49842,"text":"How to change the background color of the active nav-item?"},{"code":null,"e":49934,"s":49901,"text":"How to Use Bootstrap with React?"},{"code":null,"e":49996,"s":49934,"text":"Top 10 Projects For Beginners To Practice HTML and CSS Skills"},{"code":null,"e":50046,"s":49996,"text":"How to insert spaces/tabs in text using HTML/CSS?"},{"code":null,"e":50104,"s":50046,"text":"How to create footer to stay at the bottom of a Web page?"},{"code":null,"e":50152,"s":50104,"text":"How to update Node.js and NPM to next version ?"}],"string":"[\n {\n \"code\": null,\n \"e\": 24461,\n \"s\": 24433,\n \"text\": \"\\n22 Dec, 2021\"\n },\n {\n \"code\": null,\n \"e\": 24699,\n \"s\": 24461,\n \"text\": \"With the advent of new frameworks in web technologies, it has become quite easy to design and implement feature-rich and responsive web pages. Here, we are going to design a responsive image gallery using HTML, CSS, jQuery and Bootstrap.\"\n },\n {\n \"code\": null,\n \"e\": 24741,\n \"s\": 24699,\n \"text\": \"Features or Functionalities to implement:\"\n },\n {\n \"code\": null,\n \"e\": 24759,\n \"s\": 24741,\n \"text\": \"Responsive images\"\n },\n {\n \"code\": null,\n \"e\": 24782,\n \"s\": 24759,\n \"text\": \"Responsive Grid System\"\n },\n {\n \"code\": null,\n \"e\": 24795,\n \"s\": 24782,\n \"text\": \"Image viewer\"\n },\n {\n \"code\": null,\n \"e\": 24949,\n \"s\": 24795,\n \"text\": \"Prerequisites: Basic knowledge of HTML, CSS, JavaScript, jQuery, and Bootstrap. Also, the user should be aware of how the grid system in Bootstrap works.\"\n },\n {\n \"code\": null,\n \"e\": 25233,\n \"s\": 24949,\n \"text\": \"We will divide the complete solution into three different sections in the first section we will create the structure for the gallery. In the second section, we will design the gallery by using CSS. And in the last section will make it available to respond to the user’s interactions.\"\n },\n {\n \"code\": null,\n \"e\": 25360,\n \"s\": 25233,\n \"text\": \"Creating structure: Initialize HTML layout and responsive images, but we will attach the images by jQuery, in an array format.\"\n },\n {\n \"code\": null,\n \"e\": 34342,\n \"s\": 25360,\n \"text\": \"HTML Code:

GeeksforGeeks

Responsive image gallery


Designing structure: We’ll be adding CSS properties as per the requirement in the project.CSS Code:Bootstrap code: We will use a bootstrap modal as image viewer and modify it according to our requirements accordingly. We will render all unnecessary components of modal transparent. Remember, we are appending the image in the modal, so we need to use on() method to attach functionalities for such selectors.Respond section: In this section we will attach all the images for the responsive gallery, make them responsive to the user. Below is the grid arrangement we’ll be using for displaying images in the image gallery. Since classes used col-sm-6 col-md-2. The logic is 2-grids for medium screen break-point and 6-grids for large breakpoints. They also divide further whenever content overlaps thereby presenting as a single grid.jQuery code: Below is the script for appending in this manner. We’ll be supposing that we are getting the images from the server (as an array of image URLs in JavaScript). Now we will append the image accordingly in the content panel of our page. Below is the implementation for the sameFinal Solution: This is the combination of the above three-section, this is the complete responsive image gallery code.Code:

GeeksforGeeks

Responsive image gallery


Output:Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes\\narrow_drop_upSave\"\n },\n {\n \"code\": \"

GeeksforGeeks

Responsive image gallery


\",\n \"e\": 35736,\n \"s\": 34342,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 35827,\n \"s\": 35736,\n \"text\": \"Designing structure: We’ll be adding CSS properties as per the requirement in the project.\"\n },\n {\n \"code\": null,\n \"e\": 36060,\n \"s\": 35827,\n \"text\": \"CSS Code:\"\n },\n {\n \"code\": \"\",\n \"e\": 36284,\n \"s\": 36060,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 37314,\n \"s\": 36284,\n \"text\": \"Bootstrap code: We will use a bootstrap modal as image viewer and modify it according to our requirements accordingly. We will render all unnecessary components of modal transparent. Remember, we are appending the image in the modal, so we need to use on() method to attach functionalities for such selectors.\"\n },\n {\n \"code\": \"\",\n \"e\": 38035,\n \"s\": 37314,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 38461,\n \"s\": 38035,\n \"text\": \"Respond section: In this section we will attach all the images for the responsive gallery, make them responsive to the user. Below is the grid arrangement we’ll be using for displaying images in the image gallery. Since classes used col-sm-6 col-md-2. The logic is 2-grids for medium screen break-point and 6-grids for large breakpoints. They also divide further whenever content overlaps thereby presenting as a single grid.\"\n },\n {\n \"code\": null,\n \"e\": 40192,\n \"s\": 38461,\n \"text\": \"jQuery code: Below is the script for appending in this manner. We’ll be supposing that we are getting the images from the server (as an array of image URLs in JavaScript). Now we will append the image accordingly in the content panel of our page. Below is the implementation for the same\"\n },\n {\n \"code\": \"\",\n \"e\": 41636,\n \"s\": 40192,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 41756,\n \"s\": 41636,\n \"text\": \"Final Solution: This is the combination of the above three-section, this is the complete responsive image gallery code.\"\n },\n {\n \"code\": null,\n \"e\": 45532,\n \"s\": 41756,\n \"text\": \"Code:

GeeksforGeeks

Responsive image gallery


\"\n },\n {\n \"code\": \"

GeeksforGeeks

Responsive image gallery


\",\n \"e\": 49303,\n \"s\": 45532,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 49311,\n \"s\": 49303,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 49448,\n \"s\": 49311,\n \"text\": \"Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.\"\n },\n {\n \"code\": null,\n \"e\": 49465,\n \"s\": 49448,\n \"text\": \"arorakashish0911\"\n },\n {\n \"code\": null,\n \"e\": 49474,\n \"s\": 49465,\n \"text\": \"CSS-Misc\"\n },\n {\n \"code\": null,\n \"e\": 49484,\n \"s\": 49474,\n \"text\": \"HTML-Misc\"\n },\n {\n \"code\": null,\n \"e\": 49500,\n \"s\": 49484,\n \"text\": \"JavaScript-Misc\"\n },\n {\n \"code\": null,\n \"e\": 49524,\n \"s\": 49500,\n \"text\": \"Technical Scripter 2019\"\n },\n {\n \"code\": null,\n \"e\": 49534,\n \"s\": 49524,\n \"text\": \"Bootstrap\"\n },\n {\n \"code\": null,\n \"e\": 49538,\n \"s\": 49534,\n \"text\": \"CSS\"\n },\n {\n \"code\": null,\n \"e\": 49543,\n \"s\": 49538,\n \"text\": \"HTML\"\n },\n {\n \"code\": null,\n \"e\": 49550,\n \"s\": 49543,\n \"text\": \"JQuery\"\n },\n {\n \"code\": null,\n \"e\": 49567,\n \"s\": 49550,\n \"text\": \"Web Technologies\"\n },\n {\n \"code\": null,\n \"e\": 49594,\n \"s\": 49567,\n \"text\": \"Web technologies Questions\"\n },\n {\n \"code\": null,\n \"e\": 49599,\n \"s\": 49594,\n \"text\": \"HTML\"\n },\n {\n \"code\": null,\n \"e\": 49697,\n \"s\": 49599,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 49738,\n \"s\": 49697,\n \"text\": \"How to pass data into a bootstrap modal?\"\n },\n {\n \"code\": null,\n \"e\": 49779,\n \"s\": 49738,\n \"text\": \"How to Show Images on Click using HTML ?\"\n },\n {\n \"code\": null,\n \"e\": 49842,\n \"s\": 49779,\n \"text\": \"How to set Bootstrap Timepicker using datetimepicker library ?\"\n },\n {\n \"code\": null,\n \"e\": 49901,\n \"s\": 49842,\n \"text\": \"How to change the background color of the active nav-item?\"\n },\n {\n \"code\": null,\n \"e\": 49934,\n \"s\": 49901,\n \"text\": \"How to Use Bootstrap with React?\"\n },\n {\n \"code\": null,\n \"e\": 49996,\n \"s\": 49934,\n \"text\": \"Top 10 Projects For Beginners To Practice HTML and CSS Skills\"\n },\n {\n \"code\": null,\n \"e\": 50046,\n \"s\": 49996,\n \"text\": \"How to insert spaces/tabs in text using HTML/CSS?\"\n },\n {\n \"code\": null,\n \"e\": 50104,\n \"s\": 50046,\n \"text\": \"How to create footer to stay at the bottom of a Web page?\"\n },\n {\n \"code\": null,\n \"e\": 50152,\n \"s\": 50104,\n \"text\": \"How to update Node.js and NPM to next version ?\"\n }\n]"}}},{"rowIdx":110,"cells":{"title":{"kind":"string","value":"Java String trim() Method"},"text":{"kind":"string","value":"❮ String Methods\n\nRemove whitespace from both sides of a string:\nString myStr = \" Hello World! \";\nSystem.out.println(myStr);\nSystem.out.println(myStr.trim());\n\nTry it Yourself »\n\nThe trim() method removes whitespace from both ends of a string.\nNote: This method does not change the original string.\npublic String trim()\n\nNone.\nWe just launchedW3Schools videos\nGet certifiedby completinga course today!\nIf you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:\nhelp@w3schools.com\nYour message has been sent to W3Schools."},"parsed":{"kind":"list like","value":[{"code":null,"e":19,"s":0,"text":"\n❮ String Methods\n"},{"code":null,"e":66,"s":19,"text":"Remove whitespace from both sides of a string:"},{"code":null,"e":172,"s":66,"text":"String myStr = \" Hello World! \";\nSystem.out.println(myStr);\nSystem.out.println(myStr.trim());"},{"code":null,"e":192,"s":172,"text":"\nTry it Yourself »\n"},{"code":null,"e":257,"s":192,"text":"The trim() method removes whitespace from both ends of a string."},{"code":null,"e":312,"s":257,"text":"Note: This method does not change the original string."},{"code":null,"e":334,"s":312,"text":"public String trim()\n"},{"code":null,"e":340,"s":334,"text":"None."},{"code":null,"e":373,"s":340,"text":"We just launchedW3Schools videos"},{"code":null,"e":415,"s":373,"text":"Get certifiedby completinga course today!"},{"code":null,"e":522,"s":415,"text":"If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"},{"code":null,"e":541,"s":522,"text":"help@w3schools.com"}],"string":"[\n {\n \"code\": null,\n \"e\": 19,\n \"s\": 0,\n \"text\": \"\\n❮ String Methods\\n\"\n },\n {\n \"code\": null,\n \"e\": 66,\n \"s\": 19,\n \"text\": \"Remove whitespace from both sides of a string:\"\n },\n {\n \"code\": null,\n \"e\": 172,\n \"s\": 66,\n \"text\": \"String myStr = \\\" Hello World! \\\";\\nSystem.out.println(myStr);\\nSystem.out.println(myStr.trim());\"\n },\n {\n \"code\": null,\n \"e\": 192,\n \"s\": 172,\n \"text\": \"\\nTry it Yourself »\\n\"\n },\n {\n \"code\": null,\n \"e\": 257,\n \"s\": 192,\n \"text\": \"The trim() method removes whitespace from both ends of a string.\"\n },\n {\n \"code\": null,\n \"e\": 312,\n \"s\": 257,\n \"text\": \"Note: This method does not change the original string.\"\n },\n {\n \"code\": null,\n \"e\": 334,\n \"s\": 312,\n \"text\": \"public String trim()\\n\"\n },\n {\n \"code\": null,\n \"e\": 340,\n \"s\": 334,\n \"text\": \"None.\"\n },\n {\n \"code\": null,\n \"e\": 373,\n \"s\": 340,\n \"text\": \"We just launchedW3Schools videos\"\n },\n {\n \"code\": null,\n \"e\": 415,\n \"s\": 373,\n \"text\": \"Get certifiedby completinga course today!\"\n },\n {\n \"code\": null,\n \"e\": 522,\n \"s\": 415,\n \"text\": \"If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:\"\n },\n {\n \"code\": null,\n \"e\": 541,\n \"s\": 522,\n \"text\": \"help@w3schools.com\"\n }\n]"}}},{"rowIdx":111,"cells":{"title":{"kind":"string","value":"Find m-th summation of first n natural numbers. - GeeksforGeeks"},"text":{"kind":"string","value":"22 Mar, 2021\nm-th summation of first n natural numbers is defined as following. \nIf m > 1\n SUM(n, m) = SUM(SUM(n, m - 1), 1)\nElse \n SUM(n, 1) = Sum of first n natural numbers.\nWe are given m and n, we need to find SUM(n, m).Examples: \nInput : n = 4, m = 1 \nOutput : SUM(4, 1) = 10\nExplanation : 1 + 2 + 3 + 4 = 10\n\nInput : n = 3, m = 2 \nOutput : SUM(3, 2) = 21\nExplanation : SUM(3, 2) \n = SUM(SUM(3, 1), 1) \n = SUM(6, 1) \n = 21\n \nNaive Approach : We can solve this problem using two nested loop, where outer loop iterate for m and inner loop iterate for n. After completion of a single outer iteration, we should update n as whole of inner loop got executed and value of n must be changed then. Time complexity should be O(n*m). \nfor (int i = 1;i <= m;i++)\n{\n sum = 0;\n for (int j = 1;j <= n;j++)\n sum += j;\n n = sum; // update n\n}\nEfficient Approach : We can use direct formula for sum of first n numbers to reduce time. We can also use recursion. In this approach m = 1 will be our base condition and for any intermediate step SUM(n, m), we will call SUM (SUM(n, m-1), 1) and for a single step SUM(n, 1) = n * (n + 1) / 2 will be used. This will reduce our time complexity to O(m). \nint SUM (int n, int m)\n{\n if (m == 1)\n return (n * (n + 1) / 2);\n int sum = SUM(n, m-1);\n return (sum * (sum + 1) / 2);\n}\nBelow is the implementation of above idea : \nC++\nJava\nC#\nPHP\nJavascript\n// CPP program to find m-th summation#include using namespace std; // Function to return mth summationint SUM(int n, int m){ // base case if (m == 1) return (n * (n + 1) / 2); int sum = SUM(n, m-1); return (sum * (sum + 1) / 2);} // driver programint main(){ int n = 5; int m = 3; cout << \"SUM(\" << n << \", \" << m << \"): \" << SUM(n, m); return 0;}\n// Java program to find m-th summation.class GFG { // Function to return mth summation static int SUM(int n, int m) { // base case if (m == 1) return (n * (n + 1) / 2); int sum = SUM(n, m - 1); return (sum * (sum + 1) / 2); } // Driver code public static void main(String[] args) { int n = 5; int m = 3; System.out.println(\"SUM(\" + n + \", \" + m + \"): \" + SUM(n, m)); }} // This code is contributed by Anant Agarwal.\nPython3 \n\n# Python3 program to find m-th summation \n\n# Function to return mth summation\ndef SUM(n, m):\n\n # base case\n if (m == 1):\n return (n * (n + 1) / 2)\n \n sum = SUM(n, m-1)\n return int(sum * (sum + 1) / 2)\n\n\n# driver program\nn = 5\nm = 3\nprint(\"SUM(\", n, \", \", m, \"):\", SUM(n, m))\n\n# This code is contributed by Smitha Dinesh Semwal\n\n// C# program to find m-th summation.using System; class GFG{ // Function to return mth summation static int SUM(int n, int m) { // base case if (m == 1) return (n * (n + 1) / 2); int sum = SUM(n, m - 1); return (sum * (sum + 1) / 2); } // Driver Code public static void Main() { int n = 5; int m = 3; Console.Write(\"SUM(\" + n + \", \" + m + \"): \" + SUM(n, m)); }} // This code is contributed by Nitin Mittal.\n\n\nOutput: \nSUM(5, 3): 7260\nThis article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. \nnitin mittal\nvt_m\nRajput-Ji\nMathematical\nRecursion\nMathematical\nRecursion\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nComments\nOld Comments\nFind all factors of a natural number | Set 1\nCheck if a number is Palindrome\nProgram to print prime numbers from 1 to N.\nProgram to add two binary strings\nProgram to multiply two matrices\nGiven an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)\nRecursion\nProgram for Tower of Hanoi\nProgram for Sum of the digits of a given number\nBacktracking | Introduction"},"parsed":{"kind":"list like","value":[{"code":null,"e":24327,"s":24299,"text":"\n22 Mar, 2021"},{"code":null,"e":24395,"s":24327,"text":"m-th summation of first n natural numbers is defined as following. "},{"code":null,"e":24492,"s":24395,"text":"If m > 1\n SUM(n, m) = SUM(SUM(n, m - 1), 1)\nElse \n SUM(n, 1) = Sum of first n natural numbers."},{"code":null,"e":24552,"s":24492,"text":"We are given m and n, we need to find SUM(n, m).Examples: "},{"code":null,"e":24783,"s":24552,"text":"Input : n = 4, m = 1 \nOutput : SUM(4, 1) = 10\nExplanation : 1 + 2 + 3 + 4 = 10\n\nInput : n = 3, m = 2 \nOutput : SUM(3, 2) = 21\nExplanation : SUM(3, 2) \n = SUM(SUM(3, 1), 1) \n = SUM(6, 1) \n = 21"},{"code":null,"e":25086,"s":24785,"text":"Naive Approach : We can solve this problem using two nested loop, where outer loop iterate for m and inner loop iterate for n. After completion of a single outer iteration, we should update n as whole of inner loop got executed and value of n must be changed then. Time complexity should be O(n*m). "},{"code":null,"e":25205,"s":25086,"text":"for (int i = 1;i <= m;i++)\n{\n sum = 0;\n for (int j = 1;j <= n;j++)\n sum += j;\n n = sum; // update n\n}"},{"code":null,"e":25559,"s":25205,"text":"Efficient Approach : We can use direct formula for sum of first n numbers to reduce time. We can also use recursion. In this approach m = 1 will be our base condition and for any intermediate step SUM(n, m), we will call SUM (SUM(n, m-1), 1) and for a single step SUM(n, 1) = n * (n + 1) / 2 will be used. This will reduce our time complexity to O(m). "},{"code":null,"e":25697,"s":25559,"text":"int SUM (int n, int m)\n{\n if (m == 1)\n return (n * (n + 1) / 2);\n int sum = SUM(n, m-1);\n return (sum * (sum + 1) / 2);\n}"},{"code":null,"e":25742,"s":25697,"text":"Below is the implementation of above idea : "},{"code":null,"e":25746,"s":25742,"text":"C++"},{"code":null,"e":25751,"s":25746,"text":"Java"},{"code":null,"e":25754,"s":25751,"text":"C#"},{"code":null,"e":25758,"s":25754,"text":"PHP"},{"code":null,"e":25769,"s":25758,"text":"Javascript"},{"code":"// CPP program to find m-th summation#include using namespace std; // Function to return mth summationint SUM(int n, int m){ // base case if (m == 1) return (n * (n + 1) / 2); int sum = SUM(n, m-1); return (sum * (sum + 1) / 2);} // driver programint main(){ int n = 5; int m = 3; cout << \"SUM(\" << n << \", \" << m << \"): \" << SUM(n, m); return 0;}","e":26182,"s":25769,"text":null},{"code":"// Java program to find m-th summation.class GFG { // Function to return mth summation static int SUM(int n, int m) { // base case if (m == 1) return (n * (n + 1) / 2); int sum = SUM(n, m - 1); return (sum * (sum + 1) / 2); } // Driver code public static void main(String[] args) { int n = 5; int m = 3; System.out.println(\"SUM(\" + n + \", \" + m + \"): \" + SUM(n, m)); }} // This code is contributed by Anant Agarwal.","e":26753,"s":26182,"text":null},{"code":null,"e":26762,"s":26753,"text":"Python3 "},{"code":null,"e":27117,"s":26762,"text":"\n# Python3 program to find m-th summation \n\n# Function to return mth summation\ndef SUM(n, m):\n\n # base case\n if (m == 1):\n return (n * (n + 1) / 2)\n \n sum = SUM(n, m-1)\n return int(sum * (sum + 1) / 2)\n\n\n# driver program\nn = 5\nm = 3\nprint(\"SUM(\", n, \", \", m, \"):\", SUM(n, m))\n\n# This code is contributed by Smitha Dinesh Semwal\n"},{"code":"// C# program to find m-th summation.using System; class GFG{ // Function to return mth summation static int SUM(int n, int m) { // base case if (m == 1) return (n * (n + 1) / 2); int sum = SUM(n, m - 1); return (sum * (sum + 1) / 2); } // Driver Code public static void Main() { int n = 5; int m = 3; Console.Write(\"SUM(\" + n + \", \" + m + \"): \" + SUM(n, m)); }} // This code is contributed by Nitin Mittal.","e":27682,"s":27117,"text":null},{"code":"","e":28071,"s":27682,"text":null},{"code":"","e":28481,"s":28071,"text":null},{"code":null,"e":28491,"s":28481,"text":"Output: "},{"code":null,"e":28507,"s":28491,"text":"SUM(5, 3): 7260"},{"code":null,"e":28947,"s":28507,"text":"This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "},{"code":null,"e":28960,"s":28947,"text":"nitin mittal"},{"code":null,"e":28965,"s":28960,"text":"vt_m"},{"code":null,"e":28975,"s":28965,"text":"Rajput-Ji"},{"code":null,"e":28988,"s":28975,"text":"Mathematical"},{"code":null,"e":28998,"s":28988,"text":"Recursion"},{"code":null,"e":29011,"s":28998,"text":"Mathematical"},{"code":null,"e":29021,"s":29011,"text":"Recursion"},{"code":null,"e":29119,"s":29021,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":29128,"s":29119,"text":"Comments"},{"code":null,"e":29141,"s":29128,"text":"Old Comments"},{"code":null,"e":29186,"s":29141,"text":"Find all factors of a natural number | Set 1"},{"code":null,"e":29218,"s":29186,"text":"Check if a number is Palindrome"},{"code":null,"e":29262,"s":29218,"text":"Program to print prime numbers from 1 to N."},{"code":null,"e":29296,"s":29262,"text":"Program to add two binary strings"},{"code":null,"e":29329,"s":29296,"text":"Program to multiply two matrices"},{"code":null,"e":29414,"s":29329,"text":"Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"},{"code":null,"e":29424,"s":29414,"text":"Recursion"},{"code":null,"e":29451,"s":29424,"text":"Program for Tower of Hanoi"},{"code":null,"e":29499,"s":29451,"text":"Program for Sum of the digits of a given number"}],"string":"[\n {\n \"code\": null,\n \"e\": 24327,\n \"s\": 24299,\n \"text\": \"\\n22 Mar, 2021\"\n },\n {\n \"code\": null,\n \"e\": 24395,\n \"s\": 24327,\n \"text\": \"m-th summation of first n natural numbers is defined as following. \"\n },\n {\n \"code\": null,\n \"e\": 24492,\n \"s\": 24395,\n \"text\": \"If m > 1\\n SUM(n, m) = SUM(SUM(n, m - 1), 1)\\nElse \\n SUM(n, 1) = Sum of first n natural numbers.\"\n },\n {\n \"code\": null,\n \"e\": 24552,\n \"s\": 24492,\n \"text\": \"We are given m and n, we need to find SUM(n, m).Examples: \"\n },\n {\n \"code\": null,\n \"e\": 24783,\n \"s\": 24552,\n \"text\": \"Input : n = 4, m = 1 \\nOutput : SUM(4, 1) = 10\\nExplanation : 1 + 2 + 3 + 4 = 10\\n\\nInput : n = 3, m = 2 \\nOutput : SUM(3, 2) = 21\\nExplanation : SUM(3, 2) \\n = SUM(SUM(3, 1), 1) \\n = SUM(6, 1) \\n = 21\"\n },\n {\n \"code\": null,\n \"e\": 25086,\n \"s\": 24785,\n \"text\": \"Naive Approach : We can solve this problem using two nested loop, where outer loop iterate for m and inner loop iterate for n. After completion of a single outer iteration, we should update n as whole of inner loop got executed and value of n must be changed then. Time complexity should be O(n*m). \"\n },\n {\n \"code\": null,\n \"e\": 25205,\n \"s\": 25086,\n \"text\": \"for (int i = 1;i <= m;i++)\\n{\\n sum = 0;\\n for (int j = 1;j <= n;j++)\\n sum += j;\\n n = sum; // update n\\n}\"\n },\n {\n \"code\": null,\n \"e\": 25559,\n \"s\": 25205,\n \"text\": \"Efficient Approach : We can use direct formula for sum of first n numbers to reduce time. We can also use recursion. In this approach m = 1 will be our base condition and for any intermediate step SUM(n, m), we will call SUM (SUM(n, m-1), 1) and for a single step SUM(n, 1) = n * (n + 1) / 2 will be used. This will reduce our time complexity to O(m). \"\n },\n {\n \"code\": null,\n \"e\": 25697,\n \"s\": 25559,\n \"text\": \"int SUM (int n, int m)\\n{\\n if (m == 1)\\n return (n * (n + 1) / 2);\\n int sum = SUM(n, m-1);\\n return (sum * (sum + 1) / 2);\\n}\"\n },\n {\n \"code\": null,\n \"e\": 25742,\n \"s\": 25697,\n \"text\": \"Below is the implementation of above idea : \"\n },\n {\n \"code\": null,\n \"e\": 25746,\n \"s\": 25742,\n \"text\": \"C++\"\n },\n {\n \"code\": null,\n \"e\": 25751,\n \"s\": 25746,\n \"text\": \"Java\"\n },\n {\n \"code\": null,\n \"e\": 25754,\n \"s\": 25751,\n \"text\": \"C#\"\n },\n {\n \"code\": null,\n \"e\": 25758,\n \"s\": 25754,\n \"text\": \"PHP\"\n },\n {\n \"code\": null,\n \"e\": 25769,\n \"s\": 25758,\n \"text\": \"Javascript\"\n },\n {\n \"code\": \"// CPP program to find m-th summation#include using namespace std; // Function to return mth summationint SUM(int n, int m){ // base case if (m == 1) return (n * (n + 1) / 2); int sum = SUM(n, m-1); return (sum * (sum + 1) / 2);} // driver programint main(){ int n = 5; int m = 3; cout << \\\"SUM(\\\" << n << \\\", \\\" << m << \\\"): \\\" << SUM(n, m); return 0;}\",\n \"e\": 26182,\n \"s\": 25769,\n \"text\": null\n },\n {\n \"code\": \"// Java program to find m-th summation.class GFG { // Function to return mth summation static int SUM(int n, int m) { // base case if (m == 1) return (n * (n + 1) / 2); int sum = SUM(n, m - 1); return (sum * (sum + 1) / 2); } // Driver code public static void main(String[] args) { int n = 5; int m = 3; System.out.println(\\\"SUM(\\\" + n + \\\", \\\" + m + \\\"): \\\" + SUM(n, m)); }} // This code is contributed by Anant Agarwal.\",\n \"e\": 26753,\n \"s\": 26182,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 26762,\n \"s\": 26753,\n \"text\": \"Python3 \"\n },\n {\n \"code\": null,\n \"e\": 27117,\n \"s\": 26762,\n \"text\": \"\\n# Python3 program to find m-th summation \\n\\n# Function to return mth summation\\ndef SUM(n, m):\\n\\n # base case\\n if (m == 1):\\n return (n * (n + 1) / 2)\\n \\n sum = SUM(n, m-1)\\n return int(sum * (sum + 1) / 2)\\n\\n\\n# driver program\\nn = 5\\nm = 3\\nprint(\\\"SUM(\\\", n, \\\", \\\", m, \\\"):\\\", SUM(n, m))\\n\\n# This code is contributed by Smitha Dinesh Semwal\\n\"\n },\n {\n \"code\": \"// C# program to find m-th summation.using System; class GFG{ // Function to return mth summation static int SUM(int n, int m) { // base case if (m == 1) return (n * (n + 1) / 2); int sum = SUM(n, m - 1); return (sum * (sum + 1) / 2); } // Driver Code public static void Main() { int n = 5; int m = 3; Console.Write(\\\"SUM(\\\" + n + \\\", \\\" + m + \\\"): \\\" + SUM(n, m)); }} // This code is contributed by Nitin Mittal.\",\n \"e\": 27682,\n \"s\": 27117,\n \"text\": null\n },\n {\n \"code\": \"\",\n \"e\": 28071,\n \"s\": 27682,\n \"text\": null\n },\n {\n \"code\": \"\",\n \"e\": 28481,\n \"s\": 28071,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 28491,\n \"s\": 28481,\n \"text\": \"Output: \"\n },\n {\n \"code\": null,\n \"e\": 28507,\n \"s\": 28491,\n \"text\": \"SUM(5, 3): 7260\"\n },\n {\n \"code\": null,\n \"e\": 28947,\n \"s\": 28507,\n \"text\": \"This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. \"\n },\n {\n \"code\": null,\n \"e\": 28960,\n \"s\": 28947,\n \"text\": \"nitin mittal\"\n },\n {\n \"code\": null,\n \"e\": 28965,\n \"s\": 28960,\n \"text\": \"vt_m\"\n },\n {\n \"code\": null,\n \"e\": 28975,\n \"s\": 28965,\n \"text\": \"Rajput-Ji\"\n },\n {\n \"code\": null,\n \"e\": 28988,\n \"s\": 28975,\n \"text\": \"Mathematical\"\n },\n {\n \"code\": null,\n \"e\": 28998,\n \"s\": 28988,\n \"text\": \"Recursion\"\n },\n {\n \"code\": null,\n \"e\": 29011,\n \"s\": 28998,\n \"text\": \"Mathematical\"\n },\n {\n \"code\": null,\n \"e\": 29021,\n \"s\": 29011,\n \"text\": \"Recursion\"\n },\n {\n \"code\": null,\n \"e\": 29119,\n \"s\": 29021,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 29128,\n \"s\": 29119,\n \"text\": \"Comments\"\n },\n {\n \"code\": null,\n \"e\": 29141,\n \"s\": 29128,\n \"text\": \"Old Comments\"\n },\n {\n \"code\": null,\n \"e\": 29186,\n \"s\": 29141,\n \"text\": \"Find all factors of a natural number | Set 1\"\n },\n {\n \"code\": null,\n \"e\": 29218,\n \"s\": 29186,\n \"text\": \"Check if a number is Palindrome\"\n },\n {\n \"code\": null,\n \"e\": 29262,\n \"s\": 29218,\n \"text\": \"Program to print prime numbers from 1 to N.\"\n },\n {\n \"code\": null,\n \"e\": 29296,\n \"s\": 29262,\n \"text\": \"Program to add two binary strings\"\n },\n {\n \"code\": null,\n \"e\": 29329,\n \"s\": 29296,\n \"text\": \"Program to multiply two matrices\"\n },\n {\n \"code\": null,\n \"e\": 29414,\n \"s\": 29329,\n \"text\": \"Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)\"\n },\n {\n \"code\": null,\n \"e\": 29424,\n \"s\": 29414,\n \"text\": \"Recursion\"\n },\n {\n \"code\": null,\n \"e\": 29451,\n \"s\": 29424,\n \"text\": \"Program for Tower of Hanoi\"\n },\n {\n \"code\": null,\n \"e\": 29499,\n \"s\": 29451,\n \"text\": \"Program for Sum of the digits of a given number\"\n }\n]"}}},{"rowIdx":112,"cells":{"title":{"kind":"string","value":"Best practices for caching in Spark SQL | by David Vrba | Towards Data Science"},"text":{"kind":"string","value":"In Spark SQL caching is a common technique for reusing some computation. It has the potential to speedup other queries that are using the same data, but there are some caveats that are good to keep in mind if we want to achieve good performance. In this article, we will take a look under the hood to see how caching works internally and we will try to demystify Spark's behavior related to data persistence.\nIn DataFrame API, there are two functions that can be used to cache a DataFrame, cache() and persist():\ndf.cache() # see in PySpark docs heredf.persist() # see in PySpark docs here\nThey are almost equivalent, the difference is that persist can take an optional argument storageLevel by which we can specify where the data will be persisted. The default value of the storageLevel for both functions is MEMORY_AND_DISK which means that the data will be stored in memory if there is space for it, otherwise, it will be stored on disk. Here you can see the (PySpark) documentation for other possible storage levels.\nCaching is a lazy transformation, so immediately after calling the function nothing happens with the data but the query plan is updated by the Cache Manager by adding a new operator — InMemoryRelation. So this is just some information that will be used during the query execution later on when some action is called. Spark will look for the data in the caching layer and read it from there if it is available. If it doesn’t find the data in the caching layer (which happens for sure the first time the query runs), it will become responsible for getting the data there and it will use it immediately afterward.\nThe Cache Manager is responsible to keep track of what computation has already been cached in terms of the query plan. When the caching function is called, the Cache Manager is invoked directly under the hood and it pulls out the analyzed logical plan of the DataFrame on which the caching function is called and stores that plan in an indexed sequence called cachedData.\nThe phase of the Cache Manager is part of logical planning and it takes place after the analyzer and before the optimizer:\nWhen you run a query with an action, the query plan will be processed and transformed. In the step of the Cache Manager (just before the optimizer) Spark will check for each subtree of the analyzed plan if it is stored in the cachedData sequence. If it finds a match it means that the same plan (the same computation) has already been cached (perhaps in some previous query) and so Spark can use that and thus it adds that information to the query plan using the InMemoryRelation operator which will carry information about this cached plan. This InMemoryRelation is then used in the phase of physical planning to create a physical operator— InMemoryTableScan.\ndf = spark.table(\"users\").filter(col(col_name) > x).cache()df.count() # now check the query plan in Spark UI\nHere in the above picture you can see graphical and string representation of a query which was using caching. To see what transformations were cached you need to look into the string representation of the plan because the graphical representation doesn’t show this information.\nLet’s see a simple example to understand better how the Cache Manager works:\ndf = spark.read.parquet(data_path)df.select(col1, col2).filter(col2 > 0).cache()\nConsider the following three queries. Which one of them will leverage the cached data?\n1) df.filter(col2 > 0).select(col1, col2)2) df.select(col1, col2).filter(col2 > 10)3) df.select(col1).filter(col2 > 0)\nThe decisive factor is the analyzed logical plan. If it is the same as the analyzed plan of the cached query, then the cache will be leveraged. For query number 1 you might be tempted to say that it has the same plan because the filter will be pushed by the optimizer in both cases anyway. But this is actually not entirely accurate. The important thing to understand is that the phase of the Cache Manager takes place before the optimizer. What would be the same are the optimized plans but not analyzed plans. So query n. 1 will not leverage the cache simply because the analyzed plans are different.\nFor query n. 2 you might be again tempted to assume that it will use the cached data because the filter is more restrictive than the filter in the cached query. We can logically see that the queried data is in the cache, but Spark will not read it from there because of the same reason as before — the analyzed plans are different — this time the filtering condition is not the same. To use the cached data we can, however, fix the second query just by adding the filter there:\ndf.select(col1, col2).filter(col2 > 0).filter(col2 > 10)\nAt first sight, the filter col2 > 0 seems to be useless here, but it is not because now part of the analyzed logical plan will be identical with the cached plan and the Cache Manager will be able to find it and use the InMemoryRelation in the query plan.\nQuery number 3 is tricky, at first sight, it appears that it also will have a different analyzed plan because the query is different — we select only col1. The filtering condition is, however, using col2, which is not present in the previous projection and so the analyzer will invoke a rule ResolveMissingReferences and it will add col2 to the projection and the analyzed plan will actually become identical with the cached plan. This time the Cache Manager will find it and use it.\nSo the final answer is that query n. 3 will leverage the cached data.\nLet’s list a couple of rules of thumb related to caching:\nWhen you cache a DataFrame create a new variable for it cachedDF = df.cache(). This will allow you to bypass the problems that we were solving in our example, that sometimes it is not clear what is the analyzed plan and what was actually cached. Here whenever you call cachedDF.select(...) it will leverage the cached data.\nUnpersist the DataFrame after it is no longer needed using cachedDF.unpersist(). If the caching layer becomes full, Spark will start evicting the data from memory using the LRU (least recently used) strategy. So it is good practice to use unpersist to stay more in control about what should be evicted. Also, the more space you have in memory the more can Spark use for execution, for instance, for building hash maps and so on.\nBefore you cache, make sure you are caching only what you will need in your queries. For example, if one query will use (col1, col2, col3) and the second query will use (col2, col3, col4), select a superset of these columns: cachedDF = df.select(col1, col2, col3, col4).cache(). It is not very useful to call cachedDF = df.cache() if the df contains lots of columns and only a small subset will be needed in follow-up queries.\nUse the caching only if it makes sense. That is if the cached computation will be used multiple times. It is good to understand that putting the data to memory is also related to some overhead, so in some cases, it might be even faster to simply run the computation again if it is fast enough and not use caching at all as you can see in the next paragraph.\nThere are situations where caching doesn’t help at all and on the contrary slows down the execution. This is related for instance to queries based on large datasets stored in a columnar file format that supports column pruning and predicate pushdown such as parquet. Let’s consider the following example, in which we will cache the entire dataset and then run some queries on top of it. We will use the following dataset and cluster properties:\ndataset size: 14.3GB in compressed parquet sitting on S3cluster size: 2 workers c5.4xlarge (32 cores together)platform: Databricks (runtime 6.6 wit Spark 2.4.5)\nFirst, let’s measure the execution times for the queries where caching is not used:\ndf = spark.table(table_name)df.count() # runs 7.9sdf.filter(col(\"id\") > xxx).count() # runs 18.2s\nNow run the same queries with caching (the entire dataset doesn’t fit in memory and about 30% is cached on disk):\ndf = spark.table(table_name).cache()# this count will take long because it is putting data to memorydf.count() # runs 1.28mindf.count() # runs 14sdf.filter(col(\"id\") > xxx).count() # runs 20.6s\nNo wonder that the first count takes 1.3min, there is the overhead related to putting data to memory. However, as you can see, also the second count and the query with the filter take longer for the cached dataset as compared to reading directly from parquet. It is a combination of two major reasons. The first one is the properties of the parquet file format — queries based on top of parquet are fast on its own. In the case of reading from parquet, Spark will read only the metadata to get the count so it doesn’t need to scan the entire dataset. For the filtering query, it will use column pruning and scan only the id column. On the other hand, when reading the data from the cache, Spark will read the entire dataset. This can be seen from Spark UI, where you can check the input size for the first stage (see the picture below).\nThe second reason is that the dataset is large and doesn’t fit entirely in ram. Part of the data is stored on disk as well and reading from the disk is much slower than reading from ram.\nIf you prefer using directly SQL instead of DataFrame DSL, you can still use caching, there are some differences, however.\nspark.sql(\"cache table table_name\")\nThe main difference is that using SQL the caching is eager by default, so a job will run immediately and will put the data to the caching layer. To make it lazy as it is in the DataFrame DSL we can use the lazy keyword explicitly:\nspark.sql(\"cache lazy table table_name\")\nTo remove the data from the cache, just call:\nspark.sql(\"uncache table table_name\")\nSometimes you may wonder what data is already cached. One possibility is to check Spark UI which provides some basic information about data that is already cached on the cluster.\nHere for each cached dataset, you can see how much space it takes in memory or on disk. You can even zoom more and click on the record in the table which will take you to another page with details about each partition.\nTo check whether the entire table is cached we can use Catalog API:\nspark.catalog.isCached(\"table_name\")\nThe Catalog API can also be used to remove all data from the cache as follows:\nspark.catalog.clearCache()\nIn Scala API you can also use the internal API of the Cache Manager which provides some functions, for instance, you can ask whether the Cache Manager is empty:\n// In Scala API:val cm = spark.sharedState.cacheManagercm.isEmpty\nCaching is one of more techniques that can be used for reusing some computation. Apart from caching there is also checkpointing and exchange-reuse.\nThe checkpointing is useful for instance in situations where we need to break the query plan because it is too large. A large query plan may become a bottleneck in the driver where it is processed because the processing of a very large plan will take to long. The checkpoint will however break the plan and materialize the query. For the next transformations, Spark will start building a new plan. The checkpointing is related to two functions checkpoint and localCheckpoint which differ by the storage used for the data.\nThe exchange-reuse where Spark persists the output of a shuffle on disk, is, on the other hand, a technique that can not be controlled directly by some API function, but instead, it is an internal feature that Spark handles on its own. In some special situations, it can be controlled indirectly by rewriting the query trying to achieve identical exchange branches. To read more about exchange-reuse, you can check my other article, where I describe it more in detail.\nIn this article, we tried to demystify Spark's behavior related to caching. We have seen how it works under the hood and what are the differences between using DSL vs SQL. We discussed some best practices on how to make caching as efficient as possible. On one example we showed that for big datasets that do not fit in memory, it might be faster to avoid caching especially if the data is stored in columnar file format. We also mentioned some alternatives to caching such as checkpointing or reused exchange that can be useful for data persistence in some situations."},"parsed":{"kind":"list like","value":[{"code":null,"e":581,"s":172,"text":"In Spark SQL caching is a common technique for reusing some computation. It has the potential to speedup other queries that are using the same data, but there are some caveats that are good to keep in mind if we want to achieve good performance. In this article, we will take a look under the hood to see how caching works internally and we will try to demystify Spark's behavior related to data persistence."},{"code":null,"e":685,"s":581,"text":"In DataFrame API, there are two functions that can be used to cache a DataFrame, cache() and persist():"},{"code":null,"e":762,"s":685,"text":"df.cache() # see in PySpark docs heredf.persist() # see in PySpark docs here"},{"code":null,"e":1193,"s":762,"text":"They are almost equivalent, the difference is that persist can take an optional argument storageLevel by which we can specify where the data will be persisted. The default value of the storageLevel for both functions is MEMORY_AND_DISK which means that the data will be stored in memory if there is space for it, otherwise, it will be stored on disk. Here you can see the (PySpark) documentation for other possible storage levels."},{"code":null,"e":1804,"s":1193,"text":"Caching is a lazy transformation, so immediately after calling the function nothing happens with the data but the query plan is updated by the Cache Manager by adding a new operator — InMemoryRelation. So this is just some information that will be used during the query execution later on when some action is called. Spark will look for the data in the caching layer and read it from there if it is available. If it doesn’t find the data in the caching layer (which happens for sure the first time the query runs), it will become responsible for getting the data there and it will use it immediately afterward."},{"code":null,"e":2176,"s":1804,"text":"The Cache Manager is responsible to keep track of what computation has already been cached in terms of the query plan. When the caching function is called, the Cache Manager is invoked directly under the hood and it pulls out the analyzed logical plan of the DataFrame on which the caching function is called and stores that plan in an indexed sequence called cachedData."},{"code":null,"e":2299,"s":2176,"text":"The phase of the Cache Manager is part of logical planning and it takes place after the analyzer and before the optimizer:"},{"code":null,"e":2960,"s":2299,"text":"When you run a query with an action, the query plan will be processed and transformed. In the step of the Cache Manager (just before the optimizer) Spark will check for each subtree of the analyzed plan if it is stored in the cachedData sequence. If it finds a match it means that the same plan (the same computation) has already been cached (perhaps in some previous query) and so Spark can use that and thus it adds that information to the query plan using the InMemoryRelation operator which will carry information about this cached plan. This InMemoryRelation is then used in the phase of physical planning to create a physical operator— InMemoryTableScan."},{"code":null,"e":3069,"s":2960,"text":"df = spark.table(\"users\").filter(col(col_name) > x).cache()df.count() # now check the query plan in Spark UI"},{"code":null,"e":3347,"s":3069,"text":"Here in the above picture you can see graphical and string representation of a query which was using caching. To see what transformations were cached you need to look into the string representation of the plan because the graphical representation doesn’t show this information."},{"code":null,"e":3424,"s":3347,"text":"Let’s see a simple example to understand better how the Cache Manager works:"},{"code":null,"e":3505,"s":3424,"text":"df = spark.read.parquet(data_path)df.select(col1, col2).filter(col2 > 0).cache()"},{"code":null,"e":3592,"s":3505,"text":"Consider the following three queries. Which one of them will leverage the cached data?"},{"code":null,"e":3711,"s":3592,"text":"1) df.filter(col2 > 0).select(col1, col2)2) df.select(col1, col2).filter(col2 > 10)3) df.select(col1).filter(col2 > 0)"},{"code":null,"e":4314,"s":3711,"text":"The decisive factor is the analyzed logical plan. If it is the same as the analyzed plan of the cached query, then the cache will be leveraged. For query number 1 you might be tempted to say that it has the same plan because the filter will be pushed by the optimizer in both cases anyway. But this is actually not entirely accurate. The important thing to understand is that the phase of the Cache Manager takes place before the optimizer. What would be the same are the optimized plans but not analyzed plans. So query n. 1 will not leverage the cache simply because the analyzed plans are different."},{"code":null,"e":4792,"s":4314,"text":"For query n. 2 you might be again tempted to assume that it will use the cached data because the filter is more restrictive than the filter in the cached query. We can logically see that the queried data is in the cache, but Spark will not read it from there because of the same reason as before — the analyzed plans are different — this time the filtering condition is not the same. To use the cached data we can, however, fix the second query just by adding the filter there:"},{"code":null,"e":4849,"s":4792,"text":"df.select(col1, col2).filter(col2 > 0).filter(col2 > 10)"},{"code":null,"e":5104,"s":4849,"text":"At first sight, the filter col2 > 0 seems to be useless here, but it is not because now part of the analyzed logical plan will be identical with the cached plan and the Cache Manager will be able to find it and use the InMemoryRelation in the query plan."},{"code":null,"e":5588,"s":5104,"text":"Query number 3 is tricky, at first sight, it appears that it also will have a different analyzed plan because the query is different — we select only col1. The filtering condition is, however, using col2, which is not present in the previous projection and so the analyzer will invoke a rule ResolveMissingReferences and it will add col2 to the projection and the analyzed plan will actually become identical with the cached plan. This time the Cache Manager will find it and use it."},{"code":null,"e":5658,"s":5588,"text":"So the final answer is that query n. 3 will leverage the cached data."},{"code":null,"e":5716,"s":5658,"text":"Let’s list a couple of rules of thumb related to caching:"},{"code":null,"e":6040,"s":5716,"text":"When you cache a DataFrame create a new variable for it cachedDF = df.cache(). This will allow you to bypass the problems that we were solving in our example, that sometimes it is not clear what is the analyzed plan and what was actually cached. Here whenever you call cachedDF.select(...) it will leverage the cached data."},{"code":null,"e":6469,"s":6040,"text":"Unpersist the DataFrame after it is no longer needed using cachedDF.unpersist(). If the caching layer becomes full, Spark will start evicting the data from memory using the LRU (least recently used) strategy. So it is good practice to use unpersist to stay more in control about what should be evicted. Also, the more space you have in memory the more can Spark use for execution, for instance, for building hash maps and so on."},{"code":null,"e":6896,"s":6469,"text":"Before you cache, make sure you are caching only what you will need in your queries. For example, if one query will use (col1, col2, col3) and the second query will use (col2, col3, col4), select a superset of these columns: cachedDF = df.select(col1, col2, col3, col4).cache(). It is not very useful to call cachedDF = df.cache() if the df contains lots of columns and only a small subset will be needed in follow-up queries."},{"code":null,"e":7254,"s":6896,"text":"Use the caching only if it makes sense. That is if the cached computation will be used multiple times. It is good to understand that putting the data to memory is also related to some overhead, so in some cases, it might be even faster to simply run the computation again if it is fast enough and not use caching at all as you can see in the next paragraph."},{"code":null,"e":7699,"s":7254,"text":"There are situations where caching doesn’t help at all and on the contrary slows down the execution. This is related for instance to queries based on large datasets stored in a columnar file format that supports column pruning and predicate pushdown such as parquet. Let’s consider the following example, in which we will cache the entire dataset and then run some queries on top of it. We will use the following dataset and cluster properties:"},{"code":null,"e":7860,"s":7699,"text":"dataset size: 14.3GB in compressed parquet sitting on S3cluster size: 2 workers c5.4xlarge (32 cores together)platform: Databricks (runtime 6.6 wit Spark 2.4.5)"},{"code":null,"e":7944,"s":7860,"text":"First, let’s measure the execution times for the queries where caching is not used:"},{"code":null,"e":8042,"s":7944,"text":"df = spark.table(table_name)df.count() # runs 7.9sdf.filter(col(\"id\") > xxx).count() # runs 18.2s"},{"code":null,"e":8156,"s":8042,"text":"Now run the same queries with caching (the entire dataset doesn’t fit in memory and about 30% is cached on disk):"},{"code":null,"e":8350,"s":8156,"text":"df = spark.table(table_name).cache()# this count will take long because it is putting data to memorydf.count() # runs 1.28mindf.count() # runs 14sdf.filter(col(\"id\") > xxx).count() # runs 20.6s"},{"code":null,"e":9187,"s":8350,"text":"No wonder that the first count takes 1.3min, there is the overhead related to putting data to memory. However, as you can see, also the second count and the query with the filter take longer for the cached dataset as compared to reading directly from parquet. It is a combination of two major reasons. The first one is the properties of the parquet file format — queries based on top of parquet are fast on its own. In the case of reading from parquet, Spark will read only the metadata to get the count so it doesn’t need to scan the entire dataset. For the filtering query, it will use column pruning and scan only the id column. On the other hand, when reading the data from the cache, Spark will read the entire dataset. This can be seen from Spark UI, where you can check the input size for the first stage (see the picture below)."},{"code":null,"e":9374,"s":9187,"text":"The second reason is that the dataset is large and doesn’t fit entirely in ram. Part of the data is stored on disk as well and reading from the disk is much slower than reading from ram."},{"code":null,"e":9497,"s":9374,"text":"If you prefer using directly SQL instead of DataFrame DSL, you can still use caching, there are some differences, however."},{"code":null,"e":9533,"s":9497,"text":"spark.sql(\"cache table table_name\")"},{"code":null,"e":9764,"s":9533,"text":"The main difference is that using SQL the caching is eager by default, so a job will run immediately and will put the data to the caching layer. To make it lazy as it is in the DataFrame DSL we can use the lazy keyword explicitly:"},{"code":null,"e":9805,"s":9764,"text":"spark.sql(\"cache lazy table table_name\")"},{"code":null,"e":9851,"s":9805,"text":"To remove the data from the cache, just call:"},{"code":null,"e":9889,"s":9851,"text":"spark.sql(\"uncache table table_name\")"},{"code":null,"e":10068,"s":9889,"text":"Sometimes you may wonder what data is already cached. One possibility is to check Spark UI which provides some basic information about data that is already cached on the cluster."},{"code":null,"e":10287,"s":10068,"text":"Here for each cached dataset, you can see how much space it takes in memory or on disk. You can even zoom more and click on the record in the table which will take you to another page with details about each partition."},{"code":null,"e":10355,"s":10287,"text":"To check whether the entire table is cached we can use Catalog API:"},{"code":null,"e":10392,"s":10355,"text":"spark.catalog.isCached(\"table_name\")"},{"code":null,"e":10471,"s":10392,"text":"The Catalog API can also be used to remove all data from the cache as follows:"},{"code":null,"e":10498,"s":10471,"text":"spark.catalog.clearCache()"},{"code":null,"e":10659,"s":10498,"text":"In Scala API you can also use the internal API of the Cache Manager which provides some functions, for instance, you can ask whether the Cache Manager is empty:"},{"code":null,"e":10725,"s":10659,"text":"// In Scala API:val cm = spark.sharedState.cacheManagercm.isEmpty"},{"code":null,"e":10873,"s":10725,"text":"Caching is one of more techniques that can be used for reusing some computation. Apart from caching there is also checkpointing and exchange-reuse."},{"code":null,"e":11395,"s":10873,"text":"The checkpointing is useful for instance in situations where we need to break the query plan because it is too large. A large query plan may become a bottleneck in the driver where it is processed because the processing of a very large plan will take to long. The checkpoint will however break the plan and materialize the query. For the next transformations, Spark will start building a new plan. The checkpointing is related to two functions checkpoint and localCheckpoint which differ by the storage used for the data."},{"code":null,"e":11864,"s":11395,"text":"The exchange-reuse where Spark persists the output of a shuffle on disk, is, on the other hand, a technique that can not be controlled directly by some API function, but instead, it is an internal feature that Spark handles on its own. In some special situations, it can be controlled indirectly by rewriting the query trying to achieve identical exchange branches. To read more about exchange-reuse, you can check my other article, where I describe it more in detail."}],"string":"[\n {\n \"code\": null,\n \"e\": 581,\n \"s\": 172,\n \"text\": \"In Spark SQL caching is a common technique for reusing some computation. It has the potential to speedup other queries that are using the same data, but there are some caveats that are good to keep in mind if we want to achieve good performance. In this article, we will take a look under the hood to see how caching works internally and we will try to demystify Spark's behavior related to data persistence.\"\n },\n {\n \"code\": null,\n \"e\": 685,\n \"s\": 581,\n \"text\": \"In DataFrame API, there are two functions that can be used to cache a DataFrame, cache() and persist():\"\n },\n {\n \"code\": null,\n \"e\": 762,\n \"s\": 685,\n \"text\": \"df.cache() # see in PySpark docs heredf.persist() # see in PySpark docs here\"\n },\n {\n \"code\": null,\n \"e\": 1193,\n \"s\": 762,\n \"text\": \"They are almost equivalent, the difference is that persist can take an optional argument storageLevel by which we can specify where the data will be persisted. The default value of the storageLevel for both functions is MEMORY_AND_DISK which means that the data will be stored in memory if there is space for it, otherwise, it will be stored on disk. Here you can see the (PySpark) documentation for other possible storage levels.\"\n },\n {\n \"code\": null,\n \"e\": 1804,\n \"s\": 1193,\n \"text\": \"Caching is a lazy transformation, so immediately after calling the function nothing happens with the data but the query plan is updated by the Cache Manager by adding a new operator — InMemoryRelation. So this is just some information that will be used during the query execution later on when some action is called. Spark will look for the data in the caching layer and read it from there if it is available. If it doesn’t find the data in the caching layer (which happens for sure the first time the query runs), it will become responsible for getting the data there and it will use it immediately afterward.\"\n },\n {\n \"code\": null,\n \"e\": 2176,\n \"s\": 1804,\n \"text\": \"The Cache Manager is responsible to keep track of what computation has already been cached in terms of the query plan. When the caching function is called, the Cache Manager is invoked directly under the hood and it pulls out the analyzed logical plan of the DataFrame on which the caching function is called and stores that plan in an indexed sequence called cachedData.\"\n },\n {\n \"code\": null,\n \"e\": 2299,\n \"s\": 2176,\n \"text\": \"The phase of the Cache Manager is part of logical planning and it takes place after the analyzer and before the optimizer:\"\n },\n {\n \"code\": null,\n \"e\": 2960,\n \"s\": 2299,\n \"text\": \"When you run a query with an action, the query plan will be processed and transformed. In the step of the Cache Manager (just before the optimizer) Spark will check for each subtree of the analyzed plan if it is stored in the cachedData sequence. If it finds a match it means that the same plan (the same computation) has already been cached (perhaps in some previous query) and so Spark can use that and thus it adds that information to the query plan using the InMemoryRelation operator which will carry information about this cached plan. This InMemoryRelation is then used in the phase of physical planning to create a physical operator— InMemoryTableScan.\"\n },\n {\n \"code\": null,\n \"e\": 3069,\n \"s\": 2960,\n \"text\": \"df = spark.table(\\\"users\\\").filter(col(col_name) > x).cache()df.count() # now check the query plan in Spark UI\"\n },\n {\n \"code\": null,\n \"e\": 3347,\n \"s\": 3069,\n \"text\": \"Here in the above picture you can see graphical and string representation of a query which was using caching. To see what transformations were cached you need to look into the string representation of the plan because the graphical representation doesn’t show this information.\"\n },\n {\n \"code\": null,\n \"e\": 3424,\n \"s\": 3347,\n \"text\": \"Let’s see a simple example to understand better how the Cache Manager works:\"\n },\n {\n \"code\": null,\n \"e\": 3505,\n \"s\": 3424,\n \"text\": \"df = spark.read.parquet(data_path)df.select(col1, col2).filter(col2 > 0).cache()\"\n },\n {\n \"code\": null,\n \"e\": 3592,\n \"s\": 3505,\n \"text\": \"Consider the following three queries. Which one of them will leverage the cached data?\"\n },\n {\n \"code\": null,\n \"e\": 3711,\n \"s\": 3592,\n \"text\": \"1) df.filter(col2 > 0).select(col1, col2)2) df.select(col1, col2).filter(col2 > 10)3) df.select(col1).filter(col2 > 0)\"\n },\n {\n \"code\": null,\n \"e\": 4314,\n \"s\": 3711,\n \"text\": \"The decisive factor is the analyzed logical plan. If it is the same as the analyzed plan of the cached query, then the cache will be leveraged. For query number 1 you might be tempted to say that it has the same plan because the filter will be pushed by the optimizer in both cases anyway. But this is actually not entirely accurate. The important thing to understand is that the phase of the Cache Manager takes place before the optimizer. What would be the same are the optimized plans but not analyzed plans. So query n. 1 will not leverage the cache simply because the analyzed plans are different.\"\n },\n {\n \"code\": null,\n \"e\": 4792,\n \"s\": 4314,\n \"text\": \"For query n. 2 you might be again tempted to assume that it will use the cached data because the filter is more restrictive than the filter in the cached query. We can logically see that the queried data is in the cache, but Spark will not read it from there because of the same reason as before — the analyzed plans are different — this time the filtering condition is not the same. To use the cached data we can, however, fix the second query just by adding the filter there:\"\n },\n {\n \"code\": null,\n \"e\": 4849,\n \"s\": 4792,\n \"text\": \"df.select(col1, col2).filter(col2 > 0).filter(col2 > 10)\"\n },\n {\n \"code\": null,\n \"e\": 5104,\n \"s\": 4849,\n \"text\": \"At first sight, the filter col2 > 0 seems to be useless here, but it is not because now part of the analyzed logical plan will be identical with the cached plan and the Cache Manager will be able to find it and use the InMemoryRelation in the query plan.\"\n },\n {\n \"code\": null,\n \"e\": 5588,\n \"s\": 5104,\n \"text\": \"Query number 3 is tricky, at first sight, it appears that it also will have a different analyzed plan because the query is different — we select only col1. The filtering condition is, however, using col2, which is not present in the previous projection and so the analyzer will invoke a rule ResolveMissingReferences and it will add col2 to the projection and the analyzed plan will actually become identical with the cached plan. This time the Cache Manager will find it and use it.\"\n },\n {\n \"code\": null,\n \"e\": 5658,\n \"s\": 5588,\n \"text\": \"So the final answer is that query n. 3 will leverage the cached data.\"\n },\n {\n \"code\": null,\n \"e\": 5716,\n \"s\": 5658,\n \"text\": \"Let’s list a couple of rules of thumb related to caching:\"\n },\n {\n \"code\": null,\n \"e\": 6040,\n \"s\": 5716,\n \"text\": \"When you cache a DataFrame create a new variable for it cachedDF = df.cache(). This will allow you to bypass the problems that we were solving in our example, that sometimes it is not clear what is the analyzed plan and what was actually cached. Here whenever you call cachedDF.select(...) it will leverage the cached data.\"\n },\n {\n \"code\": null,\n \"e\": 6469,\n \"s\": 6040,\n \"text\": \"Unpersist the DataFrame after it is no longer needed using cachedDF.unpersist(). If the caching layer becomes full, Spark will start evicting the data from memory using the LRU (least recently used) strategy. So it is good practice to use unpersist to stay more in control about what should be evicted. Also, the more space you have in memory the more can Spark use for execution, for instance, for building hash maps and so on.\"\n },\n {\n \"code\": null,\n \"e\": 6896,\n \"s\": 6469,\n \"text\": \"Before you cache, make sure you are caching only what you will need in your queries. For example, if one query will use (col1, col2, col3) and the second query will use (col2, col3, col4), select a superset of these columns: cachedDF = df.select(col1, col2, col3, col4).cache(). It is not very useful to call cachedDF = df.cache() if the df contains lots of columns and only a small subset will be needed in follow-up queries.\"\n },\n {\n \"code\": null,\n \"e\": 7254,\n \"s\": 6896,\n \"text\": \"Use the caching only if it makes sense. That is if the cached computation will be used multiple times. It is good to understand that putting the data to memory is also related to some overhead, so in some cases, it might be even faster to simply run the computation again if it is fast enough and not use caching at all as you can see in the next paragraph.\"\n },\n {\n \"code\": null,\n \"e\": 7699,\n \"s\": 7254,\n \"text\": \"There are situations where caching doesn’t help at all and on the contrary slows down the execution. This is related for instance to queries based on large datasets stored in a columnar file format that supports column pruning and predicate pushdown such as parquet. Let’s consider the following example, in which we will cache the entire dataset and then run some queries on top of it. We will use the following dataset and cluster properties:\"\n },\n {\n \"code\": null,\n \"e\": 7860,\n \"s\": 7699,\n \"text\": \"dataset size: 14.3GB in compressed parquet sitting on S3cluster size: 2 workers c5.4xlarge (32 cores together)platform: Databricks (runtime 6.6 wit Spark 2.4.5)\"\n },\n {\n \"code\": null,\n \"e\": 7944,\n \"s\": 7860,\n \"text\": \"First, let’s measure the execution times for the queries where caching is not used:\"\n },\n {\n \"code\": null,\n \"e\": 8042,\n \"s\": 7944,\n \"text\": \"df = spark.table(table_name)df.count() # runs 7.9sdf.filter(col(\\\"id\\\") > xxx).count() # runs 18.2s\"\n },\n {\n \"code\": null,\n \"e\": 8156,\n \"s\": 8042,\n \"text\": \"Now run the same queries with caching (the entire dataset doesn’t fit in memory and about 30% is cached on disk):\"\n },\n {\n \"code\": null,\n \"e\": 8350,\n \"s\": 8156,\n \"text\": \"df = spark.table(table_name).cache()# this count will take long because it is putting data to memorydf.count() # runs 1.28mindf.count() # runs 14sdf.filter(col(\\\"id\\\") > xxx).count() # runs 20.6s\"\n },\n {\n \"code\": null,\n \"e\": 9187,\n \"s\": 8350,\n \"text\": \"No wonder that the first count takes 1.3min, there is the overhead related to putting data to memory. However, as you can see, also the second count and the query with the filter take longer for the cached dataset as compared to reading directly from parquet. It is a combination of two major reasons. The first one is the properties of the parquet file format — queries based on top of parquet are fast on its own. In the case of reading from parquet, Spark will read only the metadata to get the count so it doesn’t need to scan the entire dataset. For the filtering query, it will use column pruning and scan only the id column. On the other hand, when reading the data from the cache, Spark will read the entire dataset. This can be seen from Spark UI, where you can check the input size for the first stage (see the picture below).\"\n },\n {\n \"code\": null,\n \"e\": 9374,\n \"s\": 9187,\n \"text\": \"The second reason is that the dataset is large and doesn’t fit entirely in ram. Part of the data is stored on disk as well and reading from the disk is much slower than reading from ram.\"\n },\n {\n \"code\": null,\n \"e\": 9497,\n \"s\": 9374,\n \"text\": \"If you prefer using directly SQL instead of DataFrame DSL, you can still use caching, there are some differences, however.\"\n },\n {\n \"code\": null,\n \"e\": 9533,\n \"s\": 9497,\n \"text\": \"spark.sql(\\\"cache table table_name\\\")\"\n },\n {\n \"code\": null,\n \"e\": 9764,\n \"s\": 9533,\n \"text\": \"The main difference is that using SQL the caching is eager by default, so a job will run immediately and will put the data to the caching layer. To make it lazy as it is in the DataFrame DSL we can use the lazy keyword explicitly:\"\n },\n {\n \"code\": null,\n \"e\": 9805,\n \"s\": 9764,\n \"text\": \"spark.sql(\\\"cache lazy table table_name\\\")\"\n },\n {\n \"code\": null,\n \"e\": 9851,\n \"s\": 9805,\n \"text\": \"To remove the data from the cache, just call:\"\n },\n {\n \"code\": null,\n \"e\": 9889,\n \"s\": 9851,\n \"text\": \"spark.sql(\\\"uncache table table_name\\\")\"\n },\n {\n \"code\": null,\n \"e\": 10068,\n \"s\": 9889,\n \"text\": \"Sometimes you may wonder what data is already cached. One possibility is to check Spark UI which provides some basic information about data that is already cached on the cluster.\"\n },\n {\n \"code\": null,\n \"e\": 10287,\n \"s\": 10068,\n \"text\": \"Here for each cached dataset, you can see how much space it takes in memory or on disk. You can even zoom more and click on the record in the table which will take you to another page with details about each partition.\"\n },\n {\n \"code\": null,\n \"e\": 10355,\n \"s\": 10287,\n \"text\": \"To check whether the entire table is cached we can use Catalog API:\"\n },\n {\n \"code\": null,\n \"e\": 10392,\n \"s\": 10355,\n \"text\": \"spark.catalog.isCached(\\\"table_name\\\")\"\n },\n {\n \"code\": null,\n \"e\": 10471,\n \"s\": 10392,\n \"text\": \"The Catalog API can also be used to remove all data from the cache as follows:\"\n },\n {\n \"code\": null,\n \"e\": 10498,\n \"s\": 10471,\n \"text\": \"spark.catalog.clearCache()\"\n },\n {\n \"code\": null,\n \"e\": 10659,\n \"s\": 10498,\n \"text\": \"In Scala API you can also use the internal API of the Cache Manager which provides some functions, for instance, you can ask whether the Cache Manager is empty:\"\n },\n {\n \"code\": null,\n \"e\": 10725,\n \"s\": 10659,\n \"text\": \"// In Scala API:val cm = spark.sharedState.cacheManagercm.isEmpty\"\n },\n {\n \"code\": null,\n \"e\": 10873,\n \"s\": 10725,\n \"text\": \"Caching is one of more techniques that can be used for reusing some computation. Apart from caching there is also checkpointing and exchange-reuse.\"\n },\n {\n \"code\": null,\n \"e\": 11395,\n \"s\": 10873,\n \"text\": \"The checkpointing is useful for instance in situations where we need to break the query plan because it is too large. A large query plan may become a bottleneck in the driver where it is processed because the processing of a very large plan will take to long. The checkpoint will however break the plan and materialize the query. For the next transformations, Spark will start building a new plan. The checkpointing is related to two functions checkpoint and localCheckpoint which differ by the storage used for the data.\"\n },\n {\n \"code\": null,\n \"e\": 11864,\n \"s\": 11395,\n \"text\": \"The exchange-reuse where Spark persists the output of a shuffle on disk, is, on the other hand, a technique that can not be controlled directly by some API function, but instead, it is an internal feature that Spark handles on its own. In some special situations, it can be controlled indirectly by rewriting the query trying to achieve identical exchange branches. To read more about exchange-reuse, you can check my other article, where I describe it more in detail.\"\n }\n]"}}},{"rowIdx":113,"cells":{"title":{"kind":"string","value":"C library function - gmtime()"},"text":{"kind":"string","value":"The C library function struct tm *gmtime(const time_t *timer) uses the value pointed by timer to fill a tm structure with the values that represent the corresponding time, expressed in Coordinated Universal Time (UTC) or GMT timezone.\nFollowing is the declaration for gmtime() function.\nstruct tm *gmtime(const time_t *timer)\ntimeptr − This is the pointer to a time_t value representing a calendar time.\ntimeptr − This is the pointer to a time_t value representing a calendar time.\nThis function returns pointer to a tm structure with the time information filled in. Below is the detail of timeptr structure −\nstruct tm {\n int tm_sec; /* seconds, range 0 to 59 */\n int tm_min; /* minutes, range 0 to 59 */\n int tm_hour; /* hours, range 0 to 23 */\n int tm_mday; /* day of the month, range 1 to 31 */\n int tm_mon; /* month, range 0 to 11 */\n int tm_year; /* The number of years since 1900 */\n int tm_wday; /* day of the week, range 0 to 6 */\n int tm_yday; /* day in the year, range 0 to 365 */\n int tm_isdst; /* daylight saving time */\t\n};\nThe following example shows the usage of gmtime() function.\n#include \n#include \n\n#define BST (+1)\n#define CCT (+8)\n\nint main () {\n\n time_t rawtime;\n struct tm *info;\n\n time(&rawtime);\n /* Get GMT time */\n info = gmtime(&rawtime );\n \n printf(\"Current world clock:\\n\");\n printf(\"London : %2d:%02d\\n\", (info->tm_hour+BST)%24, info->tm_min);\n printf(\"China : %2d:%02d\\n\", (info->tm_hour+CCT)%24, info->tm_min);\n\n return(0);\n}\nLet us compile and run the above program that will produce the following result −\nCurrent world clock:\nLondon : 14:10\nChina : 21:10\n\n\n 12 Lectures \n 2 hours \n\n Nishant Malik\n\n 12 Lectures \n 2.5 hours \n\n Nishant Malik\n\n 48 Lectures \n 6.5 hours \n\n Asif Hussain\n\n 12 Lectures \n 2 hours \n\n Richa Maheshwari\n\n 20 Lectures \n 3.5 hours \n\n Vandana Annavaram\n\n 44 Lectures \n 1 hours \n\n Amit Diwan\n Print\n Add Notes\n Bookmark this page"},"parsed":{"kind":"list like","value":[{"code":null,"e":2242,"s":2007,"text":"The C library function struct tm *gmtime(const time_t *timer) uses the value pointed by timer to fill a tm structure with the values that represent the corresponding time, expressed in Coordinated Universal Time (UTC) or GMT timezone."},{"code":null,"e":2294,"s":2242,"text":"Following is the declaration for gmtime() function."},{"code":null,"e":2333,"s":2294,"text":"struct tm *gmtime(const time_t *timer)"},{"code":null,"e":2411,"s":2333,"text":"timeptr − This is the pointer to a time_t value representing a calendar time."},{"code":null,"e":2489,"s":2411,"text":"timeptr − This is the pointer to a time_t value representing a calendar time."},{"code":null,"e":2617,"s":2489,"text":"This function returns pointer to a tm structure with the time information filled in. Below is the detail of timeptr structure −"},{"code":null,"e":3191,"s":2617,"text":"struct tm {\n int tm_sec; /* seconds, range 0 to 59 */\n int tm_min; /* minutes, range 0 to 59 */\n int tm_hour; /* hours, range 0 to 23 */\n int tm_mday; /* day of the month, range 1 to 31 */\n int tm_mon; /* month, range 0 to 11 */\n int tm_year; /* The number of years since 1900 */\n int tm_wday; /* day of the week, range 0 to 6 */\n int tm_yday; /* day in the year, range 0 to 365 */\n int tm_isdst; /* daylight saving time */\t\n};"},{"code":null,"e":3251,"s":3191,"text":"The following example shows the usage of gmtime() function."},{"code":null,"e":3651,"s":3251,"text":"#include \n#include \n\n#define BST (+1)\n#define CCT (+8)\n\nint main () {\n\n time_t rawtime;\n struct tm *info;\n\n time(&rawtime);\n /* Get GMT time */\n info = gmtime(&rawtime );\n \n printf(\"Current world clock:\\n\");\n printf(\"London : %2d:%02d\\n\", (info->tm_hour+BST)%24, info->tm_min);\n printf(\"China : %2d:%02d\\n\", (info->tm_hour+CCT)%24, info->tm_min);\n\n return(0);\n}"},{"code":null,"e":3733,"s":3651,"text":"Let us compile and run the above program that will produce the following result −"},{"code":null,"e":3784,"s":3733,"text":"Current world clock:\nLondon : 14:10\nChina : 21:10\n"},{"code":null,"e":3817,"s":3784,"text":"\n 12 Lectures \n 2 hours \n"},{"code":null,"e":3832,"s":3817,"text":" Nishant Malik"},{"code":null,"e":3867,"s":3832,"text":"\n 12 Lectures \n 2.5 hours \n"},{"code":null,"e":3882,"s":3867,"text":" Nishant Malik"},{"code":null,"e":3917,"s":3882,"text":"\n 48 Lectures \n 6.5 hours \n"},{"code":null,"e":3931,"s":3917,"text":" Asif Hussain"},{"code":null,"e":3964,"s":3931,"text":"\n 12 Lectures \n 2 hours \n"},{"code":null,"e":3982,"s":3964,"text":" Richa Maheshwari"},{"code":null,"e":4017,"s":3982,"text":"\n 20 Lectures \n 3.5 hours \n"},{"code":null,"e":4036,"s":4017,"text":" Vandana Annavaram"},{"code":null,"e":4069,"s":4036,"text":"\n 44 Lectures \n 1 hours \n"},{"code":null,"e":4081,"s":4069,"text":" Amit Diwan"},{"code":null,"e":4088,"s":4081,"text":" Print"},{"code":null,"e":4099,"s":4088,"text":" Add Notes"}],"string":"[\n {\n \"code\": null,\n \"e\": 2242,\n \"s\": 2007,\n \"text\": \"The C library function struct tm *gmtime(const time_t *timer) uses the value pointed by timer to fill a tm structure with the values that represent the corresponding time, expressed in Coordinated Universal Time (UTC) or GMT timezone.\"\n },\n {\n \"code\": null,\n \"e\": 2294,\n \"s\": 2242,\n \"text\": \"Following is the declaration for gmtime() function.\"\n },\n {\n \"code\": null,\n \"e\": 2333,\n \"s\": 2294,\n \"text\": \"struct tm *gmtime(const time_t *timer)\"\n },\n {\n \"code\": null,\n \"e\": 2411,\n \"s\": 2333,\n \"text\": \"timeptr − This is the pointer to a time_t value representing a calendar time.\"\n },\n {\n \"code\": null,\n \"e\": 2489,\n \"s\": 2411,\n \"text\": \"timeptr − This is the pointer to a time_t value representing a calendar time.\"\n },\n {\n \"code\": null,\n \"e\": 2617,\n \"s\": 2489,\n \"text\": \"This function returns pointer to a tm structure with the time information filled in. Below is the detail of timeptr structure −\"\n },\n {\n \"code\": null,\n \"e\": 3191,\n \"s\": 2617,\n \"text\": \"struct tm {\\n int tm_sec; /* seconds, range 0 to 59 */\\n int tm_min; /* minutes, range 0 to 59 */\\n int tm_hour; /* hours, range 0 to 23 */\\n int tm_mday; /* day of the month, range 1 to 31 */\\n int tm_mon; /* month, range 0 to 11 */\\n int tm_year; /* The number of years since 1900 */\\n int tm_wday; /* day of the week, range 0 to 6 */\\n int tm_yday; /* day in the year, range 0 to 365 */\\n int tm_isdst; /* daylight saving time */\\t\\n};\"\n },\n {\n \"code\": null,\n \"e\": 3251,\n \"s\": 3191,\n \"text\": \"The following example shows the usage of gmtime() function.\"\n },\n {\n \"code\": null,\n \"e\": 3651,\n \"s\": 3251,\n \"text\": \"#include \\n#include \\n\\n#define BST (+1)\\n#define CCT (+8)\\n\\nint main () {\\n\\n time_t rawtime;\\n struct tm *info;\\n\\n time(&rawtime);\\n /* Get GMT time */\\n info = gmtime(&rawtime );\\n \\n printf(\\\"Current world clock:\\\\n\\\");\\n printf(\\\"London : %2d:%02d\\\\n\\\", (info->tm_hour+BST)%24, info->tm_min);\\n printf(\\\"China : %2d:%02d\\\\n\\\", (info->tm_hour+CCT)%24, info->tm_min);\\n\\n return(0);\\n}\"\n },\n {\n \"code\": null,\n \"e\": 3733,\n \"s\": 3651,\n \"text\": \"Let us compile and run the above program that will produce the following result −\"\n },\n {\n \"code\": null,\n \"e\": 3784,\n \"s\": 3733,\n \"text\": \"Current world clock:\\nLondon : 14:10\\nChina : 21:10\\n\"\n },\n {\n \"code\": null,\n \"e\": 3817,\n \"s\": 3784,\n \"text\": \"\\n 12 Lectures \\n 2 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 3832,\n \"s\": 3817,\n \"text\": \" Nishant Malik\"\n },\n {\n \"code\": null,\n \"e\": 3867,\n \"s\": 3832,\n \"text\": \"\\n 12 Lectures \\n 2.5 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 3882,\n \"s\": 3867,\n \"text\": \" Nishant Malik\"\n },\n {\n \"code\": null,\n \"e\": 3917,\n \"s\": 3882,\n \"text\": \"\\n 48 Lectures \\n 6.5 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 3931,\n \"s\": 3917,\n \"text\": \" Asif Hussain\"\n },\n {\n \"code\": null,\n \"e\": 3964,\n \"s\": 3931,\n \"text\": \"\\n 12 Lectures \\n 2 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 3982,\n \"s\": 3964,\n \"text\": \" Richa Maheshwari\"\n },\n {\n \"code\": null,\n \"e\": 4017,\n \"s\": 3982,\n \"text\": \"\\n 20 Lectures \\n 3.5 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 4036,\n \"s\": 4017,\n \"text\": \" Vandana Annavaram\"\n },\n {\n \"code\": null,\n \"e\": 4069,\n \"s\": 4036,\n \"text\": \"\\n 44 Lectures \\n 1 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 4081,\n \"s\": 4069,\n \"text\": \" Amit Diwan\"\n },\n {\n \"code\": null,\n \"e\": 4088,\n \"s\": 4081,\n \"text\": \" Print\"\n },\n {\n \"code\": null,\n \"e\": 4099,\n \"s\": 4088,\n \"text\": \" Add Notes\"\n }\n]"}}},{"rowIdx":114,"cells":{"title":{"kind":"string","value":"Concurrent data pipelines in golang | Towards Data Science"},"text":{"kind":"string","value":"Data is a vital piece for all applications. Applications mainly receive data, process it and then create some sort of output out of it. The amount of data that is available nowadays is immense, which brings many challenges when trying to make sense out of it and transforming it into useful information. Besides the usual data system process, we also have to consider the data that is generated by the execution of such systems, like logs and metrics. Everything is data.\nTherefore, there’s a growing need for data driven applications. It’s not unusual to have systems only dealing with moving and transforming data. From one place to another or from one structure to another. That is even more common in distributed systems, because each system generates data for their own purpose, structured the way it’s easier for them to process. However, those systems still have to communicate, so the data has to be transformed and moved. Moreover, sometimes the data has to be transferred to a different environment, or to a different platform. Even more trouble!\nThere are very sophisticated tools to do this job, but very often they are a real pain to configure and maintain, not to mention the costs involved. Thus they are not always the best option. Some times, depending on the use case, you can create your own pipelines to move data with a simpler solution. In this article we are going to see how to build data pipelines using golang.\nPipelines are a really good way to express how we want to deal with data. By definition, pipelines are a sequence of steps or actions that are executed. Usually the output of a previous step is used as the input for the following step. When pipelines are designed, each step doesn’t have to worry about other steps’ work, relying only on the inputs and outputs contracts. This makes the design very robust, as it’s based on contracts and abstractions. Also it’s a very flexible design as you can add more steps as long as you don’t break the contracts. Fun!\nThere are countless ways of doing it. In this article we will focus on how we can leverage go’s concurrency model, which I wrote about here, to create data pipelines.\nAs we mentioned earlier, data pipelines are a sequence of steps that are executed using the output of a previous step as the input for the next one. That sound like a really good usage for goroutines and channels. We can create each step as a goroutine, and the communications between them as channels. It means that our data pipeline can execute concurrently, which is a great benefit if used wisely. Let’s jump to an example to make things easier.\nIn this example we are going to create a simple pipeline for reading some GUID’s from a text file, transform them into the input data structure we are going to use for processing, fetch related data from an external service and finally persist the data in a data storage using a batch operation. Here’s what the high level workflow looks like:\nAs we can see on this diagram, each operation is going to be created using a goroutine (represented by gophers) and tied together using channels. The whole idea on how to do that is that each function (besides the data generator) will receive its input channel as parameter and return the output channel as the return value of the function. Inside each function we are going to spin a goroutine to actually listen to the input channel and act on each one of the items received, as well as send the result on the output channel.\nAll channels are unbuffered for simplicity, it means that each one of the GUID’s stored on the guids.txt file will pass trough the pipeline individually. The only batch operation will be at the very end, where we persist them into batches to the data storage. Also for simplicity the error handling has been simplified, bear in mind that for a production pipeline you would want to make it more robust. Alright, enough explanation, let’s get cracking with this example. You can find the entire source code in my github repository.\nHere’s what the guids.txt file looks like:\nea464197-d864-4f8a-8a60-2d3a6f3d87bf74c1a7bd-b536-4f9e-be36-5e16c491d833c524c1e9-e473-42eb-b74d-97d82575b720d5003029-7e10-4128-8a18-392e384ef0bdb1fbf405-7b3c-4b82-8b51-4c5c2c0cca56b4f6a28c-86b2-4741-89e5-612451346eb7353629f7-c9ba-4ed1-8e1b-b7694381a36ad3b305cb-eb1b-4f8a-8a23-4741960c26a466c03c1a-45f7-4255-b568-669d9dc553d99272d9f4-da5a-4449-8826-f8529ce4f428\nThe first piece of our pipeline is to read each line of that file, parse it into auuid.UUID type and send it over on a channel. Here’s how this function can look like:\nThe important part here is that we are creating the output channel (line 13) and returning it (line 37), as well as using it on the goroutine that actually does the job of reading the file and sending the parsed uuid.UUID values (line 15). That is very powerful, because it allow us to use that channel as input for another function straight away, without worrying on how the internal job is done. Also important is the fact that we are closing the channel once the job is done, this way we can safely use the for range statement on that channel without worrying about infinite loops. Let’s jump on to our second step, preparing the data:\nHere the function signature changes slightly. We are receiving the channel we want to use as input. However the internal technique of creating the channel output channel (line 16) and returning it (line 26) is still the same. For this specific step we are only using the uuid.UUID received on the input channel and transforming them into a dummy struct inputData as well as logging what is being processed. This is a very basic example, but it illustrates what you can do for data transforming (a very common step in data pipelines) you only have to change apply the same logic for any struct you want. Let’s check a more in depth example with our third step, data fetching:\nThis function uses pretty much the same technique as before, we receive an input channel and return an output channel. In this case I decided to emulate the external call for simplicity, so we are actually generating in memory random related values for a given GUID. The interesting thing here is that we are actually using concurrency to call this (fake) external service. This allows the rest of the pipeline to still run while we are waiting for a specific value to return form the external value. We still want to wait for all the calls to the external service to finish before closing our output channel (saying that our job for this piece of the pipeline is done).\nTo do that I introduced a very common pattern when working with asynchronous calls that need to be synchronised back at some point, using sync.WaitGroup. We wait (synchronise) right before calling the close(oc) on line 29. This way we can make sure that all calls to the external service are finished before closing the channel. It happens because this specific step may run slower than the prior step on the data pipeline, as it depends on external services, so all values may be received from the input channel before we can process all of them, calling the external service.\nThat was a very interesting step, let’s have a look on the last step of our pipeline, the data store:\nIn this step we are introducing a different technique, batching. This may be useful for services where calling each operation for each item is not very efficient in terms of performance or cost. So in order to workaround that we can batch some items together. I created a simple batching mechanism based on the amount of data we want to add to the batch. You can use any mechanism you want, I’m sure the logic will be very similar. In this case we are batching 7 items at once, so every time we have 7 items to persist to the database, we call the persisting function (fake) and open the next batch. Before finishing we are checking if there is an open batch and save it in that case. Also we are returning a channel with the information of what items were saved and a timestamp. Now we only need to put this pipeline together:\nAs you can see we call the pipeline in a reversed order. You can change the parameters to make it more clear if you want. However for this case it is working almost like a decorator pattern. If we start with the generateData() function, that is the one that receives no channels but returns one. So the returned channel from that function is used as input parameter for prepareData. The output channel from that function is used as parameter for the fetchData. The output channel is used finally by saveData as input. The last function also returns a channel, that we are going to range over to print which items have been saved. If we execute this example, we are going to see something like:\n./data-pipeline-golang2020/06/10 09:49:50 Data ready for processing: {id:ea464197-d864-4f8a-8a60-2d3a6f3d87bf timestamp:1591778990056111000}2020/06/10 09:49:50 Data ready for processing: {id:74c1a7bd-b536-4f9e-be36-5e16c491d833 timestamp:1591778990056467000}2020/06/10 09:49:50 Data ready for processing: {id:c524c1e9-e473-42eb-b74d-97d82575b720 timestamp:1591778990056587000}2020/06/10 09:49:50 Data ready for processing: {id:d5003029-7e10-4128-8a18-392e384ef0bd timestamp:1591778990056744000}2020/06/10 09:49:50 Data ready for processing: {id:b1fbf405-7b3c-4b82-8b51-4c5c2c0cca56 timestamp:1591778990056773000}2020/06/10 09:49:50 Data ready for processing: {id:b4f6a28c-86b2-4741-89e5-612451346eb7 timestamp:1591778990056803000}2020/06/10 09:49:50 Data ready for processing: {id:353629f7-c9ba-4ed1-8e1b-b7694381a36a timestamp:1591778990056814000}2020/06/10 09:49:50 Data ready for processing: {id:d3b305cb-eb1b-4f8a-8a23-4741960c26a4 timestamp:1591778990056984000}2020/06/10 09:49:50 Data ready for processing: {id:66c03c1a-45f7-4255-b568-669d9dc553d9 timestamp:1591778990057220000}2020/06/10 09:49:50 Items saved: {idsSaved:[66c03c1a-45f7-4255-b568-669d9dc553d9 c524c1e9-e473-42eb-b74d-97d82575b720 353629f7-c9ba-4ed1-8e1b-b7694381a36a b4f6a28c-86b2-4741-89e5-612451346eb7 74c1a7bd-b536-4f9e-be36-5e16c491d833 b1fbf405-7b3c-4b82-8b51-4c5c2c0cca56 ea464197-d864-4f8a-8a60-2d3a6f3d87bf] timestamp:1591778990097935000}2020/06/10 09:49:50 Items saved: {idsSaved:[d3b305cb-eb1b-4f8a-8a23-4741960c26a4 d5003029-7e10-4128-8a18-392e384ef0bd] timestamp:1591778990105146000}\nWe can see that the prepareData function logged 9 items that were ready for being processed, and the main function logged that 2 batches were actually saved, the first one containing 7 items and the second one containing 2 items.\nCreating data pipelines is a very common task for engineers dealing with data driven or data intensive applications. Data pipelines are essential to transform and move data from one system to another, one platform to another or even one environment to another. If we understand golang’s concurrency model we can leverage that to create concurrent data pipelines in a very clean and easy way. The main pattern used here is to create and return a channel for each step, this way we can easily pipe all steps together. Using this paradigm we can boost our pipeline with all sort of cools things, like parallel execution for steps, multiple workers for a specific pipeline step, so on.\nThis technique is not always the right choice, and there are many tools available out there that can be an easier solution depending on each case."},"parsed":{"kind":"list like","value":[{"code":null,"e":518,"s":46,"text":"Data is a vital piece for all applications. Applications mainly receive data, process it and then create some sort of output out of it. The amount of data that is available nowadays is immense, which brings many challenges when trying to make sense out of it and transforming it into useful information. Besides the usual data system process, we also have to consider the data that is generated by the execution of such systems, like logs and metrics. Everything is data."},{"code":null,"e":1103,"s":518,"text":"Therefore, there’s a growing need for data driven applications. It’s not unusual to have systems only dealing with moving and transforming data. From one place to another or from one structure to another. That is even more common in distributed systems, because each system generates data for their own purpose, structured the way it’s easier for them to process. However, those systems still have to communicate, so the data has to be transformed and moved. Moreover, sometimes the data has to be transferred to a different environment, or to a different platform. Even more trouble!"},{"code":null,"e":1483,"s":1103,"text":"There are very sophisticated tools to do this job, but very often they are a real pain to configure and maintain, not to mention the costs involved. Thus they are not always the best option. Some times, depending on the use case, you can create your own pipelines to move data with a simpler solution. In this article we are going to see how to build data pipelines using golang."},{"code":null,"e":2041,"s":1483,"text":"Pipelines are a really good way to express how we want to deal with data. By definition, pipelines are a sequence of steps or actions that are executed. Usually the output of a previous step is used as the input for the following step. When pipelines are designed, each step doesn’t have to worry about other steps’ work, relying only on the inputs and outputs contracts. This makes the design very robust, as it’s based on contracts and abstractions. Also it’s a very flexible design as you can add more steps as long as you don’t break the contracts. Fun!"},{"code":null,"e":2208,"s":2041,"text":"There are countless ways of doing it. In this article we will focus on how we can leverage go’s concurrency model, which I wrote about here, to create data pipelines."},{"code":null,"e":2658,"s":2208,"text":"As we mentioned earlier, data pipelines are a sequence of steps that are executed using the output of a previous step as the input for the next one. That sound like a really good usage for goroutines and channels. We can create each step as a goroutine, and the communications between them as channels. It means that our data pipeline can execute concurrently, which is a great benefit if used wisely. Let’s jump to an example to make things easier."},{"code":null,"e":3002,"s":2658,"text":"In this example we are going to create a simple pipeline for reading some GUID’s from a text file, transform them into the input data structure we are going to use for processing, fetch related data from an external service and finally persist the data in a data storage using a batch operation. Here’s what the high level workflow looks like:"},{"code":null,"e":3530,"s":3002,"text":"As we can see on this diagram, each operation is going to be created using a goroutine (represented by gophers) and tied together using channels. The whole idea on how to do that is that each function (besides the data generator) will receive its input channel as parameter and return the output channel as the return value of the function. Inside each function we are going to spin a goroutine to actually listen to the input channel and act on each one of the items received, as well as send the result on the output channel."},{"code":null,"e":4061,"s":3530,"text":"All channels are unbuffered for simplicity, it means that each one of the GUID’s stored on the guids.txt file will pass trough the pipeline individually. The only batch operation will be at the very end, where we persist them into batches to the data storage. Also for simplicity the error handling has been simplified, bear in mind that for a production pipeline you would want to make it more robust. Alright, enough explanation, let’s get cracking with this example. You can find the entire source code in my github repository."},{"code":null,"e":4104,"s":4061,"text":"Here’s what the guids.txt file looks like:"},{"code":null,"e":4465,"s":4104,"text":"ea464197-d864-4f8a-8a60-2d3a6f3d87bf74c1a7bd-b536-4f9e-be36-5e16c491d833c524c1e9-e473-42eb-b74d-97d82575b720d5003029-7e10-4128-8a18-392e384ef0bdb1fbf405-7b3c-4b82-8b51-4c5c2c0cca56b4f6a28c-86b2-4741-89e5-612451346eb7353629f7-c9ba-4ed1-8e1b-b7694381a36ad3b305cb-eb1b-4f8a-8a23-4741960c26a466c03c1a-45f7-4255-b568-669d9dc553d99272d9f4-da5a-4449-8826-f8529ce4f428"},{"code":null,"e":4633,"s":4465,"text":"The first piece of our pipeline is to read each line of that file, parse it into auuid.UUID type and send it over on a channel. Here’s how this function can look like:"},{"code":null,"e":5272,"s":4633,"text":"The important part here is that we are creating the output channel (line 13) and returning it (line 37), as well as using it on the goroutine that actually does the job of reading the file and sending the parsed uuid.UUID values (line 15). That is very powerful, because it allow us to use that channel as input for another function straight away, without worrying on how the internal job is done. Also important is the fact that we are closing the channel once the job is done, this way we can safely use the for range statement on that channel without worrying about infinite loops. Let’s jump on to our second step, preparing the data:"},{"code":null,"e":5947,"s":5272,"text":"Here the function signature changes slightly. We are receiving the channel we want to use as input. However the internal technique of creating the channel output channel (line 16) and returning it (line 26) is still the same. For this specific step we are only using the uuid.UUID received on the input channel and transforming them into a dummy struct inputData as well as logging what is being processed. This is a very basic example, but it illustrates what you can do for data transforming (a very common step in data pipelines) you only have to change apply the same logic for any struct you want. Let’s check a more in depth example with our third step, data fetching:"},{"code":null,"e":6618,"s":5947,"text":"This function uses pretty much the same technique as before, we receive an input channel and return an output channel. In this case I decided to emulate the external call for simplicity, so we are actually generating in memory random related values for a given GUID. The interesting thing here is that we are actually using concurrency to call this (fake) external service. This allows the rest of the pipeline to still run while we are waiting for a specific value to return form the external value. We still want to wait for all the calls to the external service to finish before closing our output channel (saying that our job for this piece of the pipeline is done)."},{"code":null,"e":7196,"s":6618,"text":"To do that I introduced a very common pattern when working with asynchronous calls that need to be synchronised back at some point, using sync.WaitGroup. We wait (synchronise) right before calling the close(oc) on line 29. This way we can make sure that all calls to the external service are finished before closing the channel. It happens because this specific step may run slower than the prior step on the data pipeline, as it depends on external services, so all values may be received from the input channel before we can process all of them, calling the external service."},{"code":null,"e":7298,"s":7196,"text":"That was a very interesting step, let’s have a look on the last step of our pipeline, the data store:"},{"code":null,"e":8126,"s":7298,"text":"In this step we are introducing a different technique, batching. This may be useful for services where calling each operation for each item is not very efficient in terms of performance or cost. So in order to workaround that we can batch some items together. I created a simple batching mechanism based on the amount of data we want to add to the batch. You can use any mechanism you want, I’m sure the logic will be very similar. In this case we are batching 7 items at once, so every time we have 7 items to persist to the database, we call the persisting function (fake) and open the next batch. Before finishing we are checking if there is an open batch and save it in that case. Also we are returning a channel with the information of what items were saved and a timestamp. Now we only need to put this pipeline together:"},{"code":null,"e":8820,"s":8126,"text":"As you can see we call the pipeline in a reversed order. You can change the parameters to make it more clear if you want. However for this case it is working almost like a decorator pattern. If we start with the generateData() function, that is the one that receives no channels but returns one. So the returned channel from that function is used as input parameter for prepareData. The output channel from that function is used as parameter for the fetchData. The output channel is used finally by saveData as input. The last function also returns a channel, that we are going to range over to print which items have been saved. If we execute this example, we are going to see something like:"},{"code":null,"e":10388,"s":8820,"text":"./data-pipeline-golang2020/06/10 09:49:50 Data ready for processing: {id:ea464197-d864-4f8a-8a60-2d3a6f3d87bf timestamp:1591778990056111000}2020/06/10 09:49:50 Data ready for processing: {id:74c1a7bd-b536-4f9e-be36-5e16c491d833 timestamp:1591778990056467000}2020/06/10 09:49:50 Data ready for processing: {id:c524c1e9-e473-42eb-b74d-97d82575b720 timestamp:1591778990056587000}2020/06/10 09:49:50 Data ready for processing: {id:d5003029-7e10-4128-8a18-392e384ef0bd timestamp:1591778990056744000}2020/06/10 09:49:50 Data ready for processing: {id:b1fbf405-7b3c-4b82-8b51-4c5c2c0cca56 timestamp:1591778990056773000}2020/06/10 09:49:50 Data ready for processing: {id:b4f6a28c-86b2-4741-89e5-612451346eb7 timestamp:1591778990056803000}2020/06/10 09:49:50 Data ready for processing: {id:353629f7-c9ba-4ed1-8e1b-b7694381a36a timestamp:1591778990056814000}2020/06/10 09:49:50 Data ready for processing: {id:d3b305cb-eb1b-4f8a-8a23-4741960c26a4 timestamp:1591778990056984000}2020/06/10 09:49:50 Data ready for processing: {id:66c03c1a-45f7-4255-b568-669d9dc553d9 timestamp:1591778990057220000}2020/06/10 09:49:50 Items saved: {idsSaved:[66c03c1a-45f7-4255-b568-669d9dc553d9 c524c1e9-e473-42eb-b74d-97d82575b720 353629f7-c9ba-4ed1-8e1b-b7694381a36a b4f6a28c-86b2-4741-89e5-612451346eb7 74c1a7bd-b536-4f9e-be36-5e16c491d833 b1fbf405-7b3c-4b82-8b51-4c5c2c0cca56 ea464197-d864-4f8a-8a60-2d3a6f3d87bf] timestamp:1591778990097935000}2020/06/10 09:49:50 Items saved: {idsSaved:[d3b305cb-eb1b-4f8a-8a23-4741960c26a4 d5003029-7e10-4128-8a18-392e384ef0bd] timestamp:1591778990105146000}"},{"code":null,"e":10618,"s":10388,"text":"We can see that the prepareData function logged 9 items that were ready for being processed, and the main function logged that 2 batches were actually saved, the first one containing 7 items and the second one containing 2 items."},{"code":null,"e":11300,"s":10618,"text":"Creating data pipelines is a very common task for engineers dealing with data driven or data intensive applications. Data pipelines are essential to transform and move data from one system to another, one platform to another or even one environment to another. If we understand golang’s concurrency model we can leverage that to create concurrent data pipelines in a very clean and easy way. The main pattern used here is to create and return a channel for each step, this way we can easily pipe all steps together. Using this paradigm we can boost our pipeline with all sort of cools things, like parallel execution for steps, multiple workers for a specific pipeline step, so on."}],"string":"[\n {\n \"code\": null,\n \"e\": 518,\n \"s\": 46,\n \"text\": \"Data is a vital piece for all applications. Applications mainly receive data, process it and then create some sort of output out of it. The amount of data that is available nowadays is immense, which brings many challenges when trying to make sense out of it and transforming it into useful information. Besides the usual data system process, we also have to consider the data that is generated by the execution of such systems, like logs and metrics. Everything is data.\"\n },\n {\n \"code\": null,\n \"e\": 1103,\n \"s\": 518,\n \"text\": \"Therefore, there’s a growing need for data driven applications. It’s not unusual to have systems only dealing with moving and transforming data. From one place to another or from one structure to another. That is even more common in distributed systems, because each system generates data for their own purpose, structured the way it’s easier for them to process. However, those systems still have to communicate, so the data has to be transformed and moved. Moreover, sometimes the data has to be transferred to a different environment, or to a different platform. Even more trouble!\"\n },\n {\n \"code\": null,\n \"e\": 1483,\n \"s\": 1103,\n \"text\": \"There are very sophisticated tools to do this job, but very often they are a real pain to configure and maintain, not to mention the costs involved. Thus they are not always the best option. Some times, depending on the use case, you can create your own pipelines to move data with a simpler solution. In this article we are going to see how to build data pipelines using golang.\"\n },\n {\n \"code\": null,\n \"e\": 2041,\n \"s\": 1483,\n \"text\": \"Pipelines are a really good way to express how we want to deal with data. By definition, pipelines are a sequence of steps or actions that are executed. Usually the output of a previous step is used as the input for the following step. When pipelines are designed, each step doesn’t have to worry about other steps’ work, relying only on the inputs and outputs contracts. This makes the design very robust, as it’s based on contracts and abstractions. Also it’s a very flexible design as you can add more steps as long as you don’t break the contracts. Fun!\"\n },\n {\n \"code\": null,\n \"e\": 2208,\n \"s\": 2041,\n \"text\": \"There are countless ways of doing it. In this article we will focus on how we can leverage go’s concurrency model, which I wrote about here, to create data pipelines.\"\n },\n {\n \"code\": null,\n \"e\": 2658,\n \"s\": 2208,\n \"text\": \"As we mentioned earlier, data pipelines are a sequence of steps that are executed using the output of a previous step as the input for the next one. That sound like a really good usage for goroutines and channels. We can create each step as a goroutine, and the communications between them as channels. It means that our data pipeline can execute concurrently, which is a great benefit if used wisely. Let’s jump to an example to make things easier.\"\n },\n {\n \"code\": null,\n \"e\": 3002,\n \"s\": 2658,\n \"text\": \"In this example we are going to create a simple pipeline for reading some GUID’s from a text file, transform them into the input data structure we are going to use for processing, fetch related data from an external service and finally persist the data in a data storage using a batch operation. Here’s what the high level workflow looks like:\"\n },\n {\n \"code\": null,\n \"e\": 3530,\n \"s\": 3002,\n \"text\": \"As we can see on this diagram, each operation is going to be created using a goroutine (represented by gophers) and tied together using channels. The whole idea on how to do that is that each function (besides the data generator) will receive its input channel as parameter and return the output channel as the return value of the function. Inside each function we are going to spin a goroutine to actually listen to the input channel and act on each one of the items received, as well as send the result on the output channel.\"\n },\n {\n \"code\": null,\n \"e\": 4061,\n \"s\": 3530,\n \"text\": \"All channels are unbuffered for simplicity, it means that each one of the GUID’s stored on the guids.txt file will pass trough the pipeline individually. The only batch operation will be at the very end, where we persist them into batches to the data storage. Also for simplicity the error handling has been simplified, bear in mind that for a production pipeline you would want to make it more robust. Alright, enough explanation, let’s get cracking with this example. You can find the entire source code in my github repository.\"\n },\n {\n \"code\": null,\n \"e\": 4104,\n \"s\": 4061,\n \"text\": \"Here’s what the guids.txt file looks like:\"\n },\n {\n \"code\": null,\n \"e\": 4465,\n \"s\": 4104,\n \"text\": \"ea464197-d864-4f8a-8a60-2d3a6f3d87bf74c1a7bd-b536-4f9e-be36-5e16c491d833c524c1e9-e473-42eb-b74d-97d82575b720d5003029-7e10-4128-8a18-392e384ef0bdb1fbf405-7b3c-4b82-8b51-4c5c2c0cca56b4f6a28c-86b2-4741-89e5-612451346eb7353629f7-c9ba-4ed1-8e1b-b7694381a36ad3b305cb-eb1b-4f8a-8a23-4741960c26a466c03c1a-45f7-4255-b568-669d9dc553d99272d9f4-da5a-4449-8826-f8529ce4f428\"\n },\n {\n \"code\": null,\n \"e\": 4633,\n \"s\": 4465,\n \"text\": \"The first piece of our pipeline is to read each line of that file, parse it into auuid.UUID type and send it over on a channel. Here’s how this function can look like:\"\n },\n {\n \"code\": null,\n \"e\": 5272,\n \"s\": 4633,\n \"text\": \"The important part here is that we are creating the output channel (line 13) and returning it (line 37), as well as using it on the goroutine that actually does the job of reading the file and sending the parsed uuid.UUID values (line 15). That is very powerful, because it allow us to use that channel as input for another function straight away, without worrying on how the internal job is done. Also important is the fact that we are closing the channel once the job is done, this way we can safely use the for range statement on that channel without worrying about infinite loops. Let’s jump on to our second step, preparing the data:\"\n },\n {\n \"code\": null,\n \"e\": 5947,\n \"s\": 5272,\n \"text\": \"Here the function signature changes slightly. We are receiving the channel we want to use as input. However the internal technique of creating the channel output channel (line 16) and returning it (line 26) is still the same. For this specific step we are only using the uuid.UUID received on the input channel and transforming them into a dummy struct inputData as well as logging what is being processed. This is a very basic example, but it illustrates what you can do for data transforming (a very common step in data pipelines) you only have to change apply the same logic for any struct you want. Let’s check a more in depth example with our third step, data fetching:\"\n },\n {\n \"code\": null,\n \"e\": 6618,\n \"s\": 5947,\n \"text\": \"This function uses pretty much the same technique as before, we receive an input channel and return an output channel. In this case I decided to emulate the external call for simplicity, so we are actually generating in memory random related values for a given GUID. The interesting thing here is that we are actually using concurrency to call this (fake) external service. This allows the rest of the pipeline to still run while we are waiting for a specific value to return form the external value. We still want to wait for all the calls to the external service to finish before closing our output channel (saying that our job for this piece of the pipeline is done).\"\n },\n {\n \"code\": null,\n \"e\": 7196,\n \"s\": 6618,\n \"text\": \"To do that I introduced a very common pattern when working with asynchronous calls that need to be synchronised back at some point, using sync.WaitGroup. We wait (synchronise) right before calling the close(oc) on line 29. This way we can make sure that all calls to the external service are finished before closing the channel. It happens because this specific step may run slower than the prior step on the data pipeline, as it depends on external services, so all values may be received from the input channel before we can process all of them, calling the external service.\"\n },\n {\n \"code\": null,\n \"e\": 7298,\n \"s\": 7196,\n \"text\": \"That was a very interesting step, let’s have a look on the last step of our pipeline, the data store:\"\n },\n {\n \"code\": null,\n \"e\": 8126,\n \"s\": 7298,\n \"text\": \"In this step we are introducing a different technique, batching. This may be useful for services where calling each operation for each item is not very efficient in terms of performance or cost. So in order to workaround that we can batch some items together. I created a simple batching mechanism based on the amount of data we want to add to the batch. You can use any mechanism you want, I’m sure the logic will be very similar. In this case we are batching 7 items at once, so every time we have 7 items to persist to the database, we call the persisting function (fake) and open the next batch. Before finishing we are checking if there is an open batch and save it in that case. Also we are returning a channel with the information of what items were saved and a timestamp. Now we only need to put this pipeline together:\"\n },\n {\n \"code\": null,\n \"e\": 8820,\n \"s\": 8126,\n \"text\": \"As you can see we call the pipeline in a reversed order. You can change the parameters to make it more clear if you want. However for this case it is working almost like a decorator pattern. If we start with the generateData() function, that is the one that receives no channels but returns one. So the returned channel from that function is used as input parameter for prepareData. The output channel from that function is used as parameter for the fetchData. The output channel is used finally by saveData as input. The last function also returns a channel, that we are going to range over to print which items have been saved. If we execute this example, we are going to see something like:\"\n },\n {\n \"code\": null,\n \"e\": 10388,\n \"s\": 8820,\n \"text\": \"./data-pipeline-golang2020/06/10 09:49:50 Data ready for processing: {id:ea464197-d864-4f8a-8a60-2d3a6f3d87bf timestamp:1591778990056111000}2020/06/10 09:49:50 Data ready for processing: {id:74c1a7bd-b536-4f9e-be36-5e16c491d833 timestamp:1591778990056467000}2020/06/10 09:49:50 Data ready for processing: {id:c524c1e9-e473-42eb-b74d-97d82575b720 timestamp:1591778990056587000}2020/06/10 09:49:50 Data ready for processing: {id:d5003029-7e10-4128-8a18-392e384ef0bd timestamp:1591778990056744000}2020/06/10 09:49:50 Data ready for processing: {id:b1fbf405-7b3c-4b82-8b51-4c5c2c0cca56 timestamp:1591778990056773000}2020/06/10 09:49:50 Data ready for processing: {id:b4f6a28c-86b2-4741-89e5-612451346eb7 timestamp:1591778990056803000}2020/06/10 09:49:50 Data ready for processing: {id:353629f7-c9ba-4ed1-8e1b-b7694381a36a timestamp:1591778990056814000}2020/06/10 09:49:50 Data ready for processing: {id:d3b305cb-eb1b-4f8a-8a23-4741960c26a4 timestamp:1591778990056984000}2020/06/10 09:49:50 Data ready for processing: {id:66c03c1a-45f7-4255-b568-669d9dc553d9 timestamp:1591778990057220000}2020/06/10 09:49:50 Items saved: {idsSaved:[66c03c1a-45f7-4255-b568-669d9dc553d9 c524c1e9-e473-42eb-b74d-97d82575b720 353629f7-c9ba-4ed1-8e1b-b7694381a36a b4f6a28c-86b2-4741-89e5-612451346eb7 74c1a7bd-b536-4f9e-be36-5e16c491d833 b1fbf405-7b3c-4b82-8b51-4c5c2c0cca56 ea464197-d864-4f8a-8a60-2d3a6f3d87bf] timestamp:1591778990097935000}2020/06/10 09:49:50 Items saved: {idsSaved:[d3b305cb-eb1b-4f8a-8a23-4741960c26a4 d5003029-7e10-4128-8a18-392e384ef0bd] timestamp:1591778990105146000}\"\n },\n {\n \"code\": null,\n \"e\": 10618,\n \"s\": 10388,\n \"text\": \"We can see that the prepareData function logged 9 items that were ready for being processed, and the main function logged that 2 batches were actually saved, the first one containing 7 items and the second one containing 2 items.\"\n },\n {\n \"code\": null,\n \"e\": 11300,\n \"s\": 10618,\n \"text\": \"Creating data pipelines is a very common task for engineers dealing with data driven or data intensive applications. Data pipelines are essential to transform and move data from one system to another, one platform to another or even one environment to another. If we understand golang’s concurrency model we can leverage that to create concurrent data pipelines in a very clean and easy way. The main pattern used here is to create and return a channel for each step, this way we can easily pipe all steps together. Using this paradigm we can boost our pipeline with all sort of cools things, like parallel execution for steps, multiple workers for a specific pipeline step, so on.\"\n }\n]"}}},{"rowIdx":115,"cells":{"title":{"kind":"string","value":"Understanding and Writing your first Text Mining Script with R | by Lorna Maria A | Towards Data Science"},"text":{"kind":"string","value":"One of the reasons data science has become popular is because of it’s ability to reveal so much information on large data sets in a split second or just a query.\nThink about it deeply ,on a daily basis how much information in form of text do we give out? All this information contains our sentiments,our opinions ,our plans ,pieces of advice ,our favourite phrase among other things.\nHowever revealing each of those this can seem like finding a needle from a haystack at a glance ,until we use techniques like text mining/analysis .\nText mining takes in account information retrieval ,analysis and study of word frequencies and pattern recognition to aid visualisation and predictive analytics.\nIn this article ,We go through the major steps that a data set undergoes to get ready for further analysis.we shall write our script using R and the code will be written in R studio .\nTo achieve our goal ,we shall use an R package called “tm”.This package supports all text mining functions like loading data,cleaning data and building a term matrix.It is available on CRAN.\n#downloading and installing the package from CRANinstall.packages(\"tm\")#loading tmlibrary(tm)\nText to be mined can be loaded into R from different source formats.It can come from text files(.txt),pdfs (.pdf),csv files(.csv) e.t.c ,but no matter the source format ,to be used in the tm package it is turned into a “corpus”.\nA corpus is defined as “a collection of written texts, especially the entire works of a particular author or a body of writing on a particular subject”.\nThe tm package use the Corpus() function to create a corpus.\n#loading a text file from local computernewdata<- readlines(filepath)#Load data as corpus#VectorSource() creates character vectorsmydata <- Corpus(VectorSource(newdata))\nRefer to this guide to learn more about importing files into R.\nOnce we have successfully loaded the data into the work space,it is time to clean this data .Our goal at this step is to create independent terms(words) from the data file before we can start counting how frequent they appear.\nSince R is case sensitive ,we shall first convert the entire text to lowercase to avoid considering same words like “write” and “Write” differently.\nWe shall remove : URLs ,emojis,non-english words,punctuations,numbers,whitespace and stop words.\nStop words: The commonly used english words like “a”,” is ”,”the” in the tm package are referred to as stop words. These words have to be eliminated so as to render the results more accurate.It is also possible to create your own custom stop words.\n# convert to lower casemydata <- tm_map(mydata, content_transformer(tolower))#remove ������ what would be emojismydata<-tm_map(mydata, content_transformer(gsub), pattern=\"\\\\W\",replace=\" \")# remove URLsremoveURL <- function(x) gsub(\"http[^[:space:]]*\", \"\", x)mydata <- tm_map(mydata, content_transformer(removeURL))# remove anything other than English letters or spaceremoveNumPunct <- function(x) gsub(\"[^[:alpha:][:space:]]*\", \"\", x)mydata <- tm_map(mydata, content_transformer(removeNumPunct))# remove stopwordsmydata <- tm_map(mydata, removeWords, stopwords(\"english\"))#u can create custom stop words using the code below.#myStopwords <- c(setdiff(stopwords('english'), c(\"r\", \"big\")),\"use\", \"see\", \"used\", \"via\", \"amp\")#mydata <- tm_map(mydata, removeWords, myStopwords)# remove extra whitespacemydata <- tm_map(mydata, stripWhitespace)# Remove numbersmydata <- tm_map(mydata, removeNumbers)# Remove punctuationsmydata <- tm_map(mydata, removePunctuation)\nStemming is the process of gathering words of similar origin into one word for example “communication”, “communicates”, “communicate”. Stemming helps us increase accuracy in our mined text by removing suffixes and reducing words to their basic forms.We shall use the SnowballC library.\nlibrary(SnowballC)mydata <- tm_map(mydata, stemDocument)\nAfter the cleaning process ,we are left with independent terms that exist throughout the document.These are stored in a matrix that shows each of their occurrence. This matrix logs the number of times the term appears in our clean data set thus being called a term matrix.\n#create a term matrix and store it as dtmdtm <- TermDocumentMatrix(mydata)\nWord frequencies : These are the number of times words appear in data set.Word frequencies will indicate to us from the most frequently used words in the data set to the least used using the compilation of occurrences from the term matrix.\nWe have just written a basic text mining script ,however it is just the beginning of text mining.The ability to get the text in its raw format and clean it to this point will give us direction to things like building a word cloud,sentiment analysis and building models.\nHold on to this script because it will come in handy when we start doing sentiment analysis.\nFeel free to reach out to me with any question > @lornamariak ."},"parsed":{"kind":"list like","value":[{"code":null,"e":209,"s":47,"text":"One of the reasons data science has become popular is because of it’s ability to reveal so much information on large data sets in a split second or just a query."},{"code":null,"e":431,"s":209,"text":"Think about it deeply ,on a daily basis how much information in form of text do we give out? All this information contains our sentiments,our opinions ,our plans ,pieces of advice ,our favourite phrase among other things."},{"code":null,"e":580,"s":431,"text":"However revealing each of those this can seem like finding a needle from a haystack at a glance ,until we use techniques like text mining/analysis ."},{"code":null,"e":742,"s":580,"text":"Text mining takes in account information retrieval ,analysis and study of word frequencies and pattern recognition to aid visualisation and predictive analytics."},{"code":null,"e":926,"s":742,"text":"In this article ,We go through the major steps that a data set undergoes to get ready for further analysis.we shall write our script using R and the code will be written in R studio ."},{"code":null,"e":1117,"s":926,"text":"To achieve our goal ,we shall use an R package called “tm”.This package supports all text mining functions like loading data,cleaning data and building a term matrix.It is available on CRAN."},{"code":null,"e":1211,"s":1117,"text":"#downloading and installing the package from CRANinstall.packages(\"tm\")#loading tmlibrary(tm)"},{"code":null,"e":1440,"s":1211,"text":"Text to be mined can be loaded into R from different source formats.It can come from text files(.txt),pdfs (.pdf),csv files(.csv) e.t.c ,but no matter the source format ,to be used in the tm package it is turned into a “corpus”."},{"code":null,"e":1593,"s":1440,"text":"A corpus is defined as “a collection of written texts, especially the entire works of a particular author or a body of writing on a particular subject”."},{"code":null,"e":1654,"s":1593,"text":"The tm package use the Corpus() function to create a corpus."},{"code":null,"e":1824,"s":1654,"text":"#loading a text file from local computernewdata<- readlines(filepath)#Load data as corpus#VectorSource() creates character vectorsmydata <- Corpus(VectorSource(newdata))"},{"code":null,"e":1888,"s":1824,"text":"Refer to this guide to learn more about importing files into R."},{"code":null,"e":2115,"s":1888,"text":"Once we have successfully loaded the data into the work space,it is time to clean this data .Our goal at this step is to create independent terms(words) from the data file before we can start counting how frequent they appear."},{"code":null,"e":2264,"s":2115,"text":"Since R is case sensitive ,we shall first convert the entire text to lowercase to avoid considering same words like “write” and “Write” differently."},{"code":null,"e":2361,"s":2264,"text":"We shall remove : URLs ,emojis,non-english words,punctuations,numbers,whitespace and stop words."},{"code":null,"e":2610,"s":2361,"text":"Stop words: The commonly used english words like “a”,” is ”,”the” in the tm package are referred to as stop words. These words have to be eliminated so as to render the results more accurate.It is also possible to create your own custom stop words."},{"code":null,"e":3570,"s":2610,"text":"# convert to lower casemydata <- tm_map(mydata, content_transformer(tolower))#remove ������ what would be emojismydata<-tm_map(mydata, content_transformer(gsub), pattern=\"\\\\W\",replace=\" \")# remove URLsremoveURL <- function(x) gsub(\"http[^[:space:]]*\", \"\", x)mydata <- tm_map(mydata, content_transformer(removeURL))# remove anything other than English letters or spaceremoveNumPunct <- function(x) gsub(\"[^[:alpha:][:space:]]*\", \"\", x)mydata <- tm_map(mydata, content_transformer(removeNumPunct))# remove stopwordsmydata <- tm_map(mydata, removeWords, stopwords(\"english\"))#u can create custom stop words using the code below.#myStopwords <- c(setdiff(stopwords('english'), c(\"r\", \"big\")),\"use\", \"see\", \"used\", \"via\", \"amp\")#mydata <- tm_map(mydata, removeWords, myStopwords)# remove extra whitespacemydata <- tm_map(mydata, stripWhitespace)# Remove numbersmydata <- tm_map(mydata, removeNumbers)# Remove punctuationsmydata <- tm_map(mydata, removePunctuation)"},{"code":null,"e":3856,"s":3570,"text":"Stemming is the process of gathering words of similar origin into one word for example “communication”, “communicates”, “communicate”. Stemming helps us increase accuracy in our mined text by removing suffixes and reducing words to their basic forms.We shall use the SnowballC library."},{"code":null,"e":3913,"s":3856,"text":"library(SnowballC)mydata <- tm_map(mydata, stemDocument)"},{"code":null,"e":4186,"s":3913,"text":"After the cleaning process ,we are left with independent terms that exist throughout the document.These are stored in a matrix that shows each of their occurrence. This matrix logs the number of times the term appears in our clean data set thus being called a term matrix."},{"code":null,"e":4261,"s":4186,"text":"#create a term matrix and store it as dtmdtm <- TermDocumentMatrix(mydata)"},{"code":null,"e":4501,"s":4261,"text":"Word frequencies : These are the number of times words appear in data set.Word frequencies will indicate to us from the most frequently used words in the data set to the least used using the compilation of occurrences from the term matrix."},{"code":null,"e":4771,"s":4501,"text":"We have just written a basic text mining script ,however it is just the beginning of text mining.The ability to get the text in its raw format and clean it to this point will give us direction to things like building a word cloud,sentiment analysis and building models."},{"code":null,"e":4864,"s":4771,"text":"Hold on to this script because it will come in handy when we start doing sentiment analysis."}],"string":"[\n {\n \"code\": null,\n \"e\": 209,\n \"s\": 47,\n \"text\": \"One of the reasons data science has become popular is because of it’s ability to reveal so much information on large data sets in a split second or just a query.\"\n },\n {\n \"code\": null,\n \"e\": 431,\n \"s\": 209,\n \"text\": \"Think about it deeply ,on a daily basis how much information in form of text do we give out? All this information contains our sentiments,our opinions ,our plans ,pieces of advice ,our favourite phrase among other things.\"\n },\n {\n \"code\": null,\n \"e\": 580,\n \"s\": 431,\n \"text\": \"However revealing each of those this can seem like finding a needle from a haystack at a glance ,until we use techniques like text mining/analysis .\"\n },\n {\n \"code\": null,\n \"e\": 742,\n \"s\": 580,\n \"text\": \"Text mining takes in account information retrieval ,analysis and study of word frequencies and pattern recognition to aid visualisation and predictive analytics.\"\n },\n {\n \"code\": null,\n \"e\": 926,\n \"s\": 742,\n \"text\": \"In this article ,We go through the major steps that a data set undergoes to get ready for further analysis.we shall write our script using R and the code will be written in R studio .\"\n },\n {\n \"code\": null,\n \"e\": 1117,\n \"s\": 926,\n \"text\": \"To achieve our goal ,we shall use an R package called “tm”.This package supports all text mining functions like loading data,cleaning data and building a term matrix.It is available on CRAN.\"\n },\n {\n \"code\": null,\n \"e\": 1211,\n \"s\": 1117,\n \"text\": \"#downloading and installing the package from CRANinstall.packages(\\\"tm\\\")#loading tmlibrary(tm)\"\n },\n {\n \"code\": null,\n \"e\": 1440,\n \"s\": 1211,\n \"text\": \"Text to be mined can be loaded into R from different source formats.It can come from text files(.txt),pdfs (.pdf),csv files(.csv) e.t.c ,but no matter the source format ,to be used in the tm package it is turned into a “corpus”.\"\n },\n {\n \"code\": null,\n \"e\": 1593,\n \"s\": 1440,\n \"text\": \"A corpus is defined as “a collection of written texts, especially the entire works of a particular author or a body of writing on a particular subject”.\"\n },\n {\n \"code\": null,\n \"e\": 1654,\n \"s\": 1593,\n \"text\": \"The tm package use the Corpus() function to create a corpus.\"\n },\n {\n \"code\": null,\n \"e\": 1824,\n \"s\": 1654,\n \"text\": \"#loading a text file from local computernewdata<- readlines(filepath)#Load data as corpus#VectorSource() creates character vectorsmydata <- Corpus(VectorSource(newdata))\"\n },\n {\n \"code\": null,\n \"e\": 1888,\n \"s\": 1824,\n \"text\": \"Refer to this guide to learn more about importing files into R.\"\n },\n {\n \"code\": null,\n \"e\": 2115,\n \"s\": 1888,\n \"text\": \"Once we have successfully loaded the data into the work space,it is time to clean this data .Our goal at this step is to create independent terms(words) from the data file before we can start counting how frequent they appear.\"\n },\n {\n \"code\": null,\n \"e\": 2264,\n \"s\": 2115,\n \"text\": \"Since R is case sensitive ,we shall first convert the entire text to lowercase to avoid considering same words like “write” and “Write” differently.\"\n },\n {\n \"code\": null,\n \"e\": 2361,\n \"s\": 2264,\n \"text\": \"We shall remove : URLs ,emojis,non-english words,punctuations,numbers,whitespace and stop words.\"\n },\n {\n \"code\": null,\n \"e\": 2610,\n \"s\": 2361,\n \"text\": \"Stop words: The commonly used english words like “a”,” is ”,”the” in the tm package are referred to as stop words. These words have to be eliminated so as to render the results more accurate.It is also possible to create your own custom stop words.\"\n },\n {\n \"code\": null,\n \"e\": 3570,\n \"s\": 2610,\n \"text\": \"# convert to lower casemydata <- tm_map(mydata, content_transformer(tolower))#remove ������ what would be emojismydata<-tm_map(mydata, content_transformer(gsub), pattern=\\\"\\\\\\\\W\\\",replace=\\\" \\\")# remove URLsremoveURL <- function(x) gsub(\\\"http[^[:space:]]*\\\", \\\"\\\", x)mydata <- tm_map(mydata, content_transformer(removeURL))# remove anything other than English letters or spaceremoveNumPunct <- function(x) gsub(\\\"[^[:alpha:][:space:]]*\\\", \\\"\\\", x)mydata <- tm_map(mydata, content_transformer(removeNumPunct))# remove stopwordsmydata <- tm_map(mydata, removeWords, stopwords(\\\"english\\\"))#u can create custom stop words using the code below.#myStopwords <- c(setdiff(stopwords('english'), c(\\\"r\\\", \\\"big\\\")),\\\"use\\\", \\\"see\\\", \\\"used\\\", \\\"via\\\", \\\"amp\\\")#mydata <- tm_map(mydata, removeWords, myStopwords)# remove extra whitespacemydata <- tm_map(mydata, stripWhitespace)# Remove numbersmydata <- tm_map(mydata, removeNumbers)# Remove punctuationsmydata <- tm_map(mydata, removePunctuation)\"\n },\n {\n \"code\": null,\n \"e\": 3856,\n \"s\": 3570,\n \"text\": \"Stemming is the process of gathering words of similar origin into one word for example “communication”, “communicates”, “communicate”. Stemming helps us increase accuracy in our mined text by removing suffixes and reducing words to their basic forms.We shall use the SnowballC library.\"\n },\n {\n \"code\": null,\n \"e\": 3913,\n \"s\": 3856,\n \"text\": \"library(SnowballC)mydata <- tm_map(mydata, stemDocument)\"\n },\n {\n \"code\": null,\n \"e\": 4186,\n \"s\": 3913,\n \"text\": \"After the cleaning process ,we are left with independent terms that exist throughout the document.These are stored in a matrix that shows each of their occurrence. This matrix logs the number of times the term appears in our clean data set thus being called a term matrix.\"\n },\n {\n \"code\": null,\n \"e\": 4261,\n \"s\": 4186,\n \"text\": \"#create a term matrix and store it as dtmdtm <- TermDocumentMatrix(mydata)\"\n },\n {\n \"code\": null,\n \"e\": 4501,\n \"s\": 4261,\n \"text\": \"Word frequencies : These are the number of times words appear in data set.Word frequencies will indicate to us from the most frequently used words in the data set to the least used using the compilation of occurrences from the term matrix.\"\n },\n {\n \"code\": null,\n \"e\": 4771,\n \"s\": 4501,\n \"text\": \"We have just written a basic text mining script ,however it is just the beginning of text mining.The ability to get the text in its raw format and clean it to this point will give us direction to things like building a word cloud,sentiment analysis and building models.\"\n },\n {\n \"code\": null,\n \"e\": 4864,\n \"s\": 4771,\n \"text\": \"Hold on to this script because it will come in handy when we start doing sentiment analysis.\"\n }\n]"}}},{"rowIdx":116,"cells":{"title":{"kind":"string","value":"How to merge two lists in Python | Merging two Lists in Python"},"text":{"kind":"string","value":"PROGRAMMINGJava ExamplesC Examples\nJava Examples\nC Examples\nC Tutorials\naws\nJAVAEXCEPTIONSCOLLECTIONSSWINGJDBC\nEXCEPTIONS\nCOLLECTIONS\nSWING\nJDBC\nJAVA 8\nSPRING\nSPRING BOOT\nHIBERNATE\nPYTHON\nPHP\nJQUERY\nPROGRAMMINGJava ExamplesC Examples\nJava Examples\nC Examples\nC Tutorials\naws\nThere are different ways to merge two lists in python. According to our python version and packages installed, we can use any one of them to merge two lists.\n#Input\nlist1 = [10, 20, 30]\nlist2 = [40, 50, 60]\n#Output\n[10, 20, 30, 40, 50, 60]\n\nWe can simply merge two lists using + operator like below.\nlist1 = [10, 20, 30]\nlist2 = [40, 50, 60]\nmerged_list = list1+list2\n\nprint(\"Merged List: \",merged_list)\n\n#It is also equivalent to above code using +=\n\nlist1 += list2\nprint(\"Merged List using +=: \",list1)\nThe above solution internally creates a new list (merged_list) with a shallow copy of list1 and is concatenated with a shallow copy of list2.\nOutput:\nMerged List: [10, 20, 30, 40, 50, 60]\nMerged List using +=: [10, 20, 30, 40, 50, 60]\nIf you are using python >= 3.5 version the PEP additional unpacking generations allows you to concatenate lists using * operator.\nlist1 = [10, 20, 30]\nlist2 = [40, 50, 60]\n\nmergedList = [*list1, *list2]\nprint(mergedList)\nOutput:\n[10, 20, 30, 40, 50, 60]\nThe itertools allows us to chain the multiple lists so that the simple solution is to iterating the items in both the lists and generate a new list (or we can even use for processing).\nimport itertools\n\nlist1 = [10, 20, 30]\nlist2 = [40, 50, 60]\n\nfor item in itertools.chain(list1, list2):\n print(item)\n\nOutput:\n10\n20\n30\n40\n50\n60\nAs we know, the list allows duplicate items. So if we wanted to remove duplicates while merging two lists, we could use the below solution.\nlist1 = [10, 20, 30, 40]\nlist2 = [30, 40, 50, 60]\n\nmerged_list = list(set(list1+list2))\nprint(\"Merged List with out duplicates: \",merged_list)\nOutput:\nMerged List with out duplicates: [40, 10, 50, 20, 60, 30]\nWe can even extend the list by appending another list using the list.extend().\nlist1 = [10, 20, 30, 40]\nlist2 = [30, 40, 50, 60]\n\nlist1.extend(list2)\nprint(list1)\nOutput:\n[10, 20, 30, 40, 30, 40, 50, 60]\nPython List in depth\nPython more on Lists\nHappy Learning 🙂\n\nPython List Data Structure In Depth\nPython Set Data Structure in Depth\nPython Tuple Data Structure in Depth\nHow to Convert Python List Of Objects to CSV File\nPython – How to merge two dict in Python ?\nJava 8 How to get common elements from two lists\nHow to Read CSV File in Python\nPython – How to remove key from dictionary ?\nHow to get the size of a Directory in Python ?\nPython – How to remove duplicate elements from List\nPython – Print different vowels present in a String\nPython – Find the biggest of 2 given numbers\nHow to Remove Spaces from String in Python\nHow to get Words Count in Python from a File\nHow to get Characters Count in Python from a File\n\nPython List Data Structure In Depth\nPython Set Data Structure in Depth\nPython Tuple Data Structure in Depth\nHow to Convert Python List Of Objects to CSV File\nPython – How to merge two dict in Python ?\nJava 8 How to get common elements from two lists\nHow to Read CSV File in Python\nPython – How to remove key from dictionary ?\nHow to get the size of a Directory in Python ?\nPython – How to remove duplicate elements from List\nPython – Print different vowels present in a String\nPython – Find the biggest of 2 given numbers\nHow to Remove Spaces from String in Python\nHow to get Words Count in Python from a File\nHow to get Characters Count in Python from a File\n \n\n\nΔ\n Python – Introduction\n Python – Features\n Python – Install on Windows\n Python – Modes of Program\n Python – Number System\n Python – Identifiers\n Python – Operators\n Python – Ternary Operator\n Python – Command Line Arguments\n Python – Keywords\n Python – Data Types\n Python – Upgrade Python PIP\n Python – Virtual Environment\n Pyhton – Type Casting\n Python – String to Int\n Python – Conditional Statements\n Python – if statement\n Python – *args and **kwargs\n Python – Date Formatting\n Python – Read input from keyboard\n Python – raw_input\n Python – List In Depth\n Python – List Comprehension\n Python – Set in Depth\n Python – Dictionary in Depth\n Python – Tuple in Depth\n Python – Stack Datastructure\n Python – Classes and Objects\n Python – Constructors\n Python – Object Introspection\n Python – Inheritance\n Python – Decorators\n Python – Serialization with Pickle\n Python – Exceptions Handling\n Python – User defined Exceptions\n Python – Multiprocessing\n Python – Default function parameters\n Python – Lambdas Functions\n Python – NumPy Library\n Python – MySQL Connector\n Python – MySQL Create Database\n Python – MySQL Read Data\n Python – MySQL Insert Data\n Python – MySQL Update Records\n Python – MySQL Delete Records\n Python – String Case Conversion\n Howto – Find biggest of 2 numbers\n Howto – Remove duplicates from List\n Howto – Convert any Number to Binary\n Howto – Merge two Lists\n Howto – Merge two dicts\n Howto – Get Characters Count in a File\n Howto – Get Words Count in a File\n Howto – Remove Spaces from String\n Howto – Read Env variables\n Howto – Read a text File\n Howto – Read a JSON File\n Howto – Read Config.ini files\n Howto – Iterate Dictionary\n Howto – Convert List Of Objects to CSV\n Howto – Merge two dict in Python\n Howto – create Zip File\n Howto – Get OS info\n Howto – Get size of Directory\n Howto – Check whether a file exists\n Howto – Remove key from dictionary\n Howto – Sort Objects\n Howto – Create or Delete Directories\n Howto – Read CSV File\n Howto – Create Python Iterable class\n Howto – Access for loop index\n Howto – Clear all elements from List\n Howto – Remove empty lists from a List\n Howto – Remove special characters from String\n Howto – Sort dictionary by key\n Howto – Filter a list"},"parsed":{"kind":"list like","value":[{"code":null,"e":158,"s":123,"text":"PROGRAMMINGJava ExamplesC Examples"},{"code":null,"e":172,"s":158,"text":"Java Examples"},{"code":null,"e":183,"s":172,"text":"C Examples"},{"code":null,"e":195,"s":183,"text":"C Tutorials"},{"code":null,"e":199,"s":195,"text":"aws"},{"code":null,"e":234,"s":199,"text":"JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"},{"code":null,"e":245,"s":234,"text":"EXCEPTIONS"},{"code":null,"e":257,"s":245,"text":"COLLECTIONS"},{"code":null,"e":263,"s":257,"text":"SWING"},{"code":null,"e":268,"s":263,"text":"JDBC"},{"code":null,"e":275,"s":268,"text":"JAVA 8"},{"code":null,"e":282,"s":275,"text":"SPRING"},{"code":null,"e":294,"s":282,"text":"SPRING BOOT"},{"code":null,"e":304,"s":294,"text":"HIBERNATE"},{"code":null,"e":311,"s":304,"text":"PYTHON"},{"code":null,"e":315,"s":311,"text":"PHP"},{"code":null,"e":322,"s":315,"text":"JQUERY"},{"code":null,"e":357,"s":322,"text":"PROGRAMMINGJava ExamplesC Examples"},{"code":null,"e":371,"s":357,"text":"Java Examples"},{"code":null,"e":382,"s":371,"text":"C Examples"},{"code":null,"e":394,"s":382,"text":"C Tutorials"},{"code":null,"e":398,"s":394,"text":"aws"},{"code":null,"e":556,"s":398,"text":"There are different ways to merge two lists in python. According to our python version and packages installed, we can use any one of them to merge two lists."},{"code":null,"e":639,"s":556,"text":"#Input\nlist1 = [10, 20, 30]\nlist2 = [40, 50, 60]\n#Output\n[10, 20, 30, 40, 50, 60]\n"},{"code":null,"e":698,"s":639,"text":"We can simply merge two lists using + operator like below."},{"code":null,"e":903,"s":698,"text":"list1 = [10, 20, 30]\nlist2 = [40, 50, 60]\nmerged_list = list1+list2\n\nprint(\"Merged List: \",merged_list)\n\n#It is also equivalent to above code using +=\n\nlist1 += list2\nprint(\"Merged List using +=: \",list1)"},{"code":null,"e":1045,"s":903,"text":"The above solution internally creates a new list (merged_list) with a shallow copy of list1 and is concatenated with a shallow copy of list2."},{"code":null,"e":1053,"s":1045,"text":"Output:"},{"code":null,"e":1139,"s":1053,"text":"Merged List: [10, 20, 30, 40, 50, 60]\nMerged List using +=: [10, 20, 30, 40, 50, 60]"},{"code":null,"e":1269,"s":1139,"text":"If you are using python >= 3.5 version the PEP additional unpacking generations allows you to concatenate lists using * operator."},{"code":null,"e":1360,"s":1269,"text":"list1 = [10, 20, 30]\nlist2 = [40, 50, 60]\n\nmergedList = [*list1, *list2]\nprint(mergedList)"},{"code":null,"e":1368,"s":1360,"text":"Output:"},{"code":null,"e":1393,"s":1368,"text":"[10, 20, 30, 40, 50, 60]"},{"code":null,"e":1578,"s":1393,"text":"The itertools allows us to chain the multiple lists so that the simple solution is to iterating the items in both the lists and generate a new list (or we can even use for processing)."},{"code":null,"e":1699,"s":1578,"text":"import itertools\n\nlist1 = [10, 20, 30]\nlist2 = [40, 50, 60]\n\nfor item in itertools.chain(list1, list2):\n print(item)\n"},{"code":null,"e":1707,"s":1699,"text":"Output:"},{"code":null,"e":1725,"s":1707,"text":"10\n20\n30\n40\n50\n60"},{"code":null,"e":1865,"s":1725,"text":"As we know, the list allows duplicate items. So if we wanted to remove duplicates while merging two lists, we could use the below solution."},{"code":null,"e":2008,"s":1865,"text":"list1 = [10, 20, 30, 40]\nlist2 = [30, 40, 50, 60]\n\nmerged_list = list(set(list1+list2))\nprint(\"Merged List with out duplicates: \",merged_list)"},{"code":null,"e":2016,"s":2008,"text":"Output:"},{"code":null,"e":2075,"s":2016,"text":"Merged List with out duplicates: [40, 10, 50, 20, 60, 30]"},{"code":null,"e":2154,"s":2075,"text":"We can even extend the list by appending another list using the list.extend()."},{"code":null,"e":2238,"s":2154,"text":"list1 = [10, 20, 30, 40]\nlist2 = [30, 40, 50, 60]\n\nlist1.extend(list2)\nprint(list1)"},{"code":null,"e":2246,"s":2238,"text":"Output:"},{"code":null,"e":2279,"s":2246,"text":"[10, 20, 30, 40, 30, 40, 50, 60]"},{"code":null,"e":2300,"s":2279,"text":"Python List in depth"},{"code":null,"e":2321,"s":2300,"text":"Python more on Lists"},{"code":null,"e":2338,"s":2321,"text":"Happy Learning 🙂"},{"code":null,"e":3000,"s":2338,"text":"\nPython List Data Structure In Depth\nPython Set Data Structure in Depth\nPython Tuple Data Structure in Depth\nHow to Convert Python List Of Objects to CSV File\nPython – How to merge two dict in Python ?\nJava 8 How to get common elements from two lists\nHow to Read CSV File in Python\nPython – How to remove key from dictionary ?\nHow to get the size of a Directory in Python ?\nPython – How to remove duplicate elements from List\nPython – Print different vowels present in a String\nPython – Find the biggest of 2 given numbers\nHow to Remove Spaces from String in Python\nHow to get Words Count in Python from a File\nHow to get Characters Count in Python from a File\n"},{"code":null,"e":3036,"s":3000,"text":"Python List Data Structure In Depth"},{"code":null,"e":3071,"s":3036,"text":"Python Set Data Structure in Depth"},{"code":null,"e":3108,"s":3071,"text":"Python Tuple Data Structure in Depth"},{"code":null,"e":3158,"s":3108,"text":"How to Convert Python List Of Objects to CSV File"},{"code":null,"e":3201,"s":3158,"text":"Python – How to merge two dict in Python ?"},{"code":null,"e":3250,"s":3201,"text":"Java 8 How to get common elements from two lists"},{"code":null,"e":3281,"s":3250,"text":"How to Read CSV File in Python"},{"code":null,"e":3326,"s":3281,"text":"Python – How to remove key from dictionary ?"},{"code":null,"e":3373,"s":3326,"text":"How to get the size of a Directory in Python ?"},{"code":null,"e":3425,"s":3373,"text":"Python – How to remove duplicate elements from List"},{"code":null,"e":3477,"s":3425,"text":"Python – Print different vowels present in a String"},{"code":null,"e":3522,"s":3477,"text":"Python – Find the biggest of 2 given numbers"},{"code":null,"e":3565,"s":3522,"text":"How to Remove Spaces from String in Python"},{"code":null,"e":3610,"s":3565,"text":"How to get Words Count in Python from a File"},{"code":null,"e":3660,"s":3610,"text":"How to get Characters Count in Python from a File"},{"code":null,"e":3666,"s":3664,"text":"Δ"},{"code":null,"e":3689,"s":3666,"text":" Python – Introduction"},{"code":null,"e":3708,"s":3689,"text":" Python – Features"},{"code":null,"e":3737,"s":3708,"text":" Python – Install on Windows"},{"code":null,"e":3764,"s":3737,"text":" Python – Modes of Program"},{"code":null,"e":3788,"s":3764,"text":" Python – Number System"},{"code":null,"e":3810,"s":3788,"text":" Python – Identifiers"},{"code":null,"e":3830,"s":3810,"text":" Python – Operators"},{"code":null,"e":3857,"s":3830,"text":" Python – Ternary Operator"},{"code":null,"e":3890,"s":3857,"text":" Python – Command Line Arguments"},{"code":null,"e":3909,"s":3890,"text":" Python – Keywords"},{"code":null,"e":3930,"s":3909,"text":" Python – Data Types"},{"code":null,"e":3959,"s":3930,"text":" Python – Upgrade Python PIP"},{"code":null,"e":3989,"s":3959,"text":" Python – Virtual Environment"},{"code":null,"e":4012,"s":3989,"text":" Pyhton – Type Casting"},{"code":null,"e":4036,"s":4012,"text":" Python – String to Int"},{"code":null,"e":4069,"s":4036,"text":" Python – Conditional Statements"},{"code":null,"e":4092,"s":4069,"text":" Python – if statement"},{"code":null,"e":4121,"s":4092,"text":" Python – *args and **kwargs"},{"code":null,"e":4147,"s":4121,"text":" Python – Date Formatting"},{"code":null,"e":4182,"s":4147,"text":" Python – Read input from keyboard"},{"code":null,"e":4202,"s":4182,"text":" Python – raw_input"},{"code":null,"e":4226,"s":4202,"text":" Python – List In Depth"},{"code":null,"e":4255,"s":4226,"text":" Python – List Comprehension"},{"code":null,"e":4278,"s":4255,"text":" Python – Set in Depth"},{"code":null,"e":4308,"s":4278,"text":" Python – Dictionary in Depth"},{"code":null,"e":4333,"s":4308,"text":" Python – Tuple in Depth"},{"code":null,"e":4363,"s":4333,"text":" Python – Stack Datastructure"},{"code":null,"e":4393,"s":4363,"text":" Python – Classes and Objects"},{"code":null,"e":4416,"s":4393,"text":" Python – Constructors"},{"code":null,"e":4447,"s":4416,"text":" Python – Object Introspection"},{"code":null,"e":4469,"s":4447,"text":" Python – Inheritance"},{"code":null,"e":4490,"s":4469,"text":" Python – Decorators"},{"code":null,"e":4526,"s":4490,"text":" Python – Serialization with Pickle"},{"code":null,"e":4556,"s":4526,"text":" Python – Exceptions Handling"},{"code":null,"e":4590,"s":4556,"text":" Python – User defined Exceptions"},{"code":null,"e":4616,"s":4590,"text":" Python – Multiprocessing"},{"code":null,"e":4654,"s":4616,"text":" Python – Default function parameters"},{"code":null,"e":4682,"s":4654,"text":" Python – Lambdas Functions"},{"code":null,"e":4706,"s":4682,"text":" Python – NumPy Library"},{"code":null,"e":4732,"s":4706,"text":" Python – MySQL Connector"},{"code":null,"e":4764,"s":4732,"text":" Python – MySQL Create Database"},{"code":null,"e":4790,"s":4764,"text":" Python – MySQL Read Data"},{"code":null,"e":4818,"s":4790,"text":" Python – MySQL Insert Data"},{"code":null,"e":4849,"s":4818,"text":" Python – MySQL Update Records"},{"code":null,"e":4880,"s":4849,"text":" Python – MySQL Delete Records"},{"code":null,"e":4913,"s":4880,"text":" Python – String Case Conversion"},{"code":null,"e":4948,"s":4913,"text":" Howto – Find biggest of 2 numbers"},{"code":null,"e":4985,"s":4948,"text":" Howto – Remove duplicates from List"},{"code":null,"e":5023,"s":4985,"text":" Howto – Convert any Number to Binary"},{"code":null,"e":5049,"s":5023,"text":" Howto – Merge two Lists"},{"code":null,"e":5074,"s":5049,"text":" Howto – Merge two dicts"},{"code":null,"e":5114,"s":5074,"text":" Howto – Get Characters Count in a File"},{"code":null,"e":5149,"s":5114,"text":" Howto – Get Words Count in a File"},{"code":null,"e":5184,"s":5149,"text":" Howto – Remove Spaces from String"},{"code":null,"e":5213,"s":5184,"text":" Howto – Read Env variables"},{"code":null,"e":5239,"s":5213,"text":" Howto – Read a text File"},{"code":null,"e":5265,"s":5239,"text":" Howto – Read a JSON File"},{"code":null,"e":5297,"s":5265,"text":" Howto – Read Config.ini files"},{"code":null,"e":5325,"s":5297,"text":" Howto – Iterate Dictionary"},{"code":null,"e":5365,"s":5325,"text":" Howto – Convert List Of Objects to CSV"},{"code":null,"e":5399,"s":5365,"text":" Howto – Merge two dict in Python"},{"code":null,"e":5424,"s":5399,"text":" Howto – create Zip File"},{"code":null,"e":5445,"s":5424,"text":" Howto – Get OS info"},{"code":null,"e":5476,"s":5445,"text":" Howto – Get size of Directory"},{"code":null,"e":5513,"s":5476,"text":" Howto – Check whether a file exists"},{"code":null,"e":5550,"s":5513,"text":" Howto – Remove key from dictionary"},{"code":null,"e":5572,"s":5550,"text":" Howto – Sort Objects"},{"code":null,"e":5610,"s":5572,"text":" Howto – Create or Delete Directories"},{"code":null,"e":5633,"s":5610,"text":" Howto – Read CSV File"},{"code":null,"e":5671,"s":5633,"text":" Howto – Create Python Iterable class"},{"code":null,"e":5702,"s":5671,"text":" Howto – Access for loop index"},{"code":null,"e":5740,"s":5702,"text":" Howto – Clear all elements from List"},{"code":null,"e":5780,"s":5740,"text":" Howto – Remove empty lists from a List"},{"code":null,"e":5827,"s":5780,"text":" Howto – Remove special characters from String"},{"code":null,"e":5859,"s":5827,"text":" Howto – Sort dictionary by key"}],"string":"[\n {\n \"code\": null,\n \"e\": 158,\n \"s\": 123,\n \"text\": \"PROGRAMMINGJava ExamplesC Examples\"\n },\n {\n \"code\": null,\n \"e\": 172,\n \"s\": 158,\n \"text\": \"Java Examples\"\n },\n {\n \"code\": null,\n \"e\": 183,\n \"s\": 172,\n \"text\": \"C Examples\"\n },\n {\n \"code\": null,\n \"e\": 195,\n \"s\": 183,\n \"text\": \"C Tutorials\"\n },\n {\n \"code\": null,\n \"e\": 199,\n \"s\": 195,\n \"text\": \"aws\"\n },\n {\n \"code\": null,\n \"e\": 234,\n \"s\": 199,\n \"text\": \"JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC\"\n },\n {\n \"code\": null,\n \"e\": 245,\n \"s\": 234,\n \"text\": \"EXCEPTIONS\"\n },\n {\n \"code\": null,\n \"e\": 257,\n \"s\": 245,\n \"text\": \"COLLECTIONS\"\n },\n {\n \"code\": null,\n \"e\": 263,\n \"s\": 257,\n \"text\": \"SWING\"\n },\n {\n \"code\": null,\n \"e\": 268,\n \"s\": 263,\n \"text\": \"JDBC\"\n },\n {\n \"code\": null,\n \"e\": 275,\n \"s\": 268,\n \"text\": \"JAVA 8\"\n },\n {\n \"code\": null,\n \"e\": 282,\n \"s\": 275,\n \"text\": \"SPRING\"\n },\n {\n \"code\": null,\n \"e\": 294,\n \"s\": 282,\n \"text\": \"SPRING BOOT\"\n },\n {\n \"code\": null,\n \"e\": 304,\n \"s\": 294,\n \"text\": \"HIBERNATE\"\n },\n {\n \"code\": null,\n \"e\": 311,\n \"s\": 304,\n \"text\": \"PYTHON\"\n },\n {\n \"code\": null,\n \"e\": 315,\n \"s\": 311,\n \"text\": \"PHP\"\n },\n {\n \"code\": null,\n \"e\": 322,\n \"s\": 315,\n \"text\": \"JQUERY\"\n },\n {\n \"code\": null,\n \"e\": 357,\n \"s\": 322,\n \"text\": \"PROGRAMMINGJava ExamplesC Examples\"\n },\n {\n \"code\": null,\n \"e\": 371,\n \"s\": 357,\n \"text\": \"Java Examples\"\n },\n {\n \"code\": null,\n \"e\": 382,\n \"s\": 371,\n \"text\": \"C Examples\"\n },\n {\n \"code\": null,\n \"e\": 394,\n \"s\": 382,\n \"text\": \"C Tutorials\"\n },\n {\n \"code\": null,\n \"e\": 398,\n \"s\": 394,\n \"text\": \"aws\"\n },\n {\n \"code\": null,\n \"e\": 556,\n \"s\": 398,\n \"text\": \"There are different ways to merge two lists in python. According to our python version and packages installed, we can use any one of them to merge two lists.\"\n },\n {\n \"code\": null,\n \"e\": 639,\n \"s\": 556,\n \"text\": \"#Input\\nlist1 = [10, 20, 30]\\nlist2 = [40, 50, 60]\\n#Output\\n[10, 20, 30, 40, 50, 60]\\n\"\n },\n {\n \"code\": null,\n \"e\": 698,\n \"s\": 639,\n \"text\": \"We can simply merge two lists using + operator like below.\"\n },\n {\n \"code\": null,\n \"e\": 903,\n \"s\": 698,\n \"text\": \"list1 = [10, 20, 30]\\nlist2 = [40, 50, 60]\\nmerged_list = list1+list2\\n\\nprint(\\\"Merged List: \\\",merged_list)\\n\\n#It is also equivalent to above code using +=\\n\\nlist1 += list2\\nprint(\\\"Merged List using +=: \\\",list1)\"\n },\n {\n \"code\": null,\n \"e\": 1045,\n \"s\": 903,\n \"text\": \"The above solution internally creates a new list (merged_list) with a shallow copy of list1 and is concatenated with a shallow copy of list2.\"\n },\n {\n \"code\": null,\n \"e\": 1053,\n \"s\": 1045,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 1139,\n \"s\": 1053,\n \"text\": \"Merged List: [10, 20, 30, 40, 50, 60]\\nMerged List using +=: [10, 20, 30, 40, 50, 60]\"\n },\n {\n \"code\": null,\n \"e\": 1269,\n \"s\": 1139,\n \"text\": \"If you are using python >= 3.5 version the PEP additional unpacking generations allows you to concatenate lists using * operator.\"\n },\n {\n \"code\": null,\n \"e\": 1360,\n \"s\": 1269,\n \"text\": \"list1 = [10, 20, 30]\\nlist2 = [40, 50, 60]\\n\\nmergedList = [*list1, *list2]\\nprint(mergedList)\"\n },\n {\n \"code\": null,\n \"e\": 1368,\n \"s\": 1360,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 1393,\n \"s\": 1368,\n \"text\": \"[10, 20, 30, 40, 50, 60]\"\n },\n {\n \"code\": null,\n \"e\": 1578,\n \"s\": 1393,\n \"text\": \"The itertools allows us to chain the multiple lists so that the simple solution is to iterating the items in both the lists and generate a new list (or we can even use for processing).\"\n },\n {\n \"code\": null,\n \"e\": 1699,\n \"s\": 1578,\n \"text\": \"import itertools\\n\\nlist1 = [10, 20, 30]\\nlist2 = [40, 50, 60]\\n\\nfor item in itertools.chain(list1, list2):\\n print(item)\\n\"\n },\n {\n \"code\": null,\n \"e\": 1707,\n \"s\": 1699,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 1725,\n \"s\": 1707,\n \"text\": \"10\\n20\\n30\\n40\\n50\\n60\"\n },\n {\n \"code\": null,\n \"e\": 1865,\n \"s\": 1725,\n \"text\": \"As we know, the list allows duplicate items. So if we wanted to remove duplicates while merging two lists, we could use the below solution.\"\n },\n {\n \"code\": null,\n \"e\": 2008,\n \"s\": 1865,\n \"text\": \"list1 = [10, 20, 30, 40]\\nlist2 = [30, 40, 50, 60]\\n\\nmerged_list = list(set(list1+list2))\\nprint(\\\"Merged List with out duplicates: \\\",merged_list)\"\n },\n {\n \"code\": null,\n \"e\": 2016,\n \"s\": 2008,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 2075,\n \"s\": 2016,\n \"text\": \"Merged List with out duplicates: [40, 10, 50, 20, 60, 30]\"\n },\n {\n \"code\": null,\n \"e\": 2154,\n \"s\": 2075,\n \"text\": \"We can even extend the list by appending another list using the list.extend().\"\n },\n {\n \"code\": null,\n \"e\": 2238,\n \"s\": 2154,\n \"text\": \"list1 = [10, 20, 30, 40]\\nlist2 = [30, 40, 50, 60]\\n\\nlist1.extend(list2)\\nprint(list1)\"\n },\n {\n \"code\": null,\n \"e\": 2246,\n \"s\": 2238,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 2279,\n \"s\": 2246,\n \"text\": \"[10, 20, 30, 40, 30, 40, 50, 60]\"\n },\n {\n \"code\": null,\n \"e\": 2300,\n \"s\": 2279,\n \"text\": \"Python List in depth\"\n },\n {\n \"code\": null,\n \"e\": 2321,\n \"s\": 2300,\n \"text\": \"Python more on Lists\"\n },\n {\n \"code\": null,\n \"e\": 2338,\n \"s\": 2321,\n \"text\": \"Happy Learning 🙂\"\n },\n {\n \"code\": null,\n \"e\": 3000,\n \"s\": 2338,\n \"text\": \"\\nPython List Data Structure In Depth\\nPython Set Data Structure in Depth\\nPython Tuple Data Structure in Depth\\nHow to Convert Python List Of Objects to CSV File\\nPython – How to merge two dict in Python ?\\nJava 8 How to get common elements from two lists\\nHow to Read CSV File in Python\\nPython – How to remove key from dictionary ?\\nHow to get the size of a Directory in Python ?\\nPython – How to remove duplicate elements from List\\nPython – Print different vowels present in a String\\nPython – Find the biggest of 2 given numbers\\nHow to Remove Spaces from String in Python\\nHow to get Words Count in Python from a File\\nHow to get Characters Count in Python from a File\\n\"\n },\n {\n \"code\": null,\n \"e\": 3036,\n \"s\": 3000,\n \"text\": \"Python List Data Structure In Depth\"\n },\n {\n \"code\": null,\n \"e\": 3071,\n \"s\": 3036,\n \"text\": \"Python Set Data Structure in Depth\"\n },\n {\n \"code\": null,\n \"e\": 3108,\n \"s\": 3071,\n \"text\": \"Python Tuple Data Structure in Depth\"\n },\n {\n \"code\": null,\n \"e\": 3158,\n \"s\": 3108,\n \"text\": \"How to Convert Python List Of Objects to CSV File\"\n },\n {\n \"code\": null,\n \"e\": 3201,\n \"s\": 3158,\n \"text\": \"Python – How to merge two dict in Python ?\"\n },\n {\n \"code\": null,\n \"e\": 3250,\n \"s\": 3201,\n \"text\": \"Java 8 How to get common elements from two lists\"\n },\n {\n \"code\": null,\n \"e\": 3281,\n \"s\": 3250,\n \"text\": \"How to Read CSV File in Python\"\n },\n {\n \"code\": null,\n \"e\": 3326,\n \"s\": 3281,\n \"text\": \"Python – How to remove key from dictionary ?\"\n },\n {\n \"code\": null,\n \"e\": 3373,\n \"s\": 3326,\n \"text\": \"How to get the size of a Directory in Python ?\"\n },\n {\n \"code\": null,\n \"e\": 3425,\n \"s\": 3373,\n \"text\": \"Python – How to remove duplicate elements from List\"\n },\n {\n \"code\": null,\n \"e\": 3477,\n \"s\": 3425,\n \"text\": \"Python – Print different vowels present in a String\"\n },\n {\n \"code\": null,\n \"e\": 3522,\n \"s\": 3477,\n \"text\": \"Python – Find the biggest of 2 given numbers\"\n },\n {\n \"code\": null,\n \"e\": 3565,\n \"s\": 3522,\n \"text\": \"How to Remove Spaces from String in Python\"\n },\n {\n \"code\": null,\n \"e\": 3610,\n \"s\": 3565,\n \"text\": \"How to get Words Count in Python from a File\"\n },\n {\n \"code\": null,\n \"e\": 3660,\n \"s\": 3610,\n \"text\": \"How to get Characters Count in Python from a File\"\n },\n {\n \"code\": null,\n \"e\": 3666,\n \"s\": 3664,\n \"text\": \"Δ\"\n },\n {\n \"code\": null,\n \"e\": 3689,\n \"s\": 3666,\n \"text\": \" Python – Introduction\"\n },\n {\n \"code\": null,\n \"e\": 3708,\n \"s\": 3689,\n \"text\": \" Python – Features\"\n },\n {\n \"code\": null,\n \"e\": 3737,\n \"s\": 3708,\n \"text\": \" Python – Install on Windows\"\n },\n {\n \"code\": null,\n \"e\": 3764,\n \"s\": 3737,\n \"text\": \" Python – Modes of Program\"\n },\n {\n \"code\": null,\n \"e\": 3788,\n \"s\": 3764,\n \"text\": \" Python – Number System\"\n },\n {\n \"code\": null,\n \"e\": 3810,\n \"s\": 3788,\n \"text\": \" Python – Identifiers\"\n },\n {\n \"code\": null,\n \"e\": 3830,\n \"s\": 3810,\n \"text\": \" Python – Operators\"\n },\n {\n \"code\": null,\n \"e\": 3857,\n \"s\": 3830,\n \"text\": \" Python – Ternary Operator\"\n },\n {\n \"code\": null,\n \"e\": 3890,\n \"s\": 3857,\n \"text\": \" Python – Command Line Arguments\"\n },\n {\n \"code\": null,\n \"e\": 3909,\n \"s\": 3890,\n \"text\": \" Python – Keywords\"\n },\n {\n \"code\": null,\n \"e\": 3930,\n \"s\": 3909,\n \"text\": \" Python – Data Types\"\n },\n {\n \"code\": null,\n \"e\": 3959,\n \"s\": 3930,\n \"text\": \" Python – Upgrade Python PIP\"\n },\n {\n \"code\": null,\n \"e\": 3989,\n \"s\": 3959,\n \"text\": \" Python – Virtual Environment\"\n },\n {\n \"code\": null,\n \"e\": 4012,\n \"s\": 3989,\n \"text\": \" Pyhton – Type Casting\"\n },\n {\n \"code\": null,\n \"e\": 4036,\n \"s\": 4012,\n \"text\": \" Python – String to Int\"\n },\n {\n \"code\": null,\n \"e\": 4069,\n \"s\": 4036,\n \"text\": \" Python – Conditional Statements\"\n },\n {\n \"code\": null,\n \"e\": 4092,\n \"s\": 4069,\n \"text\": \" Python – if statement\"\n },\n {\n \"code\": null,\n \"e\": 4121,\n \"s\": 4092,\n \"text\": \" Python – *args and **kwargs\"\n },\n {\n \"code\": null,\n \"e\": 4147,\n \"s\": 4121,\n \"text\": \" Python – Date Formatting\"\n },\n {\n \"code\": null,\n \"e\": 4182,\n \"s\": 4147,\n \"text\": \" Python – Read input from keyboard\"\n },\n {\n \"code\": null,\n \"e\": 4202,\n \"s\": 4182,\n \"text\": \" Python – raw_input\"\n },\n {\n \"code\": null,\n \"e\": 4226,\n \"s\": 4202,\n \"text\": \" Python – List In Depth\"\n },\n {\n \"code\": null,\n \"e\": 4255,\n \"s\": 4226,\n \"text\": \" Python – List Comprehension\"\n },\n {\n \"code\": null,\n \"e\": 4278,\n \"s\": 4255,\n \"text\": \" Python – Set in Depth\"\n },\n {\n \"code\": null,\n \"e\": 4308,\n \"s\": 4278,\n \"text\": \" Python – Dictionary in Depth\"\n },\n {\n \"code\": null,\n \"e\": 4333,\n \"s\": 4308,\n \"text\": \" Python – Tuple in Depth\"\n },\n {\n \"code\": null,\n \"e\": 4363,\n \"s\": 4333,\n \"text\": \" Python – Stack Datastructure\"\n },\n {\n \"code\": null,\n \"e\": 4393,\n \"s\": 4363,\n \"text\": \" Python – Classes and Objects\"\n },\n {\n \"code\": null,\n \"e\": 4416,\n \"s\": 4393,\n \"text\": \" Python – Constructors\"\n },\n {\n \"code\": null,\n \"e\": 4447,\n \"s\": 4416,\n \"text\": \" Python – Object Introspection\"\n },\n {\n \"code\": null,\n \"e\": 4469,\n \"s\": 4447,\n \"text\": \" Python – Inheritance\"\n },\n {\n \"code\": null,\n \"e\": 4490,\n \"s\": 4469,\n \"text\": \" Python – Decorators\"\n },\n {\n \"code\": null,\n \"e\": 4526,\n \"s\": 4490,\n \"text\": \" Python – Serialization with Pickle\"\n },\n {\n \"code\": null,\n \"e\": 4556,\n \"s\": 4526,\n \"text\": \" Python – Exceptions Handling\"\n },\n {\n \"code\": null,\n \"e\": 4590,\n \"s\": 4556,\n \"text\": \" Python – User defined Exceptions\"\n },\n {\n \"code\": null,\n \"e\": 4616,\n \"s\": 4590,\n \"text\": \" Python – Multiprocessing\"\n },\n {\n \"code\": null,\n \"e\": 4654,\n \"s\": 4616,\n \"text\": \" Python – Default function parameters\"\n },\n {\n \"code\": null,\n \"e\": 4682,\n \"s\": 4654,\n \"text\": \" Python – Lambdas Functions\"\n },\n {\n \"code\": null,\n \"e\": 4706,\n \"s\": 4682,\n \"text\": \" Python – NumPy Library\"\n },\n {\n \"code\": null,\n \"e\": 4732,\n \"s\": 4706,\n \"text\": \" Python – MySQL Connector\"\n },\n {\n \"code\": null,\n \"e\": 4764,\n \"s\": 4732,\n \"text\": \" Python – MySQL Create Database\"\n },\n {\n \"code\": null,\n \"e\": 4790,\n \"s\": 4764,\n \"text\": \" Python – MySQL Read Data\"\n },\n {\n \"code\": null,\n \"e\": 4818,\n \"s\": 4790,\n \"text\": \" Python – MySQL Insert Data\"\n },\n {\n \"code\": null,\n \"e\": 4849,\n \"s\": 4818,\n \"text\": \" Python – MySQL Update Records\"\n },\n {\n \"code\": null,\n \"e\": 4880,\n \"s\": 4849,\n \"text\": \" Python – MySQL Delete Records\"\n },\n {\n \"code\": null,\n \"e\": 4913,\n \"s\": 4880,\n \"text\": \" Python – String Case Conversion\"\n },\n {\n \"code\": null,\n \"e\": 4948,\n \"s\": 4913,\n \"text\": \" Howto – Find biggest of 2 numbers\"\n },\n {\n \"code\": null,\n \"e\": 4985,\n \"s\": 4948,\n \"text\": \" Howto – Remove duplicates from List\"\n },\n {\n \"code\": null,\n \"e\": 5023,\n \"s\": 4985,\n \"text\": \" Howto – Convert any Number to Binary\"\n },\n {\n \"code\": null,\n \"e\": 5049,\n \"s\": 5023,\n \"text\": \" Howto – Merge two Lists\"\n },\n {\n \"code\": null,\n \"e\": 5074,\n \"s\": 5049,\n \"text\": \" Howto – Merge two dicts\"\n },\n {\n \"code\": null,\n \"e\": 5114,\n \"s\": 5074,\n \"text\": \" Howto – Get Characters Count in a File\"\n },\n {\n \"code\": null,\n \"e\": 5149,\n \"s\": 5114,\n \"text\": \" Howto – Get Words Count in a File\"\n },\n {\n \"code\": null,\n \"e\": 5184,\n \"s\": 5149,\n \"text\": \" Howto – Remove Spaces from String\"\n },\n {\n \"code\": null,\n \"e\": 5213,\n \"s\": 5184,\n \"text\": \" Howto – Read Env variables\"\n },\n {\n \"code\": null,\n \"e\": 5239,\n \"s\": 5213,\n \"text\": \" Howto – Read a text File\"\n },\n {\n \"code\": null,\n \"e\": 5265,\n \"s\": 5239,\n \"text\": \" Howto – Read a JSON File\"\n },\n {\n \"code\": null,\n \"e\": 5297,\n \"s\": 5265,\n \"text\": \" Howto – Read Config.ini files\"\n },\n {\n \"code\": null,\n \"e\": 5325,\n \"s\": 5297,\n \"text\": \" Howto – Iterate Dictionary\"\n },\n {\n \"code\": null,\n \"e\": 5365,\n \"s\": 5325,\n \"text\": \" Howto – Convert List Of Objects to CSV\"\n },\n {\n \"code\": null,\n \"e\": 5399,\n \"s\": 5365,\n \"text\": \" Howto – Merge two dict in Python\"\n },\n {\n \"code\": null,\n \"e\": 5424,\n \"s\": 5399,\n \"text\": \" Howto – create Zip File\"\n },\n {\n \"code\": null,\n \"e\": 5445,\n \"s\": 5424,\n \"text\": \" Howto – Get OS info\"\n },\n {\n \"code\": null,\n \"e\": 5476,\n \"s\": 5445,\n \"text\": \" Howto – Get size of Directory\"\n },\n {\n \"code\": null,\n \"e\": 5513,\n \"s\": 5476,\n \"text\": \" Howto – Check whether a file exists\"\n },\n {\n \"code\": null,\n \"e\": 5550,\n \"s\": 5513,\n \"text\": \" Howto – Remove key from dictionary\"\n },\n {\n \"code\": null,\n \"e\": 5572,\n \"s\": 5550,\n \"text\": \" Howto – Sort Objects\"\n },\n {\n \"code\": null,\n \"e\": 5610,\n \"s\": 5572,\n \"text\": \" Howto – Create or Delete Directories\"\n },\n {\n \"code\": null,\n \"e\": 5633,\n \"s\": 5610,\n \"text\": \" Howto – Read CSV File\"\n },\n {\n \"code\": null,\n \"e\": 5671,\n \"s\": 5633,\n \"text\": \" Howto – Create Python Iterable class\"\n },\n {\n \"code\": null,\n \"e\": 5702,\n \"s\": 5671,\n \"text\": \" Howto – Access for loop index\"\n },\n {\n \"code\": null,\n \"e\": 5740,\n \"s\": 5702,\n \"text\": \" Howto – Clear all elements from List\"\n },\n {\n \"code\": null,\n \"e\": 5780,\n \"s\": 5740,\n \"text\": \" Howto – Remove empty lists from a List\"\n },\n {\n \"code\": null,\n \"e\": 5827,\n \"s\": 5780,\n \"text\": \" Howto – Remove special characters from String\"\n },\n {\n \"code\": null,\n \"e\": 5859,\n \"s\": 5827,\n \"text\": \" Howto – Sort dictionary by key\"\n }\n]"}}},{"rowIdx":117,"cells":{"title":{"kind":"string","value":"Find a form feed character with JavaScript RegExp."},"text":{"kind":"string","value":"To find a form feed character with JavaScript Regular Expression, use the following −\n\\f\nYou can try to run the following code to find a form feed character. It returns the position where the form feed (\\f) character is found −\n\n \n JavaScript Regular Expression\n \n \n \n \n"},"parsed":{"kind":"list like","value":[{"code":null,"e":1148,"s":1062,"text":"To find a form feed character with JavaScript Regular Expression, use the following −"},{"code":null,"e":1151,"s":1148,"text":"\\f"},{"code":null,"e":1290,"s":1151,"text":"You can try to run the following code to find a form feed character. It returns the position where the form feed (\\f) character is found −"},{"code":null,"e":1580,"s":1290,"text":"\n \n JavaScript Regular Expression\n \n \n \n \n"}],"string":"[\n {\n \"code\": null,\n \"e\": 1148,\n \"s\": 1062,\n \"text\": \"To find a form feed character with JavaScript Regular Expression, use the following −\"\n },\n {\n \"code\": null,\n \"e\": 1151,\n \"s\": 1148,\n \"text\": \"\\\\f\"\n },\n {\n \"code\": null,\n \"e\": 1290,\n \"s\": 1151,\n \"text\": \"You can try to run the following code to find a form feed character. It returns the position where the form feed (\\\\f) character is found −\"\n },\n {\n \"code\": null,\n \"e\": 1580,\n \"s\": 1290,\n \"text\": \"\\n \\n JavaScript Regular Expression\\n \\n \\n \\n \\n\"\n }\n]"}}},{"rowIdx":118,"cells":{"title":{"kind":"string","value":"AngularJS | ng-form Directive - GeeksforGeeks"},"text":{"kind":"string","value":"29 Mar, 2019\nThe ng-form Directive in AngularJS is used to create nested form i.e. one form inside the other form. It specifies an inherit control from HTML form. It creates control group inside a form directive which can be used to determine the validity of a sub-group of controls.\nSyntax:\n Contents... \n\nExample 1: This example uses ng-form Directive to hide the input text fields and display its content.\n ng-form Directive

GeeksforGeeks

ng-form Directive

Full Name:

Username:

First Name:{{fName}}
User Name:{{uName}}
\nOutput:Before Clicking the button:After Clicking the button:\nExample 2: This example uses ng-form Directive to validate email and save it.\n ng-form Directive

GeeksforGeeks

ng-form Directive

Enter Email:
Email is required
\nOutput:Invalid Input:Valid Input:\nAngularJS-Directives\nAngularJS\nWeb Technologies\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nTop 10 Angular Libraries For Web Developers\nAngular PrimeNG Dropdown Component\nAngular 10 (blur) Event\nHow to make a Bootstrap Modal Popup in Angular 9/8 ?\nAngular 10 (focus) Event\nRoadmap to Become a Web Developer in 2022\nInstallation of Node.js on Linux\nHow to fetch data from an API in ReactJS ?\nTop 10 Projects For Beginners To Practice HTML and CSS Skills\nHow to insert spaces/tabs in text using HTML/CSS?"},"parsed":{"kind":"list like","value":[{"code":null,"e":25109,"s":25081,"text":"\n29 Mar, 2019"},{"code":null,"e":25380,"s":25109,"text":"The ng-form Directive in AngularJS is used to create nested form i.e. one form inside the other form. It specifies an inherit control from HTML form. It creates control group inside a form directive which can be used to determine the validity of a sub-group of controls."},{"code":null,"e":25388,"s":25380,"text":"Syntax:"},{"code":null,"e":25438,"s":25388,"text":" Contents... \n"},{"code":null,"e":25540,"s":25438,"text":"Example 1: This example uses ng-form Directive to hide the input text fields and display its content."},{"code":" ng-form Directive

GeeksforGeeks

ng-form Directive

Full Name:

Username:

First Name:{{fName}}
User Name:{{uName}}
","e":26396,"s":25540,"text":null},{"code":null,"e":26457,"s":26396,"text":"Output:Before Clicking the button:After Clicking the button:"},{"code":null,"e":26535,"s":26457,"text":"Example 2: This example uses ng-form Directive to validate email and save it."},{"code":" ng-form Directive

GeeksforGeeks

ng-form Directive

Enter Email:
Email is required
","e":27416,"s":26535,"text":null},{"code":null,"e":27450,"s":27416,"text":"Output:Invalid Input:Valid Input:"},{"code":null,"e":27471,"s":27450,"text":"AngularJS-Directives"},{"code":null,"e":27481,"s":27471,"text":"AngularJS"},{"code":null,"e":27498,"s":27481,"text":"Web Technologies"},{"code":null,"e":27596,"s":27498,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":27640,"s":27596,"text":"Top 10 Angular Libraries For Web Developers"},{"code":null,"e":27675,"s":27640,"text":"Angular PrimeNG Dropdown Component"},{"code":null,"e":27699,"s":27675,"text":"Angular 10 (blur) Event"},{"code":null,"e":27752,"s":27699,"text":"How to make a Bootstrap Modal Popup in Angular 9/8 ?"},{"code":null,"e":27777,"s":27752,"text":"Angular 10 (focus) Event"},{"code":null,"e":27819,"s":27777,"text":"Roadmap to Become a Web Developer in 2022"},{"code":null,"e":27852,"s":27819,"text":"Installation of Node.js on Linux"},{"code":null,"e":27895,"s":27852,"text":"How to fetch data from an API in ReactJS ?"},{"code":null,"e":27957,"s":27895,"text":"Top 10 Projects For Beginners To Practice HTML and CSS Skills"}],"string":"[\n {\n \"code\": null,\n \"e\": 25109,\n \"s\": 25081,\n \"text\": \"\\n29 Mar, 2019\"\n },\n {\n \"code\": null,\n \"e\": 25380,\n \"s\": 25109,\n \"text\": \"The ng-form Directive in AngularJS is used to create nested form i.e. one form inside the other form. It specifies an inherit control from HTML form. It creates control group inside a form directive which can be used to determine the validity of a sub-group of controls.\"\n },\n {\n \"code\": null,\n \"e\": 25388,\n \"s\": 25380,\n \"text\": \"Syntax:\"\n },\n {\n \"code\": null,\n \"e\": 25438,\n \"s\": 25388,\n \"text\": \" Contents... \\n\"\n },\n {\n \"code\": null,\n \"e\": 25540,\n \"s\": 25438,\n \"text\": \"Example 1: This example uses ng-form Directive to hide the input text fields and display its content.\"\n },\n {\n \"code\": \" ng-form Directive

GeeksforGeeks

ng-form Directive

Full Name:

Username:

First Name:{{fName}}
User Name:{{uName}}
\",\n \"e\": 26396,\n \"s\": 25540,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 26457,\n \"s\": 26396,\n \"text\": \"Output:Before Clicking the button:After Clicking the button:\"\n },\n {\n \"code\": null,\n \"e\": 26535,\n \"s\": 26457,\n \"text\": \"Example 2: This example uses ng-form Directive to validate email and save it.\"\n },\n {\n \"code\": \" ng-form Directive

GeeksforGeeks

ng-form Directive

Enter Email:
Email is required
\",\n \"e\": 27416,\n \"s\": 26535,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 27450,\n \"s\": 27416,\n \"text\": \"Output:Invalid Input:Valid Input:\"\n },\n {\n \"code\": null,\n \"e\": 27471,\n \"s\": 27450,\n \"text\": \"AngularJS-Directives\"\n },\n {\n \"code\": null,\n \"e\": 27481,\n \"s\": 27471,\n \"text\": \"AngularJS\"\n },\n {\n \"code\": null,\n \"e\": 27498,\n \"s\": 27481,\n \"text\": \"Web Technologies\"\n },\n {\n \"code\": null,\n \"e\": 27596,\n \"s\": 27498,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 27640,\n \"s\": 27596,\n \"text\": \"Top 10 Angular Libraries For Web Developers\"\n },\n {\n \"code\": null,\n \"e\": 27675,\n \"s\": 27640,\n \"text\": \"Angular PrimeNG Dropdown Component\"\n },\n {\n \"code\": null,\n \"e\": 27699,\n \"s\": 27675,\n \"text\": \"Angular 10 (blur) Event\"\n },\n {\n \"code\": null,\n \"e\": 27752,\n \"s\": 27699,\n \"text\": \"How to make a Bootstrap Modal Popup in Angular 9/8 ?\"\n },\n {\n \"code\": null,\n \"e\": 27777,\n \"s\": 27752,\n \"text\": \"Angular 10 (focus) Event\"\n },\n {\n \"code\": null,\n \"e\": 27819,\n \"s\": 27777,\n \"text\": \"Roadmap to Become a Web Developer in 2022\"\n },\n {\n \"code\": null,\n \"e\": 27852,\n \"s\": 27819,\n \"text\": \"Installation of Node.js on Linux\"\n },\n {\n \"code\": null,\n \"e\": 27895,\n \"s\": 27852,\n \"text\": \"How to fetch data from an API in ReactJS ?\"\n },\n {\n \"code\": null,\n \"e\": 27957,\n \"s\": 27895,\n \"text\": \"Top 10 Projects For Beginners To Practice HTML and CSS Skills\"\n }\n]"}}},{"rowIdx":119,"cells":{"title":{"kind":"string","value":"MongoDB query by sub-field?"},"text":{"kind":"string","value":"You can use dot(.) notation to query by subfield. Let us create a collection with a document. The query to create a collection with a document is as follows −\n> db.queryBySubFieldDemo.insertOne(\n ... {\n ... \"StudentPersonalDetails\" : {\"StudentName\" : \"John\",\"StudentHobby\" :\"Photography\"},\n ... \"StudentScores\" : {\"MathScore\" : 56}\n ... }\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c92c2995259fcd195499808\")\n}\n> db.queryBySubFieldDemo.insertOne(\n ... {\n ... \"StudentPersonalDetails\" : {\"StudentName\" : \"Chris\",\"StudentHobby\" :\"Reading\"},\n ... \"StudentScores\" : {\"MathScore\" : 97}\n ... }\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c92c2df5259fcd195499809\")\n}\nDisplay all documents from a collection with the help of find() method. The query is as follows −\n> db.queryBySubFieldDemo.find().pretty();\nThe following is the output −\n{\n \"_id\" : ObjectId(\"5c92c2995259fcd195499808\"),\n \"StudentPersonalDetails\" : {\n \"StudentName\" : \"John\",\n \"StudentHobby\" : \"Photography\"\n },\n \"StudentScores\" : {\n \"MathScore\" : 56\n }\n}\n{\n \"_id\" : ObjectId(\"5c92c2df5259fcd195499809\"),\n \"StudentPersonalDetails\" : {\n \"StudentName\" : \"Chris\",\n \"StudentHobby\" : \"Reading\"\n },\n \"StudentScores\" : {\n \"MathScore\" : 97\n }\n}\nHere is the query by subfield −\n> db.queryBySubFieldDemo.find({\"StudentPersonalDetails.StudentName\":\"Chris\"}).pretty();\nThe following is the output −\n{\n \"_id\" : ObjectId(\"5c92c2df5259fcd195499809\"),\n \"StudentPersonalDetails\" : {\n \"StudentName\" : \"Chris\",\n \"StudentHobby\" : \"Reading\"\n },\n \"StudentScores\" : {\n \"MathScore\" : 97\n }\n}"},"parsed":{"kind":"list like","value":[{"code":null,"e":1221,"s":1062,"text":"You can use dot(.) notation to query by subfield. Let us create a collection with a document. The query to create a collection with a document is as follows −"},{"code":null,"e":1790,"s":1221,"text":"> db.queryBySubFieldDemo.insertOne(\n ... {\n ... \"StudentPersonalDetails\" : {\"StudentName\" : \"John\",\"StudentHobby\" :\"Photography\"},\n ... \"StudentScores\" : {\"MathScore\" : 56}\n ... }\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c92c2995259fcd195499808\")\n}\n> db.queryBySubFieldDemo.insertOne(\n ... {\n ... \"StudentPersonalDetails\" : {\"StudentName\" : \"Chris\",\"StudentHobby\" :\"Reading\"},\n ... \"StudentScores\" : {\"MathScore\" : 97}\n ... }\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c92c2df5259fcd195499809\")\n}"},{"code":null,"e":1888,"s":1790,"text":"Display all documents from a collection with the help of find() method. The query is as follows −"},{"code":null,"e":1930,"s":1888,"text":"> db.queryBySubFieldDemo.find().pretty();"},{"code":null,"e":1960,"s":1930,"text":"The following is the output −"},{"code":null,"e":2375,"s":1960,"text":"{\n \"_id\" : ObjectId(\"5c92c2995259fcd195499808\"),\n \"StudentPersonalDetails\" : {\n \"StudentName\" : \"John\",\n \"StudentHobby\" : \"Photography\"\n },\n \"StudentScores\" : {\n \"MathScore\" : 56\n }\n}\n{\n \"_id\" : ObjectId(\"5c92c2df5259fcd195499809\"),\n \"StudentPersonalDetails\" : {\n \"StudentName\" : \"Chris\",\n \"StudentHobby\" : \"Reading\"\n },\n \"StudentScores\" : {\n \"MathScore\" : 97\n }\n}"},{"code":null,"e":2407,"s":2375,"text":"Here is the query by subfield −"},{"code":null,"e":2495,"s":2407,"text":"> db.queryBySubFieldDemo.find({\"StudentPersonalDetails.StudentName\":\"Chris\"}).pretty();"},{"code":null,"e":2525,"s":2495,"text":"The following is the output −"},{"code":null,"e":2731,"s":2525,"text":"{\n \"_id\" : ObjectId(\"5c92c2df5259fcd195499809\"),\n \"StudentPersonalDetails\" : {\n \"StudentName\" : \"Chris\",\n \"StudentHobby\" : \"Reading\"\n },\n \"StudentScores\" : {\n \"MathScore\" : 97\n }\n}"}],"string":"[\n {\n \"code\": null,\n \"e\": 1221,\n \"s\": 1062,\n \"text\": \"You can use dot(.) notation to query by subfield. Let us create a collection with a document. The query to create a collection with a document is as follows −\"\n },\n {\n \"code\": null,\n \"e\": 1790,\n \"s\": 1221,\n \"text\": \"> db.queryBySubFieldDemo.insertOne(\\n ... {\\n ... \\\"StudentPersonalDetails\\\" : {\\\"StudentName\\\" : \\\"John\\\",\\\"StudentHobby\\\" :\\\"Photography\\\"},\\n ... \\\"StudentScores\\\" : {\\\"MathScore\\\" : 56}\\n ... }\\n... );\\n{\\n \\\"acknowledged\\\" : true,\\n \\\"insertedId\\\" : ObjectId(\\\"5c92c2995259fcd195499808\\\")\\n}\\n> db.queryBySubFieldDemo.insertOne(\\n ... {\\n ... \\\"StudentPersonalDetails\\\" : {\\\"StudentName\\\" : \\\"Chris\\\",\\\"StudentHobby\\\" :\\\"Reading\\\"},\\n ... \\\"StudentScores\\\" : {\\\"MathScore\\\" : 97}\\n ... }\\n... );\\n{\\n \\\"acknowledged\\\" : true,\\n \\\"insertedId\\\" : ObjectId(\\\"5c92c2df5259fcd195499809\\\")\\n}\"\n },\n {\n \"code\": null,\n \"e\": 1888,\n \"s\": 1790,\n \"text\": \"Display all documents from a collection with the help of find() method. The query is as follows −\"\n },\n {\n \"code\": null,\n \"e\": 1930,\n \"s\": 1888,\n \"text\": \"> db.queryBySubFieldDemo.find().pretty();\"\n },\n {\n \"code\": null,\n \"e\": 1960,\n \"s\": 1930,\n \"text\": \"The following is the output −\"\n },\n {\n \"code\": null,\n \"e\": 2375,\n \"s\": 1960,\n \"text\": \"{\\n \\\"_id\\\" : ObjectId(\\\"5c92c2995259fcd195499808\\\"),\\n \\\"StudentPersonalDetails\\\" : {\\n \\\"StudentName\\\" : \\\"John\\\",\\n \\\"StudentHobby\\\" : \\\"Photography\\\"\\n },\\n \\\"StudentScores\\\" : {\\n \\\"MathScore\\\" : 56\\n }\\n}\\n{\\n \\\"_id\\\" : ObjectId(\\\"5c92c2df5259fcd195499809\\\"),\\n \\\"StudentPersonalDetails\\\" : {\\n \\\"StudentName\\\" : \\\"Chris\\\",\\n \\\"StudentHobby\\\" : \\\"Reading\\\"\\n },\\n \\\"StudentScores\\\" : {\\n \\\"MathScore\\\" : 97\\n }\\n}\"\n },\n {\n \"code\": null,\n \"e\": 2407,\n \"s\": 2375,\n \"text\": \"Here is the query by subfield −\"\n },\n {\n \"code\": null,\n \"e\": 2495,\n \"s\": 2407,\n \"text\": \"> db.queryBySubFieldDemo.find({\\\"StudentPersonalDetails.StudentName\\\":\\\"Chris\\\"}).pretty();\"\n },\n {\n \"code\": null,\n \"e\": 2525,\n \"s\": 2495,\n \"text\": \"The following is the output −\"\n },\n {\n \"code\": null,\n \"e\": 2731,\n \"s\": 2525,\n \"text\": \"{\\n \\\"_id\\\" : ObjectId(\\\"5c92c2df5259fcd195499809\\\"),\\n \\\"StudentPersonalDetails\\\" : {\\n \\\"StudentName\\\" : \\\"Chris\\\",\\n \\\"StudentHobby\\\" : \\\"Reading\\\"\\n },\\n \\\"StudentScores\\\" : {\\n \\\"MathScore\\\" : 97\\n }\\n}\"\n }\n]"}}},{"rowIdx":120,"cells":{"title":{"kind":"string","value":"SQL Server with Python. The world’s favorite database + the... | by James Briggs | Towards Data Science"},"text":{"kind":"string","value":"Everyone uses SQL, and everyone uses Python. SQL is the de-facto standard for databases. Python on the other hand is an all-star, a top language for data analytics, machine learning, and web development. Imagine both, together.\nThis is actually incredibly easy to setup. We can quickly utilize the dynamic nature of Python, to control and build queries in SQL. The best part? After set-up, you don’t need to do anything.\nBoth of these amazing tools together, allow us to reach new heights of automation and efficiency.\nOur bridge between the two technologies is pyodbc. This library allows easy access to ODBC databases.\nODBC, short for Open Database Connectivity, is a standardised application programming interface (API) for accessing databases, developed by the SQL Access group back in the early 90's.\nCompliant database management systems (DBMS) include:\nIBM Db2\nMS Access\nMS SQL Server\nMySQL\nOracle\nIn this article, we will be using MS SQL Server. For the most part, this should be directly transferable for use with any ODBC compliant database. The only change required should be with the connection setup.\nThe first thing we need to do is create a connection to the SQL server. We can do this using pyodbc.connect. Within this function we must also pass a connection string.\nThis connection string must specify the DBMS Driver, the Server, a specific Database to connect to, and our connection settings.\nSo, lets assume we want to connect to server UKXXX00123,45600, database DB01 , to do this we want to use SQL Server Native Client 11.0.\nWe will be connecting from an internal, and thus trusted connection (we do not need to enter our username and password).\ncnxn_str = (\"Driver={SQL Server Native Client 11.0};\" \"Server=UKXXX00123,45600;\" \"Database=DB01;\" \"Trusted_Connection=yes;\")\nOur connection is now initialized with:\ncnxn = pyodbc.connect(cnxn_str)\nIf we are not accessing the database via a trusted connection, we will need to enter the username and password that we would usually use to access the server via SQL Server Management Studio (SSMS).\nFor example, if our username is JoeBloggs, and our password is Password123, we should immediately change our password.\nBut before changing that horrible password, we can connect like so:\ncnxn_str = (\"Driver={SQL Server Native Client 11.0};\" \"Server=UKXXX00123,45600;\" \"Database=DB01;\" \"UID=JoeBloggs;\" \"PWD=Password123;\")cnxn = pyodbc.connect(cnxn_str)\nNow we are connected to the database, we can begin performing SQL queries via Python.\nEvery query we run on SQL Server now will consist of a cursor initialization, and query execution. Additionally, if we make any changes inside the server, we also need to commit these changes to the server (which we cover in the next section).\nTo initialize a cursor:\ncursor = cnxn.cursor()\nNow, whenever we want to perform a query, we use this cursor object.\nLet’s first select the top 1000 rows from a table called customers:\ncursor.execute(\"SELECT TOP(1000) * FROM customers\")\nThis performs the operation, but within the server, and so nothing is actually returned to Python. So let’s look at extracting this data from SQL.\nTo extract our data from SQL into Python, we use pandas. Pandas provides us with a very convenient function called read_sql, this function, as you may have guessed, reads data from SQL.\nread_sql requires both a query and the connection instance cnxn, like so:\ndata = pd.read_sql(\"SELECT TOP(1000) * FROM customers\", cnxn)\nThis returns a dataframe containing the top 1000 rows from the customers table.\nNow, if we wanted to change the data in SQL, we need to add another step to the original initialize connection, execute query process.\nWhen we execute queries in SQL, these changes are kept in a temporarily existing space, they are not made directly to the data.\nTo make these changes permanent, we must commit them. Lets concatenate the firstName and lastName columns, to create a fullName column.\ncursor = cnxn.cursor()# first alter the table, adding a columncursor.execute(\"ALTER TABLE customer \" + \"ADD fullName VARCHAR(20)\")# now update that column to contain firstName + lastNamecursor.execute(\"UPDATE customer \" + \"SET fullName = firstName + \" \" + lastName\")\nAt this point, fullName does not exist in our database. We must commit these changes to make them permanent:\ncnxn.commit()\nOnce we have performed whichever manipulation tasks we needed to do. We can extract our data to Python — alternatively, we can extract the data to Python and manipulate it there too.\nWhichever approach you take, once the data is there in Python, we can do a multitude of useful things with it that were simply not possible before.\nMaybe we need to perform some daily reporting, with which we would usually query the newest batch of data in SQL server, calculate some basic statistics, and send the results via email.\nLet’s automate that:\nAnd with that, we are done! Running this code quickly extracts the prior week’s data, calculates our key measures, and sends a summary of this to our boss.\nSo, in a few simple, easy steps, we’ve taken a first look at quickly setting up a more efficient, automated workflow using an integration of both SQL and Python.\nI have found this to be incredibly useful, and not just for the use-cases described above.\nPython simply kicks open new routes that were impassable to us before with just SQL alone.\nLet me know your opinions, ideas, or use-cases, I’d love to hear them! If you’d like more content like this, I post on YouTube too.\nThanks for reading!\nIf you enjoyed this article, you may be interested in a deeper look at email automation with Python. I covered this in a previous article, check it out if you’re interested:\ntowardsdatascience.com\nThis GitHub repo also contains documentation and code showing the implementation of a few useful methods."},"parsed":{"kind":"list like","value":[{"code":null,"e":400,"s":172,"text":"Everyone uses SQL, and everyone uses Python. SQL is the de-facto standard for databases. Python on the other hand is an all-star, a top language for data analytics, machine learning, and web development. Imagine both, together."},{"code":null,"e":593,"s":400,"text":"This is actually incredibly easy to setup. We can quickly utilize the dynamic nature of Python, to control and build queries in SQL. The best part? After set-up, you don’t need to do anything."},{"code":null,"e":691,"s":593,"text":"Both of these amazing tools together, allow us to reach new heights of automation and efficiency."},{"code":null,"e":793,"s":691,"text":"Our bridge between the two technologies is pyodbc. This library allows easy access to ODBC databases."},{"code":null,"e":978,"s":793,"text":"ODBC, short for Open Database Connectivity, is a standardised application programming interface (API) for accessing databases, developed by the SQL Access group back in the early 90's."},{"code":null,"e":1032,"s":978,"text":"Compliant database management systems (DBMS) include:"},{"code":null,"e":1040,"s":1032,"text":"IBM Db2"},{"code":null,"e":1050,"s":1040,"text":"MS Access"},{"code":null,"e":1064,"s":1050,"text":"MS SQL Server"},{"code":null,"e":1070,"s":1064,"text":"MySQL"},{"code":null,"e":1077,"s":1070,"text":"Oracle"},{"code":null,"e":1286,"s":1077,"text":"In this article, we will be using MS SQL Server. For the most part, this should be directly transferable for use with any ODBC compliant database. The only change required should be with the connection setup."},{"code":null,"e":1455,"s":1286,"text":"The first thing we need to do is create a connection to the SQL server. We can do this using pyodbc.connect. Within this function we must also pass a connection string."},{"code":null,"e":1584,"s":1455,"text":"This connection string must specify the DBMS Driver, the Server, a specific Database to connect to, and our connection settings."},{"code":null,"e":1720,"s":1584,"text":"So, lets assume we want to connect to server UKXXX00123,45600, database DB01 , to do this we want to use SQL Server Native Client 11.0."},{"code":null,"e":1841,"s":1720,"text":"We will be connecting from an internal, and thus trusted connection (we do not need to enter our username and password)."},{"code":null,"e":1999,"s":1841,"text":"cnxn_str = (\"Driver={SQL Server Native Client 11.0};\" \"Server=UKXXX00123,45600;\" \"Database=DB01;\" \"Trusted_Connection=yes;\")"},{"code":null,"e":2039,"s":1999,"text":"Our connection is now initialized with:"},{"code":null,"e":2071,"s":2039,"text":"cnxn = pyodbc.connect(cnxn_str)"},{"code":null,"e":2270,"s":2071,"text":"If we are not accessing the database via a trusted connection, we will need to enter the username and password that we would usually use to access the server via SQL Server Management Studio (SSMS)."},{"code":null,"e":2389,"s":2270,"text":"For example, if our username is JoeBloggs, and our password is Password123, we should immediately change our password."},{"code":null,"e":2457,"s":2389,"text":"But before changing that horrible password, we can connect like so:"},{"code":null,"e":2667,"s":2457,"text":"cnxn_str = (\"Driver={SQL Server Native Client 11.0};\" \"Server=UKXXX00123,45600;\" \"Database=DB01;\" \"UID=JoeBloggs;\" \"PWD=Password123;\")cnxn = pyodbc.connect(cnxn_str)"},{"code":null,"e":2753,"s":2667,"text":"Now we are connected to the database, we can begin performing SQL queries via Python."},{"code":null,"e":2997,"s":2753,"text":"Every query we run on SQL Server now will consist of a cursor initialization, and query execution. Additionally, if we make any changes inside the server, we also need to commit these changes to the server (which we cover in the next section)."},{"code":null,"e":3021,"s":2997,"text":"To initialize a cursor:"},{"code":null,"e":3044,"s":3021,"text":"cursor = cnxn.cursor()"},{"code":null,"e":3113,"s":3044,"text":"Now, whenever we want to perform a query, we use this cursor object."},{"code":null,"e":3181,"s":3113,"text":"Let’s first select the top 1000 rows from a table called customers:"},{"code":null,"e":3233,"s":3181,"text":"cursor.execute(\"SELECT TOP(1000) * FROM customers\")"},{"code":null,"e":3380,"s":3233,"text":"This performs the operation, but within the server, and so nothing is actually returned to Python. So let’s look at extracting this data from SQL."},{"code":null,"e":3566,"s":3380,"text":"To extract our data from SQL into Python, we use pandas. Pandas provides us with a very convenient function called read_sql, this function, as you may have guessed, reads data from SQL."},{"code":null,"e":3640,"s":3566,"text":"read_sql requires both a query and the connection instance cnxn, like so:"},{"code":null,"e":3702,"s":3640,"text":"data = pd.read_sql(\"SELECT TOP(1000) * FROM customers\", cnxn)"},{"code":null,"e":3782,"s":3702,"text":"This returns a dataframe containing the top 1000 rows from the customers table."},{"code":null,"e":3917,"s":3782,"text":"Now, if we wanted to change the data in SQL, we need to add another step to the original initialize connection, execute query process."},{"code":null,"e":4045,"s":3917,"text":"When we execute queries in SQL, these changes are kept in a temporarily existing space, they are not made directly to the data."},{"code":null,"e":4181,"s":4045,"text":"To make these changes permanent, we must commit them. Lets concatenate the firstName and lastName columns, to create a fullName column."},{"code":null,"e":4476,"s":4181,"text":"cursor = cnxn.cursor()# first alter the table, adding a columncursor.execute(\"ALTER TABLE customer \" + \"ADD fullName VARCHAR(20)\")# now update that column to contain firstName + lastNamecursor.execute(\"UPDATE customer \" + \"SET fullName = firstName + \" \" + lastName\")"},{"code":null,"e":4585,"s":4476,"text":"At this point, fullName does not exist in our database. We must commit these changes to make them permanent:"},{"code":null,"e":4599,"s":4585,"text":"cnxn.commit()"},{"code":null,"e":4782,"s":4599,"text":"Once we have performed whichever manipulation tasks we needed to do. We can extract our data to Python — alternatively, we can extract the data to Python and manipulate it there too."},{"code":null,"e":4930,"s":4782,"text":"Whichever approach you take, once the data is there in Python, we can do a multitude of useful things with it that were simply not possible before."},{"code":null,"e":5116,"s":4930,"text":"Maybe we need to perform some daily reporting, with which we would usually query the newest batch of data in SQL server, calculate some basic statistics, and send the results via email."},{"code":null,"e":5137,"s":5116,"text":"Let’s automate that:"},{"code":null,"e":5293,"s":5137,"text":"And with that, we are done! Running this code quickly extracts the prior week’s data, calculates our key measures, and sends a summary of this to our boss."},{"code":null,"e":5455,"s":5293,"text":"So, in a few simple, easy steps, we’ve taken a first look at quickly setting up a more efficient, automated workflow using an integration of both SQL and Python."},{"code":null,"e":5546,"s":5455,"text":"I have found this to be incredibly useful, and not just for the use-cases described above."},{"code":null,"e":5637,"s":5546,"text":"Python simply kicks open new routes that were impassable to us before with just SQL alone."},{"code":null,"e":5769,"s":5637,"text":"Let me know your opinions, ideas, or use-cases, I’d love to hear them! If you’d like more content like this, I post on YouTube too."},{"code":null,"e":5789,"s":5769,"text":"Thanks for reading!"},{"code":null,"e":5963,"s":5789,"text":"If you enjoyed this article, you may be interested in a deeper look at email automation with Python. I covered this in a previous article, check it out if you’re interested:"},{"code":null,"e":5986,"s":5963,"text":"towardsdatascience.com"}],"string":"[\n {\n \"code\": null,\n \"e\": 400,\n \"s\": 172,\n \"text\": \"Everyone uses SQL, and everyone uses Python. SQL is the de-facto standard for databases. Python on the other hand is an all-star, a top language for data analytics, machine learning, and web development. Imagine both, together.\"\n },\n {\n \"code\": null,\n \"e\": 593,\n \"s\": 400,\n \"text\": \"This is actually incredibly easy to setup. We can quickly utilize the dynamic nature of Python, to control and build queries in SQL. The best part? After set-up, you don’t need to do anything.\"\n },\n {\n \"code\": null,\n \"e\": 691,\n \"s\": 593,\n \"text\": \"Both of these amazing tools together, allow us to reach new heights of automation and efficiency.\"\n },\n {\n \"code\": null,\n \"e\": 793,\n \"s\": 691,\n \"text\": \"Our bridge between the two technologies is pyodbc. This library allows easy access to ODBC databases.\"\n },\n {\n \"code\": null,\n \"e\": 978,\n \"s\": 793,\n \"text\": \"ODBC, short for Open Database Connectivity, is a standardised application programming interface (API) for accessing databases, developed by the SQL Access group back in the early 90's.\"\n },\n {\n \"code\": null,\n \"e\": 1032,\n \"s\": 978,\n \"text\": \"Compliant database management systems (DBMS) include:\"\n },\n {\n \"code\": null,\n \"e\": 1040,\n \"s\": 1032,\n \"text\": \"IBM Db2\"\n },\n {\n \"code\": null,\n \"e\": 1050,\n \"s\": 1040,\n \"text\": \"MS Access\"\n },\n {\n \"code\": null,\n \"e\": 1064,\n \"s\": 1050,\n \"text\": \"MS SQL Server\"\n },\n {\n \"code\": null,\n \"e\": 1070,\n \"s\": 1064,\n \"text\": \"MySQL\"\n },\n {\n \"code\": null,\n \"e\": 1077,\n \"s\": 1070,\n \"text\": \"Oracle\"\n },\n {\n \"code\": null,\n \"e\": 1286,\n \"s\": 1077,\n \"text\": \"In this article, we will be using MS SQL Server. For the most part, this should be directly transferable for use with any ODBC compliant database. The only change required should be with the connection setup.\"\n },\n {\n \"code\": null,\n \"e\": 1455,\n \"s\": 1286,\n \"text\": \"The first thing we need to do is create a connection to the SQL server. We can do this using pyodbc.connect. Within this function we must also pass a connection string.\"\n },\n {\n \"code\": null,\n \"e\": 1584,\n \"s\": 1455,\n \"text\": \"This connection string must specify the DBMS Driver, the Server, a specific Database to connect to, and our connection settings.\"\n },\n {\n \"code\": null,\n \"e\": 1720,\n \"s\": 1584,\n \"text\": \"So, lets assume we want to connect to server UKXXX00123,45600, database DB01 , to do this we want to use SQL Server Native Client 11.0.\"\n },\n {\n \"code\": null,\n \"e\": 1841,\n \"s\": 1720,\n \"text\": \"We will be connecting from an internal, and thus trusted connection (we do not need to enter our username and password).\"\n },\n {\n \"code\": null,\n \"e\": 1999,\n \"s\": 1841,\n \"text\": \"cnxn_str = (\\\"Driver={SQL Server Native Client 11.0};\\\" \\\"Server=UKXXX00123,45600;\\\" \\\"Database=DB01;\\\" \\\"Trusted_Connection=yes;\\\")\"\n },\n {\n \"code\": null,\n \"e\": 2039,\n \"s\": 1999,\n \"text\": \"Our connection is now initialized with:\"\n },\n {\n \"code\": null,\n \"e\": 2071,\n \"s\": 2039,\n \"text\": \"cnxn = pyodbc.connect(cnxn_str)\"\n },\n {\n \"code\": null,\n \"e\": 2270,\n \"s\": 2071,\n \"text\": \"If we are not accessing the database via a trusted connection, we will need to enter the username and password that we would usually use to access the server via SQL Server Management Studio (SSMS).\"\n },\n {\n \"code\": null,\n \"e\": 2389,\n \"s\": 2270,\n \"text\": \"For example, if our username is JoeBloggs, and our password is Password123, we should immediately change our password.\"\n },\n {\n \"code\": null,\n \"e\": 2457,\n \"s\": 2389,\n \"text\": \"But before changing that horrible password, we can connect like so:\"\n },\n {\n \"code\": null,\n \"e\": 2667,\n \"s\": 2457,\n \"text\": \"cnxn_str = (\\\"Driver={SQL Server Native Client 11.0};\\\" \\\"Server=UKXXX00123,45600;\\\" \\\"Database=DB01;\\\" \\\"UID=JoeBloggs;\\\" \\\"PWD=Password123;\\\")cnxn = pyodbc.connect(cnxn_str)\"\n },\n {\n \"code\": null,\n \"e\": 2753,\n \"s\": 2667,\n \"text\": \"Now we are connected to the database, we can begin performing SQL queries via Python.\"\n },\n {\n \"code\": null,\n \"e\": 2997,\n \"s\": 2753,\n \"text\": \"Every query we run on SQL Server now will consist of a cursor initialization, and query execution. Additionally, if we make any changes inside the server, we also need to commit these changes to the server (which we cover in the next section).\"\n },\n {\n \"code\": null,\n \"e\": 3021,\n \"s\": 2997,\n \"text\": \"To initialize a cursor:\"\n },\n {\n \"code\": null,\n \"e\": 3044,\n \"s\": 3021,\n \"text\": \"cursor = cnxn.cursor()\"\n },\n {\n \"code\": null,\n \"e\": 3113,\n \"s\": 3044,\n \"text\": \"Now, whenever we want to perform a query, we use this cursor object.\"\n },\n {\n \"code\": null,\n \"e\": 3181,\n \"s\": 3113,\n \"text\": \"Let’s first select the top 1000 rows from a table called customers:\"\n },\n {\n \"code\": null,\n \"e\": 3233,\n \"s\": 3181,\n \"text\": \"cursor.execute(\\\"SELECT TOP(1000) * FROM customers\\\")\"\n },\n {\n \"code\": null,\n \"e\": 3380,\n \"s\": 3233,\n \"text\": \"This performs the operation, but within the server, and so nothing is actually returned to Python. So let’s look at extracting this data from SQL.\"\n },\n {\n \"code\": null,\n \"e\": 3566,\n \"s\": 3380,\n \"text\": \"To extract our data from SQL into Python, we use pandas. Pandas provides us with a very convenient function called read_sql, this function, as you may have guessed, reads data from SQL.\"\n },\n {\n \"code\": null,\n \"e\": 3640,\n \"s\": 3566,\n \"text\": \"read_sql requires both a query and the connection instance cnxn, like so:\"\n },\n {\n \"code\": null,\n \"e\": 3702,\n \"s\": 3640,\n \"text\": \"data = pd.read_sql(\\\"SELECT TOP(1000) * FROM customers\\\", cnxn)\"\n },\n {\n \"code\": null,\n \"e\": 3782,\n \"s\": 3702,\n \"text\": \"This returns a dataframe containing the top 1000 rows from the customers table.\"\n },\n {\n \"code\": null,\n \"e\": 3917,\n \"s\": 3782,\n \"text\": \"Now, if we wanted to change the data in SQL, we need to add another step to the original initialize connection, execute query process.\"\n },\n {\n \"code\": null,\n \"e\": 4045,\n \"s\": 3917,\n \"text\": \"When we execute queries in SQL, these changes are kept in a temporarily existing space, they are not made directly to the data.\"\n },\n {\n \"code\": null,\n \"e\": 4181,\n \"s\": 4045,\n \"text\": \"To make these changes permanent, we must commit them. Lets concatenate the firstName and lastName columns, to create a fullName column.\"\n },\n {\n \"code\": null,\n \"e\": 4476,\n \"s\": 4181,\n \"text\": \"cursor = cnxn.cursor()# first alter the table, adding a columncursor.execute(\\\"ALTER TABLE customer \\\" + \\\"ADD fullName VARCHAR(20)\\\")# now update that column to contain firstName + lastNamecursor.execute(\\\"UPDATE customer \\\" + \\\"SET fullName = firstName + \\\" \\\" + lastName\\\")\"\n },\n {\n \"code\": null,\n \"e\": 4585,\n \"s\": 4476,\n \"text\": \"At this point, fullName does not exist in our database. We must commit these changes to make them permanent:\"\n },\n {\n \"code\": null,\n \"e\": 4599,\n \"s\": 4585,\n \"text\": \"cnxn.commit()\"\n },\n {\n \"code\": null,\n \"e\": 4782,\n \"s\": 4599,\n \"text\": \"Once we have performed whichever manipulation tasks we needed to do. We can extract our data to Python — alternatively, we can extract the data to Python and manipulate it there too.\"\n },\n {\n \"code\": null,\n \"e\": 4930,\n \"s\": 4782,\n \"text\": \"Whichever approach you take, once the data is there in Python, we can do a multitude of useful things with it that were simply not possible before.\"\n },\n {\n \"code\": null,\n \"e\": 5116,\n \"s\": 4930,\n \"text\": \"Maybe we need to perform some daily reporting, with which we would usually query the newest batch of data in SQL server, calculate some basic statistics, and send the results via email.\"\n },\n {\n \"code\": null,\n \"e\": 5137,\n \"s\": 5116,\n \"text\": \"Let’s automate that:\"\n },\n {\n \"code\": null,\n \"e\": 5293,\n \"s\": 5137,\n \"text\": \"And with that, we are done! Running this code quickly extracts the prior week’s data, calculates our key measures, and sends a summary of this to our boss.\"\n },\n {\n \"code\": null,\n \"e\": 5455,\n \"s\": 5293,\n \"text\": \"So, in a few simple, easy steps, we’ve taken a first look at quickly setting up a more efficient, automated workflow using an integration of both SQL and Python.\"\n },\n {\n \"code\": null,\n \"e\": 5546,\n \"s\": 5455,\n \"text\": \"I have found this to be incredibly useful, and not just for the use-cases described above.\"\n },\n {\n \"code\": null,\n \"e\": 5637,\n \"s\": 5546,\n \"text\": \"Python simply kicks open new routes that were impassable to us before with just SQL alone.\"\n },\n {\n \"code\": null,\n \"e\": 5769,\n \"s\": 5637,\n \"text\": \"Let me know your opinions, ideas, or use-cases, I’d love to hear them! If you’d like more content like this, I post on YouTube too.\"\n },\n {\n \"code\": null,\n \"e\": 5789,\n \"s\": 5769,\n \"text\": \"Thanks for reading!\"\n },\n {\n \"code\": null,\n \"e\": 5963,\n \"s\": 5789,\n \"text\": \"If you enjoyed this article, you may be interested in a deeper look at email automation with Python. I covered this in a previous article, check it out if you’re interested:\"\n },\n {\n \"code\": null,\n \"e\": 5986,\n \"s\": 5963,\n \"text\": \"towardsdatascience.com\"\n }\n]"}}},{"rowIdx":121,"cells":{"title":{"kind":"string","value":"find_element_by_xpath() driver method - Selenium Python - GeeksforGeeks"},"text":{"kind":"string","value":"22 Nov, 2021\nSelenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provide a simple API to write functional/acceptance tests using Selenium WebDriver. After you have installed selenium and checked out – Navigating links using the get method, you might want to play more with Selenium Python. After one has opened a page using selenium such as geeksforgeeks, one might want to click some buttons automatically or fill a form automatically or any such automated task. This article revolves around how to grab or locate elements in a webpage using locating strategies of Selenium Web Driver. More specifically, find_element_by_xpath() is discussed in this article. XPath is the language used for locating nodes in an XML document. As HTML can be an implementation of XML (XHTML), Selenium users can leverage this powerful language to target elements in their web applications. XPath extends beyond (as well as supporting) the simple methods of locating by id or name attributes, and opens up all sorts of new possibilities such as locating the third checkbox on the page. \nSyntax – \ndriver.find_element_by_xpath(\"xpath\")\nExample – For instance, consider this page source: \nhtml\n
\nNow after you have created a driver, you can grab an element using – \nlogin_form = driver.find_element_by_xpath(\"/html/body/form[1]\")\nlogin_form = driver.find_element_by_xpath(\"//form[1]\")\n \nLet’s try to practically implement this method and get an element instance for “https://www.geeksforgeeks.org/”. Let’s try to grab search form input using its name “search”. Create a file called run.py to demonstrate the find_element_by_xpath method – \nPython3\n# Python program to demonstrate# selenium # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # enter keyword to searchkeyword = \"geeksforgeeks\" # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get elementelement = driver.find_element_by_xpath(\"//form[input/@name ='search']\") # print complete elementprint(element)\nNow run using – \nPython run.py\nFirst, it will open the firefox window with geeksforgeeks, and then select the element and print it on the terminal as shown below. Browser Output – \nTerminal Output – \n \n.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } \nNaveenArora\nsurinderdawra388\ngulshankumarar231\nkumaripunam984122\nPython-selenium\nselenium\nPython\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nPython Dictionary\nRead a file line by line in Python\nEnumerate() in Python\nHow to Install PIP on Windows ?\nIterate over a list in Python\nDifferent ways to create Pandas Dataframe\nPython String | replace()\nCreate a Pandas DataFrame from Lists\nPython program to convert a list to string\nReading and Writing to text files in Python"},"parsed":{"kind":"list like","value":[{"code":null,"e":24800,"s":24772,"text":"\n22 Nov, 2021"},{"code":null,"e":25904,"s":24800,"text":"Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provide a simple API to write functional/acceptance tests using Selenium WebDriver. After you have installed selenium and checked out – Navigating links using the get method, you might want to play more with Selenium Python. After one has opened a page using selenium such as geeksforgeeks, one might want to click some buttons automatically or fill a form automatically or any such automated task. This article revolves around how to grab or locate elements in a webpage using locating strategies of Selenium Web Driver. More specifically, find_element_by_xpath() is discussed in this article. XPath is the language used for locating nodes in an XML document. As HTML can be an implementation of XML (XHTML), Selenium users can leverage this powerful language to target elements in their web applications. XPath extends beyond (as well as supporting) the simple methods of locating by id or name attributes, and opens up all sorts of new possibilities such as locating the third checkbox on the page. "},{"code":null,"e":25915,"s":25904,"text":"Syntax – "},{"code":null,"e":25953,"s":25915,"text":"driver.find_element_by_xpath(\"xpath\")"},{"code":null,"e":26005,"s":25953,"text":"Example – For instance, consider this page source: "},{"code":null,"e":26010,"s":26005,"text":"html"},{"code":"
","e":26210,"s":26010,"text":null},{"code":null,"e":26280,"s":26210,"text":"Now after you have created a driver, you can grab an element using – "},{"code":null,"e":26399,"s":26280,"text":"login_form = driver.find_element_by_xpath(\"/html/body/form[1]\")\nlogin_form = driver.find_element_by_xpath(\"//form[1]\")"},{"code":null,"e":26654,"s":26401,"text":"Let’s try to practically implement this method and get an element instance for “https://www.geeksforgeeks.org/”. Let’s try to grab search form input using its name “search”. Create a file called run.py to demonstrate the find_element_by_xpath method – "},{"code":null,"e":26662,"s":26654,"text":"Python3"},{"code":"# Python program to demonstrate# selenium # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # enter keyword to searchkeyword = \"geeksforgeeks\" # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get elementelement = driver.find_element_by_xpath(\"//form[input/@name ='search']\") # print complete elementprint(element)","e":27050,"s":26662,"text":null},{"code":null,"e":27067,"s":27050,"text":"Now run using – "},{"code":null,"e":27081,"s":27067,"text":"Python run.py"},{"code":null,"e":27231,"s":27081,"text":"First, it will open the firefox window with geeksforgeeks, and then select the element and print it on the terminal as shown below. Browser Output – "},{"code":null,"e":27250,"s":27231,"text":"Terminal Output – "},{"code":null,"e":27594,"s":27252,"text":".math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } "},{"code":null,"e":27606,"s":27594,"text":"NaveenArora"},{"code":null,"e":27623,"s":27606,"text":"surinderdawra388"},{"code":null,"e":27641,"s":27623,"text":"gulshankumarar231"},{"code":null,"e":27659,"s":27641,"text":"kumaripunam984122"},{"code":null,"e":27675,"s":27659,"text":"Python-selenium"},{"code":null,"e":27684,"s":27675,"text":"selenium"},{"code":null,"e":27691,"s":27684,"text":"Python"},{"code":null,"e":27789,"s":27691,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":27807,"s":27789,"text":"Python Dictionary"},{"code":null,"e":27842,"s":27807,"text":"Read a file line by line in Python"},{"code":null,"e":27864,"s":27842,"text":"Enumerate() in Python"},{"code":null,"e":27896,"s":27864,"text":"How to Install PIP on Windows ?"},{"code":null,"e":27926,"s":27896,"text":"Iterate over a list in Python"},{"code":null,"e":27968,"s":27926,"text":"Different ways to create Pandas Dataframe"},{"code":null,"e":27994,"s":27968,"text":"Python String | replace()"},{"code":null,"e":28031,"s":27994,"text":"Create a Pandas DataFrame from Lists"},{"code":null,"e":28074,"s":28031,"text":"Python program to convert a list to string"}],"string":"[\n {\n \"code\": null,\n \"e\": 24800,\n \"s\": 24772,\n \"text\": \"\\n22 Nov, 2021\"\n },\n {\n \"code\": null,\n \"e\": 25904,\n \"s\": 24800,\n \"text\": \"Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provide a simple API to write functional/acceptance tests using Selenium WebDriver. After you have installed selenium and checked out – Navigating links using the get method, you might want to play more with Selenium Python. After one has opened a page using selenium such as geeksforgeeks, one might want to click some buttons automatically or fill a form automatically or any such automated task. This article revolves around how to grab or locate elements in a webpage using locating strategies of Selenium Web Driver. More specifically, find_element_by_xpath() is discussed in this article. XPath is the language used for locating nodes in an XML document. As HTML can be an implementation of XML (XHTML), Selenium users can leverage this powerful language to target elements in their web applications. XPath extends beyond (as well as supporting) the simple methods of locating by id or name attributes, and opens up all sorts of new possibilities such as locating the third checkbox on the page. \"\n },\n {\n \"code\": null,\n \"e\": 25915,\n \"s\": 25904,\n \"text\": \"Syntax – \"\n },\n {\n \"code\": null,\n \"e\": 25953,\n \"s\": 25915,\n \"text\": \"driver.find_element_by_xpath(\\\"xpath\\\")\"\n },\n {\n \"code\": null,\n \"e\": 26005,\n \"s\": 25953,\n \"text\": \"Example – For instance, consider this page source: \"\n },\n {\n \"code\": null,\n \"e\": 26010,\n \"s\": 26005,\n \"text\": \"html\"\n },\n {\n \"code\": \"
\",\n \"e\": 26210,\n \"s\": 26010,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 26280,\n \"s\": 26210,\n \"text\": \"Now after you have created a driver, you can grab an element using – \"\n },\n {\n \"code\": null,\n \"e\": 26399,\n \"s\": 26280,\n \"text\": \"login_form = driver.find_element_by_xpath(\\\"/html/body/form[1]\\\")\\nlogin_form = driver.find_element_by_xpath(\\\"//form[1]\\\")\"\n },\n {\n \"code\": null,\n \"e\": 26654,\n \"s\": 26401,\n \"text\": \"Let’s try to practically implement this method and get an element instance for “https://www.geeksforgeeks.org/”. Let’s try to grab search form input using its name “search”. Create a file called run.py to demonstrate the find_element_by_xpath method – \"\n },\n {\n \"code\": null,\n \"e\": 26662,\n \"s\": 26654,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"# Python program to demonstrate# selenium # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # enter keyword to searchkeyword = \\\"geeksforgeeks\\\" # get geeksforgeeks.orgdriver.get(\\\"https://www.geeksforgeeks.org/\\\") # get elementelement = driver.find_element_by_xpath(\\\"//form[input/@name ='search']\\\") # print complete elementprint(element)\",\n \"e\": 27050,\n \"s\": 26662,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 27067,\n \"s\": 27050,\n \"text\": \"Now run using – \"\n },\n {\n \"code\": null,\n \"e\": 27081,\n \"s\": 27067,\n \"text\": \"Python run.py\"\n },\n {\n \"code\": null,\n \"e\": 27231,\n \"s\": 27081,\n \"text\": \"First, it will open the firefox window with geeksforgeeks, and then select the element and print it on the terminal as shown below. Browser Output – \"\n },\n {\n \"code\": null,\n \"e\": 27250,\n \"s\": 27231,\n \"text\": \"Terminal Output – \"\n },\n {\n \"code\": null,\n \"e\": 27594,\n \"s\": 27252,\n \"text\": \".math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } \"\n },\n {\n \"code\": null,\n \"e\": 27606,\n \"s\": 27594,\n \"text\": \"NaveenArora\"\n },\n {\n \"code\": null,\n \"e\": 27623,\n \"s\": 27606,\n \"text\": \"surinderdawra388\"\n },\n {\n \"code\": null,\n \"e\": 27641,\n \"s\": 27623,\n \"text\": \"gulshankumarar231\"\n },\n {\n \"code\": null,\n \"e\": 27659,\n \"s\": 27641,\n \"text\": \"kumaripunam984122\"\n },\n {\n \"code\": null,\n \"e\": 27675,\n \"s\": 27659,\n \"text\": \"Python-selenium\"\n },\n {\n \"code\": null,\n \"e\": 27684,\n \"s\": 27675,\n \"text\": \"selenium\"\n },\n {\n \"code\": null,\n \"e\": 27691,\n \"s\": 27684,\n \"text\": \"Python\"\n },\n {\n \"code\": null,\n \"e\": 27789,\n \"s\": 27691,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 27807,\n \"s\": 27789,\n \"text\": \"Python Dictionary\"\n },\n {\n \"code\": null,\n \"e\": 27842,\n \"s\": 27807,\n \"text\": \"Read a file line by line in Python\"\n },\n {\n \"code\": null,\n \"e\": 27864,\n \"s\": 27842,\n \"text\": \"Enumerate() in Python\"\n },\n {\n \"code\": null,\n \"e\": 27896,\n \"s\": 27864,\n \"text\": \"How to Install PIP on Windows ?\"\n },\n {\n \"code\": null,\n \"e\": 27926,\n \"s\": 27896,\n \"text\": \"Iterate over a list in Python\"\n },\n {\n \"code\": null,\n \"e\": 27968,\n \"s\": 27926,\n \"text\": \"Different ways to create Pandas Dataframe\"\n },\n {\n \"code\": null,\n \"e\": 27994,\n \"s\": 27968,\n \"text\": \"Python String | replace()\"\n },\n {\n \"code\": null,\n \"e\": 28031,\n \"s\": 27994,\n \"text\": \"Create a Pandas DataFrame from Lists\"\n },\n {\n \"code\": null,\n \"e\": 28074,\n \"s\": 28031,\n \"text\": \"Python program to convert a list to string\"\n }\n]"}}},{"rowIdx":122,"cells":{"title":{"kind":"string","value":"Angular 8 - Http Client Programming"},"text":{"kind":"string","value":"Http client programming is a must needed feature in every modern web application. Nowadays, lot of application exposes their functionality through REST API (functionality over HTTP protocol). With this in mind, Angular Team provides extensive support to access HTTP server. Angular provides a separate module, HttpClientModule and a service, HttpClient to do HTTP programming.\nLet us learn how to how to use HttpClient service in this chapter. Developer should have a basic knowledge in Http programming to understand this chapter.\nThe prerequisite to do Http programming is the basic knowledge of Http protocol and REST API technique. Http programming involves two part, server and client. Angular provides support to create client side application. Express a popular web framework provides support to create server side application.\nLet us create an Expense Rest API using express framework and then access it from our ExpenseManager application using Angular HttpClient service.\nOpen a command prompt and create a new folder, express-rest-api.\ncd /go/to/workspace \nmkdir express-rest-api \ncd expense-rest-api\n\nInitialise a new node application using below command −\nnpm init\n\nnpm init will ask some basic questions like project name (express-rest-api), entry point (server.js), etc., as mentioned below −\nThis utility will walk you through creating a package.json file. \nIt only covers the most common items, and tries to guess sensible defaults. \nSee `npm help json` for definitive documentation on these fields and exactly what they do. \nUse `npm install ` afterwards to install a package and save it as a dependency in the package.json file. \nPress ^C at any time to quit. \npackage name: (expense-rest-api) \nversion: (1.0.0) \ndescription: Rest api for Expense Application \nentry point: (index.js) server.js \ntest command:\ngit repository: \nkeywords: \nauthor: \nlicense: (ISC) \nAbout to write to \\path\\to\\workspace\\expense-rest-api\\package.json: { \n \"name\": \"expense-rest-api\", \n \"version\": \"1.0.0\", \n \"description\": \"Rest api for Expense Application\", \n \"main\": \"server.js\", \n \"scripts\": { \n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\" \n }, \n \"author\": \"\", \n \"license\": \"ISC\" \n} \nIs this OK? (yes) yes\nInstall express, sqlite and cors modules using below command −\nnpm install express sqlite3 cors\n\nCreate a new file sqlitedb.js and place below code −\nvar sqlite3 = require('sqlite3').verbose()\nconst DBSOURCE = \"expensedb.sqlite\"\n\nlet db = new sqlite3.Database(DBSOURCE, (err) => {\n if (err) {\n console.error(err.message)\n throw err\n }else{\n console.log('Connected to the SQLite database.')\n db.run(`CREATE TABLE expense (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n item text, \n amount real, \n category text, \n location text, \n spendOn text, \n createdOn text \n )`,\n (err) => {\n if (err) {\n console.log(err);\n }else{\n var insert = 'INSERT INTO expense (item, amount, category, location, spendOn, createdOn) VALUES (?,?,?,?,?,?)'\n\n db.run(insert, ['Pizza', 10, 'Food', 'KFC', '2020-05-26 10:10', '2020-05-26 10:10'])\n db.run(insert, ['Pizza', 9, 'Food', 'Mcdonald', '2020-05-28 11:10', '2020-05-28 11:10'])\n db.run(insert, ['Pizza', 12, 'Food', 'Mcdonald', '2020-05-29 09:22', '2020-05-29 09:22'])\n db.run(insert, ['Pizza', 15, 'Food', 'KFC', '2020-06-06 16:18', '2020-06-06 16:18'])\n db.run(insert, ['Pizza', 14, 'Food', 'Mcdonald', '2020-06-01 18:14', '2020-05-01 18:14'])\n }\n }\n ); \n }\n});\n\nmodule.exports = db\nHere, we are creating a new sqlite database and load some sample data.\nOpen server.js and place below code −\nvar express = require(\"express\")\nvar cors = require('cors')\nvar db = require(\"./sqlitedb.js\")\n\nvar app = express()\napp.use(cors());\n\nvar bodyParser = require(\"body-parser\");\napp.use(bodyParser.urlencoded({ extended: false }));\napp.use(bodyParser.json());\n\nvar HTTP_PORT = 8000 \napp.listen(HTTP_PORT, () => {\n console.log(\"Server running on port %PORT%\".replace(\"%PORT%\",HTTP_PORT))\n});\n\napp.get(\"/\", (req, res, next) => {\n res.json({\"message\":\"Ok\"})\n});\n\napp.get(\"/api/expense\", (req, res, next) => {\n var sql = \"select * from expense\"\n var params = []\n db.all(sql, params, (err, rows) => {\n if (err) {\n res.status(400).json({\"error\":err.message});\n return;\n }\n res.json(rows)\n });\n\n});\n\napp.get(\"/api/expense/:id\", (req, res, next) => {\n var sql = \"select * from expense where id = ?\"\n var params = [req.params.id]\n db.get(sql, params, (err, row) => {\n if (err) {\n res.status(400).json({\"error\":err.message});\n return;\n }\n res.json(row)\n });\n});\n\napp.post(\"/api/expense/\", (req, res, next) => {\n var errors=[]\n if (!req.body.item){\n errors.push(\"No item specified\");\n }\n var data = {\n item : req.body.item,\n amount: req.body.amount,\n category: req.body.category,\n location : req.body.location,\n spendOn: req.body.spendOn,\n createdOn: req.body.createdOn,\n }\n var sql = 'INSERT INTO expense (item, amount, category, location, spendOn, createdOn) VALUES (?,?,?,?,?,?)'\n var params =[data.item, data.amount, data.category, data.location, data.spendOn, data.createdOn]\n db.run(sql, params, function (err, result) {\n if (err){\n res.status(400).json({\"error\": err.message})\n return;\n }\n data.id = this.lastID;\n res.json(data);\n });\n})\n\napp.put(\"/api/expense/:id\", (req, res, next) => {\n var data = {\n item : req.body.item,\n amount: req.body.amount,\n category: req.body.category,\n location : req.body.location,\n spendOn: req.body.spendOn\n }\n db.run(\n `UPDATE expense SET\n item = ?, \n\n amount = ?,\n category = ?, \n location = ?, \n\n spendOn = ? \n WHERE id = ?`,\n [data.item, data.amount, data.category, data.location,data.spendOn, req.params.id],\n function (err, result) {\n if (err){\n console.log(err);\n res.status(400).json({\"error\": res.message})\n return;\n }\n res.json(data)\n });\n})\n\napp.delete(\"/api/expense/:id\", (req, res, next) => {\n db.run(\n 'DELETE FROM expense WHERE id = ?',\n req.params.id,\n function (err, result) {\n if (err){\n res.status(400).json({\"error\": res.message})\n return;\n }\n res.json({\"message\":\"deleted\", changes: this.changes})\n });\n})\n\napp.use(function(req, res){\n res.status(404);\n});\nHere, we create a basic CURD rest api to select, insert, update and delete expense entry.\nRun the application using below command −\nnpm run start\n\nOpen a browser, enter http://localhost:8000/ and press enter. You will see below response −\n{ \n \"message\": \"Ok\" \n}\n\nIt confirms our application is working fine.\nChange the url to http://localhost:8000/api/expense and you will see all the expense entries in JSON format.\n[\n {\n \"id\": 1,\n\n \"item\": \"Pizza\",\n \"amount\": 10,\n \"category\": \"Food\",\n \"location\": \"KFC\",\n \"spendOn\": \"2020-05-26 10:10\",\n \"createdOn\": \"2020-05-26 10:10\"\n },\n {\n \"id\": 2,\n \"item\": \"Pizza\",\n \"amount\": 14,\n \"category\": \"Food\",\n \"location\": \"Mcdonald\",\n \"spendOn\": \"2020-06-01 18:14\",\n \"createdOn\": \"2020-05-01 18:14\"\n },\n {\n \"id\": 3,\n \"item\": \"Pizza\",\n \"amount\": 15,\n \"category\": \"Food\",\n \"location\": \"KFC\",\n \"spendOn\": \"2020-06-06 16:18\",\n \"createdOn\": \"2020-06-06 16:18\"\n },\n {\n \"id\": 4,\n \"item\": \"Pizza\",\n \"amount\": 9,\n \"category\": \"Food\",\n \"location\": \"Mcdonald\",\n \"spendOn\": \"2020-05-28 11:10\",\n \"createdOn\": \"2020-05-28 11:10\"\n },\n {\n \"id\": 5,\n \"item\": \"Pizza\",\n \"amount\": 12,\n \"category\": \"Food\",\n \"location\": \"Mcdonald\",\n \"spendOn\": \"2020-05-29 09:22\",\n \"createdOn\": \"2020-05-29 09:22\"\n }\n]\nFinally, we created a simple CURD REST API for expense entry and we can access the REST API from our Angular application to learn HttpClient module.\nLet us learn how to configure HttpClient service in this chapter.\nHttpClient service is available inside the HttpClientModule module, which is available inside the @angular/common/http package.\nTo register HttpClientModule module −\nImport the HttpClientModule in AppComponent\nimport { HttpClientModule } from '@angular/common/http';\n\nInclude HttpClientModule in imports meta data of AppComponent.\n@NgModule({ \n imports: [ \n BrowserModule, \n // import HttpClientModule after BrowserModule. \n HttpClientModule, \n ] \n}) \nexport class AppModule {}\n\nLet us create a new service ExpenseEntryService in our ExpenseManager application to interact with Expense REST API. ExpenseEntryService will get the latest expense entries, insert new expense entries, modify existing expense entries and delete the unwanted expense entries.\nOpen command prompt and go to project root folder.\ncd /go/to/expense-manager\n\nStart the application.\nng serve\n\nRun the below command to generate an Angular service, ExpenseService.\nng generate service ExpenseEntry\n\nThis will create two Typescript files (expense entry service & its test) as specified below −\nCREATE src/app/expense-entry.service.spec.ts (364 bytes) \nCREATE src/app/expense-entry.service.ts (141 bytes)\n\nOpen ExpenseEntryService (src/app/expense-entry.service.ts) and import ExpenseEntry, throwError and catchError from rxjs library and import HttpClient, HttpHeaders and HttpErrorResponse from @angular/common/http package.\nimport { Injectable } from '@angular/core'; \nimport { ExpenseEntry } from './expense-entry'; import { throwError } from 'rxjs';\nimport { catchError } from 'rxjs/operators'; \nimport { HttpClient, HttpHeaders, HttpErrorResponse } from \n'@angular/common/http';\n\nInject the HttpClient service into our service.\nconstructor(private httpClient : HttpClient) { }\n\nCreate a variable, expenseRestUrl to specify the Expense Rest API endpoints.\nprivate expenseRestUrl = 'http://localhost:8000/api/expense';\n\nCreate a variable, httpOptions to set the Http Header option. This will be used during the Http Rest API call by Angular HttpClient service.\nprivate httpOptions = { \n headers: new HttpHeaders( { 'Content-Type': 'application/json' }) \n};\n\nThe complete code is as follows −\nimport { Injectable } from '@angular/core';\nimport { ExpenseEntry } from './expense-entry';\nimport { Observable, throwError } from 'rxjs';\nimport { catchError, retry } from 'rxjs/operators';\nimport { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';\n\n@Injectable({\n providedIn: 'root'\n})\nexport class ExpenseEntryService {\n private expenseRestUrl = 'api/expense';\n private httpOptions = {\n headers: new HttpHeaders( { 'Content-Type': 'application/json' })\n };\n\n constructor(\n private httpClient : HttpClient) { }\n}\n\nHttpClient provides get() method to fetch data from a web page. The main argument is the target web url. Another optional argument is the option object with below format −\n{\n headers?: HttpHeaders | {[header: string]: string | string[]},\n observe?: 'body' | 'events' | 'response',\n\n params?: HttpParams|{[param: string]: string | string[]},\n reportProgress?: boolean,\n responseType?: 'arraybuffer'|'blob'|'json'|'text',\n withCredentials?: boolean,\n}\n\nHere,\nheaders − HTTP Headers of the request, either as string, array of string or array of HttpHeaders.\nheaders − HTTP Headers of the request, either as string, array of string or array of HttpHeaders.\nobserve − Process the response and return the specific content of the response. Possible values are body, response and events. The default option of observer is body.\nobserve − Process the response and return the specific content of the response. Possible values are body, response and events. The default option of observer is body.\nparams − HTTP parameters of the request, either as string, array of string or array of HttpParams.\nparams − HTTP parameters of the request, either as string, array of string or array of HttpParams.\nreportProgress − Whether to report the progress of the process or not (true or false).\nreportProgress − Whether to report the progress of the process or not (true or false).\nresponseType − Refers the format of the response. Possible values are arraybuffer, blob, json and text.\nresponseType − Refers the format of the response. Possible values are arraybuffer, blob, json and text.\nwithCredentials − Whether the request has credentials or not (true or false).\nwithCredentials − Whether the request has credentials or not (true or false).\nAll options are optional.\nget() method returns the response of the request as Observable. The returned Observable emit the data when the response is received from the server.\nThe sample code to use get() method is as follows −\nhttpClient.get(url, options) \n.subscribe( (data) => console.log(data) );\n\nget() method has an option to return observables, which emits typed response as well. The sample code to get typed response (ExpenseEntry) is as follows:\nhttpClient.get(url, options) .subscribe( (data: T) => console.log(data) );\n\nError handling is one of the important aspect in the HTTP programming. Encountering error is one of the common scenario in HTTP programming.\nErrors in HTTP Programming can be categories into two groups −\nClient side issues can occur due to network failure, misconfiguration, etc., If client side error happens, then the get() method throws ErrorEvent object.\nClient side issues can occur due to network failure, misconfiguration, etc., If client side error happens, then the get() method throws ErrorEvent object.\nServer side issues can occur due to wrong url, server unavailability, server programming errors, etc.,\nServer side issues can occur due to wrong url, server unavailability, server programming errors, etc.,\nLet us write a simple error handling for our ExpenseEntryService service.\nprivate httpErrorHandler (error: HttpErrorResponse) {\n if (error.error instanceof ErrorEvent) {\n console.error(\"A client side error occurs. The error message is \" + error.message);\n } else {\n console.error(\n \"An error happened in server. The HTTP status code is \" + error.status + \" and the error returned is \" + error.message);\n }\n\n return throwError(\"Error occurred. Pleas try again\");\n}\n\nThe error function can be called in get() as specified below −\nhttpClient.get(url, options) \n .pipe(catchError(this.httpErrorHandler) \n .subscribe( (data) => console.log(data) )\n\nAs we mentioned earlier, errors can happen and one way is to handle it. Another option is to try for certain number of times. If the request failed due to network issue or the HTTP server is temporarily offline, the next request may succeed.\nWe can use rxjs library’s retry operator in this scenario as specified below\nhttpClient.get(url, options) \n .pipe( \n retry(5), \n catchError(this.httpErrorHandler)) \n .subscribe( (data) => console.log(data) )\n\nLet us do the actual coding to fetch the expenses from Expense Rest API in our ExpenseManager application.\nOpen command prompt and go to project root folder.\ncd /go/to/expense-manager\n\nStart the application.\nng serve\n\nAdd getExpenseEntries() and httpErrorHandler() method in ExpenseEntryService (src/app/expense-entry.service.ts) service.\ngetExpenseEntries() : Observable {\n return this.httpClient.get(this.expenseRestUrl, this.httpOptions)\n .pipe(retry(3),catchError(this.httpErrorHandler));\n}\n\ngetExpenseEntry(id: number) : Observable {\n return this.httpClient.get(this.expenseRestUrl + \"/\" + id, this.httpOptions)\n .pipe(\n retry(3),\n catchError(this.httpErrorHandler)\n );\n}\n\nprivate httpErrorHandler (error: HttpErrorResponse) {\n if (error.error instanceof ErrorEvent) {\n console.error(\"A client side error occurs. The error message is \" + error.message);\n } else {\n console.error(\n \"An error happened in server. The HTTP status code is \" + error.status + \" and the error returned is \" + error.message);\n }\n\n return throwError(\"Error occurred. Pleas try again\");\n}\nHere,\ngetExpenseEntries() calls the get() method using expense end point and also configures the error handler. Also, it configures httpClient to try for maximum of 3 times in case of failure. Finally, it returns the response from server as typed (ExpenseEntry[]) Observable object.\ngetExpenseEntries() calls the get() method using expense end point and also configures the error handler. Also, it configures httpClient to try for maximum of 3 times in case of failure. Finally, it returns the response from server as typed (ExpenseEntry[]) Observable object.\ngetExpenseEntry is similar to getExpenseEntries() except it passes the id of the ExpenseEntry object and gets ExpenseEntry Observable object.\ngetExpenseEntry is similar to getExpenseEntries() except it passes the id of the ExpenseEntry object and gets ExpenseEntry Observable object.\nThe complete coding of ExpenseEntryService is as follows −\nimport { Injectable } from '@angular/core';\nimport { ExpenseEntry } from './expense-entry';\n\nimport { Observable, throwError } from 'rxjs';\nimport { catchError, retry } from 'rxjs/operators';\nimport { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';\n\n@Injectable({\n\n providedIn: 'root'\n})\nexport class ExpenseEntryService {\n private expenseRestUrl = 'http://localhost:8000/api/expense';\n private httpOptions = {\n headers: new HttpHeaders( { 'Content-Type': 'application/json' })\n };\n\n constructor(private httpClient : HttpClient) { } \n\n getExpenseEntries() : Observable {\n return this.httpClient.get(this.expenseRestUrl, this.httpOptions)\n .pipe(\n retry(3),\n catchError(this.httpErrorHandler)\n );\n }\n\n getExpenseEntry(id: number) : Observable {\n return this.httpClient.get(this.expenseRestUrl + \"/\" + id, this.httpOptions)\n .pipe(\n retry(3),\n catchError(this.httpErrorHandler)\n );\n }\n\n private httpErrorHandler (error: HttpErrorResponse) {\n if (error.error instanceof ErrorEvent) {\n console.error(\"A client side error occurs. The error message is \" + error.message);\n } else {\n console.error(\n \"An error happened in server. The HTTP status code is \" + error.status + \" and the error returned is \" + error.message);\n }\n\n return throwError(\"Error occurred. Pleas try again\");\n }\n}\nOpen ExpenseEntryListComponent (src-entry-list-entry-list.component.ts) and inject ExpenseEntryService through constructor as specified below:\nconstructor(private debugService: DebugService, private restService : \nExpenseEntryService ) { }\n\nChange the getExpenseEntries() function. Call getExpenseEntries() method from ExpenseEntryService instead of returning the mock items.\ngetExpenseItems() { \n this.restService.getExpenseEntries() \n .subscribe( data =− this.expenseEntries = data ); \n}\n\nThe complete ExpenseEntryListComponent coding is as follows −\nimport { Component, OnInit } from '@angular/core';\nimport { ExpenseEntry } from '../expense-entry';\nimport { DebugService } from '../debug.service';\nimport { ExpenseEntryService } from '../expense-entry.service';\n\n@Component({\n selector: 'app-expense-entry-list',\n templateUrl: './expense-entry-list.component.html',\n styleUrls: ['./expense-entry-list.component.css'],\n providers: [DebugService]\n})\nexport class ExpenseEntryListComponent implements OnInit {\n title: string;\n expenseEntries: ExpenseEntry[];\n constructor(private debugService: DebugService, private restService : ExpenseEntryService ) { }\n\n ngOnInit() {\n this.debugService.info(\"Expense Entry List component initialized\");\n this.title = \"Expense Entry List\";\n\n this.getExpenseItems();\n }\n\n getExpenseItems() {\n this.restService.getExpenseEntries()\n .subscribe( data => this.expenseEntries = data );\n }\n}\nFinally, check the application and you will see the below response.\nHTTP POST is similar to HTTP GET except that the post request will send the necessary data as posted content along with the request. HTTP POST is used to insert new record into the system.\nHttpClient provides post() method, which is similar to get() except it support extra argument to send the data to the server.\nLet us add a new method, addExpenseEntry() in our ExpenseEntryService to add new expense entry as mentioned below −\naddExpenseEntry(expenseEntry: ExpenseEntry): Observable {\n return this.httpClient.post(this.expenseRestUrl, expenseEntry, this.httpOptions)\n .pipe(\n retry(3),\n catchError(this.httpErrorHandler)\n );\n}\nHTTP PUT is similar to HTTP POST request. HTTP PUT is used to update existing record in the system.\nhttpClient provides put() method, which is similar to post().\nLet us add a new method, updateExpenseEntry() in our ExpenseEntryService to update existing expense entry as mentioned below:\nupdateExpenseEntry(expenseEntry: ExpenseEntry): Observable {\n return this.httpClient.put(this.expenseRestUrl + \"/\" + expenseEntry.id, expenseEntry, this.httpOptions)\n .pipe(\n retry(3),\n catchError(this.httpErrorHandler)\n );\n}\nHTTP DELETE is similar to http GET request. HTTP DELETE is used to delete entries in the system.\nhttpclient provides delete() method, which is similar to get().\nLet us add a new method, deleteExpenseEntry() in our ExpenseEntryService to delete existing expense entry as mentioned below −\ndeleteExpenseEntry(expenseEntry: ExpenseEntry | number) : Observable {\n const id = typeof expenseEntry == 'number' ? expenseEntry : expenseEntry.id\n const url = `${this.expenseRestUrl}/${id}`;\n\n return this.httpClient.delete(url, this.httpOptions)\n .pipe(\n retry(3),\n catchError(this.httpErrorHandler)\n );\n}\n\n 16 Lectures \n 1.5 hours \n\n Anadi Sharma\n\n 28 Lectures \n 2.5 hours \n\n Anadi Sharma\n\n 11 Lectures \n 7.5 hours \n\n SHIVPRASAD KOIRALA\n\n 16 Lectures \n 2.5 hours \n\n Frahaan Hussain\n\n 69 Lectures \n 5 hours \n\n Senol Atac\n\n 53 Lectures \n 3.5 hours \n\n Senol Atac\n Print\n Add Notes\n Bookmark this page"},"parsed":{"kind":"list like","value":[{"code":null,"e":2765,"s":2388,"text":"Http client programming is a must needed feature in every modern web application. Nowadays, lot of application exposes their functionality through REST API (functionality over HTTP protocol). With this in mind, Angular Team provides extensive support to access HTTP server. Angular provides a separate module, HttpClientModule and a service, HttpClient to do HTTP programming."},{"code":null,"e":2920,"s":2765,"text":"Let us learn how to how to use HttpClient service in this chapter. Developer should have a basic knowledge in Http programming to understand this chapter."},{"code":null,"e":3223,"s":2920,"text":"The prerequisite to do Http programming is the basic knowledge of Http protocol and REST API technique. Http programming involves two part, server and client. Angular provides support to create client side application. Express a popular web framework provides support to create server side application."},{"code":null,"e":3370,"s":3223,"text":"Let us create an Expense Rest API using express framework and then access it from our ExpenseManager application using Angular HttpClient service."},{"code":null,"e":3435,"s":3370,"text":"Open a command prompt and create a new folder, express-rest-api."},{"code":null,"e":3501,"s":3435,"text":"cd /go/to/workspace \nmkdir express-rest-api \ncd expense-rest-api\n"},{"code":null,"e":3557,"s":3501,"text":"Initialise a new node application using below command −"},{"code":null,"e":3567,"s":3557,"text":"npm init\n"},{"code":null,"e":3696,"s":3567,"text":"npm init will ask some basic questions like project name (express-rest-api), entry point (server.js), etc., as mentioned below −"},{"code":null,"e":4630,"s":3696,"text":"This utility will walk you through creating a package.json file. \nIt only covers the most common items, and tries to guess sensible defaults. \nSee `npm help json` for definitive documentation on these fields and exactly what they do. \nUse `npm install ` afterwards to install a package and save it as a dependency in the package.json file. \nPress ^C at any time to quit. \npackage name: (expense-rest-api) \nversion: (1.0.0) \ndescription: Rest api for Expense Application \nentry point: (index.js) server.js \ntest command:\ngit repository: \nkeywords: \nauthor: \nlicense: (ISC) \nAbout to write to \\path\\to\\workspace\\expense-rest-api\\package.json: { \n \"name\": \"expense-rest-api\", \n \"version\": \"1.0.0\", \n \"description\": \"Rest api for Expense Application\", \n \"main\": \"server.js\", \n \"scripts\": { \n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\" \n }, \n \"author\": \"\", \n \"license\": \"ISC\" \n} \nIs this OK? (yes) yes"},{"code":null,"e":4693,"s":4630,"text":"Install express, sqlite and cors modules using below command −"},{"code":null,"e":4727,"s":4693,"text":"npm install express sqlite3 cors\n"},{"code":null,"e":4780,"s":4727,"text":"Create a new file sqlitedb.js and place below code −"},{"code":null,"e":6117,"s":4780,"text":"var sqlite3 = require('sqlite3').verbose()\nconst DBSOURCE = \"expensedb.sqlite\"\n\nlet db = new sqlite3.Database(DBSOURCE, (err) => {\n if (err) {\n console.error(err.message)\n throw err\n }else{\n console.log('Connected to the SQLite database.')\n db.run(`CREATE TABLE expense (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n item text, \n amount real, \n category text, \n location text, \n spendOn text, \n createdOn text \n )`,\n (err) => {\n if (err) {\n console.log(err);\n }else{\n var insert = 'INSERT INTO expense (item, amount, category, location, spendOn, createdOn) VALUES (?,?,?,?,?,?)'\n\n db.run(insert, ['Pizza', 10, 'Food', 'KFC', '2020-05-26 10:10', '2020-05-26 10:10'])\n db.run(insert, ['Pizza', 9, 'Food', 'Mcdonald', '2020-05-28 11:10', '2020-05-28 11:10'])\n db.run(insert, ['Pizza', 12, 'Food', 'Mcdonald', '2020-05-29 09:22', '2020-05-29 09:22'])\n db.run(insert, ['Pizza', 15, 'Food', 'KFC', '2020-06-06 16:18', '2020-06-06 16:18'])\n db.run(insert, ['Pizza', 14, 'Food', 'Mcdonald', '2020-06-01 18:14', '2020-05-01 18:14'])\n }\n }\n ); \n }\n});\n\nmodule.exports = db"},{"code":null,"e":6188,"s":6117,"text":"Here, we are creating a new sqlite database and load some sample data."},{"code":null,"e":6226,"s":6188,"text":"Open server.js and place below code −"},{"code":null,"e":9126,"s":6226,"text":"var express = require(\"express\")\nvar cors = require('cors')\nvar db = require(\"./sqlitedb.js\")\n\nvar app = express()\napp.use(cors());\n\nvar bodyParser = require(\"body-parser\");\napp.use(bodyParser.urlencoded({ extended: false }));\napp.use(bodyParser.json());\n\nvar HTTP_PORT = 8000 \napp.listen(HTTP_PORT, () => {\n console.log(\"Server running on port %PORT%\".replace(\"%PORT%\",HTTP_PORT))\n});\n\napp.get(\"/\", (req, res, next) => {\n res.json({\"message\":\"Ok\"})\n});\n\napp.get(\"/api/expense\", (req, res, next) => {\n var sql = \"select * from expense\"\n var params = []\n db.all(sql, params, (err, rows) => {\n if (err) {\n res.status(400).json({\"error\":err.message});\n return;\n }\n res.json(rows)\n });\n\n});\n\napp.get(\"/api/expense/:id\", (req, res, next) => {\n var sql = \"select * from expense where id = ?\"\n var params = [req.params.id]\n db.get(sql, params, (err, row) => {\n if (err) {\n res.status(400).json({\"error\":err.message});\n return;\n }\n res.json(row)\n });\n});\n\napp.post(\"/api/expense/\", (req, res, next) => {\n var errors=[]\n if (!req.body.item){\n errors.push(\"No item specified\");\n }\n var data = {\n item : req.body.item,\n amount: req.body.amount,\n category: req.body.category,\n location : req.body.location,\n spendOn: req.body.spendOn,\n createdOn: req.body.createdOn,\n }\n var sql = 'INSERT INTO expense (item, amount, category, location, spendOn, createdOn) VALUES (?,?,?,?,?,?)'\n var params =[data.item, data.amount, data.category, data.location, data.spendOn, data.createdOn]\n db.run(sql, params, function (err, result) {\n if (err){\n res.status(400).json({\"error\": err.message})\n return;\n }\n data.id = this.lastID;\n res.json(data);\n });\n})\n\napp.put(\"/api/expense/:id\", (req, res, next) => {\n var data = {\n item : req.body.item,\n amount: req.body.amount,\n category: req.body.category,\n location : req.body.location,\n spendOn: req.body.spendOn\n }\n db.run(\n `UPDATE expense SET\n item = ?, \n\n amount = ?,\n category = ?, \n location = ?, \n\n spendOn = ? \n WHERE id = ?`,\n [data.item, data.amount, data.category, data.location,data.spendOn, req.params.id],\n function (err, result) {\n if (err){\n console.log(err);\n res.status(400).json({\"error\": res.message})\n return;\n }\n res.json(data)\n });\n})\n\napp.delete(\"/api/expense/:id\", (req, res, next) => {\n db.run(\n 'DELETE FROM expense WHERE id = ?',\n req.params.id,\n function (err, result) {\n if (err){\n res.status(400).json({\"error\": res.message})\n return;\n }\n res.json({\"message\":\"deleted\", changes: this.changes})\n });\n})\n\napp.use(function(req, res){\n res.status(404);\n});"},{"code":null,"e":9216,"s":9126,"text":"Here, we create a basic CURD rest api to select, insert, update and delete expense entry."},{"code":null,"e":9258,"s":9216,"text":"Run the application using below command −"},{"code":null,"e":9273,"s":9258,"text":"npm run start\n"},{"code":null,"e":9365,"s":9273,"text":"Open a browser, enter http://localhost:8000/ and press enter. You will see below response −"},{"code":null,"e":9391,"s":9365,"text":"{ \n \"message\": \"Ok\" \n}\n"},{"code":null,"e":9436,"s":9391,"text":"It confirms our application is working fine."},{"code":null,"e":9545,"s":9436,"text":"Change the url to http://localhost:8000/api/expense and you will see all the expense entries in JSON format."},{"code":null,"e":10538,"s":9545,"text":"[\n {\n \"id\": 1,\n\n \"item\": \"Pizza\",\n \"amount\": 10,\n \"category\": \"Food\",\n \"location\": \"KFC\",\n \"spendOn\": \"2020-05-26 10:10\",\n \"createdOn\": \"2020-05-26 10:10\"\n },\n {\n \"id\": 2,\n \"item\": \"Pizza\",\n \"amount\": 14,\n \"category\": \"Food\",\n \"location\": \"Mcdonald\",\n \"spendOn\": \"2020-06-01 18:14\",\n \"createdOn\": \"2020-05-01 18:14\"\n },\n {\n \"id\": 3,\n \"item\": \"Pizza\",\n \"amount\": 15,\n \"category\": \"Food\",\n \"location\": \"KFC\",\n \"spendOn\": \"2020-06-06 16:18\",\n \"createdOn\": \"2020-06-06 16:18\"\n },\n {\n \"id\": 4,\n \"item\": \"Pizza\",\n \"amount\": 9,\n \"category\": \"Food\",\n \"location\": \"Mcdonald\",\n \"spendOn\": \"2020-05-28 11:10\",\n \"createdOn\": \"2020-05-28 11:10\"\n },\n {\n \"id\": 5,\n \"item\": \"Pizza\",\n \"amount\": 12,\n \"category\": \"Food\",\n \"location\": \"Mcdonald\",\n \"spendOn\": \"2020-05-29 09:22\",\n \"createdOn\": \"2020-05-29 09:22\"\n }\n]"},{"code":null,"e":10687,"s":10538,"text":"Finally, we created a simple CURD REST API for expense entry and we can access the REST API from our Angular application to learn HttpClient module."},{"code":null,"e":10753,"s":10687,"text":"Let us learn how to configure HttpClient service in this chapter."},{"code":null,"e":10881,"s":10753,"text":"HttpClient service is available inside the HttpClientModule module, which is available inside the @angular/common/http package."},{"code":null,"e":10919,"s":10881,"text":"To register HttpClientModule module −"},{"code":null,"e":10963,"s":10919,"text":"Import the HttpClientModule in AppComponent"},{"code":null,"e":11021,"s":10963,"text":"import { HttpClientModule } from '@angular/common/http';\n"},{"code":null,"e":11084,"s":11021,"text":"Include HttpClientModule in imports meta data of AppComponent."},{"code":null,"e":11251,"s":11084,"text":"@NgModule({ \n imports: [ \n BrowserModule, \n // import HttpClientModule after BrowserModule. \n HttpClientModule, \n ] \n}) \nexport class AppModule {}\n"},{"code":null,"e":11526,"s":11251,"text":"Let us create a new service ExpenseEntryService in our ExpenseManager application to interact with Expense REST API. ExpenseEntryService will get the latest expense entries, insert new expense entries, modify existing expense entries and delete the unwanted expense entries."},{"code":null,"e":11577,"s":11526,"text":"Open command prompt and go to project root folder."},{"code":null,"e":11604,"s":11577,"text":"cd /go/to/expense-manager\n"},{"code":null,"e":11627,"s":11604,"text":"Start the application."},{"code":null,"e":11637,"s":11627,"text":"ng serve\n"},{"code":null,"e":11707,"s":11637,"text":"Run the below command to generate an Angular service, ExpenseService."},{"code":null,"e":11741,"s":11707,"text":"ng generate service ExpenseEntry\n"},{"code":null,"e":11835,"s":11741,"text":"This will create two Typescript files (expense entry service & its test) as specified below −"},{"code":null,"e":11946,"s":11835,"text":"CREATE src/app/expense-entry.service.spec.ts (364 bytes) \nCREATE src/app/expense-entry.service.ts (141 bytes)\n"},{"code":null,"e":12167,"s":11946,"text":"Open ExpenseEntryService (src/app/expense-entry.service.ts) and import ExpenseEntry, throwError and catchError from rxjs library and import HttpClient, HttpHeaders and HttpErrorResponse from @angular/common/http package."},{"code":null,"e":12426,"s":12167,"text":"import { Injectable } from '@angular/core'; \nimport { ExpenseEntry } from './expense-entry'; import { throwError } from 'rxjs';\nimport { catchError } from 'rxjs/operators'; \nimport { HttpClient, HttpHeaders, HttpErrorResponse } from \n'@angular/common/http';\n"},{"code":null,"e":12474,"s":12426,"text":"Inject the HttpClient service into our service."},{"code":null,"e":12524,"s":12474,"text":"constructor(private httpClient : HttpClient) { }\n"},{"code":null,"e":12601,"s":12524,"text":"Create a variable, expenseRestUrl to specify the Expense Rest API endpoints."},{"code":null,"e":12664,"s":12601,"text":"private expenseRestUrl = 'http://localhost:8000/api/expense';\n"},{"code":null,"e":12805,"s":12664,"text":"Create a variable, httpOptions to set the Http Header option. This will be used during the Http Rest API call by Angular HttpClient service."},{"code":null,"e":12904,"s":12805,"text":"private httpOptions = { \n headers: new HttpHeaders( { 'Content-Type': 'application/json' }) \n};\n"},{"code":null,"e":12938,"s":12904,"text":"The complete code is as follows −"},{"code":null,"e":13498,"s":12938,"text":"import { Injectable } from '@angular/core';\nimport { ExpenseEntry } from './expense-entry';\nimport { Observable, throwError } from 'rxjs';\nimport { catchError, retry } from 'rxjs/operators';\nimport { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';\n\n@Injectable({\n providedIn: 'root'\n})\nexport class ExpenseEntryService {\n private expenseRestUrl = 'api/expense';\n private httpOptions = {\n headers: new HttpHeaders( { 'Content-Type': 'application/json' })\n };\n\n constructor(\n private httpClient : HttpClient) { }\n}\n"},{"code":null,"e":13670,"s":13498,"text":"HttpClient provides get() method to fetch data from a web page. The main argument is the target web url. Another optional argument is the option object with below format −"},{"code":null,"e":13961,"s":13670,"text":"{\n headers?: HttpHeaders | {[header: string]: string | string[]},\n observe?: 'body' | 'events' | 'response',\n\n params?: HttpParams|{[param: string]: string | string[]},\n reportProgress?: boolean,\n responseType?: 'arraybuffer'|'blob'|'json'|'text',\n withCredentials?: boolean,\n}\n"},{"code":null,"e":13967,"s":13961,"text":"Here,"},{"code":null,"e":14065,"s":13967,"text":"headers − HTTP Headers of the request, either as string, array of string or array of HttpHeaders."},{"code":null,"e":14163,"s":14065,"text":"headers − HTTP Headers of the request, either as string, array of string or array of HttpHeaders."},{"code":null,"e":14330,"s":14163,"text":"observe − Process the response and return the specific content of the response. Possible values are body, response and events. The default option of observer is body."},{"code":null,"e":14497,"s":14330,"text":"observe − Process the response and return the specific content of the response. Possible values are body, response and events. The default option of observer is body."},{"code":null,"e":14596,"s":14497,"text":"params − HTTP parameters of the request, either as string, array of string or array of HttpParams."},{"code":null,"e":14695,"s":14596,"text":"params − HTTP parameters of the request, either as string, array of string or array of HttpParams."},{"code":null,"e":14782,"s":14695,"text":"reportProgress − Whether to report the progress of the process or not (true or false)."},{"code":null,"e":14869,"s":14782,"text":"reportProgress − Whether to report the progress of the process or not (true or false)."},{"code":null,"e":14973,"s":14869,"text":"responseType − Refers the format of the response. Possible values are arraybuffer, blob, json and text."},{"code":null,"e":15077,"s":14973,"text":"responseType − Refers the format of the response. Possible values are arraybuffer, blob, json and text."},{"code":null,"e":15155,"s":15077,"text":"withCredentials − Whether the request has credentials or not (true or false)."},{"code":null,"e":15233,"s":15155,"text":"withCredentials − Whether the request has credentials or not (true or false)."},{"code":null,"e":15259,"s":15233,"text":"All options are optional."},{"code":null,"e":15408,"s":15259,"text":"get() method returns the response of the request as Observable. The returned Observable emit the data when the response is received from the server."},{"code":null,"e":15460,"s":15408,"text":"The sample code to use get() method is as follows −"},{"code":null,"e":15534,"s":15460,"text":"httpClient.get(url, options) \n.subscribe( (data) => console.log(data) );\n"},{"code":null,"e":15688,"s":15534,"text":"get() method has an option to return observables, which emits typed response as well. The sample code to get typed response (ExpenseEntry) is as follows:"},{"code":null,"e":15767,"s":15688,"text":"httpClient.get(url, options) .subscribe( (data: T) => console.log(data) );\n"},{"code":null,"e":15908,"s":15767,"text":"Error handling is one of the important aspect in the HTTP programming. Encountering error is one of the common scenario in HTTP programming."},{"code":null,"e":15971,"s":15908,"text":"Errors in HTTP Programming can be categories into two groups −"},{"code":null,"e":16126,"s":15971,"text":"Client side issues can occur due to network failure, misconfiguration, etc., If client side error happens, then the get() method throws ErrorEvent object."},{"code":null,"e":16281,"s":16126,"text":"Client side issues can occur due to network failure, misconfiguration, etc., If client side error happens, then the get() method throws ErrorEvent object."},{"code":null,"e":16384,"s":16281,"text":"Server side issues can occur due to wrong url, server unavailability, server programming errors, etc.,"},{"code":null,"e":16487,"s":16384,"text":"Server side issues can occur due to wrong url, server unavailability, server programming errors, etc.,"},{"code":null,"e":16561,"s":16487,"text":"Let us write a simple error handling for our ExpenseEntryService service."},{"code":null,"e":16991,"s":16561,"text":"private httpErrorHandler (error: HttpErrorResponse) {\n if (error.error instanceof ErrorEvent) {\n console.error(\"A client side error occurs. The error message is \" + error.message);\n } else {\n console.error(\n \"An error happened in server. The HTTP status code is \" + error.status + \" and the error returned is \" + error.message);\n }\n\n return throwError(\"Error occurred. Pleas try again\");\n}\n"},{"code":null,"e":17054,"s":16991,"text":"The error function can be called in get() as specified below −"},{"code":null,"e":17175,"s":17054,"text":"httpClient.get(url, options) \n .pipe(catchError(this.httpErrorHandler) \n .subscribe( (data) => console.log(data) )\n"},{"code":null,"e":17417,"s":17175,"text":"As we mentioned earlier, errors can happen and one way is to handle it. Another option is to try for certain number of times. If the request failed due to network issue or the HTTP server is temporarily offline, the next request may succeed."},{"code":null,"e":17494,"s":17417,"text":"We can use rxjs library’s retry operator in this scenario as specified below"},{"code":null,"e":17640,"s":17494,"text":"httpClient.get(url, options) \n .pipe( \n retry(5), \n catchError(this.httpErrorHandler)) \n .subscribe( (data) => console.log(data) )\n"},{"code":null,"e":17747,"s":17640,"text":"Let us do the actual coding to fetch the expenses from Expense Rest API in our ExpenseManager application."},{"code":null,"e":17798,"s":17747,"text":"Open command prompt and go to project root folder."},{"code":null,"e":17825,"s":17798,"text":"cd /go/to/expense-manager\n"},{"code":null,"e":17848,"s":17825,"text":"Start the application."},{"code":null,"e":17858,"s":17848,"text":"ng serve\n"},{"code":null,"e":17979,"s":17858,"text":"Add getExpenseEntries() and httpErrorHandler() method in ExpenseEntryService (src/app/expense-entry.service.ts) service."},{"code":null,"e":18815,"s":17979,"text":"getExpenseEntries() : Observable {\n return this.httpClient.get(this.expenseRestUrl, this.httpOptions)\n .pipe(retry(3),catchError(this.httpErrorHandler));\n}\n\ngetExpenseEntry(id: number) : Observable {\n return this.httpClient.get(this.expenseRestUrl + \"/\" + id, this.httpOptions)\n .pipe(\n retry(3),\n catchError(this.httpErrorHandler)\n );\n}\n\nprivate httpErrorHandler (error: HttpErrorResponse) {\n if (error.error instanceof ErrorEvent) {\n console.error(\"A client side error occurs. The error message is \" + error.message);\n } else {\n console.error(\n \"An error happened in server. The HTTP status code is \" + error.status + \" and the error returned is \" + error.message);\n }\n\n return throwError(\"Error occurred. Pleas try again\");\n}"},{"code":null,"e":18821,"s":18815,"text":"Here,"},{"code":null,"e":19098,"s":18821,"text":"getExpenseEntries() calls the get() method using expense end point and also configures the error handler. Also, it configures httpClient to try for maximum of 3 times in case of failure. Finally, it returns the response from server as typed (ExpenseEntry[]) Observable object."},{"code":null,"e":19375,"s":19098,"text":"getExpenseEntries() calls the get() method using expense end point and also configures the error handler. Also, it configures httpClient to try for maximum of 3 times in case of failure. Finally, it returns the response from server as typed (ExpenseEntry[]) Observable object."},{"code":null,"e":19517,"s":19375,"text":"getExpenseEntry is similar to getExpenseEntries() except it passes the id of the ExpenseEntry object and gets ExpenseEntry Observable object."},{"code":null,"e":19659,"s":19517,"text":"getExpenseEntry is similar to getExpenseEntries() except it passes the id of the ExpenseEntry object and gets ExpenseEntry Observable object."},{"code":null,"e":19718,"s":19659,"text":"The complete coding of ExpenseEntryService is as follows −"},{"code":null,"e":21159,"s":19718,"text":"import { Injectable } from '@angular/core';\nimport { ExpenseEntry } from './expense-entry';\n\nimport { Observable, throwError } from 'rxjs';\nimport { catchError, retry } from 'rxjs/operators';\nimport { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';\n\n@Injectable({\n\n providedIn: 'root'\n})\nexport class ExpenseEntryService {\n private expenseRestUrl = 'http://localhost:8000/api/expense';\n private httpOptions = {\n headers: new HttpHeaders( { 'Content-Type': 'application/json' })\n };\n\n constructor(private httpClient : HttpClient) { } \n\n getExpenseEntries() : Observable {\n return this.httpClient.get(this.expenseRestUrl, this.httpOptions)\n .pipe(\n retry(3),\n catchError(this.httpErrorHandler)\n );\n }\n\n getExpenseEntry(id: number) : Observable {\n return this.httpClient.get(this.expenseRestUrl + \"/\" + id, this.httpOptions)\n .pipe(\n retry(3),\n catchError(this.httpErrorHandler)\n );\n }\n\n private httpErrorHandler (error: HttpErrorResponse) {\n if (error.error instanceof ErrorEvent) {\n console.error(\"A client side error occurs. The error message is \" + error.message);\n } else {\n console.error(\n \"An error happened in server. The HTTP status code is \" + error.status + \" and the error returned is \" + error.message);\n }\n\n return throwError(\"Error occurred. Pleas try again\");\n }\n}"},{"code":null,"e":21302,"s":21159,"text":"Open ExpenseEntryListComponent (src-entry-list-entry-list.component.ts) and inject ExpenseEntryService through constructor as specified below:"},{"code":null,"e":21400,"s":21302,"text":"constructor(private debugService: DebugService, private restService : \nExpenseEntryService ) { }\n"},{"code":null,"e":21535,"s":21400,"text":"Change the getExpenseEntries() function. Call getExpenseEntries() method from ExpenseEntryService instead of returning the mock items."},{"code":null,"e":21658,"s":21535,"text":"getExpenseItems() { \n this.restService.getExpenseEntries() \n .subscribe( data =− this.expenseEntries = data ); \n}\n"},{"code":null,"e":21720,"s":21658,"text":"The complete ExpenseEntryListComponent coding is as follows −"},{"code":null,"e":22636,"s":21720,"text":"import { Component, OnInit } from '@angular/core';\nimport { ExpenseEntry } from '../expense-entry';\nimport { DebugService } from '../debug.service';\nimport { ExpenseEntryService } from '../expense-entry.service';\n\n@Component({\n selector: 'app-expense-entry-list',\n templateUrl: './expense-entry-list.component.html',\n styleUrls: ['./expense-entry-list.component.css'],\n providers: [DebugService]\n})\nexport class ExpenseEntryListComponent implements OnInit {\n title: string;\n expenseEntries: ExpenseEntry[];\n constructor(private debugService: DebugService, private restService : ExpenseEntryService ) { }\n\n ngOnInit() {\n this.debugService.info(\"Expense Entry List component initialized\");\n this.title = \"Expense Entry List\";\n\n this.getExpenseItems();\n }\n\n getExpenseItems() {\n this.restService.getExpenseEntries()\n .subscribe( data => this.expenseEntries = data );\n }\n}"},{"code":null,"e":22704,"s":22636,"text":"Finally, check the application and you will see the below response."},{"code":null,"e":22893,"s":22704,"text":"HTTP POST is similar to HTTP GET except that the post request will send the necessary data as posted content along with the request. HTTP POST is used to insert new record into the system."},{"code":null,"e":23019,"s":22893,"text":"HttpClient provides post() method, which is similar to get() except it support extra argument to send the data to the server."},{"code":null,"e":23135,"s":23019,"text":"Let us add a new method, addExpenseEntry() in our ExpenseEntryService to add new expense entry as mentioned below −"},{"code":null,"e":23379,"s":23135,"text":"addExpenseEntry(expenseEntry: ExpenseEntry): Observable {\n return this.httpClient.post(this.expenseRestUrl, expenseEntry, this.httpOptions)\n .pipe(\n retry(3),\n catchError(this.httpErrorHandler)\n );\n}"},{"code":null,"e":23479,"s":23379,"text":"HTTP PUT is similar to HTTP POST request. HTTP PUT is used to update existing record in the system."},{"code":null,"e":23541,"s":23479,"text":"httpClient provides put() method, which is similar to post()."},{"code":null,"e":23667,"s":23541,"text":"Let us add a new method, updateExpenseEntry() in our ExpenseEntryService to update existing expense entry as mentioned below:"},{"code":null,"e":23937,"s":23667,"text":"updateExpenseEntry(expenseEntry: ExpenseEntry): Observable {\n return this.httpClient.put(this.expenseRestUrl + \"/\" + expenseEntry.id, expenseEntry, this.httpOptions)\n .pipe(\n retry(3),\n catchError(this.httpErrorHandler)\n );\n}"},{"code":null,"e":24034,"s":23937,"text":"HTTP DELETE is similar to http GET request. HTTP DELETE is used to delete entries in the system."},{"code":null,"e":24098,"s":24034,"text":"httpclient provides delete() method, which is similar to get()."},{"code":null,"e":24225,"s":24098,"text":"Let us add a new method, deleteExpenseEntry() in our ExpenseEntryService to delete existing expense entry as mentioned below −"},{"code":null,"e":24581,"s":24225,"text":"deleteExpenseEntry(expenseEntry: ExpenseEntry | number) : Observable {\n const id = typeof expenseEntry == 'number' ? expenseEntry : expenseEntry.id\n const url = `${this.expenseRestUrl}/${id}`;\n\n return this.httpClient.delete(url, this.httpOptions)\n .pipe(\n retry(3),\n catchError(this.httpErrorHandler)\n );\n}"},{"code":null,"e":24616,"s":24581,"text":"\n 16 Lectures \n 1.5 hours \n"},{"code":null,"e":24630,"s":24616,"text":" Anadi Sharma"},{"code":null,"e":24665,"s":24630,"text":"\n 28 Lectures \n 2.5 hours \n"},{"code":null,"e":24679,"s":24665,"text":" Anadi Sharma"},{"code":null,"e":24714,"s":24679,"text":"\n 11 Lectures \n 7.5 hours \n"},{"code":null,"e":24734,"s":24714,"text":" SHIVPRASAD KOIRALA"},{"code":null,"e":24769,"s":24734,"text":"\n 16 Lectures \n 2.5 hours \n"},{"code":null,"e":24786,"s":24769,"text":" Frahaan Hussain"},{"code":null,"e":24819,"s":24786,"text":"\n 69 Lectures \n 5 hours \n"},{"code":null,"e":24831,"s":24819,"text":" Senol Atac"},{"code":null,"e":24866,"s":24831,"text":"\n 53 Lectures \n 3.5 hours \n"},{"code":null,"e":24878,"s":24866,"text":" Senol Atac"},{"code":null,"e":24885,"s":24878,"text":" Print"},{"code":null,"e":24896,"s":24885,"text":" Add Notes"}],"string":"[\n {\n \"code\": null,\n \"e\": 2765,\n \"s\": 2388,\n \"text\": \"Http client programming is a must needed feature in every modern web application. Nowadays, lot of application exposes their functionality through REST API (functionality over HTTP protocol). With this in mind, Angular Team provides extensive support to access HTTP server. Angular provides a separate module, HttpClientModule and a service, HttpClient to do HTTP programming.\"\n },\n {\n \"code\": null,\n \"e\": 2920,\n \"s\": 2765,\n \"text\": \"Let us learn how to how to use HttpClient service in this chapter. Developer should have a basic knowledge in Http programming to understand this chapter.\"\n },\n {\n \"code\": null,\n \"e\": 3223,\n \"s\": 2920,\n \"text\": \"The prerequisite to do Http programming is the basic knowledge of Http protocol and REST API technique. Http programming involves two part, server and client. Angular provides support to create client side application. Express a popular web framework provides support to create server side application.\"\n },\n {\n \"code\": null,\n \"e\": 3370,\n \"s\": 3223,\n \"text\": \"Let us create an Expense Rest API using express framework and then access it from our ExpenseManager application using Angular HttpClient service.\"\n },\n {\n \"code\": null,\n \"e\": 3435,\n \"s\": 3370,\n \"text\": \"Open a command prompt and create a new folder, express-rest-api.\"\n },\n {\n \"code\": null,\n \"e\": 3501,\n \"s\": 3435,\n \"text\": \"cd /go/to/workspace \\nmkdir express-rest-api \\ncd expense-rest-api\\n\"\n },\n {\n \"code\": null,\n \"e\": 3557,\n \"s\": 3501,\n \"text\": \"Initialise a new node application using below command −\"\n },\n {\n \"code\": null,\n \"e\": 3567,\n \"s\": 3557,\n \"text\": \"npm init\\n\"\n },\n {\n \"code\": null,\n \"e\": 3696,\n \"s\": 3567,\n \"text\": \"npm init will ask some basic questions like project name (express-rest-api), entry point (server.js), etc., as mentioned below −\"\n },\n {\n \"code\": null,\n \"e\": 4630,\n \"s\": 3696,\n \"text\": \"This utility will walk you through creating a package.json file. \\nIt only covers the most common items, and tries to guess sensible defaults. \\nSee `npm help json` for definitive documentation on these fields and exactly what they do. \\nUse `npm install ` afterwards to install a package and save it as a dependency in the package.json file. \\nPress ^C at any time to quit. \\npackage name: (expense-rest-api) \\nversion: (1.0.0) \\ndescription: Rest api for Expense Application \\nentry point: (index.js) server.js \\ntest command:\\ngit repository: \\nkeywords: \\nauthor: \\nlicense: (ISC) \\nAbout to write to \\\\path\\\\to\\\\workspace\\\\expense-rest-api\\\\package.json: { \\n \\\"name\\\": \\\"expense-rest-api\\\", \\n \\\"version\\\": \\\"1.0.0\\\", \\n \\\"description\\\": \\\"Rest api for Expense Application\\\", \\n \\\"main\\\": \\\"server.js\\\", \\n \\\"scripts\\\": { \\n \\\"test\\\": \\\"echo \\\\\\\"Error: no test specified\\\\\\\" && exit 1\\\" \\n }, \\n \\\"author\\\": \\\"\\\", \\n \\\"license\\\": \\\"ISC\\\" \\n} \\nIs this OK? (yes) yes\"\n },\n {\n \"code\": null,\n \"e\": 4693,\n \"s\": 4630,\n \"text\": \"Install express, sqlite and cors modules using below command −\"\n },\n {\n \"code\": null,\n \"e\": 4727,\n \"s\": 4693,\n \"text\": \"npm install express sqlite3 cors\\n\"\n },\n {\n \"code\": null,\n \"e\": 4780,\n \"s\": 4727,\n \"text\": \"Create a new file sqlitedb.js and place below code −\"\n },\n {\n \"code\": null,\n \"e\": 6117,\n \"s\": 4780,\n \"text\": \"var sqlite3 = require('sqlite3').verbose()\\nconst DBSOURCE = \\\"expensedb.sqlite\\\"\\n\\nlet db = new sqlite3.Database(DBSOURCE, (err) => {\\n if (err) {\\n console.error(err.message)\\n throw err\\n }else{\\n console.log('Connected to the SQLite database.')\\n db.run(`CREATE TABLE expense (\\n id INTEGER PRIMARY KEY AUTOINCREMENT,\\n item text, \\n amount real, \\n category text, \\n location text, \\n spendOn text, \\n createdOn text \\n )`,\\n (err) => {\\n if (err) {\\n console.log(err);\\n }else{\\n var insert = 'INSERT INTO expense (item, amount, category, location, spendOn, createdOn) VALUES (?,?,?,?,?,?)'\\n\\n db.run(insert, ['Pizza', 10, 'Food', 'KFC', '2020-05-26 10:10', '2020-05-26 10:10'])\\n db.run(insert, ['Pizza', 9, 'Food', 'Mcdonald', '2020-05-28 11:10', '2020-05-28 11:10'])\\n db.run(insert, ['Pizza', 12, 'Food', 'Mcdonald', '2020-05-29 09:22', '2020-05-29 09:22'])\\n db.run(insert, ['Pizza', 15, 'Food', 'KFC', '2020-06-06 16:18', '2020-06-06 16:18'])\\n db.run(insert, ['Pizza', 14, 'Food', 'Mcdonald', '2020-06-01 18:14', '2020-05-01 18:14'])\\n }\\n }\\n ); \\n }\\n});\\n\\nmodule.exports = db\"\n },\n {\n \"code\": null,\n \"e\": 6188,\n \"s\": 6117,\n \"text\": \"Here, we are creating a new sqlite database and load some sample data.\"\n },\n {\n \"code\": null,\n \"e\": 6226,\n \"s\": 6188,\n \"text\": \"Open server.js and place below code −\"\n },\n {\n \"code\": null,\n \"e\": 9126,\n \"s\": 6226,\n \"text\": \"var express = require(\\\"express\\\")\\nvar cors = require('cors')\\nvar db = require(\\\"./sqlitedb.js\\\")\\n\\nvar app = express()\\napp.use(cors());\\n\\nvar bodyParser = require(\\\"body-parser\\\");\\napp.use(bodyParser.urlencoded({ extended: false }));\\napp.use(bodyParser.json());\\n\\nvar HTTP_PORT = 8000 \\napp.listen(HTTP_PORT, () => {\\n console.log(\\\"Server running on port %PORT%\\\".replace(\\\"%PORT%\\\",HTTP_PORT))\\n});\\n\\napp.get(\\\"/\\\", (req, res, next) => {\\n res.json({\\\"message\\\":\\\"Ok\\\"})\\n});\\n\\napp.get(\\\"/api/expense\\\", (req, res, next) => {\\n var sql = \\\"select * from expense\\\"\\n var params = []\\n db.all(sql, params, (err, rows) => {\\n if (err) {\\n res.status(400).json({\\\"error\\\":err.message});\\n return;\\n }\\n res.json(rows)\\n });\\n\\n});\\n\\napp.get(\\\"/api/expense/:id\\\", (req, res, next) => {\\n var sql = \\\"select * from expense where id = ?\\\"\\n var params = [req.params.id]\\n db.get(sql, params, (err, row) => {\\n if (err) {\\n res.status(400).json({\\\"error\\\":err.message});\\n return;\\n }\\n res.json(row)\\n });\\n});\\n\\napp.post(\\\"/api/expense/\\\", (req, res, next) => {\\n var errors=[]\\n if (!req.body.item){\\n errors.push(\\\"No item specified\\\");\\n }\\n var data = {\\n item : req.body.item,\\n amount: req.body.amount,\\n category: req.body.category,\\n location : req.body.location,\\n spendOn: req.body.spendOn,\\n createdOn: req.body.createdOn,\\n }\\n var sql = 'INSERT INTO expense (item, amount, category, location, spendOn, createdOn) VALUES (?,?,?,?,?,?)'\\n var params =[data.item, data.amount, data.category, data.location, data.spendOn, data.createdOn]\\n db.run(sql, params, function (err, result) {\\n if (err){\\n res.status(400).json({\\\"error\\\": err.message})\\n return;\\n }\\n data.id = this.lastID;\\n res.json(data);\\n });\\n})\\n\\napp.put(\\\"/api/expense/:id\\\", (req, res, next) => {\\n var data = {\\n item : req.body.item,\\n amount: req.body.amount,\\n category: req.body.category,\\n location : req.body.location,\\n spendOn: req.body.spendOn\\n }\\n db.run(\\n `UPDATE expense SET\\n item = ?, \\n\\n amount = ?,\\n category = ?, \\n location = ?, \\n\\n spendOn = ? \\n WHERE id = ?`,\\n [data.item, data.amount, data.category, data.location,data.spendOn, req.params.id],\\n function (err, result) {\\n if (err){\\n console.log(err);\\n res.status(400).json({\\\"error\\\": res.message})\\n return;\\n }\\n res.json(data)\\n });\\n})\\n\\napp.delete(\\\"/api/expense/:id\\\", (req, res, next) => {\\n db.run(\\n 'DELETE FROM expense WHERE id = ?',\\n req.params.id,\\n function (err, result) {\\n if (err){\\n res.status(400).json({\\\"error\\\": res.message})\\n return;\\n }\\n res.json({\\\"message\\\":\\\"deleted\\\", changes: this.changes})\\n });\\n})\\n\\napp.use(function(req, res){\\n res.status(404);\\n});\"\n },\n {\n \"code\": null,\n \"e\": 9216,\n \"s\": 9126,\n \"text\": \"Here, we create a basic CURD rest api to select, insert, update and delete expense entry.\"\n },\n {\n \"code\": null,\n \"e\": 9258,\n \"s\": 9216,\n \"text\": \"Run the application using below command −\"\n },\n {\n \"code\": null,\n \"e\": 9273,\n \"s\": 9258,\n \"text\": \"npm run start\\n\"\n },\n {\n \"code\": null,\n \"e\": 9365,\n \"s\": 9273,\n \"text\": \"Open a browser, enter http://localhost:8000/ and press enter. You will see below response −\"\n },\n {\n \"code\": null,\n \"e\": 9391,\n \"s\": 9365,\n \"text\": \"{ \\n \\\"message\\\": \\\"Ok\\\" \\n}\\n\"\n },\n {\n \"code\": null,\n \"e\": 9436,\n \"s\": 9391,\n \"text\": \"It confirms our application is working fine.\"\n },\n {\n \"code\": null,\n \"e\": 9545,\n \"s\": 9436,\n \"text\": \"Change the url to http://localhost:8000/api/expense and you will see all the expense entries in JSON format.\"\n },\n {\n \"code\": null,\n \"e\": 10538,\n \"s\": 9545,\n \"text\": \"[\\n {\\n \\\"id\\\": 1,\\n\\n \\\"item\\\": \\\"Pizza\\\",\\n \\\"amount\\\": 10,\\n \\\"category\\\": \\\"Food\\\",\\n \\\"location\\\": \\\"KFC\\\",\\n \\\"spendOn\\\": \\\"2020-05-26 10:10\\\",\\n \\\"createdOn\\\": \\\"2020-05-26 10:10\\\"\\n },\\n {\\n \\\"id\\\": 2,\\n \\\"item\\\": \\\"Pizza\\\",\\n \\\"amount\\\": 14,\\n \\\"category\\\": \\\"Food\\\",\\n \\\"location\\\": \\\"Mcdonald\\\",\\n \\\"spendOn\\\": \\\"2020-06-01 18:14\\\",\\n \\\"createdOn\\\": \\\"2020-05-01 18:14\\\"\\n },\\n {\\n \\\"id\\\": 3,\\n \\\"item\\\": \\\"Pizza\\\",\\n \\\"amount\\\": 15,\\n \\\"category\\\": \\\"Food\\\",\\n \\\"location\\\": \\\"KFC\\\",\\n \\\"spendOn\\\": \\\"2020-06-06 16:18\\\",\\n \\\"createdOn\\\": \\\"2020-06-06 16:18\\\"\\n },\\n {\\n \\\"id\\\": 4,\\n \\\"item\\\": \\\"Pizza\\\",\\n \\\"amount\\\": 9,\\n \\\"category\\\": \\\"Food\\\",\\n \\\"location\\\": \\\"Mcdonald\\\",\\n \\\"spendOn\\\": \\\"2020-05-28 11:10\\\",\\n \\\"createdOn\\\": \\\"2020-05-28 11:10\\\"\\n },\\n {\\n \\\"id\\\": 5,\\n \\\"item\\\": \\\"Pizza\\\",\\n \\\"amount\\\": 12,\\n \\\"category\\\": \\\"Food\\\",\\n \\\"location\\\": \\\"Mcdonald\\\",\\n \\\"spendOn\\\": \\\"2020-05-29 09:22\\\",\\n \\\"createdOn\\\": \\\"2020-05-29 09:22\\\"\\n }\\n]\"\n },\n {\n \"code\": null,\n \"e\": 10687,\n \"s\": 10538,\n \"text\": \"Finally, we created a simple CURD REST API for expense entry and we can access the REST API from our Angular application to learn HttpClient module.\"\n },\n {\n \"code\": null,\n \"e\": 10753,\n \"s\": 10687,\n \"text\": \"Let us learn how to configure HttpClient service in this chapter.\"\n },\n {\n \"code\": null,\n \"e\": 10881,\n \"s\": 10753,\n \"text\": \"HttpClient service is available inside the HttpClientModule module, which is available inside the @angular/common/http package.\"\n },\n {\n \"code\": null,\n \"e\": 10919,\n \"s\": 10881,\n \"text\": \"To register HttpClientModule module −\"\n },\n {\n \"code\": null,\n \"e\": 10963,\n \"s\": 10919,\n \"text\": \"Import the HttpClientModule in AppComponent\"\n },\n {\n \"code\": null,\n \"e\": 11021,\n \"s\": 10963,\n \"text\": \"import { HttpClientModule } from '@angular/common/http';\\n\"\n },\n {\n \"code\": null,\n \"e\": 11084,\n \"s\": 11021,\n \"text\": \"Include HttpClientModule in imports meta data of AppComponent.\"\n },\n {\n \"code\": null,\n \"e\": 11251,\n \"s\": 11084,\n \"text\": \"@NgModule({ \\n imports: [ \\n BrowserModule, \\n // import HttpClientModule after BrowserModule. \\n HttpClientModule, \\n ] \\n}) \\nexport class AppModule {}\\n\"\n },\n {\n \"code\": null,\n \"e\": 11526,\n \"s\": 11251,\n \"text\": \"Let us create a new service ExpenseEntryService in our ExpenseManager application to interact with Expense REST API. ExpenseEntryService will get the latest expense entries, insert new expense entries, modify existing expense entries and delete the unwanted expense entries.\"\n },\n {\n \"code\": null,\n \"e\": 11577,\n \"s\": 11526,\n \"text\": \"Open command prompt and go to project root folder.\"\n },\n {\n \"code\": null,\n \"e\": 11604,\n \"s\": 11577,\n \"text\": \"cd /go/to/expense-manager\\n\"\n },\n {\n \"code\": null,\n \"e\": 11627,\n \"s\": 11604,\n \"text\": \"Start the application.\"\n },\n {\n \"code\": null,\n \"e\": 11637,\n \"s\": 11627,\n \"text\": \"ng serve\\n\"\n },\n {\n \"code\": null,\n \"e\": 11707,\n \"s\": 11637,\n \"text\": \"Run the below command to generate an Angular service, ExpenseService.\"\n },\n {\n \"code\": null,\n \"e\": 11741,\n \"s\": 11707,\n \"text\": \"ng generate service ExpenseEntry\\n\"\n },\n {\n \"code\": null,\n \"e\": 11835,\n \"s\": 11741,\n \"text\": \"This will create two Typescript files (expense entry service & its test) as specified below −\"\n },\n {\n \"code\": null,\n \"e\": 11946,\n \"s\": 11835,\n \"text\": \"CREATE src/app/expense-entry.service.spec.ts (364 bytes) \\nCREATE src/app/expense-entry.service.ts (141 bytes)\\n\"\n },\n {\n \"code\": null,\n \"e\": 12167,\n \"s\": 11946,\n \"text\": \"Open ExpenseEntryService (src/app/expense-entry.service.ts) and import ExpenseEntry, throwError and catchError from rxjs library and import HttpClient, HttpHeaders and HttpErrorResponse from @angular/common/http package.\"\n },\n {\n \"code\": null,\n \"e\": 12426,\n \"s\": 12167,\n \"text\": \"import { Injectable } from '@angular/core'; \\nimport { ExpenseEntry } from './expense-entry'; import { throwError } from 'rxjs';\\nimport { catchError } from 'rxjs/operators'; \\nimport { HttpClient, HttpHeaders, HttpErrorResponse } from \\n'@angular/common/http';\\n\"\n },\n {\n \"code\": null,\n \"e\": 12474,\n \"s\": 12426,\n \"text\": \"Inject the HttpClient service into our service.\"\n },\n {\n \"code\": null,\n \"e\": 12524,\n \"s\": 12474,\n \"text\": \"constructor(private httpClient : HttpClient) { }\\n\"\n },\n {\n \"code\": null,\n \"e\": 12601,\n \"s\": 12524,\n \"text\": \"Create a variable, expenseRestUrl to specify the Expense Rest API endpoints.\"\n },\n {\n \"code\": null,\n \"e\": 12664,\n \"s\": 12601,\n \"text\": \"private expenseRestUrl = 'http://localhost:8000/api/expense';\\n\"\n },\n {\n \"code\": null,\n \"e\": 12805,\n \"s\": 12664,\n \"text\": \"Create a variable, httpOptions to set the Http Header option. This will be used during the Http Rest API call by Angular HttpClient service.\"\n },\n {\n \"code\": null,\n \"e\": 12904,\n \"s\": 12805,\n \"text\": \"private httpOptions = { \\n headers: new HttpHeaders( { 'Content-Type': 'application/json' }) \\n};\\n\"\n },\n {\n \"code\": null,\n \"e\": 12938,\n \"s\": 12904,\n \"text\": \"The complete code is as follows −\"\n },\n {\n \"code\": null,\n \"e\": 13498,\n \"s\": 12938,\n \"text\": \"import { Injectable } from '@angular/core';\\nimport { ExpenseEntry } from './expense-entry';\\nimport { Observable, throwError } from 'rxjs';\\nimport { catchError, retry } from 'rxjs/operators';\\nimport { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';\\n\\n@Injectable({\\n providedIn: 'root'\\n})\\nexport class ExpenseEntryService {\\n private expenseRestUrl = 'api/expense';\\n private httpOptions = {\\n headers: new HttpHeaders( { 'Content-Type': 'application/json' })\\n };\\n\\n constructor(\\n private httpClient : HttpClient) { }\\n}\\n\"\n },\n {\n \"code\": null,\n \"e\": 13670,\n \"s\": 13498,\n \"text\": \"HttpClient provides get() method to fetch data from a web page. The main argument is the target web url. Another optional argument is the option object with below format −\"\n },\n {\n \"code\": null,\n \"e\": 13961,\n \"s\": 13670,\n \"text\": \"{\\n headers?: HttpHeaders | {[header: string]: string | string[]},\\n observe?: 'body' | 'events' | 'response',\\n\\n params?: HttpParams|{[param: string]: string | string[]},\\n reportProgress?: boolean,\\n responseType?: 'arraybuffer'|'blob'|'json'|'text',\\n withCredentials?: boolean,\\n}\\n\"\n },\n {\n \"code\": null,\n \"e\": 13967,\n \"s\": 13961,\n \"text\": \"Here,\"\n },\n {\n \"code\": null,\n \"e\": 14065,\n \"s\": 13967,\n \"text\": \"headers − HTTP Headers of the request, either as string, array of string or array of HttpHeaders.\"\n },\n {\n \"code\": null,\n \"e\": 14163,\n \"s\": 14065,\n \"text\": \"headers − HTTP Headers of the request, either as string, array of string or array of HttpHeaders.\"\n },\n {\n \"code\": null,\n \"e\": 14330,\n \"s\": 14163,\n \"text\": \"observe − Process the response and return the specific content of the response. Possible values are body, response and events. The default option of observer is body.\"\n },\n {\n \"code\": null,\n \"e\": 14497,\n \"s\": 14330,\n \"text\": \"observe − Process the response and return the specific content of the response. Possible values are body, response and events. The default option of observer is body.\"\n },\n {\n \"code\": null,\n \"e\": 14596,\n \"s\": 14497,\n \"text\": \"params − HTTP parameters of the request, either as string, array of string or array of HttpParams.\"\n },\n {\n \"code\": null,\n \"e\": 14695,\n \"s\": 14596,\n \"text\": \"params − HTTP parameters of the request, either as string, array of string or array of HttpParams.\"\n },\n {\n \"code\": null,\n \"e\": 14782,\n \"s\": 14695,\n \"text\": \"reportProgress − Whether to report the progress of the process or not (true or false).\"\n },\n {\n \"code\": null,\n \"e\": 14869,\n \"s\": 14782,\n \"text\": \"reportProgress − Whether to report the progress of the process or not (true or false).\"\n },\n {\n \"code\": null,\n \"e\": 14973,\n \"s\": 14869,\n \"text\": \"responseType − Refers the format of the response. Possible values are arraybuffer, blob, json and text.\"\n },\n {\n \"code\": null,\n \"e\": 15077,\n \"s\": 14973,\n \"text\": \"responseType − Refers the format of the response. Possible values are arraybuffer, blob, json and text.\"\n },\n {\n \"code\": null,\n \"e\": 15155,\n \"s\": 15077,\n \"text\": \"withCredentials − Whether the request has credentials or not (true or false).\"\n },\n {\n \"code\": null,\n \"e\": 15233,\n \"s\": 15155,\n \"text\": \"withCredentials − Whether the request has credentials or not (true or false).\"\n },\n {\n \"code\": null,\n \"e\": 15259,\n \"s\": 15233,\n \"text\": \"All options are optional.\"\n },\n {\n \"code\": null,\n \"e\": 15408,\n \"s\": 15259,\n \"text\": \"get() method returns the response of the request as Observable. The returned Observable emit the data when the response is received from the server.\"\n },\n {\n \"code\": null,\n \"e\": 15460,\n \"s\": 15408,\n \"text\": \"The sample code to use get() method is as follows −\"\n },\n {\n \"code\": null,\n \"e\": 15534,\n \"s\": 15460,\n \"text\": \"httpClient.get(url, options) \\n.subscribe( (data) => console.log(data) );\\n\"\n },\n {\n \"code\": null,\n \"e\": 15688,\n \"s\": 15534,\n \"text\": \"get() method has an option to return observables, which emits typed response as well. The sample code to get typed response (ExpenseEntry) is as follows:\"\n },\n {\n \"code\": null,\n \"e\": 15767,\n \"s\": 15688,\n \"text\": \"httpClient.get(url, options) .subscribe( (data: T) => console.log(data) );\\n\"\n },\n {\n \"code\": null,\n \"e\": 15908,\n \"s\": 15767,\n \"text\": \"Error handling is one of the important aspect in the HTTP programming. Encountering error is one of the common scenario in HTTP programming.\"\n },\n {\n \"code\": null,\n \"e\": 15971,\n \"s\": 15908,\n \"text\": \"Errors in HTTP Programming can be categories into two groups −\"\n },\n {\n \"code\": null,\n \"e\": 16126,\n \"s\": 15971,\n \"text\": \"Client side issues can occur due to network failure, misconfiguration, etc., If client side error happens, then the get() method throws ErrorEvent object.\"\n },\n {\n \"code\": null,\n \"e\": 16281,\n \"s\": 16126,\n \"text\": \"Client side issues can occur due to network failure, misconfiguration, etc., If client side error happens, then the get() method throws ErrorEvent object.\"\n },\n {\n \"code\": null,\n \"e\": 16384,\n \"s\": 16281,\n \"text\": \"Server side issues can occur due to wrong url, server unavailability, server programming errors, etc.,\"\n },\n {\n \"code\": null,\n \"e\": 16487,\n \"s\": 16384,\n \"text\": \"Server side issues can occur due to wrong url, server unavailability, server programming errors, etc.,\"\n },\n {\n \"code\": null,\n \"e\": 16561,\n \"s\": 16487,\n \"text\": \"Let us write a simple error handling for our ExpenseEntryService service.\"\n },\n {\n \"code\": null,\n \"e\": 16991,\n \"s\": 16561,\n \"text\": \"private httpErrorHandler (error: HttpErrorResponse) {\\n if (error.error instanceof ErrorEvent) {\\n console.error(\\\"A client side error occurs. The error message is \\\" + error.message);\\n } else {\\n console.error(\\n \\\"An error happened in server. The HTTP status code is \\\" + error.status + \\\" and the error returned is \\\" + error.message);\\n }\\n\\n return throwError(\\\"Error occurred. Pleas try again\\\");\\n}\\n\"\n },\n {\n \"code\": null,\n \"e\": 17054,\n \"s\": 16991,\n \"text\": \"The error function can be called in get() as specified below −\"\n },\n {\n \"code\": null,\n \"e\": 17175,\n \"s\": 17054,\n \"text\": \"httpClient.get(url, options) \\n .pipe(catchError(this.httpErrorHandler) \\n .subscribe( (data) => console.log(data) )\\n\"\n },\n {\n \"code\": null,\n \"e\": 17417,\n \"s\": 17175,\n \"text\": \"As we mentioned earlier, errors can happen and one way is to handle it. Another option is to try for certain number of times. If the request failed due to network issue or the HTTP server is temporarily offline, the next request may succeed.\"\n },\n {\n \"code\": null,\n \"e\": 17494,\n \"s\": 17417,\n \"text\": \"We can use rxjs library’s retry operator in this scenario as specified below\"\n },\n {\n \"code\": null,\n \"e\": 17640,\n \"s\": 17494,\n \"text\": \"httpClient.get(url, options) \\n .pipe( \\n retry(5), \\n catchError(this.httpErrorHandler)) \\n .subscribe( (data) => console.log(data) )\\n\"\n },\n {\n \"code\": null,\n \"e\": 17747,\n \"s\": 17640,\n \"text\": \"Let us do the actual coding to fetch the expenses from Expense Rest API in our ExpenseManager application.\"\n },\n {\n \"code\": null,\n \"e\": 17798,\n \"s\": 17747,\n \"text\": \"Open command prompt and go to project root folder.\"\n },\n {\n \"code\": null,\n \"e\": 17825,\n \"s\": 17798,\n \"text\": \"cd /go/to/expense-manager\\n\"\n },\n {\n \"code\": null,\n \"e\": 17848,\n \"s\": 17825,\n \"text\": \"Start the application.\"\n },\n {\n \"code\": null,\n \"e\": 17858,\n \"s\": 17848,\n \"text\": \"ng serve\\n\"\n },\n {\n \"code\": null,\n \"e\": 17979,\n \"s\": 17858,\n \"text\": \"Add getExpenseEntries() and httpErrorHandler() method in ExpenseEntryService (src/app/expense-entry.service.ts) service.\"\n },\n {\n \"code\": null,\n \"e\": 18815,\n \"s\": 17979,\n \"text\": \"getExpenseEntries() : Observable {\\n return this.httpClient.get(this.expenseRestUrl, this.httpOptions)\\n .pipe(retry(3),catchError(this.httpErrorHandler));\\n}\\n\\ngetExpenseEntry(id: number) : Observable {\\n return this.httpClient.get(this.expenseRestUrl + \\\"/\\\" + id, this.httpOptions)\\n .pipe(\\n retry(3),\\n catchError(this.httpErrorHandler)\\n );\\n}\\n\\nprivate httpErrorHandler (error: HttpErrorResponse) {\\n if (error.error instanceof ErrorEvent) {\\n console.error(\\\"A client side error occurs. The error message is \\\" + error.message);\\n } else {\\n console.error(\\n \\\"An error happened in server. The HTTP status code is \\\" + error.status + \\\" and the error returned is \\\" + error.message);\\n }\\n\\n return throwError(\\\"Error occurred. Pleas try again\\\");\\n}\"\n },\n {\n \"code\": null,\n \"e\": 18821,\n \"s\": 18815,\n \"text\": \"Here,\"\n },\n {\n \"code\": null,\n \"e\": 19098,\n \"s\": 18821,\n \"text\": \"getExpenseEntries() calls the get() method using expense end point and also configures the error handler. Also, it configures httpClient to try for maximum of 3 times in case of failure. Finally, it returns the response from server as typed (ExpenseEntry[]) Observable object.\"\n },\n {\n \"code\": null,\n \"e\": 19375,\n \"s\": 19098,\n \"text\": \"getExpenseEntries() calls the get() method using expense end point and also configures the error handler. Also, it configures httpClient to try for maximum of 3 times in case of failure. Finally, it returns the response from server as typed (ExpenseEntry[]) Observable object.\"\n },\n {\n \"code\": null,\n \"e\": 19517,\n \"s\": 19375,\n \"text\": \"getExpenseEntry is similar to getExpenseEntries() except it passes the id of the ExpenseEntry object and gets ExpenseEntry Observable object.\"\n },\n {\n \"code\": null,\n \"e\": 19659,\n \"s\": 19517,\n \"text\": \"getExpenseEntry is similar to getExpenseEntries() except it passes the id of the ExpenseEntry object and gets ExpenseEntry Observable object.\"\n },\n {\n \"code\": null,\n \"e\": 19718,\n \"s\": 19659,\n \"text\": \"The complete coding of ExpenseEntryService is as follows −\"\n },\n {\n \"code\": null,\n \"e\": 21159,\n \"s\": 19718,\n \"text\": \"import { Injectable } from '@angular/core';\\nimport { ExpenseEntry } from './expense-entry';\\n\\nimport { Observable, throwError } from 'rxjs';\\nimport { catchError, retry } from 'rxjs/operators';\\nimport { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';\\n\\n@Injectable({\\n\\n providedIn: 'root'\\n})\\nexport class ExpenseEntryService {\\n private expenseRestUrl = 'http://localhost:8000/api/expense';\\n private httpOptions = {\\n headers: new HttpHeaders( { 'Content-Type': 'application/json' })\\n };\\n\\n constructor(private httpClient : HttpClient) { } \\n\\n getExpenseEntries() : Observable {\\n return this.httpClient.get(this.expenseRestUrl, this.httpOptions)\\n .pipe(\\n retry(3),\\n catchError(this.httpErrorHandler)\\n );\\n }\\n\\n getExpenseEntry(id: number) : Observable {\\n return this.httpClient.get(this.expenseRestUrl + \\\"/\\\" + id, this.httpOptions)\\n .pipe(\\n retry(3),\\n catchError(this.httpErrorHandler)\\n );\\n }\\n\\n private httpErrorHandler (error: HttpErrorResponse) {\\n if (error.error instanceof ErrorEvent) {\\n console.error(\\\"A client side error occurs. The error message is \\\" + error.message);\\n } else {\\n console.error(\\n \\\"An error happened in server. The HTTP status code is \\\" + error.status + \\\" and the error returned is \\\" + error.message);\\n }\\n\\n return throwError(\\\"Error occurred. Pleas try again\\\");\\n }\\n}\"\n },\n {\n \"code\": null,\n \"e\": 21302,\n \"s\": 21159,\n \"text\": \"Open ExpenseEntryListComponent (src-entry-list-entry-list.component.ts) and inject ExpenseEntryService through constructor as specified below:\"\n },\n {\n \"code\": null,\n \"e\": 21400,\n \"s\": 21302,\n \"text\": \"constructor(private debugService: DebugService, private restService : \\nExpenseEntryService ) { }\\n\"\n },\n {\n \"code\": null,\n \"e\": 21535,\n \"s\": 21400,\n \"text\": \"Change the getExpenseEntries() function. Call getExpenseEntries() method from ExpenseEntryService instead of returning the mock items.\"\n },\n {\n \"code\": null,\n \"e\": 21658,\n \"s\": 21535,\n \"text\": \"getExpenseItems() { \\n this.restService.getExpenseEntries() \\n .subscribe( data =− this.expenseEntries = data ); \\n}\\n\"\n },\n {\n \"code\": null,\n \"e\": 21720,\n \"s\": 21658,\n \"text\": \"The complete ExpenseEntryListComponent coding is as follows −\"\n },\n {\n \"code\": null,\n \"e\": 22636,\n \"s\": 21720,\n \"text\": \"import { Component, OnInit } from '@angular/core';\\nimport { ExpenseEntry } from '../expense-entry';\\nimport { DebugService } from '../debug.service';\\nimport { ExpenseEntryService } from '../expense-entry.service';\\n\\n@Component({\\n selector: 'app-expense-entry-list',\\n templateUrl: './expense-entry-list.component.html',\\n styleUrls: ['./expense-entry-list.component.css'],\\n providers: [DebugService]\\n})\\nexport class ExpenseEntryListComponent implements OnInit {\\n title: string;\\n expenseEntries: ExpenseEntry[];\\n constructor(private debugService: DebugService, private restService : ExpenseEntryService ) { }\\n\\n ngOnInit() {\\n this.debugService.info(\\\"Expense Entry List component initialized\\\");\\n this.title = \\\"Expense Entry List\\\";\\n\\n this.getExpenseItems();\\n }\\n\\n getExpenseItems() {\\n this.restService.getExpenseEntries()\\n .subscribe( data => this.expenseEntries = data );\\n }\\n}\"\n },\n {\n \"code\": null,\n \"e\": 22704,\n \"s\": 22636,\n \"text\": \"Finally, check the application and you will see the below response.\"\n },\n {\n \"code\": null,\n \"e\": 22893,\n \"s\": 22704,\n \"text\": \"HTTP POST is similar to HTTP GET except that the post request will send the necessary data as posted content along with the request. HTTP POST is used to insert new record into the system.\"\n },\n {\n \"code\": null,\n \"e\": 23019,\n \"s\": 22893,\n \"text\": \"HttpClient provides post() method, which is similar to get() except it support extra argument to send the data to the server.\"\n },\n {\n \"code\": null,\n \"e\": 23135,\n \"s\": 23019,\n \"text\": \"Let us add a new method, addExpenseEntry() in our ExpenseEntryService to add new expense entry as mentioned below −\"\n },\n {\n \"code\": null,\n \"e\": 23379,\n \"s\": 23135,\n \"text\": \"addExpenseEntry(expenseEntry: ExpenseEntry): Observable {\\n return this.httpClient.post(this.expenseRestUrl, expenseEntry, this.httpOptions)\\n .pipe(\\n retry(3),\\n catchError(this.httpErrorHandler)\\n );\\n}\"\n },\n {\n \"code\": null,\n \"e\": 23479,\n \"s\": 23379,\n \"text\": \"HTTP PUT is similar to HTTP POST request. HTTP PUT is used to update existing record in the system.\"\n },\n {\n \"code\": null,\n \"e\": 23541,\n \"s\": 23479,\n \"text\": \"httpClient provides put() method, which is similar to post().\"\n },\n {\n \"code\": null,\n \"e\": 23667,\n \"s\": 23541,\n \"text\": \"Let us add a new method, updateExpenseEntry() in our ExpenseEntryService to update existing expense entry as mentioned below:\"\n },\n {\n \"code\": null,\n \"e\": 23937,\n \"s\": 23667,\n \"text\": \"updateExpenseEntry(expenseEntry: ExpenseEntry): Observable {\\n return this.httpClient.put(this.expenseRestUrl + \\\"/\\\" + expenseEntry.id, expenseEntry, this.httpOptions)\\n .pipe(\\n retry(3),\\n catchError(this.httpErrorHandler)\\n );\\n}\"\n },\n {\n \"code\": null,\n \"e\": 24034,\n \"s\": 23937,\n \"text\": \"HTTP DELETE is similar to http GET request. HTTP DELETE is used to delete entries in the system.\"\n },\n {\n \"code\": null,\n \"e\": 24098,\n \"s\": 24034,\n \"text\": \"httpclient provides delete() method, which is similar to get().\"\n },\n {\n \"code\": null,\n \"e\": 24225,\n \"s\": 24098,\n \"text\": \"Let us add a new method, deleteExpenseEntry() in our ExpenseEntryService to delete existing expense entry as mentioned below −\"\n },\n {\n \"code\": null,\n \"e\": 24581,\n \"s\": 24225,\n \"text\": \"deleteExpenseEntry(expenseEntry: ExpenseEntry | number) : Observable {\\n const id = typeof expenseEntry == 'number' ? expenseEntry : expenseEntry.id\\n const url = `${this.expenseRestUrl}/${id}`;\\n\\n return this.httpClient.delete(url, this.httpOptions)\\n .pipe(\\n retry(3),\\n catchError(this.httpErrorHandler)\\n );\\n}\"\n },\n {\n \"code\": null,\n \"e\": 24616,\n \"s\": 24581,\n \"text\": \"\\n 16 Lectures \\n 1.5 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 24630,\n \"s\": 24616,\n \"text\": \" Anadi Sharma\"\n },\n {\n \"code\": null,\n \"e\": 24665,\n \"s\": 24630,\n \"text\": \"\\n 28 Lectures \\n 2.5 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 24679,\n \"s\": 24665,\n \"text\": \" Anadi Sharma\"\n },\n {\n \"code\": null,\n \"e\": 24714,\n \"s\": 24679,\n \"text\": \"\\n 11 Lectures \\n 7.5 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 24734,\n \"s\": 24714,\n \"text\": \" SHIVPRASAD KOIRALA\"\n },\n {\n \"code\": null,\n \"e\": 24769,\n \"s\": 24734,\n \"text\": \"\\n 16 Lectures \\n 2.5 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 24786,\n \"s\": 24769,\n \"text\": \" Frahaan Hussain\"\n },\n {\n \"code\": null,\n \"e\": 24819,\n \"s\": 24786,\n \"text\": \"\\n 69 Lectures \\n 5 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 24831,\n \"s\": 24819,\n \"text\": \" Senol Atac\"\n },\n {\n \"code\": null,\n \"e\": 24866,\n \"s\": 24831,\n \"text\": \"\\n 53 Lectures \\n 3.5 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 24878,\n \"s\": 24866,\n \"text\": \" Senol Atac\"\n },\n {\n \"code\": null,\n \"e\": 24885,\n \"s\": 24878,\n \"text\": \" Print\"\n },\n {\n \"code\": null,\n \"e\": 24896,\n \"s\": 24885,\n \"text\": \" Add Notes\"\n }\n]"}}},{"rowIdx":123,"cells":{"title":{"kind":"string","value":"Tools to Securely Delete Files from Linux - GeeksforGeeks"},"text":{"kind":"string","value":"16 Feb, 2021\nEvery time you delete a file from your Linux system using the shift + delete or rm command, it doesn’t actually permanently and securely delete the file from the hard disk. When you delete a file with the rm command, the file system just frees up the appropriate inode but the contents of the old file are still in that space until it is overwritten which pave a way to recover the files.\nThe space that was used by the file that you deleted is now free to be used by other new files. But the contents of the old files are still in the hard disk, Until and unless that space is overwritten by something else, so there is a good chance that the file can be recovered by anyone (maybe by some data thieves) with good knowledge of recovering data. It is like removing the index page of a book, where the chapters are still there, it just becomes much hard to find, but we can find it. \nShred will help you to overwrite a deleted file, so it becomes difficult to recover it. It is like tearing a paper into as many pieces as you want or overwriting over the paper so that it becomes impossible to find out the original data.\nmanual of shred\nshred\nIn the above output, the meaning of the letters are:\n-u: deallocates and removes file after overwriting\n-v: enables the display of operation progress\n-z: adds a final overwrite with zeros to hide shredding\n-n: total number of times the file content will be overwritten(I gave 6).\nSecure-delete is a command containing a set of secure file deletion tools containing srm (secure_deletion) tool which is used to delete or overwrite the files securely in Linux. At first, we have to install it by typing:\nsudo apt-get install secure-delete \ninstall secure-delete\nThere is a total of 4 different types of tools consisting of this whole package and each of them performs a different type of securely delete operation. They are as follows:-\nsrm : It is a secure rm that is used to erase files by overwriting their hard disk space and deleting them.\nsfill : It is used to overwrite free space on the hard disk.\nsswap : It is used to overwrite swap space.\nsdmem : It is used to wipe the RAM Once secure-delete is installed.\n# srm Command:srm command deletes anything just like rm command but securely i.e by overwriting the file and its inode with random bytes. The larger the file, the longer it takes to wipe and rewrite it.\nsrm tool\nType srm man to get more information:\n manual\nThe Linux wipe command allows us to securely erase data from our hard disk permanently. The wipe command erases files from magnetic memory and rewrites the space repeatedly and wipe away the caches which make the data nearly impossible to be recovered. \nAt first, we have to install a wipe:\nsudo apt-get install wipe\nNow you can use wipe for secure deletion \nwipe\nTo know more about each function check wipe -h:\nmanual of wipe command\ndd command is especially used to convert or copy files. We can use this command to completely overwrite your hard drive with zeros, but DD will not zero a drive currently in use\nThe syntax is :\n- dd if= of= [Options]\nIn the above menu:\nlsblk: Lists all the disks\n/dev/urandom (input): The random data used for overwriting\n/dev/sda (output): the disk that will be overwritten. This disk will be replaced with random garbage data. \nSee the help menu of the “dd” command for more details:\ndd help menu\nLinux-Tools\nPicked\nTechnical Scripter 2020\nLinux-Unix\nTechnical Scripter\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nComments\nOld Comments\nThread functions in C/C++\nArray Basics in Shell Scripting | Set 1\nscp command in Linux with Examples\nnohup Command in Linux with Examples\nchown command in Linux with Examples\nmv command in Linux with examples\nNamed Pipe or FIFO with example C program\nSED command in Linux | Set 2\nBasic Operators in Shell Scripting\nStart/Stop/Restart Services Using Systemctl in Linux"},"parsed":{"kind":"list like","value":[{"code":null,"e":24350,"s":24322,"text":"\n16 Feb, 2021"},{"code":null,"e":24739,"s":24350,"text":"Every time you delete a file from your Linux system using the shift + delete or rm command, it doesn’t actually permanently and securely delete the file from the hard disk. When you delete a file with the rm command, the file system just frees up the appropriate inode but the contents of the old file are still in that space until it is overwritten which pave a way to recover the files."},{"code":null,"e":25233,"s":24739,"text":"The space that was used by the file that you deleted is now free to be used by other new files. But the contents of the old files are still in the hard disk, Until and unless that space is overwritten by something else, so there is a good chance that the file can be recovered by anyone (maybe by some data thieves) with good knowledge of recovering data. It is like removing the index page of a book, where the chapters are still there, it just becomes much hard to find, but we can find it. "},{"code":null,"e":25471,"s":25233,"text":"Shred will help you to overwrite a deleted file, so it becomes difficult to recover it. It is like tearing a paper into as many pieces as you want or overwriting over the paper so that it becomes impossible to find out the original data."},{"code":null,"e":25487,"s":25471,"text":"manual of shred"},{"code":null,"e":25493,"s":25487,"text":"shred"},{"code":null,"e":25546,"s":25493,"text":"In the above output, the meaning of the letters are:"},{"code":null,"e":25597,"s":25546,"text":"-u: deallocates and removes file after overwriting"},{"code":null,"e":25643,"s":25597,"text":"-v: enables the display of operation progress"},{"code":null,"e":25699,"s":25643,"text":"-z: adds a final overwrite with zeros to hide shredding"},{"code":null,"e":25773,"s":25699,"text":"-n: total number of times the file content will be overwritten(I gave 6)."},{"code":null,"e":25994,"s":25773,"text":"Secure-delete is a command containing a set of secure file deletion tools containing srm (secure_deletion) tool which is used to delete or overwrite the files securely in Linux. At first, we have to install it by typing:"},{"code":null,"e":26030,"s":25994,"text":"sudo apt-get install secure-delete "},{"code":null,"e":26052,"s":26030,"text":"install secure-delete"},{"code":null,"e":26227,"s":26052,"text":"There is a total of 4 different types of tools consisting of this whole package and each of them performs a different type of securely delete operation. They are as follows:-"},{"code":null,"e":26335,"s":26227,"text":"srm : It is a secure rm that is used to erase files by overwriting their hard disk space and deleting them."},{"code":null,"e":26396,"s":26335,"text":"sfill : It is used to overwrite free space on the hard disk."},{"code":null,"e":26440,"s":26396,"text":"sswap : It is used to overwrite swap space."},{"code":null,"e":26508,"s":26440,"text":"sdmem : It is used to wipe the RAM Once secure-delete is installed."},{"code":null,"e":26711,"s":26508,"text":"# srm Command:srm command deletes anything just like rm command but securely i.e by overwriting the file and its inode with random bytes. The larger the file, the longer it takes to wipe and rewrite it."},{"code":null,"e":26720,"s":26711,"text":"srm tool"},{"code":null,"e":26758,"s":26720,"text":"Type srm man to get more information:"},{"code":null,"e":26766,"s":26758,"text":" manual"},{"code":null,"e":27020,"s":26766,"text":"The Linux wipe command allows us to securely erase data from our hard disk permanently. The wipe command erases files from magnetic memory and rewrites the space repeatedly and wipe away the caches which make the data nearly impossible to be recovered. "},{"code":null,"e":27057,"s":27020,"text":"At first, we have to install a wipe:"},{"code":null,"e":27083,"s":27057,"text":"sudo apt-get install wipe"},{"code":null,"e":27125,"s":27083,"text":"Now you can use wipe for secure deletion "},{"code":null,"e":27130,"s":27125,"text":"wipe"},{"code":null,"e":27178,"s":27130,"text":"To know more about each function check wipe -h:"},{"code":null,"e":27201,"s":27178,"text":"manual of wipe command"},{"code":null,"e":27379,"s":27201,"text":"dd command is especially used to convert or copy files. We can use this command to completely overwrite your hard drive with zeros, but DD will not zero a drive currently in use"},{"code":null,"e":27395,"s":27379,"text":"The syntax is :"},{"code":null,"e":27434,"s":27395,"text":"- dd if= of= [Options]"},{"code":null,"e":27453,"s":27434,"text":"In the above menu:"},{"code":null,"e":27480,"s":27453,"text":"lsblk: Lists all the disks"},{"code":null,"e":27540,"s":27480,"text":"/dev/urandom (input): The random data used for overwriting"},{"code":null,"e":27648,"s":27540,"text":"/dev/sda (output): the disk that will be overwritten. This disk will be replaced with random garbage data. "},{"code":null,"e":27704,"s":27648,"text":"See the help menu of the “dd” command for more details:"},{"code":null,"e":27717,"s":27704,"text":"dd help menu"},{"code":null,"e":27729,"s":27717,"text":"Linux-Tools"},{"code":null,"e":27736,"s":27729,"text":"Picked"},{"code":null,"e":27760,"s":27736,"text":"Technical Scripter 2020"},{"code":null,"e":27771,"s":27760,"text":"Linux-Unix"},{"code":null,"e":27790,"s":27771,"text":"Technical Scripter"},{"code":null,"e":27888,"s":27790,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":27897,"s":27888,"text":"Comments"},{"code":null,"e":27910,"s":27897,"text":"Old Comments"},{"code":null,"e":27936,"s":27910,"text":"Thread functions in C/C++"},{"code":null,"e":27976,"s":27936,"text":"Array Basics in Shell Scripting | Set 1"},{"code":null,"e":28011,"s":27976,"text":"scp command in Linux with Examples"},{"code":null,"e":28048,"s":28011,"text":"nohup Command in Linux with Examples"},{"code":null,"e":28085,"s":28048,"text":"chown command in Linux with Examples"},{"code":null,"e":28119,"s":28085,"text":"mv command in Linux with examples"},{"code":null,"e":28161,"s":28119,"text":"Named Pipe or FIFO with example C program"},{"code":null,"e":28190,"s":28161,"text":"SED command in Linux | Set 2"},{"code":null,"e":28225,"s":28190,"text":"Basic Operators in Shell Scripting"}],"string":"[\n {\n \"code\": null,\n \"e\": 24350,\n \"s\": 24322,\n \"text\": \"\\n16 Feb, 2021\"\n },\n {\n \"code\": null,\n \"e\": 24739,\n \"s\": 24350,\n \"text\": \"Every time you delete a file from your Linux system using the shift + delete or rm command, it doesn’t actually permanently and securely delete the file from the hard disk. When you delete a file with the rm command, the file system just frees up the appropriate inode but the contents of the old file are still in that space until it is overwritten which pave a way to recover the files.\"\n },\n {\n \"code\": null,\n \"e\": 25233,\n \"s\": 24739,\n \"text\": \"The space that was used by the file that you deleted is now free to be used by other new files. But the contents of the old files are still in the hard disk, Until and unless that space is overwritten by something else, so there is a good chance that the file can be recovered by anyone (maybe by some data thieves) with good knowledge of recovering data. It is like removing the index page of a book, where the chapters are still there, it just becomes much hard to find, but we can find it. \"\n },\n {\n \"code\": null,\n \"e\": 25471,\n \"s\": 25233,\n \"text\": \"Shred will help you to overwrite a deleted file, so it becomes difficult to recover it. It is like tearing a paper into as many pieces as you want or overwriting over the paper so that it becomes impossible to find out the original data.\"\n },\n {\n \"code\": null,\n \"e\": 25487,\n \"s\": 25471,\n \"text\": \"manual of shred\"\n },\n {\n \"code\": null,\n \"e\": 25493,\n \"s\": 25487,\n \"text\": \"shred\"\n },\n {\n \"code\": null,\n \"e\": 25546,\n \"s\": 25493,\n \"text\": \"In the above output, the meaning of the letters are:\"\n },\n {\n \"code\": null,\n \"e\": 25597,\n \"s\": 25546,\n \"text\": \"-u: deallocates and removes file after overwriting\"\n },\n {\n \"code\": null,\n \"e\": 25643,\n \"s\": 25597,\n \"text\": \"-v: enables the display of operation progress\"\n },\n {\n \"code\": null,\n \"e\": 25699,\n \"s\": 25643,\n \"text\": \"-z: adds a final overwrite with zeros to hide shredding\"\n },\n {\n \"code\": null,\n \"e\": 25773,\n \"s\": 25699,\n \"text\": \"-n: total number of times the file content will be overwritten(I gave 6).\"\n },\n {\n \"code\": null,\n \"e\": 25994,\n \"s\": 25773,\n \"text\": \"Secure-delete is a command containing a set of secure file deletion tools containing srm (secure_deletion) tool which is used to delete or overwrite the files securely in Linux. At first, we have to install it by typing:\"\n },\n {\n \"code\": null,\n \"e\": 26030,\n \"s\": 25994,\n \"text\": \"sudo apt-get install secure-delete \"\n },\n {\n \"code\": null,\n \"e\": 26052,\n \"s\": 26030,\n \"text\": \"install secure-delete\"\n },\n {\n \"code\": null,\n \"e\": 26227,\n \"s\": 26052,\n \"text\": \"There is a total of 4 different types of tools consisting of this whole package and each of them performs a different type of securely delete operation. They are as follows:-\"\n },\n {\n \"code\": null,\n \"e\": 26335,\n \"s\": 26227,\n \"text\": \"srm : It is a secure rm that is used to erase files by overwriting their hard disk space and deleting them.\"\n },\n {\n \"code\": null,\n \"e\": 26396,\n \"s\": 26335,\n \"text\": \"sfill : It is used to overwrite free space on the hard disk.\"\n },\n {\n \"code\": null,\n \"e\": 26440,\n \"s\": 26396,\n \"text\": \"sswap : It is used to overwrite swap space.\"\n },\n {\n \"code\": null,\n \"e\": 26508,\n \"s\": 26440,\n \"text\": \"sdmem : It is used to wipe the RAM Once secure-delete is installed.\"\n },\n {\n \"code\": null,\n \"e\": 26711,\n \"s\": 26508,\n \"text\": \"# srm Command:srm command deletes anything just like rm command but securely i.e by overwriting the file and its inode with random bytes. The larger the file, the longer it takes to wipe and rewrite it.\"\n },\n {\n \"code\": null,\n \"e\": 26720,\n \"s\": 26711,\n \"text\": \"srm tool\"\n },\n {\n \"code\": null,\n \"e\": 26758,\n \"s\": 26720,\n \"text\": \"Type srm man to get more information:\"\n },\n {\n \"code\": null,\n \"e\": 26766,\n \"s\": 26758,\n \"text\": \" manual\"\n },\n {\n \"code\": null,\n \"e\": 27020,\n \"s\": 26766,\n \"text\": \"The Linux wipe command allows us to securely erase data from our hard disk permanently. The wipe command erases files from magnetic memory and rewrites the space repeatedly and wipe away the caches which make the data nearly impossible to be recovered. \"\n },\n {\n \"code\": null,\n \"e\": 27057,\n \"s\": 27020,\n \"text\": \"At first, we have to install a wipe:\"\n },\n {\n \"code\": null,\n \"e\": 27083,\n \"s\": 27057,\n \"text\": \"sudo apt-get install wipe\"\n },\n {\n \"code\": null,\n \"e\": 27125,\n \"s\": 27083,\n \"text\": \"Now you can use wipe for secure deletion \"\n },\n {\n \"code\": null,\n \"e\": 27130,\n \"s\": 27125,\n \"text\": \"wipe\"\n },\n {\n \"code\": null,\n \"e\": 27178,\n \"s\": 27130,\n \"text\": \"To know more about each function check wipe -h:\"\n },\n {\n \"code\": null,\n \"e\": 27201,\n \"s\": 27178,\n \"text\": \"manual of wipe command\"\n },\n {\n \"code\": null,\n \"e\": 27379,\n \"s\": 27201,\n \"text\": \"dd command is especially used to convert or copy files. We can use this command to completely overwrite your hard drive with zeros, but DD will not zero a drive currently in use\"\n },\n {\n \"code\": null,\n \"e\": 27395,\n \"s\": 27379,\n \"text\": \"The syntax is :\"\n },\n {\n \"code\": null,\n \"e\": 27434,\n \"s\": 27395,\n \"text\": \"- dd if= of= [Options]\"\n },\n {\n \"code\": null,\n \"e\": 27453,\n \"s\": 27434,\n \"text\": \"In the above menu:\"\n },\n {\n \"code\": null,\n \"e\": 27480,\n \"s\": 27453,\n \"text\": \"lsblk: Lists all the disks\"\n },\n {\n \"code\": null,\n \"e\": 27540,\n \"s\": 27480,\n \"text\": \"/dev/urandom (input): The random data used for overwriting\"\n },\n {\n \"code\": null,\n \"e\": 27648,\n \"s\": 27540,\n \"text\": \"/dev/sda (output): the disk that will be overwritten. This disk will be replaced with random garbage data. \"\n },\n {\n \"code\": null,\n \"e\": 27704,\n \"s\": 27648,\n \"text\": \"See the help menu of the “dd” command for more details:\"\n },\n {\n \"code\": null,\n \"e\": 27717,\n \"s\": 27704,\n \"text\": \"dd help menu\"\n },\n {\n \"code\": null,\n \"e\": 27729,\n \"s\": 27717,\n \"text\": \"Linux-Tools\"\n },\n {\n \"code\": null,\n \"e\": 27736,\n \"s\": 27729,\n \"text\": \"Picked\"\n },\n {\n \"code\": null,\n \"e\": 27760,\n \"s\": 27736,\n \"text\": \"Technical Scripter 2020\"\n },\n {\n \"code\": null,\n \"e\": 27771,\n \"s\": 27760,\n \"text\": \"Linux-Unix\"\n },\n {\n \"code\": null,\n \"e\": 27790,\n \"s\": 27771,\n \"text\": \"Technical Scripter\"\n },\n {\n \"code\": null,\n \"e\": 27888,\n \"s\": 27790,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 27897,\n \"s\": 27888,\n \"text\": \"Comments\"\n },\n {\n \"code\": null,\n \"e\": 27910,\n \"s\": 27897,\n \"text\": \"Old Comments\"\n },\n {\n \"code\": null,\n \"e\": 27936,\n \"s\": 27910,\n \"text\": \"Thread functions in C/C++\"\n },\n {\n \"code\": null,\n \"e\": 27976,\n \"s\": 27936,\n \"text\": \"Array Basics in Shell Scripting | Set 1\"\n },\n {\n \"code\": null,\n \"e\": 28011,\n \"s\": 27976,\n \"text\": \"scp command in Linux with Examples\"\n },\n {\n \"code\": null,\n \"e\": 28048,\n \"s\": 28011,\n \"text\": \"nohup Command in Linux with Examples\"\n },\n {\n \"code\": null,\n \"e\": 28085,\n \"s\": 28048,\n \"text\": \"chown command in Linux with Examples\"\n },\n {\n \"code\": null,\n \"e\": 28119,\n \"s\": 28085,\n \"text\": \"mv command in Linux with examples\"\n },\n {\n \"code\": null,\n \"e\": 28161,\n \"s\": 28119,\n \"text\": \"Named Pipe or FIFO with example C program\"\n },\n {\n \"code\": null,\n \"e\": 28190,\n \"s\": 28161,\n \"text\": \"SED command in Linux | Set 2\"\n },\n {\n \"code\": null,\n \"e\": 28225,\n \"s\": 28190,\n \"text\": \"Basic Operators in Shell Scripting\"\n }\n]"}}},{"rowIdx":124,"cells":{"title":{"kind":"string","value":"Palindrome array - JavaScript"},"text":{"kind":"string","value":"We are required to write a JavaScript function that takes in an array of literals and checks if elements are the same or not if read from front or back i.e. palindrome.\nLet’s write the code for this function −\nconst arr = [1, 5, 7, 4, 15, 4, 7, 5, 1];\nconst isPalindrome = arr => {\n const { length: l } = arr;\n const mid = Math.floor(l / 2);\n for(let i = 0; i <= mid; i++){\n if(arr[i] !== arr[l-i-1]){\n return false;\n };\n };\n return true;\n};\nconsole.log(isPalindrome(arr));\nThe output in the console: −\ntrue"},"parsed":{"kind":"list like","value":[{"code":null,"e":1231,"s":1062,"text":"We are required to write a JavaScript function that takes in an array of literals and checks if elements are the same or not if read from front or back i.e. palindrome."},{"code":null,"e":1272,"s":1231,"text":"Let’s write the code for this function −"},{"code":null,"e":1564,"s":1272,"text":"const arr = [1, 5, 7, 4, 15, 4, 7, 5, 1];\nconst isPalindrome = arr => {\n const { length: l } = arr;\n const mid = Math.floor(l / 2);\n for(let i = 0; i <= mid; i++){\n if(arr[i] !== arr[l-i-1]){\n return false;\n };\n };\n return true;\n};\nconsole.log(isPalindrome(arr));"},{"code":null,"e":1593,"s":1564,"text":"The output in the console: −"},{"code":null,"e":1598,"s":1593,"text":"true"}],"string":"[\n {\n \"code\": null,\n \"e\": 1231,\n \"s\": 1062,\n \"text\": \"We are required to write a JavaScript function that takes in an array of literals and checks if elements are the same or not if read from front or back i.e. palindrome.\"\n },\n {\n \"code\": null,\n \"e\": 1272,\n \"s\": 1231,\n \"text\": \"Let’s write the code for this function −\"\n },\n {\n \"code\": null,\n \"e\": 1564,\n \"s\": 1272,\n \"text\": \"const arr = [1, 5, 7, 4, 15, 4, 7, 5, 1];\\nconst isPalindrome = arr => {\\n const { length: l } = arr;\\n const mid = Math.floor(l / 2);\\n for(let i = 0; i <= mid; i++){\\n if(arr[i] !== arr[l-i-1]){\\n return false;\\n };\\n };\\n return true;\\n};\\nconsole.log(isPalindrome(arr));\"\n },\n {\n \"code\": null,\n \"e\": 1593,\n \"s\": 1564,\n \"text\": \"The output in the console: −\"\n },\n {\n \"code\": null,\n \"e\": 1598,\n \"s\": 1593,\n \"text\": \"true\"\n }\n]"}}},{"rowIdx":125,"cells":{"title":{"kind":"string","value":"SQL GROUP BY Statement"},"text":{"kind":"string","value":"The GROUP BY statement groups rows that have the same values into summary \nrows, like \"find the number of customers in each country\".\nThe GROUP BY statement is often used with aggregate functions (COUNT(), \nMAX(), \nMIN(), SUM(), \nAVG()) to group the result-set by one or more columns.\nBelow is a selection from the \"Customers\" table in the Northwind sample \ndatabase:\nThe following SQL statement lists the number of customers in each country:\nThe following SQL statement lists the number of customers in each country, \nsorted high to low:\nBelow is a selection from the \"Orders\" table in the Northwind sample database:\nAnd a selection from the \"Shippers\" table:\nThe following SQL statement lists the number of orders sent by each shipper:\nList the number of customers in each country.\nSELECT (CustomerID),\nCountry\nFROM Customers\n;\n\nStart the Exercise\nWe just launchedW3Schools videos\nGet certifiedby completinga course today!\nIf you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:\nhelp@w3schools.com\nYour message has been sent to W3Schools."},"parsed":{"kind":"list like","value":[{"code":null,"e":134,"s":0,"text":"The GROUP BY statement groups rows that have the same values into summary \nrows, like \"find the number of customers in each country\"."},{"code":null,"e":285,"s":134,"text":"The GROUP BY statement is often used with aggregate functions (COUNT(), \nMAX(), \nMIN(), SUM(), \nAVG()) to group the result-set by one or more columns."},{"code":null,"e":368,"s":285,"text":"Below is a selection from the \"Customers\" table in the Northwind sample \ndatabase:"},{"code":null,"e":443,"s":368,"text":"The following SQL statement lists the number of customers in each country:"},{"code":null,"e":539,"s":443,"text":"The following SQL statement lists the number of customers in each country, \nsorted high to low:"},{"code":null,"e":618,"s":539,"text":"Below is a selection from the \"Orders\" table in the Northwind sample database:"},{"code":null,"e":661,"s":618,"text":"And a selection from the \"Shippers\" table:"},{"code":null,"e":738,"s":661,"text":"The following SQL statement lists the number of orders sent by each shipper:"},{"code":null,"e":784,"s":738,"text":"List the number of customers in each country."},{"code":null,"e":831,"s":784,"text":"SELECT (CustomerID),\nCountry\nFROM Customers\n;\n"},{"code":null,"e":850,"s":831,"text":"Start the Exercise"},{"code":null,"e":883,"s":850,"text":"We just launchedW3Schools videos"},{"code":null,"e":925,"s":883,"text":"Get certifiedby completinga course today!"},{"code":null,"e":1032,"s":925,"text":"If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"},{"code":null,"e":1051,"s":1032,"text":"help@w3schools.com"}],"string":"[\n {\n \"code\": null,\n \"e\": 134,\n \"s\": 0,\n \"text\": \"The GROUP BY statement groups rows that have the same values into summary \\nrows, like \\\"find the number of customers in each country\\\".\"\n },\n {\n \"code\": null,\n \"e\": 285,\n \"s\": 134,\n \"text\": \"The GROUP BY statement is often used with aggregate functions (COUNT(), \\nMAX(), \\nMIN(), SUM(), \\nAVG()) to group the result-set by one or more columns.\"\n },\n {\n \"code\": null,\n \"e\": 368,\n \"s\": 285,\n \"text\": \"Below is a selection from the \\\"Customers\\\" table in the Northwind sample \\ndatabase:\"\n },\n {\n \"code\": null,\n \"e\": 443,\n \"s\": 368,\n \"text\": \"The following SQL statement lists the number of customers in each country:\"\n },\n {\n \"code\": null,\n \"e\": 539,\n \"s\": 443,\n \"text\": \"The following SQL statement lists the number of customers in each country, \\nsorted high to low:\"\n },\n {\n \"code\": null,\n \"e\": 618,\n \"s\": 539,\n \"text\": \"Below is a selection from the \\\"Orders\\\" table in the Northwind sample database:\"\n },\n {\n \"code\": null,\n \"e\": 661,\n \"s\": 618,\n \"text\": \"And a selection from the \\\"Shippers\\\" table:\"\n },\n {\n \"code\": null,\n \"e\": 738,\n \"s\": 661,\n \"text\": \"The following SQL statement lists the number of orders sent by each shipper:\"\n },\n {\n \"code\": null,\n \"e\": 784,\n \"s\": 738,\n \"text\": \"List the number of customers in each country.\"\n },\n {\n \"code\": null,\n \"e\": 831,\n \"s\": 784,\n \"text\": \"SELECT (CustomerID),\\nCountry\\nFROM Customers\\n;\\n\"\n },\n {\n \"code\": null,\n \"e\": 850,\n \"s\": 831,\n \"text\": \"Start the Exercise\"\n },\n {\n \"code\": null,\n \"e\": 883,\n \"s\": 850,\n \"text\": \"We just launchedW3Schools videos\"\n },\n {\n \"code\": null,\n \"e\": 925,\n \"s\": 883,\n \"text\": \"Get certifiedby completinga course today!\"\n },\n {\n \"code\": null,\n \"e\": 1032,\n \"s\": 925,\n \"text\": \"If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:\"\n },\n {\n \"code\": null,\n \"e\": 1051,\n \"s\": 1032,\n \"text\": \"help@w3schools.com\"\n }\n]"}}},{"rowIdx":126,"cells":{"title":{"kind":"string","value":"How to valid DateofBirth using fluent Validation in C# if it exceeds current year?"},"text":{"kind":"string","value":"To specify a validation rule for a particular property, call the RuleFor method, passing a lambda expression that indicates the property that you wish to validate\nTo run the validator, instantiate the validator object and call the Validate method, passing in the object to validate.\nThe Validate method returns a ValidationResult object. This contains two properties\nIsValid - a boolean that says whether the validation suceeded.\nErrors - a collection of ValidationFailure objects containing details about any validation failures\nstatic void Main(string[] args) {\n List errors = new List();\n\n PersonModel person = new PersonModel();\n person.FirstName = \"TestUser\";\n person.LastName = \"TestUser\";\n person.AccountBalance = 100;\n person.DateOfBirth = DateTime.Now.Date.AddYears(1);\n\n PersonValidator validator = new PersonValidator();\n\n ValidationResult results = validator.Validate(person);\n\n if (results.IsValid == false) {\n foreach (ValidationFailure failure in results.Errors){\n errors.Add(failure.ErrorMessage);\n }\n }\n\n foreach (var item in errors){\n Console.WriteLine(item);\n }\n Console.ReadLine();\n\n }\n}\n\npublic class PersonModel {\n public string FirstName { get; set; }\n public string LastName { get; set; }\n public decimal AccountBalance { get; set; }\n public DateTime DateOfBirth { get; set; }\n}\n\npublic class PersonValidator : AbstractValidator{\n public PersonValidator(){\n RuleFor(p => p.DateOfBirth)\n .Must(BeAValidAge).WithMessage(\"Invalid {PropertyName}\");\n }\n\n protected bool BeAValidAge(DateTime date){\n int currentYear = DateTime.Now.Year;\n int dobYear = date.Year;\n\n if (dobYear <= currentYear && dobYear > (currentYear - 120)){\n return true;\n }\n\n return false;\n }\n}\nInvalid Date Of Birth"},"parsed":{"kind":"list like","value":[{"code":null,"e":1225,"s":1062,"text":"To specify a validation rule for a particular property, call the RuleFor method, passing a lambda expression that indicates the property that you wish to validate"},{"code":null,"e":1345,"s":1225,"text":"To run the validator, instantiate the validator object and call the Validate method, passing in the object to validate."},{"code":null,"e":1429,"s":1345,"text":"The Validate method returns a ValidationResult object. This contains two properties"},{"code":null,"e":1492,"s":1429,"text":"IsValid - a boolean that says whether the validation suceeded."},{"code":null,"e":1592,"s":1492,"text":"Errors - a collection of ValidationFailure objects containing details about any validation failures"},{"code":null,"e":2855,"s":1592,"text":"static void Main(string[] args) {\n List errors = new List();\n\n PersonModel person = new PersonModel();\n person.FirstName = \"TestUser\";\n person.LastName = \"TestUser\";\n person.AccountBalance = 100;\n person.DateOfBirth = DateTime.Now.Date.AddYears(1);\n\n PersonValidator validator = new PersonValidator();\n\n ValidationResult results = validator.Validate(person);\n\n if (results.IsValid == false) {\n foreach (ValidationFailure failure in results.Errors){\n errors.Add(failure.ErrorMessage);\n }\n }\n\n foreach (var item in errors){\n Console.WriteLine(item);\n }\n Console.ReadLine();\n\n }\n}\n\npublic class PersonModel {\n public string FirstName { get; set; }\n public string LastName { get; set; }\n public decimal AccountBalance { get; set; }\n public DateTime DateOfBirth { get; set; }\n}\n\npublic class PersonValidator : AbstractValidator{\n public PersonValidator(){\n RuleFor(p => p.DateOfBirth)\n .Must(BeAValidAge).WithMessage(\"Invalid {PropertyName}\");\n }\n\n protected bool BeAValidAge(DateTime date){\n int currentYear = DateTime.Now.Year;\n int dobYear = date.Year;\n\n if (dobYear <= currentYear && dobYear > (currentYear - 120)){\n return true;\n }\n\n return false;\n }\n}"},{"code":null,"e":2877,"s":2855,"text":"Invalid Date Of Birth"}],"string":"[\n {\n \"code\": null,\n \"e\": 1225,\n \"s\": 1062,\n \"text\": \"To specify a validation rule for a particular property, call the RuleFor method, passing a lambda expression that indicates the property that you wish to validate\"\n },\n {\n \"code\": null,\n \"e\": 1345,\n \"s\": 1225,\n \"text\": \"To run the validator, instantiate the validator object and call the Validate method, passing in the object to validate.\"\n },\n {\n \"code\": null,\n \"e\": 1429,\n \"s\": 1345,\n \"text\": \"The Validate method returns a ValidationResult object. This contains two properties\"\n },\n {\n \"code\": null,\n \"e\": 1492,\n \"s\": 1429,\n \"text\": \"IsValid - a boolean that says whether the validation suceeded.\"\n },\n {\n \"code\": null,\n \"e\": 1592,\n \"s\": 1492,\n \"text\": \"Errors - a collection of ValidationFailure objects containing details about any validation failures\"\n },\n {\n \"code\": null,\n \"e\": 2855,\n \"s\": 1592,\n \"text\": \"static void Main(string[] args) {\\n List errors = new List();\\n\\n PersonModel person = new PersonModel();\\n person.FirstName = \\\"TestUser\\\";\\n person.LastName = \\\"TestUser\\\";\\n person.AccountBalance = 100;\\n person.DateOfBirth = DateTime.Now.Date.AddYears(1);\\n\\n PersonValidator validator = new PersonValidator();\\n\\n ValidationResult results = validator.Validate(person);\\n\\n if (results.IsValid == false) {\\n foreach (ValidationFailure failure in results.Errors){\\n errors.Add(failure.ErrorMessage);\\n }\\n }\\n\\n foreach (var item in errors){\\n Console.WriteLine(item);\\n }\\n Console.ReadLine();\\n\\n }\\n}\\n\\npublic class PersonModel {\\n public string FirstName { get; set; }\\n public string LastName { get; set; }\\n public decimal AccountBalance { get; set; }\\n public DateTime DateOfBirth { get; set; }\\n}\\n\\npublic class PersonValidator : AbstractValidator{\\n public PersonValidator(){\\n RuleFor(p => p.DateOfBirth)\\n .Must(BeAValidAge).WithMessage(\\\"Invalid {PropertyName}\\\");\\n }\\n\\n protected bool BeAValidAge(DateTime date){\\n int currentYear = DateTime.Now.Year;\\n int dobYear = date.Year;\\n\\n if (dobYear <= currentYear && dobYear > (currentYear - 120)){\\n return true;\\n }\\n\\n return false;\\n }\\n}\"\n },\n {\n \"code\": null,\n \"e\": 2877,\n \"s\": 2855,\n \"text\": \"Invalid Date Of Birth\"\n }\n]"}}},{"rowIdx":127,"cells":{"title":{"kind":"string","value":"Feature Selection: How to Throw Away 95% of Your Features and Get 95% Accuracy | by Samuele Mazzanti | Towards Data Science"},"text":{"kind":"string","value":"Can you recognize these handwritten digits?\nYou probably had no trouble spotting respectively a 0, a 3 and an 8.\nIf so, you were able to classify them correctly even if only 25% of the original image was shown, while the remaining 75% was covered with red pixels. This was an easy task because the “relevant” pixels were visible, while only the “irrelevant” and “redundant” ones had been hidden.\nThis was a simple example of “feature selection”.\nFeature selection is a process that is carried out in machine learning when, before feeding the data to a predictive model, some features are removed. If your data is in the form of a table, this simply means dropping many columns from your table.\nWhy bothering with feature selection? Can’t I just throw all the data inside my predictive model and let him doing the dirty work?\nActually, there are several reasons for which you may want to do feature selection:\nMemory. Big data take big space. Dropping features means that you need less memory to handle your data. Sometimes there are also external constraints (for instance, Google’s AutoML allows you to use no more than 1,000 columns. Thus, if you have more than 1,000 columns, you will be forced to keep only some of them).\nTime. Training a model on less data can save you much time.\nAccuracy. Less is more: this also goes for machine learning. Including redundant or irrelevant features means including unnecessary noise. Frequently, it happens that a model trained on less data performs better.\nInterpretability. A smaller model means also a more interpretable model. Just picture if you had to explain a model based on thousands of different factors: it would be unfeasible.\nDebugging. A smaller model is easier to mantain and troubleshoot.\nIn this article, we will compare some methods for feature selection. Our playground dataset will be the world-famous “MNIST”.\nMNIST is a dataset consisting of 70,000 black-and-white images of handwritten digits. Each image is 28 x 28 (= 784) pixels. Each pixel is encoded as an integer from 1 (white) to 255 (black): the higher this value the darker the color. As a convention, 60,000 images are used as train set and 10,000 as test set.\nThe data can be imported into Python through a Keras command (we’ll also reshape the dataset to make it 2-dimensional, as a table):\nfrom keras.datasets import mnist(X_train, y_train), (X_test, y_test) = mnist.load_data()X_train = X_train.reshape(60000, 28 * 28)X_test = X_test.reshape(10000, 28 * 28)\nFor instance, let’s print out the values of the 8th row:\nprint(X_train[7, :])\nThis is the outcome:\nThrough Matplotlib, we can also display the corresponding image:\nimport matplotlib.pyplot as pltplt.imshow(X_train[7, :].reshape(28, 28), cmap = 'binary', vmin = 0, vmax = 255)\nOur task is to select a small number of columns (i.e. pixels) that are sufficient to achieve a good level of accuracy when fed to a predictive model.\nThere are many possible strategies and algorithms to perform feature selection. In this article, we will put to the test 6 of them:\n3.1 F-Statistic\nF-Statistic is the outcome of the ANOVA F-test. This test is computed as the ratio: between-group variability / within-group variability, where the group is the target class.\nThe idea is that a pixel is relevant when the variability between the groups (images in class 0, images in class 1, ..., images in class 9) is high and the variability within the same groups is low.\nfrom sklearn.feature_selection import f_classiff = f_classif(X_train, y_train)[0]\n3.2 Mutual Information\nMutual information is a measure of the mutual dependence between two variables.\nSince the formula of MI requires knowing the probability distribution of each variable (and normally we don’t know distributions), the scikit-learn implementation employs a nonparametric approximation based on k-nearest neighbors distances.\nfrom sklearn.feature_selection import mutual_info_classifmi = mutual_info_classif(X_train, y_train)\n3.3 Logistic Regression\nIf the target variable is categorical (as in our case), a logistic regression may be fitted to the data. Then, the relative importance of the features can be used to rank them from the most to the least relevant.\nfrom sklearn.linear_model import LogisticRegressionlogreg = LogisticRegression().fit(X_train, y_train)\n3.4 LightGBM\nThe same can be done with any predictive model. For instance, LightGBM.\nfrom lightgbm import LGBMClassifierlgbm = LGBMClassifier( objective = 'multiclass', metric = 'multi_logloss', importance_type = 'gain').fit(X_train, y_train)\n3.5 Boruta\nBoruta is an elegant algorithm designed in 2010 as a package for R. The aim of Boruta is to tell whether or not each feature has some kind of relationship with the target variable. So, the output of Boruta is more a yes/no for each feature, rather than a ranking of features.\n(If you are curious to know more about the functioning of Boruta, I wrote a post about it: Boruta Explained Exactly How You Wished Someone Explained to You).\nfrom boruta import BorutaPyfrom sklearn.ensemble import RandomForestClassifierboruta = BorutaPy( estimator = RandomForestClassifier(max_depth = 5), n_estimators = 'auto', max_iter = 100).fit(X_train, y_train)\n3.6 MRMR\nMRMR (which stands for “Maximum Relevance Minimum Redundancy”) is an algorithm designed in 2005 for feature selection. The idea behind MRMR is to identify a subset of features having a high relevance with respect to the target variable and a small redundancy with each other.\n(If you are curious to know more about the functioning of MRMR, I wrote a post about it: MRMR Explained Exactly How You Wished Someone Explained to You).\nfrom mrmr import mrmr_classifmrmr = mrmr_classif(X_train, y_train)\nAll these algorithms provide a “ranking” of the features (except for Boruta, which has a yes/no outcome). Let’s see how the rankings change according to the different algorithms.\nAt this point, a natural question is:\nWhat method should I choose for feature selection?\nAs always in data science, the best choice is to test different approaches, and see which one gives better results on your data. Therefore, let’s try them on MNIST.\nWe will take the feature rankings provided by the 5 methods (since Boruta does not provide a ranking) and see what accuracy can be achieved when training a predictive model on the first K features (for K up to 40).\nimport pandas as pdfrom catboost import CatBoostClassifierfrom sklearn.metrics import accuracy_scorealgos = ['f', 'mi', 'logreg', 'lightgbm', 'mrmr']ks = [1, 2, 5, 10, 15, 20, 30, 40]accuracy = pd.DataFrame(index = ks, columns = algos)for algo in algos: for nfeats in ks: feats = ranking[algo][:n_feats] clf = CatBoostClassifier().fit( X_train[:, feats], y_train, eval_set = (X_test[:, feats], y_test), early_stopping_rounds = 20 ) accuracy.loc[k, algo] = accuracy_score( y_true = y_test, y_pred = clf.predict(X_test[:, cols])))\nThese are the outcomes:\nIn this case, MRMR outperformed the other algorithms.\nAs the plot shows, a predictor trained on the most relevant 40 pixels identified by MRMR reached 95.54% accuracy on test images!\nThis is pretty impressive, especially if we consider that:\n40 pixels are only 5% of the whole image (which consists of 28 x 28 = 784 pixels);\nwe have used a predictive model (CatBoost) with no further tuning, thus this performance can probably be improved further.\nThus, in the case of MNIST, we could throw away 95% of our data and still get more than 95% accuracy (which corresponds to an area under ROC of 99.85%!).\nEven if MNIST is a “simple” dataset, the main takeaways are valid for most real-world datasets. Often, a high level of accuracy can be achieved with just a small portion of features. An effective feature selection allows you to build data pipelines that are more efficient in terms of memory, time, accuracy, interpretability and ease of debugging.\nThank you for reading! I hope you found this post useful.\nThe results shown in this article are fully reproducible through this code: https://github.com/smazzanti/mrmr/blob/main/notebooks/mnist.ipynb.\nI appreciate feedback and constructive criticism. If you want to talk about this article or other related topics, you can text me at my Linkedin contact."},"parsed":{"kind":"list like","value":[{"code":null,"e":216,"s":172,"text":"Can you recognize these handwritten digits?"},{"code":null,"e":285,"s":216,"text":"You probably had no trouble spotting respectively a 0, a 3 and an 8."},{"code":null,"e":568,"s":285,"text":"If so, you were able to classify them correctly even if only 25% of the original image was shown, while the remaining 75% was covered with red pixels. This was an easy task because the “relevant” pixels were visible, while only the “irrelevant” and “redundant” ones had been hidden."},{"code":null,"e":618,"s":568,"text":"This was a simple example of “feature selection”."},{"code":null,"e":866,"s":618,"text":"Feature selection is a process that is carried out in machine learning when, before feeding the data to a predictive model, some features are removed. If your data is in the form of a table, this simply means dropping many columns from your table."},{"code":null,"e":997,"s":866,"text":"Why bothering with feature selection? Can’t I just throw all the data inside my predictive model and let him doing the dirty work?"},{"code":null,"e":1081,"s":997,"text":"Actually, there are several reasons for which you may want to do feature selection:"},{"code":null,"e":1398,"s":1081,"text":"Memory. Big data take big space. Dropping features means that you need less memory to handle your data. Sometimes there are also external constraints (for instance, Google’s AutoML allows you to use no more than 1,000 columns. Thus, if you have more than 1,000 columns, you will be forced to keep only some of them)."},{"code":null,"e":1458,"s":1398,"text":"Time. Training a model on less data can save you much time."},{"code":null,"e":1671,"s":1458,"text":"Accuracy. Less is more: this also goes for machine learning. Including redundant or irrelevant features means including unnecessary noise. Frequently, it happens that a model trained on less data performs better."},{"code":null,"e":1852,"s":1671,"text":"Interpretability. A smaller model means also a more interpretable model. Just picture if you had to explain a model based on thousands of different factors: it would be unfeasible."},{"code":null,"e":1918,"s":1852,"text":"Debugging. A smaller model is easier to mantain and troubleshoot."},{"code":null,"e":2044,"s":1918,"text":"In this article, we will compare some methods for feature selection. Our playground dataset will be the world-famous “MNIST”."},{"code":null,"e":2356,"s":2044,"text":"MNIST is a dataset consisting of 70,000 black-and-white images of handwritten digits. Each image is 28 x 28 (= 784) pixels. Each pixel is encoded as an integer from 1 (white) to 255 (black): the higher this value the darker the color. As a convention, 60,000 images are used as train set and 10,000 as test set."},{"code":null,"e":2488,"s":2356,"text":"The data can be imported into Python through a Keras command (we’ll also reshape the dataset to make it 2-dimensional, as a table):"},{"code":null,"e":2657,"s":2488,"text":"from keras.datasets import mnist(X_train, y_train), (X_test, y_test) = mnist.load_data()X_train = X_train.reshape(60000, 28 * 28)X_test = X_test.reshape(10000, 28 * 28)"},{"code":null,"e":2714,"s":2657,"text":"For instance, let’s print out the values of the 8th row:"},{"code":null,"e":2735,"s":2714,"text":"print(X_train[7, :])"},{"code":null,"e":2756,"s":2735,"text":"This is the outcome:"},{"code":null,"e":2821,"s":2756,"text":"Through Matplotlib, we can also display the corresponding image:"},{"code":null,"e":2933,"s":2821,"text":"import matplotlib.pyplot as pltplt.imshow(X_train[7, :].reshape(28, 28), cmap = 'binary', vmin = 0, vmax = 255)"},{"code":null,"e":3083,"s":2933,"text":"Our task is to select a small number of columns (i.e. pixels) that are sufficient to achieve a good level of accuracy when fed to a predictive model."},{"code":null,"e":3215,"s":3083,"text":"There are many possible strategies and algorithms to perform feature selection. In this article, we will put to the test 6 of them:"},{"code":null,"e":3231,"s":3215,"text":"3.1 F-Statistic"},{"code":null,"e":3406,"s":3231,"text":"F-Statistic is the outcome of the ANOVA F-test. This test is computed as the ratio: between-group variability / within-group variability, where the group is the target class."},{"code":null,"e":3605,"s":3406,"text":"The idea is that a pixel is relevant when the variability between the groups (images in class 0, images in class 1, ..., images in class 9) is high and the variability within the same groups is low."},{"code":null,"e":3687,"s":3605,"text":"from sklearn.feature_selection import f_classiff = f_classif(X_train, y_train)[0]"},{"code":null,"e":3710,"s":3687,"text":"3.2 Mutual Information"},{"code":null,"e":3790,"s":3710,"text":"Mutual information is a measure of the mutual dependence between two variables."},{"code":null,"e":4031,"s":3790,"text":"Since the formula of MI requires knowing the probability distribution of each variable (and normally we don’t know distributions), the scikit-learn implementation employs a nonparametric approximation based on k-nearest neighbors distances."},{"code":null,"e":4131,"s":4031,"text":"from sklearn.feature_selection import mutual_info_classifmi = mutual_info_classif(X_train, y_train)"},{"code":null,"e":4155,"s":4131,"text":"3.3 Logistic Regression"},{"code":null,"e":4368,"s":4155,"text":"If the target variable is categorical (as in our case), a logistic regression may be fitted to the data. Then, the relative importance of the features can be used to rank them from the most to the least relevant."},{"code":null,"e":4471,"s":4368,"text":"from sklearn.linear_model import LogisticRegressionlogreg = LogisticRegression().fit(X_train, y_train)"},{"code":null,"e":4484,"s":4471,"text":"3.4 LightGBM"},{"code":null,"e":4556,"s":4484,"text":"The same can be done with any predictive model. For instance, LightGBM."},{"code":null,"e":4723,"s":4556,"text":"from lightgbm import LGBMClassifierlgbm = LGBMClassifier( objective = 'multiclass', metric = 'multi_logloss', importance_type = 'gain').fit(X_train, y_train)"},{"code":null,"e":4734,"s":4723,"text":"3.5 Boruta"},{"code":null,"e":5010,"s":4734,"text":"Boruta is an elegant algorithm designed in 2010 as a package for R. The aim of Boruta is to tell whether or not each feature has some kind of relationship with the target variable. So, the output of Boruta is more a yes/no for each feature, rather than a ranking of features."},{"code":null,"e":5168,"s":5010,"text":"(If you are curious to know more about the functioning of Boruta, I wrote a post about it: Boruta Explained Exactly How You Wished Someone Explained to You)."},{"code":null,"e":5388,"s":5168,"text":"from boruta import BorutaPyfrom sklearn.ensemble import RandomForestClassifierboruta = BorutaPy( estimator = RandomForestClassifier(max_depth = 5), n_estimators = 'auto', max_iter = 100).fit(X_train, y_train)"},{"code":null,"e":5397,"s":5388,"text":"3.6 MRMR"},{"code":null,"e":5673,"s":5397,"text":"MRMR (which stands for “Maximum Relevance Minimum Redundancy”) is an algorithm designed in 2005 for feature selection. The idea behind MRMR is to identify a subset of features having a high relevance with respect to the target variable and a small redundancy with each other."},{"code":null,"e":5827,"s":5673,"text":"(If you are curious to know more about the functioning of MRMR, I wrote a post about it: MRMR Explained Exactly How You Wished Someone Explained to You)."},{"code":null,"e":5894,"s":5827,"text":"from mrmr import mrmr_classifmrmr = mrmr_classif(X_train, y_train)"},{"code":null,"e":6073,"s":5894,"text":"All these algorithms provide a “ranking” of the features (except for Boruta, which has a yes/no outcome). Let’s see how the rankings change according to the different algorithms."},{"code":null,"e":6111,"s":6073,"text":"At this point, a natural question is:"},{"code":null,"e":6162,"s":6111,"text":"What method should I choose for feature selection?"},{"code":null,"e":6327,"s":6162,"text":"As always in data science, the best choice is to test different approaches, and see which one gives better results on your data. Therefore, let’s try them on MNIST."},{"code":null,"e":6542,"s":6327,"text":"We will take the feature rankings provided by the 5 methods (since Boruta does not provide a ranking) and see what accuracy can be achieved when training a predictive model on the first K features (for K up to 40)."},{"code":null,"e":7126,"s":6542,"text":"import pandas as pdfrom catboost import CatBoostClassifierfrom sklearn.metrics import accuracy_scorealgos = ['f', 'mi', 'logreg', 'lightgbm', 'mrmr']ks = [1, 2, 5, 10, 15, 20, 30, 40]accuracy = pd.DataFrame(index = ks, columns = algos)for algo in algos: for nfeats in ks: feats = ranking[algo][:n_feats] clf = CatBoostClassifier().fit( X_train[:, feats], y_train, eval_set = (X_test[:, feats], y_test), early_stopping_rounds = 20 ) accuracy.loc[k, algo] = accuracy_score( y_true = y_test, y_pred = clf.predict(X_test[:, cols])))"},{"code":null,"e":7150,"s":7126,"text":"These are the outcomes:"},{"code":null,"e":7204,"s":7150,"text":"In this case, MRMR outperformed the other algorithms."},{"code":null,"e":7333,"s":7204,"text":"As the plot shows, a predictor trained on the most relevant 40 pixels identified by MRMR reached 95.54% accuracy on test images!"},{"code":null,"e":7392,"s":7333,"text":"This is pretty impressive, especially if we consider that:"},{"code":null,"e":7475,"s":7392,"text":"40 pixels are only 5% of the whole image (which consists of 28 x 28 = 784 pixels);"},{"code":null,"e":7598,"s":7475,"text":"we have used a predictive model (CatBoost) with no further tuning, thus this performance can probably be improved further."},{"code":null,"e":7752,"s":7598,"text":"Thus, in the case of MNIST, we could throw away 95% of our data and still get more than 95% accuracy (which corresponds to an area under ROC of 99.85%!)."},{"code":null,"e":8101,"s":7752,"text":"Even if MNIST is a “simple” dataset, the main takeaways are valid for most real-world datasets. Often, a high level of accuracy can be achieved with just a small portion of features. An effective feature selection allows you to build data pipelines that are more efficient in terms of memory, time, accuracy, interpretability and ease of debugging."},{"code":null,"e":8159,"s":8101,"text":"Thank you for reading! I hope you found this post useful."},{"code":null,"e":8302,"s":8159,"text":"The results shown in this article are fully reproducible through this code: https://github.com/smazzanti/mrmr/blob/main/notebooks/mnist.ipynb."}],"string":"[\n {\n \"code\": null,\n \"e\": 216,\n \"s\": 172,\n \"text\": \"Can you recognize these handwritten digits?\"\n },\n {\n \"code\": null,\n \"e\": 285,\n \"s\": 216,\n \"text\": \"You probably had no trouble spotting respectively a 0, a 3 and an 8.\"\n },\n {\n \"code\": null,\n \"e\": 568,\n \"s\": 285,\n \"text\": \"If so, you were able to classify them correctly even if only 25% of the original image was shown, while the remaining 75% was covered with red pixels. This was an easy task because the “relevant” pixels were visible, while only the “irrelevant” and “redundant” ones had been hidden.\"\n },\n {\n \"code\": null,\n \"e\": 618,\n \"s\": 568,\n \"text\": \"This was a simple example of “feature selection”.\"\n },\n {\n \"code\": null,\n \"e\": 866,\n \"s\": 618,\n \"text\": \"Feature selection is a process that is carried out in machine learning when, before feeding the data to a predictive model, some features are removed. If your data is in the form of a table, this simply means dropping many columns from your table.\"\n },\n {\n \"code\": null,\n \"e\": 997,\n \"s\": 866,\n \"text\": \"Why bothering with feature selection? Can’t I just throw all the data inside my predictive model and let him doing the dirty work?\"\n },\n {\n \"code\": null,\n \"e\": 1081,\n \"s\": 997,\n \"text\": \"Actually, there are several reasons for which you may want to do feature selection:\"\n },\n {\n \"code\": null,\n \"e\": 1398,\n \"s\": 1081,\n \"text\": \"Memory. Big data take big space. Dropping features means that you need less memory to handle your data. Sometimes there are also external constraints (for instance, Google’s AutoML allows you to use no more than 1,000 columns. Thus, if you have more than 1,000 columns, you will be forced to keep only some of them).\"\n },\n {\n \"code\": null,\n \"e\": 1458,\n \"s\": 1398,\n \"text\": \"Time. Training a model on less data can save you much time.\"\n },\n {\n \"code\": null,\n \"e\": 1671,\n \"s\": 1458,\n \"text\": \"Accuracy. Less is more: this also goes for machine learning. Including redundant or irrelevant features means including unnecessary noise. Frequently, it happens that a model trained on less data performs better.\"\n },\n {\n \"code\": null,\n \"e\": 1852,\n \"s\": 1671,\n \"text\": \"Interpretability. A smaller model means also a more interpretable model. Just picture if you had to explain a model based on thousands of different factors: it would be unfeasible.\"\n },\n {\n \"code\": null,\n \"e\": 1918,\n \"s\": 1852,\n \"text\": \"Debugging. A smaller model is easier to mantain and troubleshoot.\"\n },\n {\n \"code\": null,\n \"e\": 2044,\n \"s\": 1918,\n \"text\": \"In this article, we will compare some methods for feature selection. Our playground dataset will be the world-famous “MNIST”.\"\n },\n {\n \"code\": null,\n \"e\": 2356,\n \"s\": 2044,\n \"text\": \"MNIST is a dataset consisting of 70,000 black-and-white images of handwritten digits. Each image is 28 x 28 (= 784) pixels. Each pixel is encoded as an integer from 1 (white) to 255 (black): the higher this value the darker the color. As a convention, 60,000 images are used as train set and 10,000 as test set.\"\n },\n {\n \"code\": null,\n \"e\": 2488,\n \"s\": 2356,\n \"text\": \"The data can be imported into Python through a Keras command (we’ll also reshape the dataset to make it 2-dimensional, as a table):\"\n },\n {\n \"code\": null,\n \"e\": 2657,\n \"s\": 2488,\n \"text\": \"from keras.datasets import mnist(X_train, y_train), (X_test, y_test) = mnist.load_data()X_train = X_train.reshape(60000, 28 * 28)X_test = X_test.reshape(10000, 28 * 28)\"\n },\n {\n \"code\": null,\n \"e\": 2714,\n \"s\": 2657,\n \"text\": \"For instance, let’s print out the values of the 8th row:\"\n },\n {\n \"code\": null,\n \"e\": 2735,\n \"s\": 2714,\n \"text\": \"print(X_train[7, :])\"\n },\n {\n \"code\": null,\n \"e\": 2756,\n \"s\": 2735,\n \"text\": \"This is the outcome:\"\n },\n {\n \"code\": null,\n \"e\": 2821,\n \"s\": 2756,\n \"text\": \"Through Matplotlib, we can also display the corresponding image:\"\n },\n {\n \"code\": null,\n \"e\": 2933,\n \"s\": 2821,\n \"text\": \"import matplotlib.pyplot as pltplt.imshow(X_train[7, :].reshape(28, 28), cmap = 'binary', vmin = 0, vmax = 255)\"\n },\n {\n \"code\": null,\n \"e\": 3083,\n \"s\": 2933,\n \"text\": \"Our task is to select a small number of columns (i.e. pixels) that are sufficient to achieve a good level of accuracy when fed to a predictive model.\"\n },\n {\n \"code\": null,\n \"e\": 3215,\n \"s\": 3083,\n \"text\": \"There are many possible strategies and algorithms to perform feature selection. In this article, we will put to the test 6 of them:\"\n },\n {\n \"code\": null,\n \"e\": 3231,\n \"s\": 3215,\n \"text\": \"3.1 F-Statistic\"\n },\n {\n \"code\": null,\n \"e\": 3406,\n \"s\": 3231,\n \"text\": \"F-Statistic is the outcome of the ANOVA F-test. This test is computed as the ratio: between-group variability / within-group variability, where the group is the target class.\"\n },\n {\n \"code\": null,\n \"e\": 3605,\n \"s\": 3406,\n \"text\": \"The idea is that a pixel is relevant when the variability between the groups (images in class 0, images in class 1, ..., images in class 9) is high and the variability within the same groups is low.\"\n },\n {\n \"code\": null,\n \"e\": 3687,\n \"s\": 3605,\n \"text\": \"from sklearn.feature_selection import f_classiff = f_classif(X_train, y_train)[0]\"\n },\n {\n \"code\": null,\n \"e\": 3710,\n \"s\": 3687,\n \"text\": \"3.2 Mutual Information\"\n },\n {\n \"code\": null,\n \"e\": 3790,\n \"s\": 3710,\n \"text\": \"Mutual information is a measure of the mutual dependence between two variables.\"\n },\n {\n \"code\": null,\n \"e\": 4031,\n \"s\": 3790,\n \"text\": \"Since the formula of MI requires knowing the probability distribution of each variable (and normally we don’t know distributions), the scikit-learn implementation employs a nonparametric approximation based on k-nearest neighbors distances.\"\n },\n {\n \"code\": null,\n \"e\": 4131,\n \"s\": 4031,\n \"text\": \"from sklearn.feature_selection import mutual_info_classifmi = mutual_info_classif(X_train, y_train)\"\n },\n {\n \"code\": null,\n \"e\": 4155,\n \"s\": 4131,\n \"text\": \"3.3 Logistic Regression\"\n },\n {\n \"code\": null,\n \"e\": 4368,\n \"s\": 4155,\n \"text\": \"If the target variable is categorical (as in our case), a logistic regression may be fitted to the data. Then, the relative importance of the features can be used to rank them from the most to the least relevant.\"\n },\n {\n \"code\": null,\n \"e\": 4471,\n \"s\": 4368,\n \"text\": \"from sklearn.linear_model import LogisticRegressionlogreg = LogisticRegression().fit(X_train, y_train)\"\n },\n {\n \"code\": null,\n \"e\": 4484,\n \"s\": 4471,\n \"text\": \"3.4 LightGBM\"\n },\n {\n \"code\": null,\n \"e\": 4556,\n \"s\": 4484,\n \"text\": \"The same can be done with any predictive model. For instance, LightGBM.\"\n },\n {\n \"code\": null,\n \"e\": 4723,\n \"s\": 4556,\n \"text\": \"from lightgbm import LGBMClassifierlgbm = LGBMClassifier( objective = 'multiclass', metric = 'multi_logloss', importance_type = 'gain').fit(X_train, y_train)\"\n },\n {\n \"code\": null,\n \"e\": 4734,\n \"s\": 4723,\n \"text\": \"3.5 Boruta\"\n },\n {\n \"code\": null,\n \"e\": 5010,\n \"s\": 4734,\n \"text\": \"Boruta is an elegant algorithm designed in 2010 as a package for R. The aim of Boruta is to tell whether or not each feature has some kind of relationship with the target variable. So, the output of Boruta is more a yes/no for each feature, rather than a ranking of features.\"\n },\n {\n \"code\": null,\n \"e\": 5168,\n \"s\": 5010,\n \"text\": \"(If you are curious to know more about the functioning of Boruta, I wrote a post about it: Boruta Explained Exactly How You Wished Someone Explained to You).\"\n },\n {\n \"code\": null,\n \"e\": 5388,\n \"s\": 5168,\n \"text\": \"from boruta import BorutaPyfrom sklearn.ensemble import RandomForestClassifierboruta = BorutaPy( estimator = RandomForestClassifier(max_depth = 5), n_estimators = 'auto', max_iter = 100).fit(X_train, y_train)\"\n },\n {\n \"code\": null,\n \"e\": 5397,\n \"s\": 5388,\n \"text\": \"3.6 MRMR\"\n },\n {\n \"code\": null,\n \"e\": 5673,\n \"s\": 5397,\n \"text\": \"MRMR (which stands for “Maximum Relevance Minimum Redundancy”) is an algorithm designed in 2005 for feature selection. The idea behind MRMR is to identify a subset of features having a high relevance with respect to the target variable and a small redundancy with each other.\"\n },\n {\n \"code\": null,\n \"e\": 5827,\n \"s\": 5673,\n \"text\": \"(If you are curious to know more about the functioning of MRMR, I wrote a post about it: MRMR Explained Exactly How You Wished Someone Explained to You).\"\n },\n {\n \"code\": null,\n \"e\": 5894,\n \"s\": 5827,\n \"text\": \"from mrmr import mrmr_classifmrmr = mrmr_classif(X_train, y_train)\"\n },\n {\n \"code\": null,\n \"e\": 6073,\n \"s\": 5894,\n \"text\": \"All these algorithms provide a “ranking” of the features (except for Boruta, which has a yes/no outcome). Let’s see how the rankings change according to the different algorithms.\"\n },\n {\n \"code\": null,\n \"e\": 6111,\n \"s\": 6073,\n \"text\": \"At this point, a natural question is:\"\n },\n {\n \"code\": null,\n \"e\": 6162,\n \"s\": 6111,\n \"text\": \"What method should I choose for feature selection?\"\n },\n {\n \"code\": null,\n \"e\": 6327,\n \"s\": 6162,\n \"text\": \"As always in data science, the best choice is to test different approaches, and see which one gives better results on your data. Therefore, let’s try them on MNIST.\"\n },\n {\n \"code\": null,\n \"e\": 6542,\n \"s\": 6327,\n \"text\": \"We will take the feature rankings provided by the 5 methods (since Boruta does not provide a ranking) and see what accuracy can be achieved when training a predictive model on the first K features (for K up to 40).\"\n },\n {\n \"code\": null,\n \"e\": 7126,\n \"s\": 6542,\n \"text\": \"import pandas as pdfrom catboost import CatBoostClassifierfrom sklearn.metrics import accuracy_scorealgos = ['f', 'mi', 'logreg', 'lightgbm', 'mrmr']ks = [1, 2, 5, 10, 15, 20, 30, 40]accuracy = pd.DataFrame(index = ks, columns = algos)for algo in algos: for nfeats in ks: feats = ranking[algo][:n_feats] clf = CatBoostClassifier().fit( X_train[:, feats], y_train, eval_set = (X_test[:, feats], y_test), early_stopping_rounds = 20 ) accuracy.loc[k, algo] = accuracy_score( y_true = y_test, y_pred = clf.predict(X_test[:, cols])))\"\n },\n {\n \"code\": null,\n \"e\": 7150,\n \"s\": 7126,\n \"text\": \"These are the outcomes:\"\n },\n {\n \"code\": null,\n \"e\": 7204,\n \"s\": 7150,\n \"text\": \"In this case, MRMR outperformed the other algorithms.\"\n },\n {\n \"code\": null,\n \"e\": 7333,\n \"s\": 7204,\n \"text\": \"As the plot shows, a predictor trained on the most relevant 40 pixels identified by MRMR reached 95.54% accuracy on test images!\"\n },\n {\n \"code\": null,\n \"e\": 7392,\n \"s\": 7333,\n \"text\": \"This is pretty impressive, especially if we consider that:\"\n },\n {\n \"code\": null,\n \"e\": 7475,\n \"s\": 7392,\n \"text\": \"40 pixels are only 5% of the whole image (which consists of 28 x 28 = 784 pixels);\"\n },\n {\n \"code\": null,\n \"e\": 7598,\n \"s\": 7475,\n \"text\": \"we have used a predictive model (CatBoost) with no further tuning, thus this performance can probably be improved further.\"\n },\n {\n \"code\": null,\n \"e\": 7752,\n \"s\": 7598,\n \"text\": \"Thus, in the case of MNIST, we could throw away 95% of our data and still get more than 95% accuracy (which corresponds to an area under ROC of 99.85%!).\"\n },\n {\n \"code\": null,\n \"e\": 8101,\n \"s\": 7752,\n \"text\": \"Even if MNIST is a “simple” dataset, the main takeaways are valid for most real-world datasets. Often, a high level of accuracy can be achieved with just a small portion of features. An effective feature selection allows you to build data pipelines that are more efficient in terms of memory, time, accuracy, interpretability and ease of debugging.\"\n },\n {\n \"code\": null,\n \"e\": 8159,\n \"s\": 8101,\n \"text\": \"Thank you for reading! I hope you found this post useful.\"\n },\n {\n \"code\": null,\n \"e\": 8302,\n \"s\": 8159,\n \"text\": \"The results shown in this article are fully reproducible through this code: https://github.com/smazzanti/mrmr/blob/main/notebooks/mnist.ipynb.\"\n }\n]"}}},{"rowIdx":128,"cells":{"title":{"kind":"string","value":"Java - equals() Method"},"text":{"kind":"string","value":"The method determines whether the Number object that invokes the method is equal to the object that is passed as an argument.\npublic boolean equals(Object o)\n\nHere is the detail of parameters −\nAny object.\nThe method returns True if the argument is not null and is an object of the same type and with the same numeric value. There are some extra requirements for Double and Float objects that are described in the Java API documentation.\nThe method returns True if the argument is not null and is an object of the same type and with the same numeric value. There are some extra requirements for Double and Float objects that are described in the Java API documentation.\npublic class Test { \n\n public static void main(String args[]) {\n Integer x = 5;\n Integer y = 10;\n Integer z =5;\n Short a = 5;\n\n System.out.println(x.equals(y)); \n System.out.println(x.equals(z)); \n System.out.println(x.equals(a));\n }\n}\nThis will produce the following result −\nfalse\ntrue\nfalse\n\n\n 16 Lectures \n 2 hours \n\n Malhar Lathkar\n\n 19 Lectures \n 5 hours \n\n Malhar Lathkar\n\n 25 Lectures \n 2.5 hours \n\n Anadi Sharma\n\n 126 Lectures \n 7 hours \n\n Tushar Kale\n\n 119 Lectures \n 17.5 hours \n\n Monica Mittal\n\n 76 Lectures \n 7 hours \n\n Arnab Chakraborty\n Print\n Add Notes\n Bookmark this page"},"parsed":{"kind":"list like","value":[{"code":null,"e":2503,"s":2377,"text":"The method determines whether the Number object that invokes the method is equal to the object that is passed as an argument."},{"code":null,"e":2536,"s":2503,"text":"public boolean equals(Object o)\n"},{"code":null,"e":2571,"s":2536,"text":"Here is the detail of parameters −"},{"code":null,"e":2583,"s":2571,"text":"Any object."},{"code":null,"e":2815,"s":2583,"text":"The method returns True if the argument is not null and is an object of the same type and with the same numeric value. There are some extra requirements for Double and Float objects that are described in the Java API documentation."},{"code":null,"e":3047,"s":2815,"text":"The method returns True if the argument is not null and is an object of the same type and with the same numeric value. There are some extra requirements for Double and Float objects that are described in the Java API documentation."},{"code":null,"e":3323,"s":3047,"text":"public class Test { \n\n public static void main(String args[]) {\n Integer x = 5;\n Integer y = 10;\n Integer z =5;\n Short a = 5;\n\n System.out.println(x.equals(y)); \n System.out.println(x.equals(z)); \n System.out.println(x.equals(a));\n }\n}"},{"code":null,"e":3364,"s":3323,"text":"This will produce the following result −"},{"code":null,"e":3382,"s":3364,"text":"false\ntrue\nfalse\n"},{"code":null,"e":3415,"s":3382,"text":"\n 16 Lectures \n 2 hours \n"},{"code":null,"e":3431,"s":3415,"text":" Malhar Lathkar"},{"code":null,"e":3464,"s":3431,"text":"\n 19 Lectures \n 5 hours \n"},{"code":null,"e":3480,"s":3464,"text":" Malhar Lathkar"},{"code":null,"e":3515,"s":3480,"text":"\n 25 Lectures \n 2.5 hours \n"},{"code":null,"e":3529,"s":3515,"text":" Anadi Sharma"},{"code":null,"e":3563,"s":3529,"text":"\n 126 Lectures \n 7 hours \n"},{"code":null,"e":3577,"s":3563,"text":" Tushar Kale"},{"code":null,"e":3614,"s":3577,"text":"\n 119 Lectures \n 17.5 hours \n"},{"code":null,"e":3629,"s":3614,"text":" Monica Mittal"},{"code":null,"e":3662,"s":3629,"text":"\n 76 Lectures \n 7 hours \n"},{"code":null,"e":3681,"s":3662,"text":" Arnab Chakraborty"},{"code":null,"e":3688,"s":3681,"text":" Print"},{"code":null,"e":3699,"s":3688,"text":" Add Notes"}],"string":"[\n {\n \"code\": null,\n \"e\": 2503,\n \"s\": 2377,\n \"text\": \"The method determines whether the Number object that invokes the method is equal to the object that is passed as an argument.\"\n },\n {\n \"code\": null,\n \"e\": 2536,\n \"s\": 2503,\n \"text\": \"public boolean equals(Object o)\\n\"\n },\n {\n \"code\": null,\n \"e\": 2571,\n \"s\": 2536,\n \"text\": \"Here is the detail of parameters −\"\n },\n {\n \"code\": null,\n \"e\": 2583,\n \"s\": 2571,\n \"text\": \"Any object.\"\n },\n {\n \"code\": null,\n \"e\": 2815,\n \"s\": 2583,\n \"text\": \"The method returns True if the argument is not null and is an object of the same type and with the same numeric value. There are some extra requirements for Double and Float objects that are described in the Java API documentation.\"\n },\n {\n \"code\": null,\n \"e\": 3047,\n \"s\": 2815,\n \"text\": \"The method returns True if the argument is not null and is an object of the same type and with the same numeric value. There are some extra requirements for Double and Float objects that are described in the Java API documentation.\"\n },\n {\n \"code\": null,\n \"e\": 3323,\n \"s\": 3047,\n \"text\": \"public class Test { \\n\\n public static void main(String args[]) {\\n Integer x = 5;\\n Integer y = 10;\\n Integer z =5;\\n Short a = 5;\\n\\n System.out.println(x.equals(y)); \\n System.out.println(x.equals(z)); \\n System.out.println(x.equals(a));\\n }\\n}\"\n },\n {\n \"code\": null,\n \"e\": 3364,\n \"s\": 3323,\n \"text\": \"This will produce the following result −\"\n },\n {\n \"code\": null,\n \"e\": 3382,\n \"s\": 3364,\n \"text\": \"false\\ntrue\\nfalse\\n\"\n },\n {\n \"code\": null,\n \"e\": 3415,\n \"s\": 3382,\n \"text\": \"\\n 16 Lectures \\n 2 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 3431,\n \"s\": 3415,\n \"text\": \" Malhar Lathkar\"\n },\n {\n \"code\": null,\n \"e\": 3464,\n \"s\": 3431,\n \"text\": \"\\n 19 Lectures \\n 5 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 3480,\n \"s\": 3464,\n \"text\": \" Malhar Lathkar\"\n },\n {\n \"code\": null,\n \"e\": 3515,\n \"s\": 3480,\n \"text\": \"\\n 25 Lectures \\n 2.5 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 3529,\n \"s\": 3515,\n \"text\": \" Anadi Sharma\"\n },\n {\n \"code\": null,\n \"e\": 3563,\n \"s\": 3529,\n \"text\": \"\\n 126 Lectures \\n 7 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 3577,\n \"s\": 3563,\n \"text\": \" Tushar Kale\"\n },\n {\n \"code\": null,\n \"e\": 3614,\n \"s\": 3577,\n \"text\": \"\\n 119 Lectures \\n 17.5 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 3629,\n \"s\": 3614,\n \"text\": \" Monica Mittal\"\n },\n {\n \"code\": null,\n \"e\": 3662,\n \"s\": 3629,\n \"text\": \"\\n 76 Lectures \\n 7 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 3681,\n \"s\": 3662,\n \"text\": \" Arnab Chakraborty\"\n },\n {\n \"code\": null,\n \"e\": 3688,\n \"s\": 3681,\n \"text\": \" Print\"\n },\n {\n \"code\": null,\n \"e\": 3699,\n \"s\": 3688,\n \"text\": \" Add Notes\"\n }\n]"}}},{"rowIdx":129,"cells":{"title":{"kind":"string","value":"Can Github Copilot Make You a Better Data Scientist? | by Manfye Goh | Towards Data Science"},"text":{"kind":"string","value":"Github Copilot is the recent hype in the programming world, and many articles and youtube videos show the amazing capability of Copilot. I obtained access to Github Copilot Technical Preview recently and I’m curious about how Copilot can help data scientists in data science projects.\nGitHub Copilot is an AI pair programmer that helps you write code faster and with less work. GitHub Copilot draws context from comments and code and suggests individual lines and whole functions instantly. [3]\nCopilot has been trained on huge amounts of coding data publicly available, from GitHub repositories and other sites [2]. So basically it is a better programmer than you and me.\nCurrently, Copilot technical preview is available as VS code extension and is only limited to a small group of testers for previewing the extension. You can try to sign up here. Upon success approval, you will obtain a screen as below:\nCopilot works just like your Google autocomplete. Code suggestions will appear as dimmer color phrases and you will get a mouseover tab when pointing to the suggested code.\nCopilot will provide you tons of code suggestions, simply press Alt + ] and Alt + [ to change the suggested code and press “Tab” to accept it. You can preview multiple suggestion codes simply pressing Ctrl+Enter and get the view like below:\nCopilot is able to identify your comments and generate the function according to your comment, you can give instruction to the copilot to generate out the function just like the example below:\nP.s: you can also chat with Copilot when you are bored by typing ME: and AI: for the Q&A model.\nThat ends our short intro on Copilot, so let’s proceed with our main question:\nCan Copilot help data scientists make better data science projects?\nLet's try it!\nIn this experiment, we will use the famous Iris dataset; our target is to use Copilot to perform exploratory data analysis and train a k-NN model with purely the suggested code. We will put rules as below:\nUse only the suggested code, fix typos and data-specific issues only.Every action should be accompanied by a clear comment/command to Copilot.Only 3 Top code suggestions will be taken.\nUse only the suggested code, fix typos and data-specific issues only.\nEvery action should be accompanied by a clear comment/command to Copilot.\nOnly 3 Top code suggestions will be taken.\nAs of the time of writing, the Python notebook in VS code is relatively unstable with Copilot, so I will be using Streamlit as my platform. Streamlit provides a Jupyter notebook-like real-time code updates web application that can help us in exploring the data science project. For more information on Streamlit, you can read my article here.\nImport the library packages:\nimport streamlit as stimport pandas as pdimport numpy as npimport plotly.express as px\n# load iris.csv into dataframe\n# print the dataframe column names and shape\nIt impressed me that Copilot auto-understands the printing mechanism in Streamlit which uses st.write() instead of print() as streamlit is a relatively new package in python.\nNext, I try with:\n# create a scatter plot of the petal length and petal width using plotly express\nAnd this is what I get, looks like Copilot is not clever enough to understand the context inside the data frame 😂:\nNext, I try with exact naming, and a nice exact graph is obtained:\n# create a scatter plot of the petalLengthCm with SepalLengthCm using plotly express\nNext for creating a test and train dataset, I write this:\n# splitting the data into training and testing sets (80:20)\nand these are the suggestion I get back:\nImpressive! Copilot even knows which one is my target class and writes the full code for me, what I need to do is just select the suggestion!\nThe full code suggestion return is as below:\nNext, I try my luck with this command:\n# check for optimal K value using testing set\nAnd out of my expectation, Copilot can return me this code:\nThat’s tons of time saved in coding; Copilot even helps you plot a chart in the end. Well, the chart didn’t work out, so I have to modify the code a bit on my end using the list is created. But it still saves me lots of time going to stack overflow checking for codes.\nOut of my curiosity, I asked Copilot, “What is the optimal K value?”\nThe copilot returns me the answer without the need to plot the graph 😲😲\nSo this inspired my next command, I want:\n# create a classifier using the optimal K value\nand then, I just press enter and accept the suggested comment and codes to proceed. here is my resulted code:\nNote that I only type 1 command, and the rest is suggested by Copilot.\nOut of 5 suggested codes, 3 work perfectly and 2 suggestions: metrics.f1_score and metrics.precision_score doesn't work out.\nThat’s the end of my simple code testing with Copilot. I had published the suggested in Github, feel free to see it.\nIn this article, I demonstrated how copilot can help in the data science process and a few mistakes were done by Copilot, but the advantage of using it is more. Another concern is that the dataset I used was the Iris dataset, so it might work less effectively in a bigger dataset.\nThe new paradigm of programming is coming, instead of searching in Q&A websites such as StackOverflow, Copilot will save most of your googling time and give you multiple solutions directly. I guess it will reduce the reliance on StackOverflow and Google for programming-related questions in the future.\nWell, at the current stages, our job is still secured as Copilot still needs some basic knowledge to execute, such as guiding the direction of the projects and telling Copilot what to do.\nIn my opinion, Copilot definitely will make you a better data scientist currently. But will it take over your job as a data scientist in the future? With the feedbacks and vast amount of data input into Copilot, it will definitely become a better AI in the future, and who knows will it take over the programmer and data scientist job? 🤔🤔\nLastly, I’m still in #TeamHumanity: with our creativity, we will take over the control toward AI, and use AI for our betterment. Thank you very much for reading my articles.\nHere are some of my articles, hope you like them too:\ntowardsdatascience.com\ntowardsdatascience.com\nIris dataset from Kagglehttps://towardsdatascience.com/github-copilot-a-new-generation-of-ai-programmers-327e3c7ef3aehttps://copilot.github.com/\nIris dataset from Kaggle"},"parsed":{"kind":"list like","value":[{"code":null,"e":457,"s":172,"text":"Github Copilot is the recent hype in the programming world, and many articles and youtube videos show the amazing capability of Copilot. I obtained access to Github Copilot Technical Preview recently and I’m curious about how Copilot can help data scientists in data science projects."},{"code":null,"e":667,"s":457,"text":"GitHub Copilot is an AI pair programmer that helps you write code faster and with less work. GitHub Copilot draws context from comments and code and suggests individual lines and whole functions instantly. [3]"},{"code":null,"e":845,"s":667,"text":"Copilot has been trained on huge amounts of coding data publicly available, from GitHub repositories and other sites [2]. So basically it is a better programmer than you and me."},{"code":null,"e":1081,"s":845,"text":"Currently, Copilot technical preview is available as VS code extension and is only limited to a small group of testers for previewing the extension. You can try to sign up here. Upon success approval, you will obtain a screen as below:"},{"code":null,"e":1254,"s":1081,"text":"Copilot works just like your Google autocomplete. Code suggestions will appear as dimmer color phrases and you will get a mouseover tab when pointing to the suggested code."},{"code":null,"e":1495,"s":1254,"text":"Copilot will provide you tons of code suggestions, simply press Alt + ] and Alt + [ to change the suggested code and press “Tab” to accept it. You can preview multiple suggestion codes simply pressing Ctrl+Enter and get the view like below:"},{"code":null,"e":1688,"s":1495,"text":"Copilot is able to identify your comments and generate the function according to your comment, you can give instruction to the copilot to generate out the function just like the example below:"},{"code":null,"e":1784,"s":1688,"text":"P.s: you can also chat with Copilot when you are bored by typing ME: and AI: for the Q&A model."},{"code":null,"e":1863,"s":1784,"text":"That ends our short intro on Copilot, so let’s proceed with our main question:"},{"code":null,"e":1931,"s":1863,"text":"Can Copilot help data scientists make better data science projects?"},{"code":null,"e":1945,"s":1931,"text":"Let's try it!"},{"code":null,"e":2151,"s":1945,"text":"In this experiment, we will use the famous Iris dataset; our target is to use Copilot to perform exploratory data analysis and train a k-NN model with purely the suggested code. We will put rules as below:"},{"code":null,"e":2336,"s":2151,"text":"Use only the suggested code, fix typos and data-specific issues only.Every action should be accompanied by a clear comment/command to Copilot.Only 3 Top code suggestions will be taken."},{"code":null,"e":2406,"s":2336,"text":"Use only the suggested code, fix typos and data-specific issues only."},{"code":null,"e":2480,"s":2406,"text":"Every action should be accompanied by a clear comment/command to Copilot."},{"code":null,"e":2523,"s":2480,"text":"Only 3 Top code suggestions will be taken."},{"code":null,"e":2866,"s":2523,"text":"As of the time of writing, the Python notebook in VS code is relatively unstable with Copilot, so I will be using Streamlit as my platform. Streamlit provides a Jupyter notebook-like real-time code updates web application that can help us in exploring the data science project. For more information on Streamlit, you can read my article here."},{"code":null,"e":2895,"s":2866,"text":"Import the library packages:"},{"code":null,"e":2982,"s":2895,"text":"import streamlit as stimport pandas as pdimport numpy as npimport plotly.express as px"},{"code":null,"e":3013,"s":2982,"text":"# load iris.csv into dataframe"},{"code":null,"e":3058,"s":3013,"text":"# print the dataframe column names and shape"},{"code":null,"e":3233,"s":3058,"text":"It impressed me that Copilot auto-understands the printing mechanism in Streamlit which uses st.write() instead of print() as streamlit is a relatively new package in python."},{"code":null,"e":3251,"s":3233,"text":"Next, I try with:"},{"code":null,"e":3332,"s":3251,"text":"# create a scatter plot of the petal length and petal width using plotly express"},{"code":null,"e":3447,"s":3332,"text":"And this is what I get, looks like Copilot is not clever enough to understand the context inside the data frame 😂:"},{"code":null,"e":3514,"s":3447,"text":"Next, I try with exact naming, and a nice exact graph is obtained:"},{"code":null,"e":3599,"s":3514,"text":"# create a scatter plot of the petalLengthCm with SepalLengthCm using plotly express"},{"code":null,"e":3657,"s":3599,"text":"Next for creating a test and train dataset, I write this:"},{"code":null,"e":3717,"s":3657,"text":"# splitting the data into training and testing sets (80:20)"},{"code":null,"e":3758,"s":3717,"text":"and these are the suggestion I get back:"},{"code":null,"e":3900,"s":3758,"text":"Impressive! Copilot even knows which one is my target class and writes the full code for me, what I need to do is just select the suggestion!"},{"code":null,"e":3945,"s":3900,"text":"The full code suggestion return is as below:"},{"code":null,"e":3984,"s":3945,"text":"Next, I try my luck with this command:"},{"code":null,"e":4030,"s":3984,"text":"# check for optimal K value using testing set"},{"code":null,"e":4090,"s":4030,"text":"And out of my expectation, Copilot can return me this code:"},{"code":null,"e":4359,"s":4090,"text":"That’s tons of time saved in coding; Copilot even helps you plot a chart in the end. Well, the chart didn’t work out, so I have to modify the code a bit on my end using the list is created. But it still saves me lots of time going to stack overflow checking for codes."},{"code":null,"e":4428,"s":4359,"text":"Out of my curiosity, I asked Copilot, “What is the optimal K value?”"},{"code":null,"e":4500,"s":4428,"text":"The copilot returns me the answer without the need to plot the graph 😲😲"},{"code":null,"e":4542,"s":4500,"text":"So this inspired my next command, I want:"},{"code":null,"e":4590,"s":4542,"text":"# create a classifier using the optimal K value"},{"code":null,"e":4700,"s":4590,"text":"and then, I just press enter and accept the suggested comment and codes to proceed. here is my resulted code:"},{"code":null,"e":4771,"s":4700,"text":"Note that I only type 1 command, and the rest is suggested by Copilot."},{"code":null,"e":4896,"s":4771,"text":"Out of 5 suggested codes, 3 work perfectly and 2 suggestions: metrics.f1_score and metrics.precision_score doesn't work out."},{"code":null,"e":5013,"s":4896,"text":"That’s the end of my simple code testing with Copilot. I had published the suggested in Github, feel free to see it."},{"code":null,"e":5294,"s":5013,"text":"In this article, I demonstrated how copilot can help in the data science process and a few mistakes were done by Copilot, but the advantage of using it is more. Another concern is that the dataset I used was the Iris dataset, so it might work less effectively in a bigger dataset."},{"code":null,"e":5597,"s":5294,"text":"The new paradigm of programming is coming, instead of searching in Q&A websites such as StackOverflow, Copilot will save most of your googling time and give you multiple solutions directly. I guess it will reduce the reliance on StackOverflow and Google for programming-related questions in the future."},{"code":null,"e":5785,"s":5597,"text":"Well, at the current stages, our job is still secured as Copilot still needs some basic knowledge to execute, such as guiding the direction of the projects and telling Copilot what to do."},{"code":null,"e":6124,"s":5785,"text":"In my opinion, Copilot definitely will make you a better data scientist currently. But will it take over your job as a data scientist in the future? With the feedbacks and vast amount of data input into Copilot, it will definitely become a better AI in the future, and who knows will it take over the programmer and data scientist job? 🤔🤔"},{"code":null,"e":6298,"s":6124,"text":"Lastly, I’m still in #TeamHumanity: with our creativity, we will take over the control toward AI, and use AI for our betterment. Thank you very much for reading my articles."},{"code":null,"e":6352,"s":6298,"text":"Here are some of my articles, hope you like them too:"},{"code":null,"e":6375,"s":6352,"text":"towardsdatascience.com"},{"code":null,"e":6398,"s":6375,"text":"towardsdatascience.com"},{"code":null,"e":6543,"s":6398,"text":"Iris dataset from Kagglehttps://towardsdatascience.com/github-copilot-a-new-generation-of-ai-programmers-327e3c7ef3aehttps://copilot.github.com/"}],"string":"[\n {\n \"code\": null,\n \"e\": 457,\n \"s\": 172,\n \"text\": \"Github Copilot is the recent hype in the programming world, and many articles and youtube videos show the amazing capability of Copilot. I obtained access to Github Copilot Technical Preview recently and I’m curious about how Copilot can help data scientists in data science projects.\"\n },\n {\n \"code\": null,\n \"e\": 667,\n \"s\": 457,\n \"text\": \"GitHub Copilot is an AI pair programmer that helps you write code faster and with less work. GitHub Copilot draws context from comments and code and suggests individual lines and whole functions instantly. [3]\"\n },\n {\n \"code\": null,\n \"e\": 845,\n \"s\": 667,\n \"text\": \"Copilot has been trained on huge amounts of coding data publicly available, from GitHub repositories and other sites [2]. So basically it is a better programmer than you and me.\"\n },\n {\n \"code\": null,\n \"e\": 1081,\n \"s\": 845,\n \"text\": \"Currently, Copilot technical preview is available as VS code extension and is only limited to a small group of testers for previewing the extension. You can try to sign up here. Upon success approval, you will obtain a screen as below:\"\n },\n {\n \"code\": null,\n \"e\": 1254,\n \"s\": 1081,\n \"text\": \"Copilot works just like your Google autocomplete. Code suggestions will appear as dimmer color phrases and you will get a mouseover tab when pointing to the suggested code.\"\n },\n {\n \"code\": null,\n \"e\": 1495,\n \"s\": 1254,\n \"text\": \"Copilot will provide you tons of code suggestions, simply press Alt + ] and Alt + [ to change the suggested code and press “Tab” to accept it. You can preview multiple suggestion codes simply pressing Ctrl+Enter and get the view like below:\"\n },\n {\n \"code\": null,\n \"e\": 1688,\n \"s\": 1495,\n \"text\": \"Copilot is able to identify your comments and generate the function according to your comment, you can give instruction to the copilot to generate out the function just like the example below:\"\n },\n {\n \"code\": null,\n \"e\": 1784,\n \"s\": 1688,\n \"text\": \"P.s: you can also chat with Copilot when you are bored by typing ME: and AI: for the Q&A model.\"\n },\n {\n \"code\": null,\n \"e\": 1863,\n \"s\": 1784,\n \"text\": \"That ends our short intro on Copilot, so let’s proceed with our main question:\"\n },\n {\n \"code\": null,\n \"e\": 1931,\n \"s\": 1863,\n \"text\": \"Can Copilot help data scientists make better data science projects?\"\n },\n {\n \"code\": null,\n \"e\": 1945,\n \"s\": 1931,\n \"text\": \"Let's try it!\"\n },\n {\n \"code\": null,\n \"e\": 2151,\n \"s\": 1945,\n \"text\": \"In this experiment, we will use the famous Iris dataset; our target is to use Copilot to perform exploratory data analysis and train a k-NN model with purely the suggested code. We will put rules as below:\"\n },\n {\n \"code\": null,\n \"e\": 2336,\n \"s\": 2151,\n \"text\": \"Use only the suggested code, fix typos and data-specific issues only.Every action should be accompanied by a clear comment/command to Copilot.Only 3 Top code suggestions will be taken.\"\n },\n {\n \"code\": null,\n \"e\": 2406,\n \"s\": 2336,\n \"text\": \"Use only the suggested code, fix typos and data-specific issues only.\"\n },\n {\n \"code\": null,\n \"e\": 2480,\n \"s\": 2406,\n \"text\": \"Every action should be accompanied by a clear comment/command to Copilot.\"\n },\n {\n \"code\": null,\n \"e\": 2523,\n \"s\": 2480,\n \"text\": \"Only 3 Top code suggestions will be taken.\"\n },\n {\n \"code\": null,\n \"e\": 2866,\n \"s\": 2523,\n \"text\": \"As of the time of writing, the Python notebook in VS code is relatively unstable with Copilot, so I will be using Streamlit as my platform. Streamlit provides a Jupyter notebook-like real-time code updates web application that can help us in exploring the data science project. For more information on Streamlit, you can read my article here.\"\n },\n {\n \"code\": null,\n \"e\": 2895,\n \"s\": 2866,\n \"text\": \"Import the library packages:\"\n },\n {\n \"code\": null,\n \"e\": 2982,\n \"s\": 2895,\n \"text\": \"import streamlit as stimport pandas as pdimport numpy as npimport plotly.express as px\"\n },\n {\n \"code\": null,\n \"e\": 3013,\n \"s\": 2982,\n \"text\": \"# load iris.csv into dataframe\"\n },\n {\n \"code\": null,\n \"e\": 3058,\n \"s\": 3013,\n \"text\": \"# print the dataframe column names and shape\"\n },\n {\n \"code\": null,\n \"e\": 3233,\n \"s\": 3058,\n \"text\": \"It impressed me that Copilot auto-understands the printing mechanism in Streamlit which uses st.write() instead of print() as streamlit is a relatively new package in python.\"\n },\n {\n \"code\": null,\n \"e\": 3251,\n \"s\": 3233,\n \"text\": \"Next, I try with:\"\n },\n {\n \"code\": null,\n \"e\": 3332,\n \"s\": 3251,\n \"text\": \"# create a scatter plot of the petal length and petal width using plotly express\"\n },\n {\n \"code\": null,\n \"e\": 3447,\n \"s\": 3332,\n \"text\": \"And this is what I get, looks like Copilot is not clever enough to understand the context inside the data frame 😂:\"\n },\n {\n \"code\": null,\n \"e\": 3514,\n \"s\": 3447,\n \"text\": \"Next, I try with exact naming, and a nice exact graph is obtained:\"\n },\n {\n \"code\": null,\n \"e\": 3599,\n \"s\": 3514,\n \"text\": \"# create a scatter plot of the petalLengthCm with SepalLengthCm using plotly express\"\n },\n {\n \"code\": null,\n \"e\": 3657,\n \"s\": 3599,\n \"text\": \"Next for creating a test and train dataset, I write this:\"\n },\n {\n \"code\": null,\n \"e\": 3717,\n \"s\": 3657,\n \"text\": \"# splitting the data into training and testing sets (80:20)\"\n },\n {\n \"code\": null,\n \"e\": 3758,\n \"s\": 3717,\n \"text\": \"and these are the suggestion I get back:\"\n },\n {\n \"code\": null,\n \"e\": 3900,\n \"s\": 3758,\n \"text\": \"Impressive! Copilot even knows which one is my target class and writes the full code for me, what I need to do is just select the suggestion!\"\n },\n {\n \"code\": null,\n \"e\": 3945,\n \"s\": 3900,\n \"text\": \"The full code suggestion return is as below:\"\n },\n {\n \"code\": null,\n \"e\": 3984,\n \"s\": 3945,\n \"text\": \"Next, I try my luck with this command:\"\n },\n {\n \"code\": null,\n \"e\": 4030,\n \"s\": 3984,\n \"text\": \"# check for optimal K value using testing set\"\n },\n {\n \"code\": null,\n \"e\": 4090,\n \"s\": 4030,\n \"text\": \"And out of my expectation, Copilot can return me this code:\"\n },\n {\n \"code\": null,\n \"e\": 4359,\n \"s\": 4090,\n \"text\": \"That’s tons of time saved in coding; Copilot even helps you plot a chart in the end. Well, the chart didn’t work out, so I have to modify the code a bit on my end using the list is created. But it still saves me lots of time going to stack overflow checking for codes.\"\n },\n {\n \"code\": null,\n \"e\": 4428,\n \"s\": 4359,\n \"text\": \"Out of my curiosity, I asked Copilot, “What is the optimal K value?”\"\n },\n {\n \"code\": null,\n \"e\": 4500,\n \"s\": 4428,\n \"text\": \"The copilot returns me the answer without the need to plot the graph 😲😲\"\n },\n {\n \"code\": null,\n \"e\": 4542,\n \"s\": 4500,\n \"text\": \"So this inspired my next command, I want:\"\n },\n {\n \"code\": null,\n \"e\": 4590,\n \"s\": 4542,\n \"text\": \"# create a classifier using the optimal K value\"\n },\n {\n \"code\": null,\n \"e\": 4700,\n \"s\": 4590,\n \"text\": \"and then, I just press enter and accept the suggested comment and codes to proceed. here is my resulted code:\"\n },\n {\n \"code\": null,\n \"e\": 4771,\n \"s\": 4700,\n \"text\": \"Note that I only type 1 command, and the rest is suggested by Copilot.\"\n },\n {\n \"code\": null,\n \"e\": 4896,\n \"s\": 4771,\n \"text\": \"Out of 5 suggested codes, 3 work perfectly and 2 suggestions: metrics.f1_score and metrics.precision_score doesn't work out.\"\n },\n {\n \"code\": null,\n \"e\": 5013,\n \"s\": 4896,\n \"text\": \"That’s the end of my simple code testing with Copilot. I had published the suggested in Github, feel free to see it.\"\n },\n {\n \"code\": null,\n \"e\": 5294,\n \"s\": 5013,\n \"text\": \"In this article, I demonstrated how copilot can help in the data science process and a few mistakes were done by Copilot, but the advantage of using it is more. Another concern is that the dataset I used was the Iris dataset, so it might work less effectively in a bigger dataset.\"\n },\n {\n \"code\": null,\n \"e\": 5597,\n \"s\": 5294,\n \"text\": \"The new paradigm of programming is coming, instead of searching in Q&A websites such as StackOverflow, Copilot will save most of your googling time and give you multiple solutions directly. I guess it will reduce the reliance on StackOverflow and Google for programming-related questions in the future.\"\n },\n {\n \"code\": null,\n \"e\": 5785,\n \"s\": 5597,\n \"text\": \"Well, at the current stages, our job is still secured as Copilot still needs some basic knowledge to execute, such as guiding the direction of the projects and telling Copilot what to do.\"\n },\n {\n \"code\": null,\n \"e\": 6124,\n \"s\": 5785,\n \"text\": \"In my opinion, Copilot definitely will make you a better data scientist currently. But will it take over your job as a data scientist in the future? With the feedbacks and vast amount of data input into Copilot, it will definitely become a better AI in the future, and who knows will it take over the programmer and data scientist job? 🤔🤔\"\n },\n {\n \"code\": null,\n \"e\": 6298,\n \"s\": 6124,\n \"text\": \"Lastly, I’m still in #TeamHumanity: with our creativity, we will take over the control toward AI, and use AI for our betterment. Thank you very much for reading my articles.\"\n },\n {\n \"code\": null,\n \"e\": 6352,\n \"s\": 6298,\n \"text\": \"Here are some of my articles, hope you like them too:\"\n },\n {\n \"code\": null,\n \"e\": 6375,\n \"s\": 6352,\n \"text\": \"towardsdatascience.com\"\n },\n {\n \"code\": null,\n \"e\": 6398,\n \"s\": 6375,\n \"text\": \"towardsdatascience.com\"\n },\n {\n \"code\": null,\n \"e\": 6543,\n \"s\": 6398,\n \"text\": \"Iris dataset from Kagglehttps://towardsdatascience.com/github-copilot-a-new-generation-of-ai-programmers-327e3c7ef3aehttps://copilot.github.com/\"\n }\n]"}}},{"rowIdx":130,"cells":{"title":{"kind":"string","value":"What are the different ways of handling authentication popup window using Selenium?"},"text":{"kind":"string","value":"We can handle authentication pop-up window using Selenium webdriver by incorporating the username and password within the application URL. The format of an URL along with credential should be − https://username:password@URL\nLet us launch a web page having the authentication pop-up generated at page load −\nThe user Name and Password fields are having value as admin.\nIf we ignore this pop-up on clicking the Cancel button, we shall be navigated to the below page.\nIf proper credentials are entered and then the OK button is clicked, we shall be navigated to the below page.\nIn the above example, to handle the authentication pop-up, using the get method, the URL to be passed as a parameter should be - https://admin:admin@the−nternet.herokuapp.com/basic_auth.\nfrom selenium import webdriver\n#set chromodriver.exe path\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n#implicit wait\ndriver.implicitly_wait(0.5)\n#maximize browser\ndriver.maximize_window()\n#username, password value\np = \"admin\"\n#url format\nurl = \"https://\" + p + \":\" + p + \"@\" + \"the-internet.herokuapp.com/basic_auth\"\n#launch URL\ndriver.get(url)\n#identify element\nl = driver.find_element_by_tag_name(\"p\")\n#obtain text\ns = l.text\nprint(\"Text is: \")\nprint(s)\n#close browser\ndriver.close()"},"parsed":{"kind":"list like","value":[{"code":null,"e":1286,"s":1062,"text":"We can handle authentication pop-up window using Selenium webdriver by incorporating the username and password within the application URL. The format of an URL along with credential should be − https://username:password@URL"},{"code":null,"e":1369,"s":1286,"text":"Let us launch a web page having the authentication pop-up generated at page load −"},{"code":null,"e":1430,"s":1369,"text":"The user Name and Password fields are having value as admin."},{"code":null,"e":1527,"s":1430,"text":"If we ignore this pop-up on clicking the Cancel button, we shall be navigated to the below page."},{"code":null,"e":1637,"s":1527,"text":"If proper credentials are entered and then the OK button is clicked, we shall be navigated to the below page."},{"code":null,"e":1824,"s":1637,"text":"In the above example, to handle the authentication pop-up, using the get method, the URL to be passed as a parameter should be - https://admin:admin@the−nternet.herokuapp.com/basic_auth."},{"code":null,"e":2332,"s":1824,"text":"from selenium import webdriver\n#set chromodriver.exe path\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n#implicit wait\ndriver.implicitly_wait(0.5)\n#maximize browser\ndriver.maximize_window()\n#username, password value\np = \"admin\"\n#url format\nurl = \"https://\" + p + \":\" + p + \"@\" + \"the-internet.herokuapp.com/basic_auth\"\n#launch URL\ndriver.get(url)\n#identify element\nl = driver.find_element_by_tag_name(\"p\")\n#obtain text\ns = l.text\nprint(\"Text is: \")\nprint(s)\n#close browser\ndriver.close()"}],"string":"[\n {\n \"code\": null,\n \"e\": 1286,\n \"s\": 1062,\n \"text\": \"We can handle authentication pop-up window using Selenium webdriver by incorporating the username and password within the application URL. The format of an URL along with credential should be − https://username:password@URL\"\n },\n {\n \"code\": null,\n \"e\": 1369,\n \"s\": 1286,\n \"text\": \"Let us launch a web page having the authentication pop-up generated at page load −\"\n },\n {\n \"code\": null,\n \"e\": 1430,\n \"s\": 1369,\n \"text\": \"The user Name and Password fields are having value as admin.\"\n },\n {\n \"code\": null,\n \"e\": 1527,\n \"s\": 1430,\n \"text\": \"If we ignore this pop-up on clicking the Cancel button, we shall be navigated to the below page.\"\n },\n {\n \"code\": null,\n \"e\": 1637,\n \"s\": 1527,\n \"text\": \"If proper credentials are entered and then the OK button is clicked, we shall be navigated to the below page.\"\n },\n {\n \"code\": null,\n \"e\": 1824,\n \"s\": 1637,\n \"text\": \"In the above example, to handle the authentication pop-up, using the get method, the URL to be passed as a parameter should be - https://admin:admin@the−nternet.herokuapp.com/basic_auth.\"\n },\n {\n \"code\": null,\n \"e\": 2332,\n \"s\": 1824,\n \"text\": \"from selenium import webdriver\\n#set chromodriver.exe path\\ndriver = webdriver.Chrome(executable_path=\\\"C:\\\\\\\\chromedriver.exe\\\")\\n#implicit wait\\ndriver.implicitly_wait(0.5)\\n#maximize browser\\ndriver.maximize_window()\\n#username, password value\\np = \\\"admin\\\"\\n#url format\\nurl = \\\"https://\\\" + p + \\\":\\\" + p + \\\"@\\\" + \\\"the-internet.herokuapp.com/basic_auth\\\"\\n#launch URL\\ndriver.get(url)\\n#identify element\\nl = driver.find_element_by_tag_name(\\\"p\\\")\\n#obtain text\\ns = l.text\\nprint(\\\"Text is: \\\")\\nprint(s)\\n#close browser\\ndriver.close()\"\n }\n]"}}},{"rowIdx":131,"cells":{"title":{"kind":"string","value":"Beautiful Soup - Navigating by Tags"},"text":{"kind":"string","value":"In this chapter, we shall discuss about Navigating by Tags.\nBelow is our html document −\n>>> html_doc = \"\"\"\nTutorials Point\n\n

The Biggest Online Tutorials Library, It's all Free

\n

Top 5 most used Programming Languages are:\nJava,\nC,\nPython,\nJavaScript and\nC;\nas per online survey.

\n

Programming Languages

\n\"\"\"\n>>>\n>>> from bs4 import BeautifulSoup\n>>> soup = BeautifulSoup(html_doc, 'html.parser')\n>>>\nBased on the above document, we will try to move from one part of document to another.\nOne of the important pieces of element in any piece of HTML document are tags, which may contain other tags/strings (tag’s children). Beautiful Soup provides different ways to navigate and iterate over’s tag’s children.\nEasiest way to search a parse tree is to search the tag by its name. If you want the tag, use soup.head −\n>>> soup.head\n&t;title>Tutorials Point\n>>> soup.title\nTutorials Point\nTo get specific tag (like first tag) in the tag.\n>>> soup.body.b\nThe Biggest Online Tutorials Library, It's all Free\nUsing a tag name as an attribute will give you only the first tag by that name −\n>>> soup.a\nJava\n\nTo get all the tag’s attribute, you can use find_all() method −\n>>> soup.find_all(\"a\")\n[Java, C, Python, JavaScript, C]>>> soup.find_all(\"a\")\n[Java, C, Python, JavaScript, C]\nWe can search tag’s children in a list by its .contents −\n>>> head_tag = soup.head\n>>> head_tag\nTutorials Point\n>>> Htag = soup.head\n>>> Htag\nTutorials Point\n>>>\n>>> Htag.contents\n[Tutorials Point\n>>>\n>>> Ttag = head_tag.contents[0]\n>>> Ttag\nTutorials Point\n>>> Ttag.contents\n['Tutorials Point']\nThe BeautifulSoup object itself has children. In this case, the tag is the child of the BeautifulSoup object −\n>>> len(soup.contents)\n2\n>>> soup.contents[1].name\n'html'\nA string does not have .contents, because it can’t contain anything −\n>>> text = Ttag.contents[0]\n>>> text.contents\nself.__class__.__name__, attr))\nAttributeError: 'NavigableString' object has no attribute 'contents'\nInstead of getting them as a list, use .children generator to access tag’s children −\n>>> for child in Ttag.children:\nprint(child)\nTutorials Point\n\nThe .descendants attribute allows you to iterate over all of a tag’s children, recursively −\nits direct children and the children of its direct children and so on −\n>>> for child in Htag.descendants:\nprint(child)\nTutorials Point\nTutorials Point\n\nThe tag has only one child, but it has two descendants: the tag and the <title> tag’s child. The beautifulsoup object has only one direct child (the <html> tag), but it has a whole lot of descendants −\n>>> len(list(soup.children))\n2\n>>> len(list(soup.descendants))\n33\n\nIf the tag has only one child, and that child is a NavigableString, the child is made available as .string −\n>>> Ttag.string\n'Tutorials Point'\n\nIf a tag’s only child is another tag, and that tag has a .string, then the parent tag is considered to have the same .string as its child −\n>>> Htag.contents\n[<title>Tutorials Point]\n>>>\n>>> Htag.string\n'Tutorials Point'\nHowever, if a tag contains more than one thing, then it’s not clear what .string should refer to, so .string is defined to None −\n>>> print(soup.html.string)\nNone\n\nIf there’s more than one thing inside a tag, you can still look at just the strings. Use the .strings generator −\n>>> for string in soup.strings:\nprint(repr(string))\n'\\n'\n'Tutorials Point'\n'\\n'\n'\\n'\n\"The Biggest Online Tutorials Library, It's all Free\"\n'\\n'\n'Top 5 most used Programming Languages are: \\n'\n'Java'\n',\\n'\n'C'\n',\\n'\n'Python'\n',\\n'\n'JavaScript'\n' and\\n'\n'C'\n';\\n \\nas per online survey.'\n'\\n'\n'Programming Languages'\n'\\n'\nTo remove extra whitespace, use .stripped_strings generator −\n>>> for string in soup.stripped_strings:\nprint(repr(string))\n'Tutorials Point'\n\"The Biggest Online Tutorials Library, It's all Free\"\n'Top 5 most used Programming Languages are:'\n'Java'\n','\n'C'\n','\n'Python'\n','\n'JavaScript'\n'and'\n'C'\n';\\n \\nas per online survey.'\n'Programming Languages'\nIn a “family tree” analogy, every tag and every string has a parent: the tag that contain it:\nTo access the element’s parent element, use .parent attribute.\n>>> Ttag = soup.title\n>>> Ttag\nTutorials Point\n>>> Ttag.parent\ntitle>Tutorials Point\nIn our html_doc, the title string itself has a parent: the tag that contain it−\n>>> Ttag.string.parent\n<title>Tutorials Point\n\nThe parent of a top-level tag like is the Beautifulsoup object itself −\n>>> htmltag = soup.html\n>>> type(htmltag.parent)\n\n\nThe .parent of a Beautifulsoup object is defined as None −\n>>> print(soup.parent)\nNone\n\nTo iterate over all the parents elements, use .parents attribute.\n>>> link = soup.a\n>>> link\nJava\n>>>\n>>> for parent in link.parents:\nif parent is None:\nprint(parent)\nelse:\nprint(parent.name)\np\nbody\nhtml\n[document]\nBelow is one simple document −\n>>> sibling_soup = BeautifulSoup(\"TutorialsPointThe Biggest Online Tutorials Library, It's all Free\")\n>>> print(sibling_soup.prettify())\n\n\n \n \n TutorialsPoint\n \n \n \n The Biggest Online Tutorials Library, It's all Free\n \n \n \n\n\nIn the above doc, and tag is at the same level and they are both children of the same tag. Both and tag are siblings.\nUse .next_sibling and .previous_sibling to navigate between page elements that are on the same level of the parse tree:\n>>> sibling_soup.b.next_sibling\nThe Biggest Online Tutorials Library, It's all Free\n>>>\n>>> sibling_soup.c.previous_sibling\nTutorialsPoint\nThe tag has a .next_sibling but no .previous_sibling, as there is nothing before the tag on the same level of the tree, same case is with tag.\n>>> print(sibling_soup.b.previous_sibling)\nNone\n>>> print(sibling_soup.c.next_sibling)\nNone\n\nThe two strings are not siblings, as they don’t have the same parent.\n>>> sibling_soup.b.string\n'TutorialsPoint'\n>>>\n>>> print(sibling_soup.b.string.next_sibling)\nNone\nTo iterate over a tag’s siblings use .next_siblings and .previous_siblings.\n>>> for sibling in soup.a.next_siblings:\nprint(repr(sibling))\n',\\n'\nC\n',\\n'\n>a class=\"prog\" href=\"https://www.tutorialspoint.com/python/index.htm\" id=\"link3\">Python\n',\\n'\nJavaScript\n' and\\n'\nC\n';\\n \\nas per online survey.'\n>>> for sibling in soup.find(id=\"link3\").previous_siblings:\nprint(repr(sibling))\n',\\n'\nC\n',\\n'\nJava\n'Top 5 most used Programming Languages are: \\n'\nNow let us get back to first two lines in our previous “html_doc” example −\n&t;html>Tutorials Point\n\n

The Biggest Online Tutorials Library, It's all Free

\nAn HTML parser takes above string of characters and turns it into a series of events like “open an tag”, “open an tag”, “open the tag”, “add a string”, “close the tag”, “close the tag”, “open a

tag” and so on. BeautifulSoup offers different methods to reconstructs the initial parse of the document.\nThe .next_element attribute of a tag or string points to whatever was parsed immediately afterwards. Sometimes it looks similar to .next_sibling, however it is not same entirely.\nBelow is the final tag in our “html_doc” example document.\n>>> last_a_tag = soup.find(\"a\", id=\"link5\")\n>>> last_a_tag\nC\n>>> last_a_tag.next_sibling\n';\\n \\nas per online survey.'\nHowever the .next_element of that tag, the thing that was parsed immediately after the tag, is not the rest of that sentence: it is the word “C”:\n>>> last_a_tag.next_element\n'C'\n\nAbove behavior is because in the original markup, the letter “C” appeared before that semicolon. The parser encountered an tag, then the letter “C”, then the closing tag, then the semicolon and rest of the sentence. The semicolon is on the same level as the tag, but the letter “C” was encountered first.\nThe .previous_element attribute is the exact opposite of .next_element. It points to whatever element was parsed immediately before this one.\n>>> last_a_tag.previous_element\n' and\\n'\n>>>\n>>> last_a_tag.previous_element.next_element\nC\nWe use these iterators to move forward and backward to an element.\n>>> for element in last_a_tag.next_e lements:\nprint(repr(element))\n'C'\n';\\n \\nas per online survey.'\n'\\n'\n

Programming Languages

\n'Programming Languages'\n'\\n'\n\n\n 38 Lectures \n 3.5 hours \n\n Chandramouli Jayendran\n\n 22 Lectures \n 1 hours \n\n TELCOMA Global\n\n 6 Lectures \n 1 hours \n\n AlexanderSchlee\n\n 6 Lectures \n 1 hours \n\n AlexanderSchlee\n\n 6 Lectures \n 1 hours \n\n AlexanderSchlee\n\n 22 Lectures \n 4 hours \n\n AlexanderSchlee\n Print\n Add Notes\n Bookmark this page"},"parsed":{"kind":"list like","value":[{"code":null,"e":2045,"s":1985,"text":"In this chapter, we shall discuss about Navigating by Tags."},{"code":null,"e":2074,"s":2045,"text":"Below is our html document −"},{"code":null,"e":2946,"s":2074,"text":">>> html_doc = \"\"\"\nTutorials Point\n\n

The Biggest Online Tutorials Library, It's all Free

\n

Top 5 most used Programming Languages are:\nJava,\nC,\nPython,\nJavaScript and\nC;\nas per online survey.

\n

Programming Languages

\n\"\"\"\n>>>\n>>> from bs4 import BeautifulSoup\n>>> soup = BeautifulSoup(html_doc, 'html.parser')\n>>>"},{"code":null,"e":3033,"s":2946,"text":"Based on the above document, we will try to move from one part of document to another."},{"code":null,"e":3253,"s":3033,"text":"One of the important pieces of element in any piece of HTML document are tags, which may contain other tags/strings (tag’s children). Beautiful Soup provides different ways to navigate and iterate over’s tag’s children."},{"code":null,"e":3366,"s":3253,"text":"Easiest way to search a parse tree is to search the tag by its name. If you want the tag, use soup.head −"},{"code":null,"e":3472,"s":3366,"text":">>> soup.head\n&t;title>Tutorials Point\n>>> soup.title\nTutorials Point"},{"code":null,"e":3532,"s":3472,"text":"To get specific tag (like first tag) in the tag."},{"code":null,"e":3607,"s":3532,"text":">>> soup.body.b\nThe Biggest Online Tutorials Library, It's all Free"},{"code":null,"e":3688,"s":3607,"text":"Using a tag name as an attribute will give you only the first tag by that name −"},{"code":null,"e":3797,"s":3688,"text":">>> soup.a\nJava\n"},{"code":null,"e":3861,"s":3797,"text":"To get all the tag’s attribute, you can use find_all() method −"},{"code":null,"e":4888,"s":3861,"text":">>> soup.find_all(\"a\")\n[Java, C, Python, JavaScript, C]>>> soup.find_all(\"a\")\n[Java, C, Python, JavaScript, C]"},{"code":null,"e":4946,"s":4888,"text":"We can search tag’s children in a list by its .contents −"},{"code":null,"e":5270,"s":4946,"text":">>> head_tag = soup.head\n>>> head_tag\nTutorials Point\n>>> Htag = soup.head\n>>> Htag\nTutorials Point\n>>>\n>>> Htag.contents\n[Tutorials Point\n>>>\n>>> Ttag = head_tag.contents[0]\n>>> Ttag\nTutorials Point\n>>> Ttag.contents\n['Tutorials Point']"},{"code":null,"e":5388,"s":5270,"text":"The BeautifulSoup object itself has children. In this case, the tag is the child of the BeautifulSoup object −"},{"code":null,"e":5446,"s":5388,"text":">>> len(soup.contents)\n2\n>>> soup.contents[1].name\n'html'"},{"code":null,"e":5516,"s":5446,"text":"A string does not have .contents, because it can’t contain anything −"},{"code":null,"e":5663,"s":5516,"text":">>> text = Ttag.contents[0]\n>>> text.contents\nself.__class__.__name__, attr))\nAttributeError: 'NavigableString' object has no attribute 'contents'"},{"code":null,"e":5749,"s":5663,"text":"Instead of getting them as a list, use .children generator to access tag’s children −"},{"code":null,"e":5811,"s":5749,"text":">>> for child in Ttag.children:\nprint(child)\nTutorials Point\n"},{"code":null,"e":5904,"s":5811,"text":"The .descendants attribute allows you to iterate over all of a tag’s children, recursively −"},{"code":null,"e":5976,"s":5904,"text":"its direct children and the children of its direct children and so on −"},{"code":null,"e":6072,"s":5976,"text":">>> for child in Htag.descendants:\nprint(child)\nTutorials Point\nTutorials Point\n"},{"code":null,"e":6289,"s":6072,"text":"The tag has only one child, but it has two descendants: the tag and the <title> tag’s child. The beautifulsoup object has only one direct child (the <html> tag), but it has a whole lot of descendants −"},{"code":null,"e":6356,"s":6289,"text":">>> len(list(soup.children))\n2\n>>> len(list(soup.descendants))\n33\n"},{"code":null,"e":6465,"s":6356,"text":"If the tag has only one child, and that child is a NavigableString, the child is made available as .string −"},{"code":null,"e":6500,"s":6465,"text":">>> Ttag.string\n'Tutorials Point'\n"},{"code":null,"e":6640,"s":6500,"text":"If a tag’s only child is another tag, and that tag has a .string, then the parent tag is considered to have the same .string as its child −"},{"code":null,"e":6729,"s":6640,"text":">>> Htag.contents\n[<title>Tutorials Point]\n>>>\n>>> Htag.string\n'Tutorials Point'"},{"code":null,"e":6859,"s":6729,"text":"However, if a tag contains more than one thing, then it’s not clear what .string should refer to, so .string is defined to None −"},{"code":null,"e":6893,"s":6859,"text":">>> print(soup.html.string)\nNone\n"},{"code":null,"e":7007,"s":6893,"text":"If there’s more than one thing inside a tag, you can still look at just the strings. Use the .strings generator −"},{"code":null,"e":7327,"s":7007,"text":">>> for string in soup.strings:\nprint(repr(string))\n'\\n'\n'Tutorials Point'\n'\\n'\n'\\n'\n\"The Biggest Online Tutorials Library, It's all Free\"\n'\\n'\n'Top 5 most used Programming Languages are: \\n'\n'Java'\n',\\n'\n'C'\n',\\n'\n'Python'\n',\\n'\n'JavaScript'\n' and\\n'\n'C'\n';\\n \\nas per online survey.'\n'\\n'\n'Programming Languages'\n'\\n'"},{"code":null,"e":7389,"s":7327,"text":"To remove extra whitespace, use .stripped_strings generator −"},{"code":null,"e":7676,"s":7389,"text":">>> for string in soup.stripped_strings:\nprint(repr(string))\n'Tutorials Point'\n\"The Biggest Online Tutorials Library, It's all Free\"\n'Top 5 most used Programming Languages are:'\n'Java'\n','\n'C'\n','\n'Python'\n','\n'JavaScript'\n'and'\n'C'\n';\\n \\nas per online survey.'\n'Programming Languages'"},{"code":null,"e":7770,"s":7676,"text":"In a “family tree” analogy, every tag and every string has a parent: the tag that contain it:"},{"code":null,"e":7833,"s":7770,"text":"To access the element’s parent element, use .parent attribute."},{"code":null,"e":7954,"s":7833,"text":">>> Ttag = soup.title\n>>> Ttag\nTutorials Point\n>>> Ttag.parent\ntitle>Tutorials Point"},{"code":null,"e":8042,"s":7954,"text":"In our html_doc, the title string itself has a parent: the tag that contain it−"},{"code":null,"e":8097,"s":8042,"text":">>> Ttag.string.parent\n<title>Tutorials Point\n"},{"code":null,"e":8176,"s":8097,"text":"The parent of a top-level tag like is the Beautifulsoup object itself −"},{"code":null,"e":8254,"s":8176,"text":">>> htmltag = soup.html\n>>> type(htmltag.parent)\n\n"},{"code":null,"e":8313,"s":8254,"text":"The .parent of a Beautifulsoup object is defined as None −"},{"code":null,"e":8342,"s":8313,"text":">>> print(soup.parent)\nNone\n"},{"code":null,"e":8408,"s":8342,"text":"To iterate over all the parents elements, use .parents attribute."},{"code":null,"e":8649,"s":8408,"text":">>> link = soup.a\n>>> link\nJava\n>>>\n>>> for parent in link.parents:\nif parent is None:\nprint(parent)\nelse:\nprint(parent.name)\np\nbody\nhtml\n[document]"},{"code":null,"e":8680,"s":8649,"text":"Below is one simple document −"},{"code":null,"e":9067,"s":8680,"text":">>> sibling_soup = BeautifulSoup(\"TutorialsPointThe Biggest Online Tutorials Library, It's all Free\")\n>>> print(sibling_soup.prettify())\n\n\n \n \n TutorialsPoint\n \n \n \n The Biggest Online Tutorials Library, It's all Free\n \n \n \n\n"},{"code":null,"e":9201,"s":9067,"text":"In the above doc, and tag is at the same level and they are both children of the same tag. Both and tag are siblings."},{"code":null,"e":9321,"s":9201,"text":"Use .next_sibling and .previous_sibling to navigate between page elements that are on the same level of the parse tree:"},{"code":null,"e":9491,"s":9321,"text":">>> sibling_soup.b.next_sibling\nThe Biggest Online Tutorials Library, It's all Free\n>>>\n>>> sibling_soup.c.previous_sibling\nTutorialsPoint"},{"code":null,"e":9646,"s":9491,"text":"The tag has a .next_sibling but no .previous_sibling, as there is nothing before the tag on the same level of the tree, same case is with tag."},{"code":null,"e":9739,"s":9646,"text":">>> print(sibling_soup.b.previous_sibling)\nNone\n>>> print(sibling_soup.c.next_sibling)\nNone\n"},{"code":null,"e":9809,"s":9739,"text":"The two strings are not siblings, as they don’t have the same parent."},{"code":null,"e":9907,"s":9809,"text":">>> sibling_soup.b.string\n'TutorialsPoint'\n>>>\n>>> print(sibling_soup.b.string.next_sibling)\nNone"},{"code":null,"e":9983,"s":9907,"text":"To iterate over a tag’s siblings use .next_siblings and .previous_siblings."},{"code":null,"e":10822,"s":9983,"text":">>> for sibling in soup.a.next_siblings:\nprint(repr(sibling))\n',\\n'\nC\n',\\n'\n>a class=\"prog\" href=\"https://www.tutorialspoint.com/python/index.htm\" id=\"link3\">Python\n',\\n'\nJavaScript\n' and\\n'\nC\n';\\n \\nas per online survey.'\n>>> for sibling in soup.find(id=\"link3\").previous_siblings:\nprint(repr(sibling))\n',\\n'\nC\n',\\n'\nJava\n'Top 5 most used Programming Languages are: \\n'"},{"code":null,"e":10898,"s":10822,"text":"Now let us get back to first two lines in our previous “html_doc” example −"},{"code":null,"e":11041,"s":10898,"text":"&t;html>Tutorials Point\n\n

The Biggest Online Tutorials Library, It's all Free

"},{"code":null,"e":11385,"s":11041,"text":"An HTML parser takes above string of characters and turns it into a series of events like “open an tag”, “open an tag”, “open the tag”, “add a string”, “close the tag”, “close the tag”, “open a

tag” and so on. BeautifulSoup offers different methods to reconstructs the initial parse of the document."},{"code":null,"e":11627,"s":11385,"text":"The .next_element attribute of a tag or string points to whatever was parsed immediately afterwards. Sometimes it looks similar to .next_sibling, however it is not same entirely.\nBelow is the final tag in our “html_doc” example document."},{"code":null,"e":11830,"s":11627,"text":">>> last_a_tag = soup.find(\"a\", id=\"link5\")\n>>> last_a_tag\nC\n>>> last_a_tag.next_sibling\n';\\n \\nas per online survey.'"},{"code":null,"e":11984,"s":11830,"text":"However the .next_element of that tag, the thing that was parsed immediately after the tag, is not the rest of that sentence: it is the word “C”:"},{"code":null,"e":12017,"s":11984,"text":">>> last_a_tag.next_element\n'C'\n"},{"code":null,"e":12335,"s":12017,"text":"Above behavior is because in the original markup, the letter “C” appeared before that semicolon. The parser encountered an tag, then the letter “C”, then the closing tag, then the semicolon and rest of the sentence. The semicolon is on the same level as the tag, but the letter “C” was encountered first."},{"code":null,"e":12477,"s":12335,"text":"The .previous_element attribute is the exact opposite of .next_element. It points to whatever element was parsed immediately before this one."},{"code":null,"e":12653,"s":12477,"text":">>> last_a_tag.previous_element\n' and\\n'\n>>>\n>>> last_a_tag.previous_element.next_element\nC"},{"code":null,"e":12720,"s":12653,"text":"We use these iterators to move forward and backward to an element."},{"code":null,"e":12898,"s":12720,"text":">>> for element in last_a_tag.next_e lements:\nprint(repr(element))\n'C'\n';\\n \\nas per online survey.'\n'\\n'\n

Programming Languages

\n'Programming Languages'\n'\\n'\n"},{"code":null,"e":12933,"s":12898,"text":"\n 38 Lectures \n 3.5 hours \n"},{"code":null,"e":12957,"s":12933,"text":" Chandramouli Jayendran"},{"code":null,"e":12990,"s":12957,"text":"\n 22 Lectures \n 1 hours \n"},{"code":null,"e":13006,"s":12990,"text":" TELCOMA Global"},{"code":null,"e":13038,"s":13006,"text":"\n 6 Lectures \n 1 hours \n"},{"code":null,"e":13055,"s":13038,"text":" AlexanderSchlee"},{"code":null,"e":13087,"s":13055,"text":"\n 6 Lectures \n 1 hours \n"},{"code":null,"e":13104,"s":13087,"text":" AlexanderSchlee"},{"code":null,"e":13136,"s":13104,"text":"\n 6 Lectures \n 1 hours \n"},{"code":null,"e":13153,"s":13136,"text":" AlexanderSchlee"},{"code":null,"e":13186,"s":13153,"text":"\n 22 Lectures \n 4 hours \n"},{"code":null,"e":13203,"s":13186,"text":" AlexanderSchlee"},{"code":null,"e":13210,"s":13203,"text":" Print"},{"code":null,"e":13221,"s":13210,"text":" Add Notes"}],"string":"[\n {\n \"code\": null,\n \"e\": 2045,\n \"s\": 1985,\n \"text\": \"In this chapter, we shall discuss about Navigating by Tags.\"\n },\n {\n \"code\": null,\n \"e\": 2074,\n \"s\": 2045,\n \"text\": \"Below is our html document −\"\n },\n {\n \"code\": null,\n \"e\": 2946,\n \"s\": 2074,\n \"text\": \">>> html_doc = \\\"\\\"\\\"\\nTutorials Point\\n\\n

The Biggest Online Tutorials Library, It's all Free

\\n

Top 5 most used Programming Languages are:\\nJava,\\nC,\\nPython,\\nJavaScript and\\nC;\\nas per online survey.

\\n

Programming Languages

\\n\\\"\\\"\\\"\\n>>>\\n>>> from bs4 import BeautifulSoup\\n>>> soup = BeautifulSoup(html_doc, 'html.parser')\\n>>>\"\n },\n {\n \"code\": null,\n \"e\": 3033,\n \"s\": 2946,\n \"text\": \"Based on the above document, we will try to move from one part of document to another.\"\n },\n {\n \"code\": null,\n \"e\": 3253,\n \"s\": 3033,\n \"text\": \"One of the important pieces of element in any piece of HTML document are tags, which may contain other tags/strings (tag’s children). Beautiful Soup provides different ways to navigate and iterate over’s tag’s children.\"\n },\n {\n \"code\": null,\n \"e\": 3366,\n \"s\": 3253,\n \"text\": \"Easiest way to search a parse tree is to search the tag by its name. If you want the tag, use soup.head −\"\n },\n {\n \"code\": null,\n \"e\": 3472,\n \"s\": 3366,\n \"text\": \">>> soup.head\\n&t;title>Tutorials Point\\n>>> soup.title\\nTutorials Point\"\n },\n {\n \"code\": null,\n \"e\": 3532,\n \"s\": 3472,\n \"text\": \"To get specific tag (like first tag) in the tag.\"\n },\n {\n \"code\": null,\n \"e\": 3607,\n \"s\": 3532,\n \"text\": \">>> soup.body.b\\nThe Biggest Online Tutorials Library, It's all Free\"\n },\n {\n \"code\": null,\n \"e\": 3688,\n \"s\": 3607,\n \"text\": \"Using a tag name as an attribute will give you only the first tag by that name −\"\n },\n {\n \"code\": null,\n \"e\": 3797,\n \"s\": 3688,\n \"text\": \">>> soup.a\\nJava\\n\"\n },\n {\n \"code\": null,\n \"e\": 3861,\n \"s\": 3797,\n \"text\": \"To get all the tag’s attribute, you can use find_all() method −\"\n },\n {\n \"code\": null,\n \"e\": 4888,\n \"s\": 3861,\n \"text\": \">>> soup.find_all(\\\"a\\\")\\n[Java, C, Python, JavaScript, C]>>> soup.find_all(\\\"a\\\")\\n[Java, C, Python, JavaScript, C]\"\n },\n {\n \"code\": null,\n \"e\": 4946,\n \"s\": 4888,\n \"text\": \"We can search tag’s children in a list by its .contents −\"\n },\n {\n \"code\": null,\n \"e\": 5270,\n \"s\": 4946,\n \"text\": \">>> head_tag = soup.head\\n>>> head_tag\\nTutorials Point\\n>>> Htag = soup.head\\n>>> Htag\\nTutorials Point\\n>>>\\n>>> Htag.contents\\n[Tutorials Point\\n>>>\\n>>> Ttag = head_tag.contents[0]\\n>>> Ttag\\nTutorials Point\\n>>> Ttag.contents\\n['Tutorials Point']\"\n },\n {\n \"code\": null,\n \"e\": 5388,\n \"s\": 5270,\n \"text\": \"The BeautifulSoup object itself has children. In this case, the tag is the child of the BeautifulSoup object −\"\n },\n {\n \"code\": null,\n \"e\": 5446,\n \"s\": 5388,\n \"text\": \">>> len(soup.contents)\\n2\\n>>> soup.contents[1].name\\n'html'\"\n },\n {\n \"code\": null,\n \"e\": 5516,\n \"s\": 5446,\n \"text\": \"A string does not have .contents, because it can’t contain anything −\"\n },\n {\n \"code\": null,\n \"e\": 5663,\n \"s\": 5516,\n \"text\": \">>> text = Ttag.contents[0]\\n>>> text.contents\\nself.__class__.__name__, attr))\\nAttributeError: 'NavigableString' object has no attribute 'contents'\"\n },\n {\n \"code\": null,\n \"e\": 5749,\n \"s\": 5663,\n \"text\": \"Instead of getting them as a list, use .children generator to access tag’s children −\"\n },\n {\n \"code\": null,\n \"e\": 5811,\n \"s\": 5749,\n \"text\": \">>> for child in Ttag.children:\\nprint(child)\\nTutorials Point\\n\"\n },\n {\n \"code\": null,\n \"e\": 5904,\n \"s\": 5811,\n \"text\": \"The .descendants attribute allows you to iterate over all of a tag’s children, recursively −\"\n },\n {\n \"code\": null,\n \"e\": 5976,\n \"s\": 5904,\n \"text\": \"its direct children and the children of its direct children and so on −\"\n },\n {\n \"code\": null,\n \"e\": 6072,\n \"s\": 5976,\n \"text\": \">>> for child in Htag.descendants:\\nprint(child)\\nTutorials Point\\nTutorials Point\\n\"\n },\n {\n \"code\": null,\n \"e\": 6289,\n \"s\": 6072,\n \"text\": \"The tag has only one child, but it has two descendants: the tag and the <title> tag’s child. The beautifulsoup object has only one direct child (the <html> tag), but it has a whole lot of descendants −\"\n },\n {\n \"code\": null,\n \"e\": 6356,\n \"s\": 6289,\n \"text\": \">>> len(list(soup.children))\\n2\\n>>> len(list(soup.descendants))\\n33\\n\"\n },\n {\n \"code\": null,\n \"e\": 6465,\n \"s\": 6356,\n \"text\": \"If the tag has only one child, and that child is a NavigableString, the child is made available as .string −\"\n },\n {\n \"code\": null,\n \"e\": 6500,\n \"s\": 6465,\n \"text\": \">>> Ttag.string\\n'Tutorials Point'\\n\"\n },\n {\n \"code\": null,\n \"e\": 6640,\n \"s\": 6500,\n \"text\": \"If a tag’s only child is another tag, and that tag has a .string, then the parent tag is considered to have the same .string as its child −\"\n },\n {\n \"code\": null,\n \"e\": 6729,\n \"s\": 6640,\n \"text\": \">>> Htag.contents\\n[<title>Tutorials Point]\\n>>>\\n>>> Htag.string\\n'Tutorials Point'\"\n },\n {\n \"code\": null,\n \"e\": 6859,\n \"s\": 6729,\n \"text\": \"However, if a tag contains more than one thing, then it’s not clear what .string should refer to, so .string is defined to None −\"\n },\n {\n \"code\": null,\n \"e\": 6893,\n \"s\": 6859,\n \"text\": \">>> print(soup.html.string)\\nNone\\n\"\n },\n {\n \"code\": null,\n \"e\": 7007,\n \"s\": 6893,\n \"text\": \"If there’s more than one thing inside a tag, you can still look at just the strings. Use the .strings generator −\"\n },\n {\n \"code\": null,\n \"e\": 7327,\n \"s\": 7007,\n \"text\": \">>> for string in soup.strings:\\nprint(repr(string))\\n'\\\\n'\\n'Tutorials Point'\\n'\\\\n'\\n'\\\\n'\\n\\\"The Biggest Online Tutorials Library, It's all Free\\\"\\n'\\\\n'\\n'Top 5 most used Programming Languages are: \\\\n'\\n'Java'\\n',\\\\n'\\n'C'\\n',\\\\n'\\n'Python'\\n',\\\\n'\\n'JavaScript'\\n' and\\\\n'\\n'C'\\n';\\\\n \\\\nas per online survey.'\\n'\\\\n'\\n'Programming Languages'\\n'\\\\n'\"\n },\n {\n \"code\": null,\n \"e\": 7389,\n \"s\": 7327,\n \"text\": \"To remove extra whitespace, use .stripped_strings generator −\"\n },\n {\n \"code\": null,\n \"e\": 7676,\n \"s\": 7389,\n \"text\": \">>> for string in soup.stripped_strings:\\nprint(repr(string))\\n'Tutorials Point'\\n\\\"The Biggest Online Tutorials Library, It's all Free\\\"\\n'Top 5 most used Programming Languages are:'\\n'Java'\\n','\\n'C'\\n','\\n'Python'\\n','\\n'JavaScript'\\n'and'\\n'C'\\n';\\\\n \\\\nas per online survey.'\\n'Programming Languages'\"\n },\n {\n \"code\": null,\n \"e\": 7770,\n \"s\": 7676,\n \"text\": \"In a “family tree” analogy, every tag and every string has a parent: the tag that contain it:\"\n },\n {\n \"code\": null,\n \"e\": 7833,\n \"s\": 7770,\n \"text\": \"To access the element’s parent element, use .parent attribute.\"\n },\n {\n \"code\": null,\n \"e\": 7954,\n \"s\": 7833,\n \"text\": \">>> Ttag = soup.title\\n>>> Ttag\\nTutorials Point\\n>>> Ttag.parent\\ntitle>Tutorials Point\"\n },\n {\n \"code\": null,\n \"e\": 8042,\n \"s\": 7954,\n \"text\": \"In our html_doc, the title string itself has a parent: the tag that contain it−\"\n },\n {\n \"code\": null,\n \"e\": 8097,\n \"s\": 8042,\n \"text\": \">>> Ttag.string.parent\\n<title>Tutorials Point\\n\"\n },\n {\n \"code\": null,\n \"e\": 8176,\n \"s\": 8097,\n \"text\": \"The parent of a top-level tag like is the Beautifulsoup object itself −\"\n },\n {\n \"code\": null,\n \"e\": 8254,\n \"s\": 8176,\n \"text\": \">>> htmltag = soup.html\\n>>> type(htmltag.parent)\\n\\n\"\n },\n {\n \"code\": null,\n \"e\": 8313,\n \"s\": 8254,\n \"text\": \"The .parent of a Beautifulsoup object is defined as None −\"\n },\n {\n \"code\": null,\n \"e\": 8342,\n \"s\": 8313,\n \"text\": \">>> print(soup.parent)\\nNone\\n\"\n },\n {\n \"code\": null,\n \"e\": 8408,\n \"s\": 8342,\n \"text\": \"To iterate over all the parents elements, use .parents attribute.\"\n },\n {\n \"code\": null,\n \"e\": 8649,\n \"s\": 8408,\n \"text\": \">>> link = soup.a\\n>>> link\\nJava\\n>>>\\n>>> for parent in link.parents:\\nif parent is None:\\nprint(parent)\\nelse:\\nprint(parent.name)\\np\\nbody\\nhtml\\n[document]\"\n },\n {\n \"code\": null,\n \"e\": 8680,\n \"s\": 8649,\n \"text\": \"Below is one simple document −\"\n },\n {\n \"code\": null,\n \"e\": 9067,\n \"s\": 8680,\n \"text\": \">>> sibling_soup = BeautifulSoup(\\\"TutorialsPointThe Biggest Online Tutorials Library, It's all Free\\\")\\n>>> print(sibling_soup.prettify())\\n\\n\\n \\n \\n TutorialsPoint\\n \\n \\n \\n The Biggest Online Tutorials Library, It's all Free\\n \\n \\n \\n\\n\"\n },\n {\n \"code\": null,\n \"e\": 9201,\n \"s\": 9067,\n \"text\": \"In the above doc, and tag is at the same level and they are both children of the same tag. Both and tag are siblings.\"\n },\n {\n \"code\": null,\n \"e\": 9321,\n \"s\": 9201,\n \"text\": \"Use .next_sibling and .previous_sibling to navigate between page elements that are on the same level of the parse tree:\"\n },\n {\n \"code\": null,\n \"e\": 9491,\n \"s\": 9321,\n \"text\": \">>> sibling_soup.b.next_sibling\\nThe Biggest Online Tutorials Library, It's all Free\\n>>>\\n>>> sibling_soup.c.previous_sibling\\nTutorialsPoint\"\n },\n {\n \"code\": null,\n \"e\": 9646,\n \"s\": 9491,\n \"text\": \"The tag has a .next_sibling but no .previous_sibling, as there is nothing before the tag on the same level of the tree, same case is with tag.\"\n },\n {\n \"code\": null,\n \"e\": 9739,\n \"s\": 9646,\n \"text\": \">>> print(sibling_soup.b.previous_sibling)\\nNone\\n>>> print(sibling_soup.c.next_sibling)\\nNone\\n\"\n },\n {\n \"code\": null,\n \"e\": 9809,\n \"s\": 9739,\n \"text\": \"The two strings are not siblings, as they don’t have the same parent.\"\n },\n {\n \"code\": null,\n \"e\": 9907,\n \"s\": 9809,\n \"text\": \">>> sibling_soup.b.string\\n'TutorialsPoint'\\n>>>\\n>>> print(sibling_soup.b.string.next_sibling)\\nNone\"\n },\n {\n \"code\": null,\n \"e\": 9983,\n \"s\": 9907,\n \"text\": \"To iterate over a tag’s siblings use .next_siblings and .previous_siblings.\"\n },\n {\n \"code\": null,\n \"e\": 10822,\n \"s\": 9983,\n \"text\": \">>> for sibling in soup.a.next_siblings:\\nprint(repr(sibling))\\n',\\\\n'\\nC\\n',\\\\n'\\n>a class=\\\"prog\\\" href=\\\"https://www.tutorialspoint.com/python/index.htm\\\" id=\\\"link3\\\">Python\\n',\\\\n'\\nJavaScript\\n' and\\\\n'\\nC\\n';\\\\n \\\\nas per online survey.'\\n>>> for sibling in soup.find(id=\\\"link3\\\").previous_siblings:\\nprint(repr(sibling))\\n',\\\\n'\\nC\\n',\\\\n'\\nJava\\n'Top 5 most used Programming Languages are: \\\\n'\"\n },\n {\n \"code\": null,\n \"e\": 10898,\n \"s\": 10822,\n \"text\": \"Now let us get back to first two lines in our previous “html_doc” example −\"\n },\n {\n \"code\": null,\n \"e\": 11041,\n \"s\": 10898,\n \"text\": \"&t;html>Tutorials Point\\n\\n

The Biggest Online Tutorials Library, It's all Free

\"\n },\n {\n \"code\": null,\n \"e\": 11385,\n \"s\": 11041,\n \"text\": \"An HTML parser takes above string of characters and turns it into a series of events like “open an tag”, “open an tag”, “open the tag”, “add a string”, “close the tag”, “close the tag”, “open a

tag” and so on. BeautifulSoup offers different methods to reconstructs the initial parse of the document.\"\n },\n {\n \"code\": null,\n \"e\": 11627,\n \"s\": 11385,\n \"text\": \"The .next_element attribute of a tag or string points to whatever was parsed immediately afterwards. Sometimes it looks similar to .next_sibling, however it is not same entirely.\\nBelow is the final tag in our “html_doc” example document.\"\n },\n {\n \"code\": null,\n \"e\": 11830,\n \"s\": 11627,\n \"text\": \">>> last_a_tag = soup.find(\\\"a\\\", id=\\\"link5\\\")\\n>>> last_a_tag\\nC\\n>>> last_a_tag.next_sibling\\n';\\\\n \\\\nas per online survey.'\"\n },\n {\n \"code\": null,\n \"e\": 11984,\n \"s\": 11830,\n \"text\": \"However the .next_element of that tag, the thing that was parsed immediately after the tag, is not the rest of that sentence: it is the word “C”:\"\n },\n {\n \"code\": null,\n \"e\": 12017,\n \"s\": 11984,\n \"text\": \">>> last_a_tag.next_element\\n'C'\\n\"\n },\n {\n \"code\": null,\n \"e\": 12335,\n \"s\": 12017,\n \"text\": \"Above behavior is because in the original markup, the letter “C” appeared before that semicolon. The parser encountered an tag, then the letter “C”, then the closing tag, then the semicolon and rest of the sentence. The semicolon is on the same level as the tag, but the letter “C” was encountered first.\"\n },\n {\n \"code\": null,\n \"e\": 12477,\n \"s\": 12335,\n \"text\": \"The .previous_element attribute is the exact opposite of .next_element. It points to whatever element was parsed immediately before this one.\"\n },\n {\n \"code\": null,\n \"e\": 12653,\n \"s\": 12477,\n \"text\": \">>> last_a_tag.previous_element\\n' and\\\\n'\\n>>>\\n>>> last_a_tag.previous_element.next_element\\nC\"\n },\n {\n \"code\": null,\n \"e\": 12720,\n \"s\": 12653,\n \"text\": \"We use these iterators to move forward and backward to an element.\"\n },\n {\n \"code\": null,\n \"e\": 12898,\n \"s\": 12720,\n \"text\": \">>> for element in last_a_tag.next_e lements:\\nprint(repr(element))\\n'C'\\n';\\\\n \\\\nas per online survey.'\\n'\\\\n'\\n

Programming Languages

\\n'Programming Languages'\\n'\\\\n'\\n\"\n },\n {\n \"code\": null,\n \"e\": 12933,\n \"s\": 12898,\n \"text\": \"\\n 38 Lectures \\n 3.5 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 12957,\n \"s\": 12933,\n \"text\": \" Chandramouli Jayendran\"\n },\n {\n \"code\": null,\n \"e\": 12990,\n \"s\": 12957,\n \"text\": \"\\n 22 Lectures \\n 1 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 13006,\n \"s\": 12990,\n \"text\": \" TELCOMA Global\"\n },\n {\n \"code\": null,\n \"e\": 13038,\n \"s\": 13006,\n \"text\": \"\\n 6 Lectures \\n 1 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 13055,\n \"s\": 13038,\n \"text\": \" AlexanderSchlee\"\n },\n {\n \"code\": null,\n \"e\": 13087,\n \"s\": 13055,\n \"text\": \"\\n 6 Lectures \\n 1 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 13104,\n \"s\": 13087,\n \"text\": \" AlexanderSchlee\"\n },\n {\n \"code\": null,\n \"e\": 13136,\n \"s\": 13104,\n \"text\": \"\\n 6 Lectures \\n 1 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 13153,\n \"s\": 13136,\n \"text\": \" AlexanderSchlee\"\n },\n {\n \"code\": null,\n \"e\": 13186,\n \"s\": 13153,\n \"text\": \"\\n 22 Lectures \\n 4 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 13203,\n \"s\": 13186,\n \"text\": \" AlexanderSchlee\"\n },\n {\n \"code\": null,\n \"e\": 13210,\n \"s\": 13203,\n \"text\": \" Print\"\n },\n {\n \"code\": null,\n \"e\": 13221,\n \"s\": 13210,\n \"text\": \" Add Notes\"\n }\n]"}}},{"rowIdx":132,"cells":{"title":{"kind":"string","value":"Static vs Dynamic Binding in Java"},"text":{"kind":"string","value":"In Java static binding refers to the execution of a program where type of object is determined/known at compile time i.e when compiler executes the code it know the type of object or class to which object belongs.While in case of dynamic binding the type of object is determined at runtime.\nAlso static binding uses type of class to bind while dynamic binding uses type of object as the resolution happens only at runtime because object only created during runtime due to which dynamic binding becomes slower than in case of static binding.\nAs private,final and static modifiers binds to the class level so methods and variables uses static binding and bonded by compiler while the other methods are bonded during runtime based upon runtime object.\nIn general we can say that overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding.\n Live Demo\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashSet;\npublic class StaticDynamicBinding {\n public static void main(String[] args) {\n Collection col = new HashSet<>();\n col.add(\"hello\");\n StaticDynamicBinding sdObj = new StaticDynamicBinding();\n sdObj.print(col);\n StaticDynamicBinding sdObj1 = new StaticDynamicBindingClass();\n sdObj1.print(col);\n }\n void print(Collection col) {\n System.out.println(\"in collection method\");\n }\n void print(HashSet hs) {\n System.out.println(\"in hashset method\");\n }\n}\nclass StaticDynamicBindingClass extends StaticDynamicBinding {\n void print(Collection col) {\n System.out.println(\"in collection method of child class\");\n }\n}\nin collection method\nin collection method of child class"},"parsed":{"kind":"list like","value":[{"code":null,"e":1353,"s":1062,"text":"In Java static binding refers to the execution of a program where type of object is determined/known at compile time i.e when compiler executes the code it know the type of object or class to which object belongs.While in case of dynamic binding the type of object is determined at runtime."},{"code":null,"e":1603,"s":1353,"text":"Also static binding uses type of class to bind while dynamic binding uses type of object as the resolution happens only at runtime because object only created during runtime due to which dynamic binding becomes slower than in case of static binding."},{"code":null,"e":1811,"s":1603,"text":"As private,final and static modifiers binds to the class level so methods and variables uses static binding and bonded by compiler while the other methods are bonded during runtime based upon runtime object."},{"code":null,"e":1948,"s":1811,"text":"In general we can say that overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding."},{"code":null,"e":1959,"s":1948,"text":" Live Demo"},{"code":null,"e":2742,"s":1959,"text":"import java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashSet;\npublic class StaticDynamicBinding {\n public static void main(String[] args) {\n Collection col = new HashSet<>();\n col.add(\"hello\");\n StaticDynamicBinding sdObj = new StaticDynamicBinding();\n sdObj.print(col);\n StaticDynamicBinding sdObj1 = new StaticDynamicBindingClass();\n sdObj1.print(col);\n }\n void print(Collection col) {\n System.out.println(\"in collection method\");\n }\n void print(HashSet hs) {\n System.out.println(\"in hashset method\");\n }\n}\nclass StaticDynamicBindingClass extends StaticDynamicBinding {\n void print(Collection col) {\n System.out.println(\"in collection method of child class\");\n }\n}"},{"code":null,"e":2800,"s":2742,"text":"in collection method\nin collection method of child class\n"}],"string":"[\n {\n \"code\": null,\n \"e\": 1353,\n \"s\": 1062,\n \"text\": \"In Java static binding refers to the execution of a program where type of object is determined/known at compile time i.e when compiler executes the code it know the type of object or class to which object belongs.While in case of dynamic binding the type of object is determined at runtime.\"\n },\n {\n \"code\": null,\n \"e\": 1603,\n \"s\": 1353,\n \"text\": \"Also static binding uses type of class to bind while dynamic binding uses type of object as the resolution happens only at runtime because object only created during runtime due to which dynamic binding becomes slower than in case of static binding.\"\n },\n {\n \"code\": null,\n \"e\": 1811,\n \"s\": 1603,\n \"text\": \"As private,final and static modifiers binds to the class level so methods and variables uses static binding and bonded by compiler while the other methods are bonded during runtime based upon runtime object.\"\n },\n {\n \"code\": null,\n \"e\": 1948,\n \"s\": 1811,\n \"text\": \"In general we can say that overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding.\"\n },\n {\n \"code\": null,\n \"e\": 1959,\n \"s\": 1948,\n \"text\": \" Live Demo\"\n },\n {\n \"code\": null,\n \"e\": 2742,\n \"s\": 1959,\n \"text\": \"import java.util.Collection;\\nimport java.util.Collections;\\nimport java.util.HashSet;\\npublic class StaticDynamicBinding {\\n public static void main(String[] args) {\\n Collection col = new HashSet<>();\\n col.add(\\\"hello\\\");\\n StaticDynamicBinding sdObj = new StaticDynamicBinding();\\n sdObj.print(col);\\n StaticDynamicBinding sdObj1 = new StaticDynamicBindingClass();\\n sdObj1.print(col);\\n }\\n void print(Collection col) {\\n System.out.println(\\\"in collection method\\\");\\n }\\n void print(HashSet hs) {\\n System.out.println(\\\"in hashset method\\\");\\n }\\n}\\nclass StaticDynamicBindingClass extends StaticDynamicBinding {\\n void print(Collection col) {\\n System.out.println(\\\"in collection method of child class\\\");\\n }\\n}\"\n },\n {\n \"code\": null,\n \"e\": 2800,\n \"s\": 2742,\n \"text\": \"in collection method\\nin collection method of child class\\n\"\n }\n]"}}},{"rowIdx":133,"cells":{"title":{"kind":"string","value":"DBMS - Quick Guide"},"text":{"kind":"string","value":"Database is a collection of related data and data is a collection of facts and figures that can be processed to produce information.\nMostly data represents recordable facts. Data aids in producing information, which is based on facts. For example, if we have data about marks obtained by all students, we can then conclude about toppers and average marks.\nA database management system stores data in such a way that it becomes easier to retrieve, manipulate, and produce information.\nTraditionally, data was organized in file formats. DBMS was a new concept then, and all the research was done to make it overcome the deficiencies in traditional style of data management. A modern DBMS has the following characteristics −\nReal-world entity − A modern DBMS is more realistic and uses real-world entities to design its architecture. It uses the behavior and attributes too. For example, a school database may use students as an entity and their age as an attribute.\nReal-world entity − A modern DBMS is more realistic and uses real-world entities to design its architecture. It uses the behavior and attributes too. For example, a school database may use students as an entity and their age as an attribute.\nRelation-based tables − DBMS allows entities and relations among them to form tables. A user can understand the architecture of a database just by looking at the table names.\nRelation-based tables − DBMS allows entities and relations among them to form tables. A user can understand the architecture of a database just by looking at the table names.\nIsolation of data and application − A database system is entirely different than its data. A database is an active entity, whereas data is said to be passive, on which the database works and organizes. DBMS also stores metadata, which is data about data, to ease its own process.\nIsolation of data and application − A database system is entirely different than its data. A database is an active entity, whereas data is said to be passive, on which the database works and organizes. DBMS also stores metadata, which is data about data, to ease its own process.\nLess redundancy − DBMS follows the rules of normalization, which splits a relation when any of its attributes is having redundancy in values. Normalization is a mathematically rich and scientific process that reduces data redundancy.\nLess redundancy − DBMS follows the rules of normalization, which splits a relation when any of its attributes is having redundancy in values. Normalization is a mathematically rich and scientific process that reduces data redundancy.\nConsistency − Consistency is a state where every relation in a database remains consistent. There exist methods and techniques, which can detect attempt of leaving database in inconsistent state. A DBMS can provide greater consistency as compared to earlier forms of data storing applications like file-processing systems.\nConsistency − Consistency is a state where every relation in a database remains consistent. There exist methods and techniques, which can detect attempt of leaving database in inconsistent state. A DBMS can provide greater consistency as compared to earlier forms of data storing applications like file-processing systems.\nQuery Language − DBMS is equipped with query language, which makes it more efficient to retrieve and manipulate data. A user can apply as many and as different filtering options as required to retrieve a set of data. Traditionally it was not possible where file-processing system was used.\nQuery Language − DBMS is equipped with query language, which makes it more efficient to retrieve and manipulate data. A user can apply as many and as different filtering options as required to retrieve a set of data. Traditionally it was not possible where file-processing system was used.\nACID Properties − DBMS follows the concepts of Atomicity, Consistency, Isolation, and Durability (normally shortened as ACID). These concepts are applied on transactions, which manipulate data in a database. ACID properties help the database stay healthy in multi-transactional environments and in case of failure.\nACID Properties − DBMS follows the concepts of Atomicity, Consistency, Isolation, and Durability (normally shortened as ACID). These concepts are applied on transactions, which manipulate data in a database. ACID properties help the database stay healthy in multi-transactional environments and in case of failure.\nMultiuser and Concurrent Access − DBMS supports multi-user environment and allows them to access and manipulate data in parallel. Though there are restrictions on transactions when users attempt to handle the same data item, but users are always unaware of them.\nMultiuser and Concurrent Access − DBMS supports multi-user environment and allows them to access and manipulate data in parallel. Though there are restrictions on transactions when users attempt to handle the same data item, but users are always unaware of them.\nMultiple views − DBMS offers multiple views for different users. A user who is in the Sales department will have a different view of database than a person working in the Production department. This feature enables the users to have a concentrate view of the database according to their requirements.\nMultiple views − DBMS offers multiple views for different users. A user who is in the Sales department will have a different view of database than a person working in the Production department. This feature enables the users to have a concentrate view of the database according to their requirements.\nSecurity − Features like multiple views offer security to some extent where users are unable to access data of other users and departments. DBMS offers methods to impose constraints while entering data into the database and retrieving the same at a later stage. DBMS offers many different levels of security features, which enables multiple users to have different views with different features. For example, a user in the Sales department cannot see the data that belongs to the Purchase department. Additionally, it can also be managed how much data of the Sales department should be displayed to the user. Since a DBMS is not saved on the disk as traditional file systems, it is very hard for miscreants to break the code.\nSecurity − Features like multiple views offer security to some extent where users are unable to access data of other users and departments. DBMS offers methods to impose constraints while entering data into the database and retrieving the same at a later stage. DBMS offers many different levels of security features, which enables multiple users to have different views with different features. For example, a user in the Sales department cannot see the data that belongs to the Purchase department. Additionally, it can also be managed how much data of the Sales department should be displayed to the user. Since a DBMS is not saved on the disk as traditional file systems, it is very hard for miscreants to break the code.\nA typical DBMS has users with different rights and permissions who use it for different purposes. Some users retrieve data and some back it up. The users of a DBMS can be broadly categorized as follows −\nAdministrators − Administrators maintain the DBMS and are responsible for administrating the database. They are responsible to look after its usage and by whom it should be used. They create access profiles for users and apply limitations to maintain isolation and force security. Administrators also look after DBMS resources like system license, required tools, and other software and hardware related maintenance.\nAdministrators − Administrators maintain the DBMS and are responsible for administrating the database. They are responsible to look after its usage and by whom it should be used. They create access profiles for users and apply limitations to maintain isolation and force security. Administrators also look after DBMS resources like system license, required tools, and other software and hardware related maintenance.\nDesigners − Designers are the group of people who actually work on the designing part of the database. They keep a close watch on what data should be kept and in what format. They identify and design the whole set of entities, relations, constraints, and views.\nDesigners − Designers are the group of people who actually work on the designing part of the database. They keep a close watch on what data should be kept and in what format. They identify and design the whole set of entities, relations, constraints, and views.\nEnd Users − End users are those who actually reap the benefits of having a DBMS. End users can range from simple viewers who pay attention to the logs or market rates to sophisticated users such as business analysts.\nEnd Users − End users are those who actually reap the benefits of having a DBMS. End users can range from simple viewers who pay attention to the logs or market rates to sophisticated users such as business analysts.\nThe design of a DBMS depends on its architecture. It can be centralized or decentralized or hierarchical. The architecture of a DBMS can be seen as either single tier or multi-tier. An n-tier architecture divides the whole system into related but independent n modules, which can be independently modified, altered, changed, or replaced.\nIn 1-tier architecture, the DBMS is the only entity where the user directly sits on the DBMS and uses it. Any changes done here will directly be done on the DBMS itself. It does not provide handy tools for end-users. Database designers and programmers normally prefer to use single-tier architecture.\nIf the architecture of DBMS is 2-tier, then it must have an application through which the DBMS can be accessed. Programmers use 2-tier architecture where they access the DBMS by means of an application. Here the application tier is entirely independent of the database in terms of operation, design, and programming.\nA 3-tier architecture separates its tiers from each other based on the complexity of the users and how they use the data present in the database. It is the most widely used architecture to design a DBMS.\nDatabase (Data) Tier − At this tier, the database resides along with its query processing languages. We also have the relations that define the data and their constraints at this level.\nDatabase (Data) Tier − At this tier, the database resides along with its query processing languages. We also have the relations that define the data and their constraints at this level.\nApplication (Middle) Tier − At this tier reside the application server and the programs that access the database. For a user, this application tier presents an abstracted view of the database. End-users are unaware of any existence of the database beyond the application. At the other end, the database tier is not aware of any other user beyond the application tier. Hence, the application layer sits in the middle and acts as a mediator between the end-user and the database.\nApplication (Middle) Tier − At this tier reside the application server and the programs that access the database. For a user, this application tier presents an abstracted view of the database. End-users are unaware of any existence of the database beyond the application. At the other end, the database tier is not aware of any other user beyond the application tier. Hence, the application layer sits in the middle and acts as a mediator between the end-user and the database.\nUser (Presentation) Tier − End-users operate on this tier and they know nothing about any existence of the database beyond this layer. At this layer, multiple views of the database can be provided by the application. All views are generated by applications that reside in the application tier.\nUser (Presentation) Tier − End-users operate on this tier and they know nothing about any existence of the database beyond this layer. At this layer, multiple views of the database can be provided by the application. All views are generated by applications that reside in the application tier.\nMultiple-tier database architecture is highly modifiable, as almost all its components are independent and can be changed independently.\nData models define how the logical structure of a database is modeled. Data Models are fundamental entities to introduce abstraction in a DBMS. Data models define how data is connected to each other and how they are processed and stored inside the system.\nThe very first data model could be flat data-models, where all the data used are to be kept in the same plane. Earlier data models were not so scientific, hence they were prone to introduce lots of duplication and update anomalies.\nEntity-Relationship (ER) Model is based on the notion of real-world entities and relationships among them. While formulating real-world scenario into the database model, the ER Model creates entity set, relationship set, general attributes and constraints.\nER Model is best used for the conceptual design of a database.\nER Model is based on −\nEntities and their attributes.\nEntities and their attributes.\nRelationships among entities.\nRelationships among entities.\nThese concepts are explained below.\nEntity − An entity in an ER Model is a real-world entity having properties called attributes. Every attribute is defined by its set of values called domain. For example, in a school database, a student is considered as an entity. Student has various attributes like name, age, class, etc.\nEntity − An entity in an ER Model is a real-world entity having properties called attributes. Every attribute is defined by its set of values called domain. For example, in a school database, a student is considered as an entity. Student has various attributes like name, age, class, etc.\nRelationship − The logical association among entities is called relationship. Relationships are mapped with entities in various ways. Mapping cardinalities define the number of association between two entities.\nMapping cardinalities −\n\none to one\none to many\nmany to one\nmany to many\n\n\nRelationship − The logical association among entities is called relationship. Relationships are mapped with entities in various ways. Mapping cardinalities define the number of association between two entities.\nMapping cardinalities −\none to one\none to many\nmany to one\nmany to many\nThe most popular data model in DBMS is the Relational Model. It is more scientific a model than others. This model is based on first-order predicate logic and defines a table as an n-ary relation.\nThe main highlights of this model are −\nData is stored in tables called relations.\nRelations can be normalized.\nIn normalized relations, values saved are atomic values.\nEach row in a relation contains a unique value.\nEach column in a relation contains values from a same domain.\nA database schema is the skeleton structure that represents the logical view of the entire database. It defines how the data is organized and how the relations among them are associated. It formulates all the constraints that are to be applied on the data.\nA database schema defines its entities and the relationship among them. It contains a descriptive detail of the database, which can be depicted by means of schema diagrams. It’s the database designers who design the schema to help programmers understand the database and make it useful.\nA database schema can be divided broadly into two categories −\nPhysical Database Schema − This schema pertains to the actual storage of data and its form of storage like files, indices, etc. It defines how the data will be stored in a secondary storage.\nPhysical Database Schema − This schema pertains to the actual storage of data and its form of storage like files, indices, etc. It defines how the data will be stored in a secondary storage.\nLogical Database Schema − This schema defines all the logical constraints that need to be applied on the data stored. It defines tables, views, and integrity constraints.\nLogical Database Schema − This schema defines all the logical constraints that need to be applied on the data stored. It defines tables, views, and integrity constraints.\nIt is important that we distinguish these two terms individually. Database schema is the skeleton of database. It is designed when the database doesn't exist at all. Once the database is operational, it is very difficult to make any changes to it. A database schema does not contain any data or information.\nA database instance is a state of operational database with data at any given time. It contains a snapshot of the database. Database instances tend to change with time. A DBMS ensures that its every instance (state) is in a valid state, by diligently following all the validations, constraints, and conditions that the database designers have imposed.\nIf a database system is not multi-layered, then it becomes difficult to make any changes in the database system. Database systems are designed in multi-layers as we learnt earlier.\nA database system normally contains a lot of data in addition to users’ data. For example, it stores data about data, known as metadata, to locate and retrieve data easily. It is rather difficult to modify or update a set of metadata once it is stored in the database. But as a DBMS expands, it needs to change over time to satisfy the requirements of the users. If the entire data is dependent, it would become a tedious and highly complex job.\nMetadata itself follows a layered architecture, so that when we change data at one layer, it does not affect the data at another level. This data is independent but mapped to each other.\nLogical data is data about database, that is, it stores information about how data is managed inside. For example, a table (relation) stored in the database and all its constraints, applied on that relation.\nLogical data independence is a kind of mechanism, which liberalizes itself from actual data stored on the disk. If we do some changes on table format, it should not change the data residing on the disk.\nAll the schemas are logical, and the actual data is stored in bit format on the disk. Physical data independence is the power to change the physical data without impacting the schema or logical data.\nFor example, in case we want to change or upgrade the storage system itself − suppose we want to replace hard-disks with SSD − it should not have any impact on the logical data or schemas.\nThe ER model defines the conceptual view of a database. It works around real-world entities and the associations among them. At view level, the ER model is considered a good option for designing databases.\nAn entity can be a real-world object, either animate or inanimate, that can be easily identifiable. For example, in a school database, students, teachers, classes, and courses offered can be considered as entities. All these entities have some attributes or properties that give them their identity.\nAn entity set is a collection of similar types of entities. An entity set may contain entities with attribute sharing similar values. For example, a Students set may contain all the students of a school; likewise a Teachers set may contain all the teachers of a school from all faculties. Entity sets need not be disjoint.\nEntities are represented by means of their properties, called attributes. All attributes have values. For example, a student entity may have name, class, and age as attributes.\nThere exists a domain or range of values that can be assigned to attributes. For example, a student's name cannot be a numeric value. It has to be alphabetic. A student's age cannot be negative, etc.\nSimple attribute − Simple attributes are atomic values, which cannot be divided further. For example, a student's phone number is an atomic value of 10 digits.\nSimple attribute − Simple attributes are atomic values, which cannot be divided further. For example, a student's phone number is an atomic value of 10 digits.\nComposite attribute − Composite attributes are made of more than one simple attribute. For example, a student's complete name may have first_name and last_name.\nComposite attribute − Composite attributes are made of more than one simple attribute. For example, a student's complete name may have first_name and last_name.\nDerived attribute − Derived attributes are the attributes that do not exist in the physical database, but their values are derived from other attributes present in the database. For example, average_salary in a department should not be saved directly in the database, instead it can be derived. For another example, age can be derived from data_of_birth.\nDerived attribute − Derived attributes are the attributes that do not exist in the physical database, but their values are derived from other attributes present in the database. For example, average_salary in a department should not be saved directly in the database, instead it can be derived. For another example, age can be derived from data_of_birth.\nSingle-value attribute − Single-value attributes contain single value. For example − Social_Security_Number.\nSingle-value attribute − Single-value attributes contain single value. For example − Social_Security_Number.\nMulti-value attribute − Multi-value attributes may contain more than one values. For example, a person can have more than one phone number, email_address, etc.\nMulti-value attribute − Multi-value attributes may contain more than one values. For example, a person can have more than one phone number, email_address, etc.\nThese attribute types can come together in a way like −\nsimple single-valued attributes\nsimple multi-valued attributes\ncomposite single-valued attributes\ncomposite multi-valued attributes\nKey is an attribute or collection of attributes that uniquely identifies an entity among entity set.\nFor example, the roll_number of a student makes him/her identifiable among students.\nSuper Key − A set of attributes (one or more) that collectively identifies an entity in an entity set.\nSuper Key − A set of attributes (one or more) that collectively identifies an entity in an entity set.\nCandidate Key − A minimal super key is called a candidate key. An entity set may have more than one candidate key.\nCandidate Key − A minimal super key is called a candidate key. An entity set may have more than one candidate key.\nPrimary Key − A primary key is one of the candidate keys chosen by the database designer to uniquely identify the entity set.\nPrimary Key − A primary key is one of the candidate keys chosen by the database designer to uniquely identify the entity set.\nThe association among entities is called a relationship. For example, an employee works_at a department, a student enrolls in a course. Here, Works_at and Enrolls are called relationships.\nA set of relationships of similar type is called a relationship set. Like entities, a relationship too can have attributes. These attributes are called descriptive attributes.\nThe number of participating entities in a relationship defines the degree of the relationship.\nBinary = degree 2\nTernary = degree 3\nn-ary = degree\nCardinality defines the number of entities in one entity set, which can be associated with the number of entities of other set via relationship set.\nOne-to-one − One entity from entity set A can be associated with at most one entity of entity set B and vice versa.\nOne-to-one − One entity from entity set A can be associated with at most one entity of entity set B and vice versa.\nOne-to-many − One entity from entity set A can be associated with more than one entities of entity set B however an entity from entity set B, can be associated with at most one entity.\nOne-to-many − One entity from entity set A can be associated with more than one entities of entity set B however an entity from entity set B, can be associated with at most one entity.\nMany-to-one − More than one entities from entity set A can be associated with at most one entity of entity set B, however an entity from entity set B can be associated with more than one entity from entity set A.\nMany-to-one − More than one entities from entity set A can be associated with at most one entity of entity set B, however an entity from entity set B can be associated with more than one entity from entity set A.\nMany-to-many − One entity from A can be associated with more than one entity from B and vice versa.\nMany-to-many − One entity from A can be associated with more than one entity from B and vice versa.\nLet us now learn how the ER Model is represented by means of an ER diagram. Any object, for example, entities, attributes of an entity, relationship sets, and attributes of relationship sets, can be represented with the help of an ER diagram.\nEntities are represented by means of rectangles. Rectangles are named with the entity set they represent.\nAttributes are the properties of entities. Attributes are represented by means of ellipses. Every ellipse represents one attribute and is directly connected to its entity (rectangle).\nIf the attributes are composite, they are further divided in a tree like structure. Every node is then connected to its attribute. That is, composite attributes are represented by ellipses that are connected with an ellipse.\nMultivalued attributes are depicted by double ellipse.\nDerived attributes are depicted by dashed ellipse.\nRelationships are represented by diamond-shaped box. Name of the relationship is written inside the diamond-box. All the entities (rectangles) participating in a relationship, are connected to it by a line.\nA relationship where two entities are participating is called a binary relationship. Cardinality is the number of instance of an entity from a relation that can be associated with the relation.\nOne-to-one − When only one instance of an entity is associated with the relationship, it is marked as '1:1'. The following image reflects that only one instance of each entity should be associated with the relationship. It depicts one-to-one relationship.\nOne-to-one − When only one instance of an entity is associated with the relationship, it is marked as '1:1'. The following image reflects that only one instance of each entity should be associated with the relationship. It depicts one-to-one relationship.\nOne-to-many − When more than one instance of an entity is associated with a relationship, it is marked as '1:N'. The following image reflects that only one instance of entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts one-to-many relationship.\nOne-to-many − When more than one instance of an entity is associated with a relationship, it is marked as '1:N'. The following image reflects that only one instance of entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts one-to-many relationship.\nMany-to-one − When more than one instance of entity is associated with the relationship, it is marked as 'N:1'. The following image reflects that more than one instance of an entity on the left and only one instance of an entity on the right can be associated with the relationship. It depicts many-to-one relationship.\nMany-to-one − When more than one instance of entity is associated with the relationship, it is marked as 'N:1'. The following image reflects that more than one instance of an entity on the left and only one instance of an entity on the right can be associated with the relationship. It depicts many-to-one relationship.\nMany-to-many − The following image reflects that more than one instance of an entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts many-to-many relationship.\nMany-to-many − The following image reflects that more than one instance of an entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts many-to-many relationship.\nTotal Participation − Each entity is involved in the relationship. Total participation is represented by double lines.\nTotal Participation − Each entity is involved in the relationship. Total participation is represented by double lines.\nPartial participation − Not all entities are involved in the relationship. Partial participation is represented by single lines.\nPartial participation − Not all entities are involved in the relationship. Partial participation is represented by single lines.\nLet us now learn how the ER Model is represented by means of an ER diagram. Any object, for example, entities, attributes of an entity, relationship sets, and attributes of relationship sets, can be represented with the help of an ER diagram.\nEntities are represented by means of rectangles. Rectangles are named with the entity set they represent.\nAttributes are the properties of entities. Attributes are represented by means of ellipses. Every ellipse represents one attribute and is directly connected to its entity (rectangle).\nIf the attributes are composite, they are further divided in a tree like structure. Every node is then connected to its attribute. That is, composite attributes are represented by ellipses that are connected with an ellipse.\nMultivalued attributes are depicted by double ellipse.\nDerived attributes are depicted by dashed ellipse.\nRelationships are represented by diamond-shaped box. Name of the relationship is written inside the diamond-box. All the entities (rectangles) participating in a relationship, are connected to it by a line.\nA relationship where two entities are participating is called a binary relationship. Cardinality is the number of instance of an entity from a relation that can be associated with the relation.\nOne-to-one − When only one instance of an entity is associated with the relationship, it is marked as '1:1'. The following image reflects that only one instance of each entity should be associated with the relationship. It depicts one-to-one relationship.\nOne-to-one − When only one instance of an entity is associated with the relationship, it is marked as '1:1'. The following image reflects that only one instance of each entity should be associated with the relationship. It depicts one-to-one relationship.\nOne-to-many − When more than one instance of an entity is associated with a relationship, it is marked as '1:N'. The following image reflects that only one instance of entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts one-to-many relationship.\nOne-to-many − When more than one instance of an entity is associated with a relationship, it is marked as '1:N'. The following image reflects that only one instance of entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts one-to-many relationship.\nMany-to-one − When more than one instance of entity is associated with the relationship, it is marked as 'N:1'. The following image reflects that more than one instance of an entity on the left and only one instance of an entity on the right can be associated with the relationship. It depicts many-to-one relationship.\nMany-to-one − When more than one instance of entity is associated with the relationship, it is marked as 'N:1'. The following image reflects that more than one instance of an entity on the left and only one instance of an entity on the right can be associated with the relationship. It depicts many-to-one relationship.\nMany-to-many − The following image reflects that more than one instance of an entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts many-to-many relationship.\nMany-to-many − The following image reflects that more than one instance of an entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts many-to-many relationship.\nTotal Participation − Each entity is involved in the relationship. Total participation is represented by double lines.\nTotal Participation − Each entity is involved in the relationship. Total participation is represented by double lines.\nPartial participation − Not all entities are involved in the relationship. Partial participation is represented by single lines.\nPartial participation − Not all entities are involved in the relationship. Partial participation is represented by single lines.\nThe ER Model has the power of expressing database entities in a conceptual hierarchical manner. As the hierarchy goes up, it generalizes the view of entities, and as we go deep in the hierarchy, it gives us the detail of every entity included.\nGoing up in this structure is called generalization, where entities are clubbed together to represent a more generalized view. For example, a particular student named Mira can be generalized along with all the students. The entity shall be a student, and further, the student is a person. The reverse is called specialization where a person is a student, and that student is Mira.\nAs mentioned above, the process of generalizing entities, where the generalized entities contain the properties of all the generalized entities, is called generalization. In generalization, a number of entities are brought together into one generalized entity based on their similar characteristics. For example, pigeon, house sparrow, crow and dove can all be generalized as Birds.\nSpecialization is the opposite of generalization. In specialization, a group of entities is divided into sub-groups based on their characteristics. Take a group ‘Person’ for example. A person has name, date of birth, gender, etc. These properties are common in all persons, human beings. But in a company, persons can be identified as employee, employer, customer, or vendor, based on what role they play in the company.\nSimilarly, in a school database, persons can be specialized as teacher, student, or a staff, based on what role they play in school as entities.\nWe use all the above features of ER-Model in order to create classes of objects in object-oriented programming. The details of entities are generally hidden from the user; this process known as abstraction.\nInheritance is an important feature of Generalization and Specialization. It allows lower-level entities to inherit the attributes of higher-level entities.\nFor example, the attributes of a Person class such as name, age, and gender can be inherited by lower-level entities such as Student or Teacher.\nDr Edgar F. Codd, after his extensive research on the Relational Model of database systems, came up with twelve rules of his own, which according to him, a database must obey in order to be regarded as a true relational database.\nThese rules can be applied on any database system that manages stored data using only its relational capabilities. This is a foundation rule, which acts as a base for all the other rules.\nThe data stored in a database, may it be user data or metadata, must be a value of some table cell. Everything in a database must be stored in a table format.\nEvery single data element (value) is guaranteed to be accessible logically with a combination of table-name, primary-key (row value), and attribute-name (column value). No other means, such as pointers, can be used to access data.\nThe NULL values in a database must be given a systematic and uniform treatment. This is a very important rule because a NULL can be interpreted as one the following − data is missing, data is not known, or data is not applicable.\nThe structure description of the entire database must be stored in an online catalog, known as data dictionary, which can be accessed by authorized users. Users can use the same query language to access the catalog which they use to access the database itself.\nA database can only be accessed using a language having linear syntax that supports data definition, data manipulation, and transaction management operations. This language can be used directly or by means of some application. If the database allows access to data without any help of this language, then it is considered as a violation.\nAll the views of a database, which can theoretically be updated, must also be updatable by the system.\nA database must support high-level insertion, updation, and deletion. This must not be limited to a single row, that is, it must also support union, intersection and minus operations to yield sets of data records.\nThe data stored in a database must be independent of the applications that access the database. Any change in the physical structure of a database must not have any impact on how the data is being accessed by external applications.\nThe logical data in a database must be independent of its user’s view (application). Any change in logical data must not affect the applications using it. For example, if two tables are merged or one is split into two different tables, there should be no impact or change on the user application. This is one of the most difficult rule to apply.\nA database must be independent of the application that uses it. All its integrity constraints can be independently modified without the need of any change in the application. This rule makes a database independent of the front-end application and its interface.\nThe end-user must not be able to see that the data is distributed over various locations. Users should always get the impression that the data is located at one site only. This rule has been regarded as the foundation of distributed database systems.\nIf a system has an interface that provides access to low-level records, then the interface must not be able to subvert the system and bypass security and integrity constraints.\nRelational data model is the primary data model, which is used widely around the world for data storage and processing. This model is simple and it has all the properties and capabilities required to process data with storage efficiency.\nTables − In relational data model, relations are saved in the format of Tables. This format stores the relation among entities. A table has rows and columns, where rows represents records and columns represent the attributes.\nTuple − A single row of a table, which contains a single record for that relation is called a tuple.\nRelation instance − A finite set of tuples in the relational database system represents relation instance. Relation instances do not have duplicate tuples.\nRelation schema − A relation schema describes the relation name (table name), attributes, and their names.\nRelation key − Each row has one or more attributes, known as relation key, which can identify the row in the relation (table) uniquely.\nAttribute domain − Every attribute has some pre-defined value scope, known as attribute domain.\nEvery relation has some conditions that must hold for it to be a valid relation. These conditions are called Relational Integrity Constraints. There are three main integrity constraints −\nKey constraints\nDomain constraints\nReferential integrity constraints\nThere must be at least one minimal subset of attributes in the relation, which can identify a tuple uniquely. This minimal subset of attributes is called key for that relation. If there are more than one such minimal subsets, these are called candidate keys.\nKey constraints force that −\nin a relation with a key attribute, no two tuples can have identical values for key attributes.\nin a relation with a key attribute, no two tuples can have identical values for key attributes.\na key attribute can not have NULL values.\na key attribute can not have NULL values.\nKey constraints are also referred to as Entity Constraints.\nAttributes have specific values in real-world scenario. For example, age can only be a positive integer. The same constraints have been tried to employ on the attributes of a relation. Every attribute is bound to have a specific range of values. For example, age cannot be less than zero and telephone numbers cannot contain a digit outside 0-9.\nReferential integrity constraints work on the concept of Foreign Keys. A foreign key is a key attribute of a relation that can be referred in other relation.\nReferential integrity constraint states that if a relation refers to a key attribute of a different or same relation, then that key element must exist.\nRelational database systems are expected to be equipped with a query language that can assist its users to query the database instances. There are two kinds of query languages − relational algebra and relational calculus.\nRelational algebra is a procedural query language, which takes instances of relations as input and yields instances of relations as output. It uses operators to perform queries. An operator can be either unary or binary. They accept relations as their input and yield relations as their output. Relational algebra is performed recursively on a relation and intermediate results are also considered relations.\nThe fundamental operations of relational algebra are as follows −\nSelect\nProject\nUnion\nSet different\nCartesian product\nRename\nWe will discuss all these operations in the following sections.\nIt selects tuples that satisfy the given predicate from a relation.\nNotation − σp(r)\nWhere σ stands for selection predicate and r stands for relation. p is prepositional logic formula which may use connectors like and, or, and not. These terms may use relational operators like − =, ≠, ≥, < , >, ≤.\nFor example −\nσsubject=\"database\"(Books)\n\nσsubject=\"database\"(Books)\nOutput − Selects tuples from books where subject is 'database'.\nσsubject=\"database\" and price=\"450\"(Books)\n\nσsubject=\"database\" and price=\"450\"(Books)\nOutput − Selects tuples from books where subject is 'database' and 'price' is 450.\nσsubject=\"database\" and price < \"450\" or year > \"2010\"(Books)\n\nσsubject=\"database\" and price < \"450\" or year > \"2010\"(Books)\nOutput − Selects tuples from books where subject is 'database' and 'price' is 450 or those books published after 2010.\nIt projects column(s) that satisfy a given predicate.\nNotation − ∏A1, A2, An (r)\nWhere A1, A2 , An are attribute names of relation r.\nDuplicate rows are automatically eliminated, as relation is a set.\nFor example −\n ∏subject, author (Books)\n\n ∏subject, author (Books)\nSelects and projects columns named as subject and author from the relation Books.\nIt performs binary union between two given relations and is defined as −\n r ∪ s = { t | t ∈ r or t ∈ s} \n\n r ∪ s = { t | t ∈ r or t ∈ s} \nNotation − r U s \nWhere r and s are either database relations or relation result set (temporary relation).\nFor a union operation to be valid, the following conditions must hold −\nr, and s must have the same number of attributes.\nAttribute domains must be compatible.\nDuplicate tuples are automatically eliminated.\n ∏ author (Books) ∪ ∏ author (Articles)\n\n ∏ author (Books) ∪ ∏ author (Articles)\nOutput − Projects the names of the authors who have either written a book or an article or both.\nThe result of set difference operation is tuples, which are present in one relation but are not in the second relation.\nNotation − r − s\nFinds all the tuples that are present in r but not in s.\n ∏ author (Books) − ∏ author (Articles)\n\n ∏ author (Books) − ∏ author (Articles)\nOutput − Provides the name of authors who have written books but not articles.\nCombines information of two different relations into one. \nNotation − r Χ s\nWhere r and s are relations and their output will be defined as −\nr Χ s = { q t | q ∈ r and t ∈ s}\n ∏ author = 'tutorialspoint'(Books Χ Articles) \n\n ∏ author = 'tutorialspoint'(Books Χ Articles) \nOutput − Yields a relation, which shows all the books and articles written by tutorialspoint.\nThe results of relational algebra are also relations but without any name. The rename operation allows us to rename the output relation. 'rename' operation is denoted with small Greek letter rho ρ.\nNotation − ρ x (E)\nWhere the result of expression E is saved with name of x.\nAdditional operations are −\nSet intersection\nAssignment\nNatural join\nIn contrast to Relational Algebra, Relational Calculus is a non-procedural query language, that is, it tells what to do but never explains how to do it.\nRelational calculus exists in two forms −\nFiltering variable ranges over tuples\nNotation − {T | Condition} \nReturns all tuples T that satisfies a condition.\nFor example −\n{ T.name | Author(T) AND T.article = 'database' }\n\nOutput − Returns tuples with 'name' from Author who has written article on 'database'.\nTRC can be quantified. We can use Existential (∃) and Universal Quantifiers (∀).\nFor example −\n{ R| ∃T ∈ Authors(T.article='database' AND R.name=T.name)}\n\nOutput − The above query will yield the same result as the previous one.\nIn DRC, the filtering variable uses the domain of attributes instead of entire tuple values (as done in TRC, mentioned above).\nNotation −\n{ a1, a2, a3, ..., an | P (a1, a2, a3, ... ,an)}\nWhere a1, a2 are attributes and P stands for formulae built by inner attributes.\nFor example −\n{< article, page, subject > | ∈ TutorialsPoint ∧ subject = 'database'}\n\n{< article, page, subject > | ∈ TutorialsPoint ∧ subject = 'database'}\nOutput − Yields Article, Page, and Subject from the relation TutorialsPoint, where subject is database.\nJust like TRC, DRC can also be written using existential and universal quantifiers. DRC also involves relational operators.\nThe expression power of Tuple Relation Calculus and Domain Relation Calculus is equivalent to Relational Algebra.\nER Model, when conceptualized into diagrams, gives a good overview of entity-relationship, which is easier to understand. ER diagrams can be mapped to relational schema, that is, it is possible to create relational schema using ER diagram. We cannot import all the ER constraints into relational model, but an approximate schema can be generated.\nThere are several processes and algorithms available to convert ER Diagrams into Relational Schema. Some of them are automated and some of them are manual. We may focus here on the mapping diagram contents to relational basics.\nER diagrams mainly comprise of −\nEntity and its attributes\nRelationship, which is association among entities.\nAn entity is a real-world object with some attributes.\nCreate table for each entity.\nEntity's attributes should become fields of tables with their respective data types.\nDeclare primary key.\nA relationship is an association among entities.\nCreate table for a relationship.\nAdd the primary keys of all participating Entities as fields of table with their respective data types.\nIf relationship has any attribute, add each attribute as field of table.\nDeclare a primary key composing all the primary keys of participating entities.\nDeclare all foreign key constraints.\nA weak entity set is one which does not have any primary key associated with it.\nCreate table for weak entity set.\nAdd all its attributes to table as field.\nAdd the primary key of identifying entity set.\nDeclare all foreign key constraints.\nER specialization or generalization comes in the form of hierarchical entity sets.\nCreate tables for all higher-level entities.\nCreate tables for all higher-level entities.\nCreate tables for lower-level entities.\nCreate tables for lower-level entities.\nAdd primary keys of higher-level entities in the table of lower-level entities.\nAdd primary keys of higher-level entities in the table of lower-level entities.\nIn lower-level tables, add all other attributes of lower-level entities.\nIn lower-level tables, add all other attributes of lower-level entities.\nDeclare primary key of higher-level table and the primary key for lower-level table.\nDeclare primary key of higher-level table and the primary key for lower-level table.\nDeclare foreign key constraints.\nDeclare foreign key constraints.\nSQL is a programming language for Relational Databases. It is designed over relational algebra and tuple relational calculus. SQL comes as a package with all major distributions of RDBMS.\nSQL comprises both data definition and data manipulation languages. Using the data definition properties of SQL, one can design and modify database schema, whereas data manipulation properties allows SQL to store and retrieve data from database.\nSQL uses the following set of commands to define database schema −\nCreates new databases, tables and views from RDBMS.\nFor example −\nCreate database tutorialspoint;\nCreate table article;\nCreate view for_students;\n\nDrops commands, views, tables, and databases from RDBMS.\nFor example−\nDrop object_type object_name;\nDrop database tutorialspoint;\nDrop table article;\nDrop view for_students;\n\nModifies database schema.\nAlter object_type object_name parameters;\n\nFor example−\nAlter table article add subject varchar;\n\nThis command adds an attribute in the relation article with the name subject of string type.\nSQL is equipped with data manipulation language (DML). DML modifies the database instance by inserting, updating and deleting its data. DML is responsible for all forms data modification in a database. SQL contains the following set of commands in its DML section −\nSELECT/FROM/WHERE\nINSERT INTO/VALUES\nUPDATE/SET/WHERE\nDELETE FROM/WHERE\nThese basic constructs allow database programmers and users to enter data and information into the database and retrieve efficiently using a number of filter options.\nSELECT − This is one of the fundamental query command of SQL. It is similar to the projection operation of relational algebra. It selects the attributes based on the condition described by WHERE clause.\nSELECT − This is one of the fundamental query command of SQL. It is similar to the projection operation of relational algebra. It selects the attributes based on the condition described by WHERE clause.\nFROM − This clause takes a relation name as an argument from which attributes are to be selected/projected. In case more than one relation names are given, this clause corresponds to Cartesian product.\nFROM − This clause takes a relation name as an argument from which attributes are to be selected/projected. In case more than one relation names are given, this clause corresponds to Cartesian product.\nWHERE − This clause defines predicate or conditions, which must match in order to qualify the attributes to be projected.\nWHERE − This clause defines predicate or conditions, which must match in order to qualify the attributes to be projected.\nFor example −\nSelect author_name\nFrom book_author\nWhere age > 50;\n\nThis command will yield the names of authors from the relation book_author whose age is greater than 50.\nThis command is used for inserting values into the rows of a table (relation).\nSyntax−\nINSERT INTO table (column1 [, column2, column3 ... ]) VALUES (value1 [, value2, value3 ... ])\n\nOr\nINSERT INTO table VALUES (value1, [value2, ... ])\n\nFor example −\nINSERT INTO tutorialspoint (Author, Subject) VALUES (\"anonymous\", \"computers\");\n\nThis command is used for updating or modifying the values of columns in a table (relation).\nSyntax −\nUPDATE table_name SET column_name = value [, column_name = value ...] [WHERE condition]\n\nFor example −\nUPDATE tutorialspoint SET Author=\"webmaster\" WHERE Author=\"anonymous\";\n\nThis command is used for removing one or more rows from a table (relation).\nSyntax −\nDELETE FROM table_name [WHERE condition];\n\nFor example −\nDELETE FROM tutorialspoints\n WHERE Author=\"unknown\";\n\nFunctional dependency (FD) is a set of constraints between two attributes in a relation. Functional dependency says that if two tuples have same values for attributes A1, A2,..., An, then those two tuples must have to have same values for attributes B1, B2, ..., Bn.\nFunctional dependency is represented by an arrow sign (→) that is, X→Y, where X functionally determines Y. The left-hand side attributes determine the values of attributes on the right-hand side.\nIf F is a set of functional dependencies then the closure of F, denoted as F+, is the set of all functional dependencies logically implied by F. Armstrong's Axioms are a set of rules, that when applied repeatedly, generates a closure of functional dependencies.\nReflexive rule − If alpha is a set of attributes and beta is_subset_of alpha, then alpha holds beta.\nReflexive rule − If alpha is a set of attributes and beta is_subset_of alpha, then alpha holds beta.\nAugmentation rule − If a → b holds and y is attribute set, then ay → by also holds. That is adding attributes in dependencies, does not change the basic dependencies.\nAugmentation rule − If a → b holds and y is attribute set, then ay → by also holds. That is adding attributes in dependencies, does not change the basic dependencies.\nTransitivity rule − Same as transitive rule in algebra, if a → b holds and b → c holds, then a → c also holds. a → b is called as a functionally that determines b.\nTransitivity rule − Same as transitive rule in algebra, if a → b holds and b → c holds, then a → c also holds. a → b is called as a functionally that determines b.\nTrivial − If a functional dependency (FD) X → Y holds, where Y is a subset of X, then it is called a trivial FD. Trivial FDs always hold.\nTrivial − If a functional dependency (FD) X → Y holds, where Y is a subset of X, then it is called a trivial FD. Trivial FDs always hold.\nNon-trivial − If an FD X → Y holds, where Y is not a subset of X, then it is called a non-trivial FD.\nNon-trivial − If an FD X → Y holds, where Y is not a subset of X, then it is called a non-trivial FD.\nCompletely non-trivial − If an FD X → Y holds, where x intersect Y = Φ, it is said to be a completely non-trivial FD.\nCompletely non-trivial − If an FD X → Y holds, where x intersect Y = Φ, it is said to be a completely non-trivial FD.\nIf a database design is not perfect, it may contain anomalies, which are like a bad dream for any database administrator. Managing a database with anomalies is next to impossible.\nUpdate anomalies − If data items are scattered and are not linked to each other properly, then it could lead to strange situations. For example, when we try to update one data item having its copies scattered over several places, a few instances get updated properly while a few others are left with old values. Such instances leave the database in an inconsistent state.\nUpdate anomalies − If data items are scattered and are not linked to each other properly, then it could lead to strange situations. For example, when we try to update one data item having its copies scattered over several places, a few instances get updated properly while a few others are left with old values. Such instances leave the database in an inconsistent state.\nDeletion anomalies − We tried to delete a record, but parts of it was left undeleted because of unawareness, the data is also saved somewhere else.\nDeletion anomalies − We tried to delete a record, but parts of it was left undeleted because of unawareness, the data is also saved somewhere else.\nInsert anomalies − We tried to insert data in a record that does not exist at all.\nInsert anomalies − We tried to insert data in a record that does not exist at all.\nNormalization is a method to remove all these anomalies and bring the database to a consistent state.\nFirst Normal Form is defined in the definition of relations (tables) itself. This rule defines that all the attributes in a relation must have atomic domains. The values in an atomic domain are indivisible units.\nWe re-arrange the relation (table) as below, to convert it to First Normal Form.\nEach attribute must contain only a single value from its pre-defined domain.\nBefore we learn about the second normal form, we need to understand the following −\nPrime attribute − An attribute, which is a part of the candidate-key, is known as a prime attribute.\nPrime attribute − An attribute, which is a part of the candidate-key, is known as a prime attribute.\nNon-prime attribute − An attribute, which is not a part of the prime-key, is said to be a non-prime attribute.\nNon-prime attribute − An attribute, which is not a part of the prime-key, is said to be a non-prime attribute.\nIf we follow second normal form, then every non-prime attribute should be fully functionally dependent on prime key attribute. That is, if X → A holds, then there should not be any proper subset Y of X, for which Y → A also holds true.\nWe see here in Student_Project relation that the prime key attributes are Stu_ID and Proj_ID. According to the rule, non-key attributes, i.e. Stu_Name and Proj_Name must be dependent upon both and not on any of the prime key attribute individually. But we find that Stu_Name can be identified by Stu_ID and Proj_Name can be identified by Proj_ID independently. This is called partial dependency, which is not allowed in Second Normal Form.\nWe broke the relation in two as depicted in the above picture. So there exists no partial dependency.\nFor a relation to be in Third Normal Form, it must be in Second Normal form and the following must satisfy −\nNo non-prime attribute is transitively dependent on prime key attribute.\nFor any non-trivial functional dependency, X → A, then either −\nX is a superkey or,\nA is prime attribute.\n\n\nA is prime attribute.\nWe find that in the above Student_detail relation, Stu_ID is the key and only prime key attribute. We find that City can be identified by Stu_ID as well as Zip itself. Neither Zip is a superkey nor is City a prime attribute. Additionally, Stu_ID → Zip → City, so there exists transitive dependency.\nTo bring this relation into third normal form, we break the relation into two relations as follows −\nBoyce-Codd Normal Form (BCNF) is an extension of Third Normal Form on strict terms. BCNF states that −\nFor any non-trivial functional dependency, X → A, X must be a super-key.\nIn the above image, Stu_ID is the super-key in the relation Student_Detail and Zip is the super-key in the relation ZipCodes. So,\nStu_ID → Stu_Name, Zip\nand\nZip → City\nWhich confirms that both the relations are in BCNF.\nWe understand the benefits of taking a Cartesian product of two relations, which gives us all the possible tuples that are paired together. But it might not be feasible for us in certain cases to take a Cartesian product where we encounter huge relations with thousands of tuples having a considerable large number of attributes.\nJoin is a combination of a Cartesian product followed by a selection process. A Join operation pairs two tuples from different relations, if and only if a given join condition is satisfied.\nWe will briefly describe various join types in the following sections.\nTheta join combines tuples from different relations provided they satisfy the theta condition. The join condition is denoted by the symbol θ.\nR1 ⋈θ R2\n\nR1 and R2 are relations having attributes (A1, A2, .., An) and (B1, B2,.. ,Bn) such that the attributes don’t have anything in common, that is R1 ∩ R2 = Φ.\nTheta join can use all kinds of comparison operators.\nStudent_Detail =\nSTUDENT ⋈Student.Std = Subject.Class SUBJECT\n\nWhen Theta join uses only equality comparison operator, it is said to be equijoin. The above example corresponds to equijoin.\nNatural join does not use any comparison operator. It does not concatenate the way a Cartesian product does. We can perform a Natural Join only if there is at least one common attribute that exists between two relations. In addition, the attributes must have the same name and domain.\nNatural join acts on those matching attributes where the values of attributes in both the relations are same.\nTheta Join, Equijoin, and Natural Join are called inner joins. An inner join includes only those tuples with matching attributes and the rest are discarded in the resulting relation. Therefore, we need to use outer joins to include all the tuples from the participating relations in the resulting relation. There are three kinds of outer joins − left outer join, right outer join, and full outer join.\nAll the tuples from the Left relation, R, are included in the resulting relation. If there are tuples in R without any matching tuple in the Right relation S, then the S-attributes of the resulting relation are made NULL.\nAll the tuples from the Right relation, S, are included in the resulting relation. If there are tuples in S without any matching tuple in R, then the R-attributes of resulting relation are made NULL.\nAll the tuples from both participating relations are included in the resulting relation. If there are no matching tuples for both relations, their respective unmatched attributes are made NULL.\nDatabases are stored in file formats, which contain records. At physical level, the actual data is stored in electromagnetic format on some device. These storage devices can be broadly categorized into three types −\nPrimary Storage − The memory storage that is directly accessible to the CPU comes under this category. CPU's internal memory (registers), fast memory (cache), and main memory (RAM) are directly accessible to the CPU, as they are all placed on the motherboard or CPU chipset. This storage is typically very small, ultra-fast, and volatile. Primary storage requires continuous power supply in order to maintain its state. In case of a power failure, all its data is lost.\nPrimary Storage − The memory storage that is directly accessible to the CPU comes under this category. CPU's internal memory (registers), fast memory (cache), and main memory (RAM) are directly accessible to the CPU, as they are all placed on the motherboard or CPU chipset. This storage is typically very small, ultra-fast, and volatile. Primary storage requires continuous power supply in order to maintain its state. In case of a power failure, all its data is lost.\nSecondary Storage − Secondary storage devices are used to store data for future use or as backup. Secondary storage includes memory devices that are not a part of the CPU chipset or motherboard, for example, magnetic disks, optical disks (DVD, CD, etc.), hard disks, flash drives, and magnetic tapes.\nSecondary Storage − Secondary storage devices are used to store data for future use or as backup. Secondary storage includes memory devices that are not a part of the CPU chipset or motherboard, for example, magnetic disks, optical disks (DVD, CD, etc.), hard disks, flash drives, and magnetic tapes.\nTertiary Storage − Tertiary storage is used to store huge volumes of data. Since such storage devices are external to the computer system, they are the slowest in speed. These storage devices are mostly used to take the back up of an entire system. Optical disks and magnetic tapes are widely used as tertiary storage.\nTertiary Storage − Tertiary storage is used to store huge volumes of data. Since such storage devices are external to the computer system, they are the slowest in speed. These storage devices are mostly used to take the back up of an entire system. Optical disks and magnetic tapes are widely used as tertiary storage.\nA computer system has a well-defined hierarchy of memory. A CPU has direct access to it main memory as well as its inbuilt registers. The access time of the main memory is obviously less than the CPU speed. To minimize this speed mismatch, cache memory is introduced. Cache memory provides the fastest access time and it contains data that is most frequently accessed by the CPU.\nThe memory with the fastest access is the costliest one. Larger storage devices offer slow speed and they are less expensive, however they can store huge volumes of data as compared to CPU registers or cache memory.\nHard disk drives are the most common secondary storage devices in present computer systems. These are called magnetic disks because they use the concept of magnetization to store information. Hard disks consist of metal disks coated with magnetizable material. These disks are placed vertically on a spindle. A read/write head moves in between the disks and is used to magnetize or de-magnetize the spot under it. A magnetized spot can be recognized as 0 (zero) or 1 (one).\nHard disks are formatted in a well-defined order to store data efficiently. A hard disk plate has many concentric circles on it, called tracks. Every track is further divided into sectors. A sector on a hard disk typically stores 512 bytes of data.\nRAID stands for Redundant Array of Independent Disks, which is a technology to connect multiple secondary storage devices and use them as a single storage media.\nRAID consists of an array of disks in which multiple disks are connected together to achieve different goals. RAID levels define the use of disk arrays.\nRAID 0 − In this level, a striped array of disks is implemented. The data is broken down into blocks and the blocks are distributed among disks. Each disk receives a block of data to write/read in parallel. It enhances the speed and performance of the storage device. There is no parity and backup in Level 0.\nRAID 0 − In this level, a striped array of disks is implemented. The data is broken down into blocks and the blocks are distributed among disks. Each disk receives a block of data to write/read in parallel. It enhances the speed and performance of the storage device. There is no parity and backup in Level 0.\nRAID 1 − RAID 1 uses mirroring techniques. When data is sent to a RAID controller, it sends a copy of data to all the disks in the array. RAID level 1 is also called mirroring and provides 100% redundancy in case of a failure.\nRAID 1 − RAID 1 uses mirroring techniques. When data is sent to a RAID controller, it sends a copy of data to all the disks in the array. RAID level 1 is also called mirroring and provides 100% redundancy in case of a failure.\nRAID 2 − RAID 2 records Error Correction Code using Hamming distance for its data, striped on different disks. Like level 0, each data bit in a word is recorded on a separate disk and ECC codes of the data words are stored on a different set disks. Due to its complex structure and high cost, RAID 2 is not commercially available.\nRAID 2 − RAID 2 records Error Correction Code using Hamming distance for its data, striped on different disks. Like level 0, each data bit in a word is recorded on a separate disk and ECC codes of the data words are stored on a different set disks. Due to its complex structure and high cost, RAID 2 is not commercially available.\nRAID 3 − RAID 3 stripes the data onto multiple disks. The parity bit generated for data word is stored on a different disk. This technique makes it to overcome single disk failures.\nRAID 3 − RAID 3 stripes the data onto multiple disks. The parity bit generated for data word is stored on a different disk. This technique makes it to overcome single disk failures.\nRAID 4 − In this level, an entire block of data is written onto data disks and then the parity is generated and stored on a different disk. Note that level 3 uses byte-level striping, whereas level 4 uses block-level striping. Both level 3 and level 4 require at least three disks to implement RAID.\nRAID 4 − In this level, an entire block of data is written onto data disks and then the parity is generated and stored on a different disk. Note that level 3 uses byte-level striping, whereas level 4 uses block-level striping. Both level 3 and level 4 require at least three disks to implement RAID.\nRAID 5 − RAID 5 writes whole data blocks onto different disks, but the parity bits generated for data block stripe are distributed among all the data disks rather than storing them on a different dedicated disk.\nRAID 5 − RAID 5 writes whole data blocks onto different disks, but the parity bits generated for data block stripe are distributed among all the data disks rather than storing them on a different dedicated disk.\nRAID 6 − RAID 6 is an extension of level 5. In this level, two independent parities are generated and stored in distributed fashion among multiple disks. Two parities provide additional fault tolerance. This level requires at least four disk drives to implement RAID.\nRAID 6 − RAID 6 is an extension of level 5. In this level, two independent parities are generated and stored in distributed fashion among multiple disks. Two parities provide additional fault tolerance. This level requires at least four disk drives to implement RAID.\nRelative data and information is stored collectively in file formats. A file is a sequence of records stored in binary format. A disk drive is formatted into several blocks that can store records. File records are mapped onto those disk blocks.\nFile Organization defines how file records are mapped onto disk blocks. We have four types of File Organization to organize file records −\nWhen a file is created using Heap File Organization, the Operating System allocates memory area to that file without any further accounting details. File records can be placed anywhere in that memory area. It is the responsibility of the software to manage the records. Heap File does not support any ordering, sequencing, or indexing on its own.\nEvery file record contains a data field (attribute) to uniquely identify that record. In sequential file organization, records are placed in the file in some sequential order based on the unique key field or search key. Practically, it is not possible to store all the records sequentially in physical form.\nHash File Organization uses Hash function computation on some fields of the records. The output of the hash function determines the location of disk block where the records are to be placed.\nClustered file organization is not considered good for large databases. In this mechanism, related records from one or more relations are kept in the same disk block, that is, the ordering of records is not based on primary key or search key.\nOperations on database files can be broadly classified into two categories −\nUpdate Operations\nUpdate Operations\nRetrieval Operations\nRetrieval Operations\nUpdate operations change the data values by insertion, deletion, or update. Retrieval operations, on the other hand, do not alter the data but retrieve them after optional conditional filtering. In both types of operations, selection plays a significant role. Other than creation and deletion of a file, there could be several operations, which can be done on files.\nOpen − A file can be opened in one of the two modes, read mode or write mode. In read mode, the operating system does not allow anyone to alter data. In other words, data is read only. Files opened in read mode can be shared among several entities. Write mode allows data modification. Files opened in write mode can be read but cannot be shared.\nOpen − A file can be opened in one of the two modes, read mode or write mode. In read mode, the operating system does not allow anyone to alter data. In other words, data is read only. Files opened in read mode can be shared among several entities. Write mode allows data modification. Files opened in write mode can be read but cannot be shared.\nLocate − Every file has a file pointer, which tells the current position where the data is to be read or written. This pointer can be adjusted accordingly. Using find (seek) operation, it can be moved forward or backward.\nLocate − Every file has a file pointer, which tells the current position where the data is to be read or written. This pointer can be adjusted accordingly. Using find (seek) operation, it can be moved forward or backward.\nRead − By default, when files are opened in read mode, the file pointer points to the beginning of the file. There are options where the user can tell the operating system where to locate the file pointer at the time of opening a file. The very next data to the file pointer is read.\nRead − By default, when files are opened in read mode, the file pointer points to the beginning of the file. There are options where the user can tell the operating system where to locate the file pointer at the time of opening a file. The very next data to the file pointer is read.\nWrite − User can select to open a file in write mode, which enables them to edit its contents. It can be deletion, insertion, or modification. The file pointer can be located at the time of opening or can be dynamically changed if the operating system allows to do so.\nWrite − User can select to open a file in write mode, which enables them to edit its contents. It can be deletion, insertion, or modification. The file pointer can be located at the time of opening or can be dynamically changed if the operating system allows to do so.\nClose − This is the most important operation from the operating system’s point of view. When a request to close a file is generated, the operating system\n\nremoves all the locks (if in shared mode),\nsaves the data (if altered) to the secondary storage media, and\nreleases all the buffers and file handlers associated with the file.\n\n\nClose − This is the most important operation from the operating system’s point of view. When a request to close a file is generated, the operating system\nremoves all the locks (if in shared mode),\nsaves the data (if altered) to the secondary storage media, and\nreleases all the buffers and file handlers associated with the file.\nThe organization of data inside a file plays a major role here. The process to locate the file pointer to a desired record inside a file various based on whether the records are arranged sequentially or clustered.\nWe know that data is stored in the form of records. Every record has a key field, which helps it to be recognized uniquely.\nIndexing is a data structure technique to efficiently retrieve records from the database files based on some attributes on which the indexing has been done. Indexing in database systems is similar to what we see in books.\nIndexing is defined based on its indexing attributes. Indexing can be of the following types −\nPrimary Index − Primary index is defined on an ordered data file. The data file is ordered on a key field. The key field is generally the primary key of the relation.\nPrimary Index − Primary index is defined on an ordered data file. The data file is ordered on a key field. The key field is generally the primary key of the relation.\nSecondary Index − Secondary index may be generated from a field which is a candidate key and has a unique value in every record, or a non-key with duplicate values.\nSecondary Index − Secondary index may be generated from a field which is a candidate key and has a unique value in every record, or a non-key with duplicate values.\nClustering Index − Clustering index is defined on an ordered data file. The data file is ordered on a non-key field.\nClustering Index − Clustering index is defined on an ordered data file. The data file is ordered on a non-key field.\nOrdered Indexing is of two types −\nDense Index\nSparse Index\nIn dense index, there is an index record for every search key value in the database. This makes searching faster but requires more space to store index records itself. Index records contain search key value and a pointer to the actual record on the disk.\nIn sparse index, index records are not created for every search key. An index record here contains a search key and an actual pointer to the data on the disk. To search a record, we first proceed by index record and reach at the actual location of the data. If the data we are looking for is not where we directly reach by following the index, then the system starts sequential search until the desired data is found.\nIndex records comprise search-key values and data pointers. Multilevel index is stored on the disk along with the actual database files. As the size of the database grows, so does the size of the indices. There is an immense need to keep the index records in the main memory so as to speed up the search operations. If single-level index is used, then a large size index cannot be kept in memory which leads to multiple disk accesses.\nMulti-level Index helps in breaking down the index into several smaller indices in order to make the outermost level so small that it can be saved in a single disk block, which can easily be accommodated anywhere in the main memory.\nA B+ tree is a balanced binary search tree that follows a multi-level index format. The leaf nodes of a B+ tree denote actual data pointers. B+ tree ensures that all leaf nodes remain at the same height, thus balanced. Additionally, the leaf nodes are linked using a link list; therefore, a B+ tree can support random access as well as sequential access.\nEvery leaf node is at equal distance from the root node. A B+ tree is of the order n where n is fixed for every B+ tree.\nInternal nodes −\nInternal (non-leaf) nodes contain at least ⌈n/2⌉ pointers, except the root node.\nAt most, an internal node can contain n pointers.\nLeaf nodes −\nLeaf nodes contain at least ⌈n/2⌉ record pointers and ⌈n/2⌉ key values.\nAt most, a leaf node can contain n record pointers and n key values.\nEvery leaf node contains one block pointer P to point to next leaf node and forms a linked list.\nB+ trees are filled from bottom and each entry is done at the leaf node.\nB+ trees are filled from bottom and each entry is done at the leaf node.\nIf a leaf node overflows −\n\nSplit node into two parts.\nPartition at i = ⌊(m+1)/2⌋.\nFirst i entries are stored in one node.\nRest of the entries (i+1 onwards) are moved to a new node.\nith key is duplicated at the parent of the leaf.\n\n\nSplit node into two parts.\nSplit node into two parts.\nPartition at i = ⌊(m+1)/2⌋.\nPartition at i = ⌊(m+1)/2⌋.\nFirst i entries are stored in one node.\nFirst i entries are stored in one node.\nRest of the entries (i+1 onwards) are moved to a new node.\nRest of the entries (i+1 onwards) are moved to a new node.\nith key is duplicated at the parent of the leaf.\nith key is duplicated at the parent of the leaf.\nIf a non-leaf node overflows −\n\nSplit node into two parts.\nPartition the node at i = ⌈(m+1)/2⌉.\nEntries up to i are kept in one node.\nRest of the entries are moved to a new node.\n\n\nIf a non-leaf node overflows −\nSplit node into two parts.\nSplit node into two parts.\nPartition the node at i = ⌈(m+1)/2⌉.\nPartition the node at i = ⌈(m+1)/2⌉.\nEntries up to i are kept in one node.\nEntries up to i are kept in one node.\nRest of the entries are moved to a new node.\nRest of the entries are moved to a new node.\nB+ tree entries are deleted at the leaf nodes.\nB+ tree entries are deleted at the leaf nodes.\nThe target entry is searched and deleted.\n\nIf it is an internal node, delete and replace with the entry from the left position.\n\n\nThe target entry is searched and deleted.\nIf it is an internal node, delete and replace with the entry from the left position.\nIf it is an internal node, delete and replace with the entry from the left position.\nAfter deletion, underflow is tested,\n\nIf underflow occurs, distribute the entries from the nodes left to it.\n\n\nAfter deletion, underflow is tested,\nIf underflow occurs, distribute the entries from the nodes left to it.\nIf underflow occurs, distribute the entries from the nodes left to it.\nIf distribution is not possible from left, then\n\nDistribute from the nodes right to it.\n\n\nIf distribution is not possible from left, then\nDistribute from the nodes right to it.\nDistribute from the nodes right to it.\nIf distribution is not possible from left or from right, then\n\nMerge the node with left and right to it.\n\n\nIf distribution is not possible from left or from right, then\nMerge the node with left and right to it.\nMerge the node with left and right to it.\nFor a huge database structure, it can be almost next to impossible to search all the index values through all its level and then reach the destination data block to retrieve the desired data. Hashing is an effective technique to calculate the direct location of a data record on the disk without using index structure.\nHashing uses hash functions with search keys as parameters to generate the address of a data record.\nBucket − A hash file stores data in bucket format. Bucket is considered a unit of storage. A bucket typically stores one complete disk block, which in turn can store one or more records.\nBucket − A hash file stores data in bucket format. Bucket is considered a unit of storage. A bucket typically stores one complete disk block, which in turn can store one or more records.\nHash Function − A hash function, h, is a mapping function that maps all the set of search-keys K to the address where actual records are placed. It is a function from search keys to bucket addresses.\nHash Function − A hash function, h, is a mapping function that maps all the set of search-keys K to the address where actual records are placed. It is a function from search keys to bucket addresses.\nIn static hashing, when a search-key value is provided, the hash function always computes the same address. For example, if mod-4 hash function is used, then it shall generate only 5 values. The output address shall always be same for that function. The number of buckets provided remains unchanged at all times.\nInsertion − When a record is required to be entered using static hash, the hash function h computes the bucket address for search key K, where the record will be stored.\nBucket address = h(K)\nInsertion − When a record is required to be entered using static hash, the hash function h computes the bucket address for search key K, where the record will be stored.\nBucket address = h(K)\nSearch − When a record needs to be retrieved, the same hash function can be used to retrieve the address of the bucket where the data is stored.\nSearch − When a record needs to be retrieved, the same hash function can be used to retrieve the address of the bucket where the data is stored.\nDelete − This is simply a search followed by a deletion operation.\nDelete − This is simply a search followed by a deletion operation.\nThe condition of bucket-overflow is known as collision. This is a fatal state for any static hash function. In this case, overflow chaining can be used.\nOverflow Chaining − When buckets are full, a new bucket is allocated for the same hash result and is linked after the previous one. This mechanism is called Closed Hashing.\nOverflow Chaining − When buckets are full, a new bucket is allocated for the same hash result and is linked after the previous one. This mechanism is called Closed Hashing.\nLinear Probing − When a hash function generates an address at which data is already stored, the next free bucket is allocated to it. This mechanism is called Open Hashing.\nLinear Probing − When a hash function generates an address at which data is already stored, the next free bucket is allocated to it. This mechanism is called Open Hashing.\nThe problem with static hashing is that it does not expand or shrink dynamically as the size of the database grows or shrinks. Dynamic hashing provides a mechanism in which data buckets are added and removed dynamically and on-demand. Dynamic hashing is also known as extended hashing.\nHash function, in dynamic hashing, is made to produce a large number of values and only a few are used initially.\nThe prefix of an entire hash value is taken as a hash index. Only a portion of the hash value is used for computing bucket addresses. Every hash index has a depth value to signify how many bits are used for computing a hash function. These bits can address 2n buckets. When all these bits are consumed − that is, when all the buckets are full − then the depth value is increased linearly and twice the buckets are allocated.\nQuerying − Look at the depth value of the hash index and use those bits to compute the bucket address.\nQuerying − Look at the depth value of the hash index and use those bits to compute the bucket address.\nUpdate − Perform a query as above and update the data.\nUpdate − Perform a query as above and update the data.\nDeletion − Perform a query to locate the desired data and delete the same.\nDeletion − Perform a query to locate the desired data and delete the same.\nInsertion − Compute the address of the bucket\n\nIf the bucket is already full.\n\nAdd more buckets.\nAdd additional bits to the hash value.\nRe-compute the hash function.\n\n\nElse\n\nAdd data to the bucket,\n\n\nIf all the buckets are full, perform the remedies of static hashing.\n\n\nInsertion − Compute the address of the bucket\nIf the bucket is already full.\n\nAdd more buckets.\nAdd additional bits to the hash value.\nRe-compute the hash function.\n\n\nAdd more buckets.\nAdd additional bits to the hash value.\nRe-compute the hash function.\nElse\n\nAdd data to the bucket,\n\n\nAdd data to the bucket,\nIf all the buckets are full, perform the remedies of static hashing.\nHashing is not favorable when the data is organized in some ordering and the queries require a range of data. When data is discrete and random, hash performs the best.\nHashing algorithms have high complexity than indexing. All hash operations are done in constant time.\nA transaction can be defined as a group of tasks. A single task is the minimum processing unit which cannot be divided further.\nLet’s take an example of a simple transaction. Suppose a bank employee transfers Rs 500 from A's account to B's account. This very simple and small transaction involves several low-level tasks.\nA’s Account\nOpen_Account(A)\nOld_Balance = A.balance\nNew_Balance = Old_Balance - 500\nA.balance = New_Balance\nClose_Account(A)\n\nB’s Account\nOpen_Account(B)\nOld_Balance = B.balance\nNew_Balance = Old_Balance + 500\nB.balance = New_Balance\nClose_Account(B)\n\nA transaction is a very small unit of a program and it may contain several lowlevel tasks. A transaction in a database system must maintain Atomicity, Consistency, Isolation, and Durability − commonly known as ACID properties − in order to ensure accuracy, completeness, and data integrity.\nAtomicity − This property states that a transaction must be treated as an atomic unit, that is, either all of its operations are executed or none. There must be no state in a database where a transaction is left partially completed. States should be defined either before the execution of the transaction or after the execution/abortion/failure of the transaction.\nAtomicity − This property states that a transaction must be treated as an atomic unit, that is, either all of its operations are executed or none. There must be no state in a database where a transaction is left partially completed. States should be defined either before the execution of the transaction or after the execution/abortion/failure of the transaction.\nConsistency − The database must remain in a consistent state after any transaction. No transaction should have any adverse effect on the data residing in the database. If the database was in a consistent state before the execution of a transaction, it must remain consistent after the execution of the transaction as well.\nConsistency − The database must remain in a consistent state after any transaction. No transaction should have any adverse effect on the data residing in the database. If the database was in a consistent state before the execution of a transaction, it must remain consistent after the execution of the transaction as well.\nDurability − The database should be durable enough to hold all its latest updates even if the system fails or restarts. If a transaction updates a chunk of data in a database and commits, then the database will hold the modified data. If a transaction commits but the system fails before the data could be written on to the disk, then that data will be updated once the system springs back into action.\nDurability − The database should be durable enough to hold all its latest updates even if the system fails or restarts. If a transaction updates a chunk of data in a database and commits, then the database will hold the modified data. If a transaction commits but the system fails before the data could be written on to the disk, then that data will be updated once the system springs back into action.\nIsolation − In a database system where more than one transaction are being executed simultaneously and in parallel, the property of isolation states that all the transactions will be carried out and executed as if it is the only transaction in the system. No transaction will affect the existence of any other transaction.\nIsolation − In a database system where more than one transaction are being executed simultaneously and in parallel, the property of isolation states that all the transactions will be carried out and executed as if it is the only transaction in the system. No transaction will affect the existence of any other transaction.\nWhen multiple transactions are being executed by the operating system in a multiprogramming environment, there are possibilities that instructions of one transactions are interleaved with some other transaction.\nSchedule − A chronological execution sequence of a transaction is called a schedule. A schedule can have many transactions in it, each comprising of a number of instructions/tasks.\nSchedule − A chronological execution sequence of a transaction is called a schedule. A schedule can have many transactions in it, each comprising of a number of instructions/tasks.\nSerial Schedule − It is a schedule in which transactions are aligned in such a way that one transaction is executed first. When the first transaction completes its cycle, then the next transaction is executed. Transactions are ordered one after the other. This type of schedule is called a serial schedule, as transactions are executed in a serial manner.\nSerial Schedule − It is a schedule in which transactions are aligned in such a way that one transaction is executed first. When the first transaction completes its cycle, then the next transaction is executed. Transactions are ordered one after the other. This type of schedule is called a serial schedule, as transactions are executed in a serial manner.\nIn a multi-transaction environment, serial schedules are considered as a benchmark. The execution sequence of an instruction in a transaction cannot be changed, but two transactions can have their instructions executed in a random fashion. This execution does no harm if two transactions are mutually independent and working on different segments of data; but in case these two transactions are working on the same data, then the results may vary. This ever-varying result may bring the database to an inconsistent state.\nTo resolve this problem, we allow parallel execution of a transaction schedule, if its transactions are either serializable or have some equivalence relation among them.\nAn equivalence schedule can be of the following types −\nIf two schedules produce the same result after execution, they are said to be result equivalent. They may yield the same result for some value and different results for another set of values. That's why this equivalence is not generally considered significant.\nTwo schedules would be view equivalence if the transactions in both the schedules perform similar actions in a similar manner.\nFor example −\nIf T reads the initial data in S1, then it also reads the initial data in S2.\nIf T reads the initial data in S1, then it also reads the initial data in S2.\nIf T reads the value written by J in S1, then it also reads the value written by J in S2.\nIf T reads the value written by J in S1, then it also reads the value written by J in S2.\nIf T performs the final write on the data value in S1, then it also performs the final write on the data value in S2.\nIf T performs the final write on the data value in S1, then it also performs the final write on the data value in S2.\nTwo schedules would be conflicting if they have the following properties −\nBoth belong to separate transactions.\nBoth accesses the same data item.\nAt least one of them is \"write\" operation.\nTwo schedules having multiple transactions with conflicting operations are said to be conflict equivalent if and only if −\nBoth the schedules contain the same set of Transactions.\nThe order of conflicting pairs of operation is maintained in both the schedules.\nNote − View equivalent schedules are view serializable and conflict equivalent schedules are conflict serializable. All conflict serializable schedules are view serializable too.\nA transaction in a database can be in one of the following states −\nActive − In this state, the transaction is being executed. This is the initial state of every transaction.\nActive − In this state, the transaction is being executed. This is the initial state of every transaction.\nPartially Committed − When a transaction executes its final operation, it is said to be in a partially committed state.\nPartially Committed − When a transaction executes its final operation, it is said to be in a partially committed state.\nFailed − A transaction is said to be in a failed state if any of the checks made by the database recovery system fails. A failed transaction can no longer proceed further.\nFailed − A transaction is said to be in a failed state if any of the checks made by the database recovery system fails. A failed transaction can no longer proceed further.\nAborted − If any of the checks fails and the transaction has reached a failed state, then the recovery manager rolls back all its write operations on the database to bring the database back to its original state where it was prior to the execution of the transaction. Transactions in this state are called aborted. The database recovery module can select one of the two operations after a transaction aborts −\n\nRe-start the transaction\nKill the transaction\n\n\nAborted − If any of the checks fails and the transaction has reached a failed state, then the recovery manager rolls back all its write operations on the database to bring the database back to its original state where it was prior to the execution of the transaction. Transactions in this state are called aborted. The database recovery module can select one of the two operations after a transaction aborts −\nRe-start the transaction\nKill the transaction\nCommitted − If a transaction executes all its operations successfully, it is said to be committed. All its effects are now permanently established on the database system.\nCommitted − If a transaction executes all its operations successfully, it is said to be committed. All its effects are now permanently established on the database system.\nIn a multiprogramming environment where multiple transactions can be executed simultaneously, it is highly important to control the concurrency of transactions. We have concurrency control protocols to ensure atomicity, isolation, and serializability of concurrent transactions. Concurrency control protocols can be broadly divided into two categories −\nLock based protocols\nTime stamp based protocols\nDatabase systems equipped with lock-based protocols use a mechanism by which any transaction cannot read or write data until it acquires an appropriate lock on it. Locks are of two kinds −\nBinary Locks − A lock on a data item can be in two states; it is either locked or unlocked.\nBinary Locks − A lock on a data item can be in two states; it is either locked or unlocked.\nShared/exclusive − This type of locking mechanism differentiates the locks based on their uses. If a lock is acquired on a data item to perform a write operation, it is an exclusive lock. Allowing more than one transaction to write on the same data item would lead the database into an inconsistent state. Read locks are shared because no data value is being changed.\nShared/exclusive − This type of locking mechanism differentiates the locks based on their uses. If a lock is acquired on a data item to perform a write operation, it is an exclusive lock. Allowing more than one transaction to write on the same data item would lead the database into an inconsistent state. Read locks are shared because no data value is being changed.\nThere are four types of lock protocols available −\nSimplistic lock-based protocols allow transactions to obtain a lock on every object before a 'write' operation is performed. Transactions may unlock the data item after completing the ‘write’ operation.\nPre-claiming protocols evaluate their operations and create a list of data items on which they need locks. Before initiating an execution, the transaction requests the system for all the locks it needs beforehand. If all the locks are granted, the transaction executes and releases all the locks when all its operations are over. If all the locks are not granted, the transaction rolls back and waits until all the locks are granted.\nThis locking protocol divides the execution phase of a transaction into three parts. In the first part, when the transaction starts executing, it seeks permission for the locks it requires. The second part is where the transaction acquires all the locks. As soon as the transaction releases its first lock, the third phase starts. In this phase, the transaction cannot demand any new locks; it only releases the acquired locks.\nTwo-phase locking has two phases, one is growing, where all the locks are being acquired by the transaction; and the second phase is shrinking, where the locks held by the transaction are being released.\nTo claim an exclusive (write) lock, a transaction must first acquire a shared (read) lock and then upgrade it to an exclusive lock.\nThe first phase of Strict-2PL is same as 2PL. After acquiring all the locks in the first phase, the transaction continues to execute normally. But in contrast to 2PL, Strict-2PL does not release a lock after using it. Strict-2PL holds all the locks until the commit point and releases all the locks at a time.\nStrict-2PL does not have cascading abort as 2PL does.\nThe most commonly used concurrency protocol is the timestamp based protocol. This protocol uses either system time or logical counter as a timestamp.\nLock-based protocols manage the order between the conflicting pairs among transactions at the time of execution, whereas timestamp-based protocols start working as soon as a transaction is created.\nEvery transaction has a timestamp associated with it, and the ordering is determined by the age of the transaction. A transaction created at 0002 clock time would be older than all other transactions that come after it. For example, any transaction 'y' entering the system at 0004 is two seconds younger and the priority would be given to the older one.\nIn addition, every data item is given the latest read and write-timestamp. This lets the system know when the last ‘read and write’ operation was performed on the data item.\nThe timestamp-ordering protocol ensures serializability among transactions in their conflicting read and write operations. This is the responsibility of the protocol system that the conflicting pair of tasks should be executed according to the timestamp values of the transactions.\nThe timestamp of transaction Ti is denoted as TS(Ti).\nRead time-stamp of data-item X is denoted by R-timestamp(X).\nWrite time-stamp of data-item X is denoted by W-timestamp(X).\nTimestamp ordering protocol works as follows −\nIf a transaction Ti issues a read(X) operation −\nIf a transaction Ti issues a read(X) operation −\nIf TS(Ti) < W-timestamp(X)\n\nOperation rejected.\n\n\nOperation rejected.\nIf TS(Ti) >= W-timestamp(X)\n\nOperation executed.\n\n\nOperation executed.\nAll data-item timestamps updated.\nIf a transaction Ti issues a write(X) operation −\nIf a transaction Ti issues a write(X) operation −\nIf TS(Ti) < R-timestamp(X)\nOperation rejected.\nIf TS(Ti) < W-timestamp(X)\nOperation rejected and Ti rolled back.\nOtherwise, operation executed.\nThis rule states if TS(Ti) < W-timestamp(X), then the operation is rejected and Ti is rolled back.\nTime-stamp ordering rules can be modified to make the schedule view serializable.\nInstead of making Ti rolled back, the 'write' operation itself is ignored.\nIn a multi-process system, deadlock is an unwanted situation that arises in a shared resource environment, where a process indefinitely waits for a resource that is held by another process.\nFor example, assume a set of transactions {T0, T1, T2, ...,Tn}. T0 needs a resource X to complete its task. Resource X is held by T1, and T1 is waiting for a resource Y, which is held by T2. T2 is waiting for resource Z, which is held by T0. Thus, all the processes wait for each other to release resources. In this situation, none of the processes can finish their task. This situation is known as a deadlock.\nDeadlocks are not healthy for a system. In case a system is stuck in a deadlock, the transactions involved in the deadlock are either rolled back or restarted.\nTo prevent any deadlock situation in the system, the DBMS aggressively inspects all the operations, where transactions are about to execute. The DBMS inspects the operations and analyzes if they can create a deadlock situation. If it finds that a deadlock situation might occur, then that transaction is never allowed to be executed.\nThere are deadlock prevention schemes that use timestamp ordering mechanism of transactions in order to predetermine a deadlock situation.\nIn this scheme, if a transaction requests to lock a resource (data item), which is already held with a conflicting lock by another transaction, then one of the two possibilities may occur −\nIf TS(Ti) < TS(Tj) − that is Ti, which is requesting a conflicting lock, is older than Tj − then Ti is allowed to wait until the data-item is available.\nIf TS(Ti) < TS(Tj) − that is Ti, which is requesting a conflicting lock, is older than Tj − then Ti is allowed to wait until the data-item is available.\nIf TS(Ti) > TS(tj) − that is Ti is younger than Tj − then Ti dies. Ti is restarted later with a random delay but with the same timestamp.\nIf TS(Ti) > TS(tj) − that is Ti is younger than Tj − then Ti dies. Ti is restarted later with a random delay but with the same timestamp.\nThis scheme allows the older transaction to wait but kills the younger one.\nIn this scheme, if a transaction requests to lock a resource (data item), which is already held with conflicting lock by some another transaction, one of the two possibilities may occur −\nIf TS(Ti) < TS(Tj), then Ti forces Tj to be rolled back − that is Ti wounds Tj. Tj is restarted later with a random delay but with the same timestamp.\nIf TS(Ti) < TS(Tj), then Ti forces Tj to be rolled back − that is Ti wounds Tj. Tj is restarted later with a random delay but with the same timestamp.\nIf TS(Ti) > TS(Tj), then Ti is forced to wait until the resource is available.\nIf TS(Ti) > TS(Tj), then Ti is forced to wait until the resource is available.\nThis scheme, allows the younger transaction to wait; but when an older transaction requests an item held by a younger one, the older transaction forces the younger one to abort and release the item.\nIn both the cases, the transaction that enters the system at a later stage is aborted.\nAborting a transaction is not always a practical approach. Instead, deadlock avoidance mechanisms can be used to detect any deadlock situation in advance. Methods like \"wait-for graph\" are available but they are suitable for only those systems where transactions are lightweight having fewer instances of resource. In a bulky system, deadlock prevention techniques may work well.\nThis is a simple method available to track if any deadlock situation may arise. For each transaction entering into the system, a node is created. When a transaction Ti requests for a lock on an item, say X, which is held by some other transaction Tj, a directed edge is created from Ti to Tj. If Tj releases item X, the edge between them is dropped and Ti locks the data item.\nThe system maintains this wait-for graph for every transaction waiting for some data items held by others. The system keeps checking if there's any cycle in the graph.\nHere, we can use any of the two following approaches −\nFirst, do not allow any request for an item, which is already locked by another transaction. This is not always feasible and may cause starvation, where a transaction indefinitely waits for a data item and can never acquire it.\nFirst, do not allow any request for an item, which is already locked by another transaction. This is not always feasible and may cause starvation, where a transaction indefinitely waits for a data item and can never acquire it.\nThe second option is to roll back one of the transactions. It is not always feasible to roll back the younger transaction, as it may be important than the older one. With the help of some relative algorithm, a transaction is chosen, which is to be aborted. This transaction is known as the victim and the process is known as victim selection.\nThe second option is to roll back one of the transactions. It is not always feasible to roll back the younger transaction, as it may be important than the older one. With the help of some relative algorithm, a transaction is chosen, which is to be aborted. This transaction is known as the victim and the process is known as victim selection.\nA volatile storage like RAM stores all the active logs, disk buffers, and related data. In addition, it stores all the transactions that are being currently executed. What happens if such a volatile storage crashes abruptly? It would obviously take away all the logs and active copies of the database. It makes recovery almost impossible, as everything that is required to recover the data is lost.\nFollowing techniques may be adopted in case of loss of volatile storage −\nWe can have checkpoints at multiple stages so as to save the contents of the database periodically.\nWe can have checkpoints at multiple stages so as to save the contents of the database periodically.\nA state of active database in the volatile memory can be periodically dumped onto a stable storage, which may also contain logs and active transactions and buffer blocks.\nA state of active database in the volatile memory can be periodically dumped onto a stable storage, which may also contain logs and active transactions and buffer blocks.\n can be marked on a log file, whenever the database contents are dumped from a non-volatile memory to a stable one.\n can be marked on a log file, whenever the database contents are dumped from a non-volatile memory to a stable one.\nWhen the system recovers from a failure, it can restore the latest dump.\nWhen the system recovers from a failure, it can restore the latest dump.\nIt can maintain a redo-list and an undo-list as checkpoints.\nIt can maintain a redo-list and an undo-list as checkpoints.\nIt can recover the system by consulting undo-redo lists to restore the state of all transactions up to the last checkpoint.\nIt can recover the system by consulting undo-redo lists to restore the state of all transactions up to the last checkpoint.\nA catastrophic failure is one where a stable, secondary storage device gets corrupt. With the storage device, all the valuable data that is stored inside is lost. We have two different strategies to recover data from such a catastrophic failure −\nRemote backup &minu; Here a backup copy of the database is stored at a remote location from where it can be restored in case of a catastrophe.\nRemote backup &minu; Here a backup copy of the database is stored at a remote location from where it can be restored in case of a catastrophe.\nAlternatively, database backups can be taken on magnetic tapes and stored at a safer place. This backup can later be transferred onto a freshly installed database to bring it to the point of backup.\nAlternatively, database backups can be taken on magnetic tapes and stored at a safer place. This backup can later be transferred onto a freshly installed database to bring it to the point of backup.\nGrown-up databases are too bulky to be frequently backed up. In such cases, we have techniques where we can restore a database just by looking at its logs. So, all that we need to do here is to take a backup of all the logs at frequent intervals of time. The database can be backed up once a week, and the logs being very small can be backed up every day or as frequently as possible.\nRemote backup provides a sense of security in case the primary location where the database is located gets destroyed. Remote backup can be offline or real-time or online. In case it is offline, it is maintained manually.\nOnline backup systems are more real-time and lifesavers for database administrators and investors. An online backup system is a mechanism where every bit of the real-time data is backed up simultaneously at two distant places. One of them is directly connected to the system and the other one is kept at a remote place as backup.\nAs soon as the primary database storage fails, the backup system senses the failure and switches the user system to the remote storage. Sometimes this is so instant that the users can’t even realize a failure.\nDBMS is a highly complex system with hundreds of transactions being executed every second. The durability and robustness of a DBMS depends on its complex architecture and its underlying hardware and system software. If it fails or crashes amid transactions, it is expected that the system would follow some sort of algorithm or techniques to recover lost data.\nTo see where the problem has occurred, we generalize a failure into various categories, as follows −\nA transaction has to abort when it fails to execute or when it reaches a point from where it can’t go any further. This is called transaction failure where only a few transactions or processes are hurt.\nReasons for a transaction failure could be −\nLogical errors − Where a transaction cannot complete because it has some code error or any internal error condition.\nLogical errors − Where a transaction cannot complete because it has some code error or any internal error condition.\nSystem errors − Where the database system itself terminates an active transaction because the DBMS is not able to execute it, or it has to stop because of some system condition. For example, in case of deadlock or resource unavailability, the system aborts an active transaction.\nSystem errors − Where the database system itself terminates an active transaction because the DBMS is not able to execute it, or it has to stop because of some system condition. For example, in case of deadlock or resource unavailability, the system aborts an active transaction.\nThere are problems − external to the system − that may cause the system to stop abruptly and cause the system to crash. For example, interruptions in power supply may cause the failure of underlying hardware or software failure.\nExamples may include operating system errors.\nIn early days of technology evolution, it was a common problem where hard-disk drives or storage drives used to fail frequently.\nDisk failures include formation of bad sectors, unreachability to the disk, disk head crash or any other failure, which destroys all or a part of disk storage.\nWe have already described the storage system. In brief, the storage structure can be divided into two categories −\nVolatile storage − As the name suggests, a volatile storage cannot survive system crashes. Volatile storage devices are placed very close to the CPU; normally they are embedded onto the chipset itself. For example, main memory and cache memory are examples of volatile storage. They are fast but can store only a small amount of information.\nVolatile storage − As the name suggests, a volatile storage cannot survive system crashes. Volatile storage devices are placed very close to the CPU; normally they are embedded onto the chipset itself. For example, main memory and cache memory are examples of volatile storage. They are fast but can store only a small amount of information.\nNon-volatile storage − These memories are made to survive system crashes. They are huge in data storage capacity, but slower in accessibility. Examples may include hard-disks, magnetic tapes, flash memory, and non-volatile (battery backed up) RAM.\nNon-volatile storage − These memories are made to survive system crashes. They are huge in data storage capacity, but slower in accessibility. Examples may include hard-disks, magnetic tapes, flash memory, and non-volatile (battery backed up) RAM.\nWhen a system crashes, it may have several transactions being executed and various files opened for them to modify the data items. Transactions are made of various operations, which are atomic in nature. But according to ACID properties of DBMS, atomicity of transactions as a whole must be maintained, that is, either all the operations are executed or none.\nWhen a DBMS recovers from a crash, it should maintain the following −\nIt should check the states of all the transactions, which were being executed.\nIt should check the states of all the transactions, which were being executed.\nA transaction may be in the middle of some operation; the DBMS must ensure the atomicity of the transaction in this case.\nA transaction may be in the middle of some operation; the DBMS must ensure the atomicity of the transaction in this case.\nIt should check whether the transaction can be completed now or it needs to be rolled back.\nIt should check whether the transaction can be completed now or it needs to be rolled back.\nNo transactions would be allowed to leave the DBMS in an inconsistent state.\nNo transactions would be allowed to leave the DBMS in an inconsistent state.\nThere are two types of techniques, which can help a DBMS in recovering as well as maintaining the atomicity of a transaction −\nMaintaining the logs of each transaction, and writing them onto some stable storage before actually modifying the database.\nMaintaining the logs of each transaction, and writing them onto some stable storage before actually modifying the database.\nMaintaining shadow paging, where the changes are done on a volatile memory, and later, the actual database is updated.\nMaintaining shadow paging, where the changes are done on a volatile memory, and later, the actual database is updated.\nLog is a sequence of records, which maintains the records of actions performed by a transaction. It is important that the logs are written prior to the actual modification and stored on a stable storage media, which is failsafe.\nLog-based recovery works as follows −\nThe log file is kept on a stable storage media.\nThe log file is kept on a stable storage media.\nWhen a transaction enters the system and starts execution, it writes a log about it.\nWhen a transaction enters the system and starts execution, it writes a log about it.\n\n\nWhen the transaction modifies an item X, it write logs as follows −\nWhen the transaction modifies an item X, it write logs as follows −\n\n\nIt reads Tn has changed the value of X, from V1 to V2.\nWhen the transaction finishes, it logs −\n\n\nThe database can be modified using two approaches −\nDeferred database modification − All logs are written on to the stable storage and the database is updated when a transaction commits.\nDeferred database modification − All logs are written on to the stable storage and the database is updated when a transaction commits.\nImmediate database modification − Each log follows an actual database modification. That is, the database is modified immediately after every operation.\nImmediate database modification − Each log follows an actual database modification. That is, the database is modified immediately after every operation.\nWhen more than one transaction are being executed in parallel, the logs are interleaved. At the time of recovery, it would become hard for the recovery system to backtrack all logs, and then start recovering. To ease this situation, most modern DBMS use the concept of 'checkpoints'.\nKeeping and maintaining logs in real time and in real environment may fill out all the memory space available in the system. As time passes, the log file may grow too big to be handled at all. Checkpoint is a mechanism where all the previous logs are removed from the system and stored permanently in a storage disk. Checkpoint declares a point before which the DBMS was in consistent state, and all the transactions were committed.\nWhen a system with concurrent transactions crashes and recovers, it behaves in the following manner −\nThe recovery system reads the logs backwards from the end to the last checkpoint.\nThe recovery system reads the logs backwards from the end to the last checkpoint.\nIt maintains two lists, an undo-list and a redo-list.\nIt maintains two lists, an undo-list and a redo-list.\nIf the recovery system sees a log with and or just , it puts the transaction in the redo-list.\nIf the recovery system sees a log with and or just , it puts the transaction in the redo-list.\nIf the recovery system sees a log with but no commit or abort log found, it puts the transaction in undo-list.\nIf the recovery system sees a log with but no commit or abort log found, it puts the transaction in undo-list.\nAll the transactions in the undo-list are then undone and their logs are removed. All the transactions in the redo-list and their previous logs are removed and then redone before saving their logs.\n\n 178 Lectures \n 14.5 hours \n\n Arnab Chakraborty\n\n 194 Lectures \n 16 hours \n\n Arnab Chakraborty\n Print\n Add Notes\n Bookmark this page"},"parsed":{"kind":"list like","value":[{"code":null,"e":2415,"s":2282,"text":"Database is a collection of related data and data is a collection of facts and figures that can be processed to produce information."},{"code":null,"e":2638,"s":2415,"text":"Mostly data represents recordable facts. Data aids in producing information, which is based on facts. For example, if we have data about marks obtained by all students, we can then conclude about toppers and average marks."},{"code":null,"e":2766,"s":2638,"text":"A database management system stores data in such a way that it becomes easier to retrieve, manipulate, and produce information."},{"code":null,"e":3004,"s":2766,"text":"Traditionally, data was organized in file formats. DBMS was a new concept then, and all the research was done to make it overcome the deficiencies in traditional style of data management. A modern DBMS has the following characteristics −"},{"code":null,"e":3246,"s":3004,"text":"Real-world entity − A modern DBMS is more realistic and uses real-world entities to design its architecture. It uses the behavior and attributes too. For example, a school database may use students as an entity and their age as an attribute."},{"code":null,"e":3488,"s":3246,"text":"Real-world entity − A modern DBMS is more realistic and uses real-world entities to design its architecture. It uses the behavior and attributes too. For example, a school database may use students as an entity and their age as an attribute."},{"code":null,"e":3663,"s":3488,"text":"Relation-based tables − DBMS allows entities and relations among them to form tables. A user can understand the architecture of a database just by looking at the table names."},{"code":null,"e":3838,"s":3663,"text":"Relation-based tables − DBMS allows entities and relations among them to form tables. A user can understand the architecture of a database just by looking at the table names."},{"code":null,"e":4118,"s":3838,"text":"Isolation of data and application − A database system is entirely different than its data. A database is an active entity, whereas data is said to be passive, on which the database works and organizes. DBMS also stores metadata, which is data about data, to ease its own process."},{"code":null,"e":4398,"s":4118,"text":"Isolation of data and application − A database system is entirely different than its data. A database is an active entity, whereas data is said to be passive, on which the database works and organizes. DBMS also stores metadata, which is data about data, to ease its own process."},{"code":null,"e":4632,"s":4398,"text":"Less redundancy − DBMS follows the rules of normalization, which splits a relation when any of its attributes is having redundancy in values. Normalization is a mathematically rich and scientific process that reduces data redundancy."},{"code":null,"e":4866,"s":4632,"text":"Less redundancy − DBMS follows the rules of normalization, which splits a relation when any of its attributes is having redundancy in values. Normalization is a mathematically rich and scientific process that reduces data redundancy."},{"code":null,"e":5189,"s":4866,"text":"Consistency − Consistency is a state where every relation in a database remains consistent. There exist methods and techniques, which can detect attempt of leaving database in inconsistent state. A DBMS can provide greater consistency as compared to earlier forms of data storing applications like file-processing systems."},{"code":null,"e":5512,"s":5189,"text":"Consistency − Consistency is a state where every relation in a database remains consistent. There exist methods and techniques, which can detect attempt of leaving database in inconsistent state. A DBMS can provide greater consistency as compared to earlier forms of data storing applications like file-processing systems."},{"code":null,"e":5802,"s":5512,"text":"Query Language − DBMS is equipped with query language, which makes it more efficient to retrieve and manipulate data. A user can apply as many and as different filtering options as required to retrieve a set of data. Traditionally it was not possible where file-processing system was used."},{"code":null,"e":6092,"s":5802,"text":"Query Language − DBMS is equipped with query language, which makes it more efficient to retrieve and manipulate data. A user can apply as many and as different filtering options as required to retrieve a set of data. Traditionally it was not possible where file-processing system was used."},{"code":null,"e":6407,"s":6092,"text":"ACID Properties − DBMS follows the concepts of Atomicity, Consistency, Isolation, and Durability (normally shortened as ACID). These concepts are applied on transactions, which manipulate data in a database. ACID properties help the database stay healthy in multi-transactional environments and in case of failure."},{"code":null,"e":6722,"s":6407,"text":"ACID Properties − DBMS follows the concepts of Atomicity, Consistency, Isolation, and Durability (normally shortened as ACID). These concepts are applied on transactions, which manipulate data in a database. ACID properties help the database stay healthy in multi-transactional environments and in case of failure."},{"code":null,"e":6985,"s":6722,"text":"Multiuser and Concurrent Access − DBMS supports multi-user environment and allows them to access and manipulate data in parallel. Though there are restrictions on transactions when users attempt to handle the same data item, but users are always unaware of them."},{"code":null,"e":7248,"s":6985,"text":"Multiuser and Concurrent Access − DBMS supports multi-user environment and allows them to access and manipulate data in parallel. Though there are restrictions on transactions when users attempt to handle the same data item, but users are always unaware of them."},{"code":null,"e":7549,"s":7248,"text":"Multiple views − DBMS offers multiple views for different users. A user who is in the Sales department will have a different view of database than a person working in the Production department. This feature enables the users to have a concentrate view of the database according to their requirements."},{"code":null,"e":7850,"s":7549,"text":"Multiple views − DBMS offers multiple views for different users. A user who is in the Sales department will have a different view of database than a person working in the Production department. This feature enables the users to have a concentrate view of the database according to their requirements."},{"code":null,"e":8576,"s":7850,"text":"Security − Features like multiple views offer security to some extent where users are unable to access data of other users and departments. DBMS offers methods to impose constraints while entering data into the database and retrieving the same at a later stage. DBMS offers many different levels of security features, which enables multiple users to have different views with different features. For example, a user in the Sales department cannot see the data that belongs to the Purchase department. Additionally, it can also be managed how much data of the Sales department should be displayed to the user. Since a DBMS is not saved on the disk as traditional file systems, it is very hard for miscreants to break the code."},{"code":null,"e":9302,"s":8576,"text":"Security − Features like multiple views offer security to some extent where users are unable to access data of other users and departments. DBMS offers methods to impose constraints while entering data into the database and retrieving the same at a later stage. DBMS offers many different levels of security features, which enables multiple users to have different views with different features. For example, a user in the Sales department cannot see the data that belongs to the Purchase department. Additionally, it can also be managed how much data of the Sales department should be displayed to the user. Since a DBMS is not saved on the disk as traditional file systems, it is very hard for miscreants to break the code."},{"code":null,"e":9506,"s":9302,"text":"A typical DBMS has users with different rights and permissions who use it for different purposes. Some users retrieve data and some back it up. The users of a DBMS can be broadly categorized as follows −"},{"code":null,"e":9923,"s":9506,"text":"Administrators − Administrators maintain the DBMS and are responsible for administrating the database. They are responsible to look after its usage and by whom it should be used. They create access profiles for users and apply limitations to maintain isolation and force security. Administrators also look after DBMS resources like system license, required tools, and other software and hardware related maintenance."},{"code":null,"e":10340,"s":9923,"text":"Administrators − Administrators maintain the DBMS and are responsible for administrating the database. They are responsible to look after its usage and by whom it should be used. They create access profiles for users and apply limitations to maintain isolation and force security. Administrators also look after DBMS resources like system license, required tools, and other software and hardware related maintenance."},{"code":null,"e":10602,"s":10340,"text":"Designers − Designers are the group of people who actually work on the designing part of the database. They keep a close watch on what data should be kept and in what format. They identify and design the whole set of entities, relations, constraints, and views."},{"code":null,"e":10864,"s":10602,"text":"Designers − Designers are the group of people who actually work on the designing part of the database. They keep a close watch on what data should be kept and in what format. They identify and design the whole set of entities, relations, constraints, and views."},{"code":null,"e":11081,"s":10864,"text":"End Users − End users are those who actually reap the benefits of having a DBMS. End users can range from simple viewers who pay attention to the logs or market rates to sophisticated users such as business analysts."},{"code":null,"e":11298,"s":11081,"text":"End Users − End users are those who actually reap the benefits of having a DBMS. End users can range from simple viewers who pay attention to the logs or market rates to sophisticated users such as business analysts."},{"code":null,"e":11636,"s":11298,"text":"The design of a DBMS depends on its architecture. It can be centralized or decentralized or hierarchical. The architecture of a DBMS can be seen as either single tier or multi-tier. An n-tier architecture divides the whole system into related but independent n modules, which can be independently modified, altered, changed, or replaced."},{"code":null,"e":11937,"s":11636,"text":"In 1-tier architecture, the DBMS is the only entity where the user directly sits on the DBMS and uses it. Any changes done here will directly be done on the DBMS itself. It does not provide handy tools for end-users. Database designers and programmers normally prefer to use single-tier architecture."},{"code":null,"e":12254,"s":11937,"text":"If the architecture of DBMS is 2-tier, then it must have an application through which the DBMS can be accessed. Programmers use 2-tier architecture where they access the DBMS by means of an application. Here the application tier is entirely independent of the database in terms of operation, design, and programming."},{"code":null,"e":12458,"s":12254,"text":"A 3-tier architecture separates its tiers from each other based on the complexity of the users and how they use the data present in the database. It is the most widely used architecture to design a DBMS."},{"code":null,"e":12644,"s":12458,"text":"Database (Data) Tier − At this tier, the database resides along with its query processing languages. We also have the relations that define the data and their constraints at this level."},{"code":null,"e":12830,"s":12644,"text":"Database (Data) Tier − At this tier, the database resides along with its query processing languages. We also have the relations that define the data and their constraints at this level."},{"code":null,"e":13308,"s":12830,"text":"Application (Middle) Tier − At this tier reside the application server and the programs that access the database. For a user, this application tier presents an abstracted view of the database. End-users are unaware of any existence of the database beyond the application. At the other end, the database tier is not aware of any other user beyond the application tier. Hence, the application layer sits in the middle and acts as a mediator between the end-user and the database."},{"code":null,"e":13786,"s":13308,"text":"Application (Middle) Tier − At this tier reside the application server and the programs that access the database. For a user, this application tier presents an abstracted view of the database. End-users are unaware of any existence of the database beyond the application. At the other end, the database tier is not aware of any other user beyond the application tier. Hence, the application layer sits in the middle and acts as a mediator between the end-user and the database."},{"code":null,"e":14080,"s":13786,"text":"User (Presentation) Tier − End-users operate on this tier and they know nothing about any existence of the database beyond this layer. At this layer, multiple views of the database can be provided by the application. All views are generated by applications that reside in the application tier."},{"code":null,"e":14374,"s":14080,"text":"User (Presentation) Tier − End-users operate on this tier and they know nothing about any existence of the database beyond this layer. At this layer, multiple views of the database can be provided by the application. All views are generated by applications that reside in the application tier."},{"code":null,"e":14511,"s":14374,"text":"Multiple-tier database architecture is highly modifiable, as almost all its components are independent and can be changed independently."},{"code":null,"e":14767,"s":14511,"text":"Data models define how the logical structure of a database is modeled. Data Models are fundamental entities to introduce abstraction in a DBMS. Data models define how data is connected to each other and how they are processed and stored inside the system."},{"code":null,"e":14999,"s":14767,"text":"The very first data model could be flat data-models, where all the data used are to be kept in the same plane. Earlier data models were not so scientific, hence they were prone to introduce lots of duplication and update anomalies."},{"code":null,"e":15256,"s":14999,"text":"Entity-Relationship (ER) Model is based on the notion of real-world entities and relationships among them. While formulating real-world scenario into the database model, the ER Model creates entity set, relationship set, general attributes and constraints."},{"code":null,"e":15319,"s":15256,"text":"ER Model is best used for the conceptual design of a database."},{"code":null,"e":15342,"s":15319,"text":"ER Model is based on −"},{"code":null,"e":15373,"s":15342,"text":"Entities and their attributes."},{"code":null,"e":15404,"s":15373,"text":"Entities and their attributes."},{"code":null,"e":15434,"s":15404,"text":"Relationships among entities."},{"code":null,"e":15464,"s":15434,"text":"Relationships among entities."},{"code":null,"e":15500,"s":15464,"text":"These concepts are explained below."},{"code":null,"e":15789,"s":15500,"text":"Entity − An entity in an ER Model is a real-world entity having properties called attributes. Every attribute is defined by its set of values called domain. For example, in a school database, a student is considered as an entity. Student has various attributes like name, age, class, etc."},{"code":null,"e":16078,"s":15789,"text":"Entity − An entity in an ER Model is a real-world entity having properties called attributes. Every attribute is defined by its set of values called domain. For example, in a school database, a student is considered as an entity. Student has various attributes like name, age, class, etc."},{"code":null,"e":16364,"s":16078,"text":"Relationship − The logical association among entities is called relationship. Relationships are mapped with entities in various ways. Mapping cardinalities define the number of association between two entities.\nMapping cardinalities −\n\none to one\none to many\nmany to one\nmany to many\n\n"},{"code":null,"e":16575,"s":16364,"text":"Relationship − The logical association among entities is called relationship. Relationships are mapped with entities in various ways. Mapping cardinalities define the number of association between two entities."},{"code":null,"e":16599,"s":16575,"text":"Mapping cardinalities −"},{"code":null,"e":16610,"s":16599,"text":"one to one"},{"code":null,"e":16622,"s":16610,"text":"one to many"},{"code":null,"e":16634,"s":16622,"text":"many to one"},{"code":null,"e":16647,"s":16634,"text":"many to many"},{"code":null,"e":16844,"s":16647,"text":"The most popular data model in DBMS is the Relational Model. It is more scientific a model than others. This model is based on first-order predicate logic and defines a table as an n-ary relation."},{"code":null,"e":16884,"s":16844,"text":"The main highlights of this model are −"},{"code":null,"e":16927,"s":16884,"text":"Data is stored in tables called relations."},{"code":null,"e":16956,"s":16927,"text":"Relations can be normalized."},{"code":null,"e":17013,"s":16956,"text":"In normalized relations, values saved are atomic values."},{"code":null,"e":17061,"s":17013,"text":"Each row in a relation contains a unique value."},{"code":null,"e":17123,"s":17061,"text":"Each column in a relation contains values from a same domain."},{"code":null,"e":17380,"s":17123,"text":"A database schema is the skeleton structure that represents the logical view of the entire database. It defines how the data is organized and how the relations among them are associated. It formulates all the constraints that are to be applied on the data."},{"code":null,"e":17667,"s":17380,"text":"A database schema defines its entities and the relationship among them. It contains a descriptive detail of the database, which can be depicted by means of schema diagrams. It’s the database designers who design the schema to help programmers understand the database and make it useful."},{"code":null,"e":17730,"s":17667,"text":"A database schema can be divided broadly into two categories −"},{"code":null,"e":17921,"s":17730,"text":"Physical Database Schema − This schema pertains to the actual storage of data and its form of storage like files, indices, etc. It defines how the data will be stored in a secondary storage."},{"code":null,"e":18112,"s":17921,"text":"Physical Database Schema − This schema pertains to the actual storage of data and its form of storage like files, indices, etc. It defines how the data will be stored in a secondary storage."},{"code":null,"e":18283,"s":18112,"text":"Logical Database Schema − This schema defines all the logical constraints that need to be applied on the data stored. It defines tables, views, and integrity constraints."},{"code":null,"e":18454,"s":18283,"text":"Logical Database Schema − This schema defines all the logical constraints that need to be applied on the data stored. It defines tables, views, and integrity constraints."},{"code":null,"e":18762,"s":18454,"text":"It is important that we distinguish these two terms individually. Database schema is the skeleton of database. It is designed when the database doesn't exist at all. Once the database is operational, it is very difficult to make any changes to it. A database schema does not contain any data or information."},{"code":null,"e":19114,"s":18762,"text":"A database instance is a state of operational database with data at any given time. It contains a snapshot of the database. Database instances tend to change with time. A DBMS ensures that its every instance (state) is in a valid state, by diligently following all the validations, constraints, and conditions that the database designers have imposed."},{"code":null,"e":19295,"s":19114,"text":"If a database system is not multi-layered, then it becomes difficult to make any changes in the database system. Database systems are designed in multi-layers as we learnt earlier."},{"code":null,"e":19741,"s":19295,"text":"A database system normally contains a lot of data in addition to users’ data. For example, it stores data about data, known as metadata, to locate and retrieve data easily. It is rather difficult to modify or update a set of metadata once it is stored in the database. But as a DBMS expands, it needs to change over time to satisfy the requirements of the users. If the entire data is dependent, it would become a tedious and highly complex job."},{"code":null,"e":19928,"s":19741,"text":"Metadata itself follows a layered architecture, so that when we change data at one layer, it does not affect the data at another level. This data is independent but mapped to each other."},{"code":null,"e":20136,"s":19928,"text":"Logical data is data about database, that is, it stores information about how data is managed inside. For example, a table (relation) stored in the database and all its constraints, applied on that relation."},{"code":null,"e":20339,"s":20136,"text":"Logical data independence is a kind of mechanism, which liberalizes itself from actual data stored on the disk. If we do some changes on table format, it should not change the data residing on the disk."},{"code":null,"e":20539,"s":20339,"text":"All the schemas are logical, and the actual data is stored in bit format on the disk. Physical data independence is the power to change the physical data without impacting the schema or logical data."},{"code":null,"e":20728,"s":20539,"text":"For example, in case we want to change or upgrade the storage system itself − suppose we want to replace hard-disks with SSD − it should not have any impact on the logical data or schemas."},{"code":null,"e":20934,"s":20728,"text":"The ER model defines the conceptual view of a database. It works around real-world entities and the associations among them. At view level, the ER model is considered a good option for designing databases."},{"code":null,"e":21234,"s":20934,"text":"An entity can be a real-world object, either animate or inanimate, that can be easily identifiable. For example, in a school database, students, teachers, classes, and courses offered can be considered as entities. All these entities have some attributes or properties that give them their identity."},{"code":null,"e":21557,"s":21234,"text":"An entity set is a collection of similar types of entities. An entity set may contain entities with attribute sharing similar values. For example, a Students set may contain all the students of a school; likewise a Teachers set may contain all the teachers of a school from all faculties. Entity sets need not be disjoint."},{"code":null,"e":21734,"s":21557,"text":"Entities are represented by means of their properties, called attributes. All attributes have values. For example, a student entity may have name, class, and age as attributes."},{"code":null,"e":21934,"s":21734,"text":"There exists a domain or range of values that can be assigned to attributes. For example, a student's name cannot be a numeric value. It has to be alphabetic. A student's age cannot be negative, etc."},{"code":null,"e":22094,"s":21934,"text":"Simple attribute − Simple attributes are atomic values, which cannot be divided further. For example, a student's phone number is an atomic value of 10 digits."},{"code":null,"e":22254,"s":22094,"text":"Simple attribute − Simple attributes are atomic values, which cannot be divided further. For example, a student's phone number is an atomic value of 10 digits."},{"code":null,"e":22415,"s":22254,"text":"Composite attribute − Composite attributes are made of more than one simple attribute. For example, a student's complete name may have first_name and last_name."},{"code":null,"e":22576,"s":22415,"text":"Composite attribute − Composite attributes are made of more than one simple attribute. For example, a student's complete name may have first_name and last_name."},{"code":null,"e":22931,"s":22576,"text":"Derived attribute − Derived attributes are the attributes that do not exist in the physical database, but their values are derived from other attributes present in the database. For example, average_salary in a department should not be saved directly in the database, instead it can be derived. For another example, age can be derived from data_of_birth."},{"code":null,"e":23286,"s":22931,"text":"Derived attribute − Derived attributes are the attributes that do not exist in the physical database, but their values are derived from other attributes present in the database. For example, average_salary in a department should not be saved directly in the database, instead it can be derived. For another example, age can be derived from data_of_birth."},{"code":null,"e":23395,"s":23286,"text":"Single-value attribute − Single-value attributes contain single value. For example − Social_Security_Number."},{"code":null,"e":23504,"s":23395,"text":"Single-value attribute − Single-value attributes contain single value. For example − Social_Security_Number."},{"code":null,"e":23664,"s":23504,"text":"Multi-value attribute − Multi-value attributes may contain more than one values. For example, a person can have more than one phone number, email_address, etc."},{"code":null,"e":23824,"s":23664,"text":"Multi-value attribute − Multi-value attributes may contain more than one values. For example, a person can have more than one phone number, email_address, etc."},{"code":null,"e":23880,"s":23824,"text":"These attribute types can come together in a way like −"},{"code":null,"e":23912,"s":23880,"text":"simple single-valued attributes"},{"code":null,"e":23943,"s":23912,"text":"simple multi-valued attributes"},{"code":null,"e":23978,"s":23943,"text":"composite single-valued attributes"},{"code":null,"e":24012,"s":23978,"text":"composite multi-valued attributes"},{"code":null,"e":24113,"s":24012,"text":"Key is an attribute or collection of attributes that uniquely identifies an entity among entity set."},{"code":null,"e":24198,"s":24113,"text":"For example, the roll_number of a student makes him/her identifiable among students."},{"code":null,"e":24301,"s":24198,"text":"Super Key − A set of attributes (one or more) that collectively identifies an entity in an entity set."},{"code":null,"e":24404,"s":24301,"text":"Super Key − A set of attributes (one or more) that collectively identifies an entity in an entity set."},{"code":null,"e":24519,"s":24404,"text":"Candidate Key − A minimal super key is called a candidate key. An entity set may have more than one candidate key."},{"code":null,"e":24634,"s":24519,"text":"Candidate Key − A minimal super key is called a candidate key. An entity set may have more than one candidate key."},{"code":null,"e":24760,"s":24634,"text":"Primary Key − A primary key is one of the candidate keys chosen by the database designer to uniquely identify the entity set."},{"code":null,"e":24886,"s":24760,"text":"Primary Key − A primary key is one of the candidate keys chosen by the database designer to uniquely identify the entity set."},{"code":null,"e":25075,"s":24886,"text":"The association among entities is called a relationship. For example, an employee works_at a department, a student enrolls in a course. Here, Works_at and Enrolls are called relationships."},{"code":null,"e":25251,"s":25075,"text":"A set of relationships of similar type is called a relationship set. Like entities, a relationship too can have attributes. These attributes are called descriptive attributes."},{"code":null,"e":25346,"s":25251,"text":"The number of participating entities in a relationship defines the degree of the relationship."},{"code":null,"e":25364,"s":25346,"text":"Binary = degree 2"},{"code":null,"e":25383,"s":25364,"text":"Ternary = degree 3"},{"code":null,"e":25398,"s":25383,"text":"n-ary = degree"},{"code":null,"e":25547,"s":25398,"text":"Cardinality defines the number of entities in one entity set, which can be associated with the number of entities of other set via relationship set."},{"code":null,"e":25663,"s":25547,"text":"One-to-one − One entity from entity set A can be associated with at most one entity of entity set B and vice versa."},{"code":null,"e":25779,"s":25663,"text":"One-to-one − One entity from entity set A can be associated with at most one entity of entity set B and vice versa."},{"code":null,"e":25964,"s":25779,"text":"One-to-many − One entity from entity set A can be associated with more than one entities of entity set B however an entity from entity set B, can be associated with at most one entity."},{"code":null,"e":26149,"s":25964,"text":"One-to-many − One entity from entity set A can be associated with more than one entities of entity set B however an entity from entity set B, can be associated with at most one entity."},{"code":null,"e":26362,"s":26149,"text":"Many-to-one − More than one entities from entity set A can be associated with at most one entity of entity set B, however an entity from entity set B can be associated with more than one entity from entity set A."},{"code":null,"e":26575,"s":26362,"text":"Many-to-one − More than one entities from entity set A can be associated with at most one entity of entity set B, however an entity from entity set B can be associated with more than one entity from entity set A."},{"code":null,"e":26675,"s":26575,"text":"Many-to-many − One entity from A can be associated with more than one entity from B and vice versa."},{"code":null,"e":26775,"s":26675,"text":"Many-to-many − One entity from A can be associated with more than one entity from B and vice versa."},{"code":null,"e":27018,"s":26775,"text":"Let us now learn how the ER Model is represented by means of an ER diagram. Any object, for example, entities, attributes of an entity, relationship sets, and attributes of relationship sets, can be represented with the help of an ER diagram."},{"code":null,"e":27124,"s":27018,"text":"Entities are represented by means of rectangles. Rectangles are named with the entity set they represent."},{"code":null,"e":27308,"s":27124,"text":"Attributes are the properties of entities. Attributes are represented by means of ellipses. Every ellipse represents one attribute and is directly connected to its entity (rectangle)."},{"code":null,"e":27533,"s":27308,"text":"If the attributes are composite, they are further divided in a tree like structure. Every node is then connected to its attribute. That is, composite attributes are represented by ellipses that are connected with an ellipse."},{"code":null,"e":27588,"s":27533,"text":"Multivalued attributes are depicted by double ellipse."},{"code":null,"e":27639,"s":27588,"text":"Derived attributes are depicted by dashed ellipse."},{"code":null,"e":27846,"s":27639,"text":"Relationships are represented by diamond-shaped box. Name of the relationship is written inside the diamond-box. All the entities (rectangles) participating in a relationship, are connected to it by a line."},{"code":null,"e":28040,"s":27846,"text":"A relationship where two entities are participating is called a binary relationship. Cardinality is the number of instance of an entity from a relation that can be associated with the relation."},{"code":null,"e":28296,"s":28040,"text":"One-to-one − When only one instance of an entity is associated with the relationship, it is marked as '1:1'. The following image reflects that only one instance of each entity should be associated with the relationship. It depicts one-to-one relationship."},{"code":null,"e":28552,"s":28296,"text":"One-to-one − When only one instance of an entity is associated with the relationship, it is marked as '1:1'. The following image reflects that only one instance of each entity should be associated with the relationship. It depicts one-to-one relationship."},{"code":null,"e":28870,"s":28552,"text":"One-to-many − When more than one instance of an entity is associated with a relationship, it is marked as '1:N'. The following image reflects that only one instance of entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts one-to-many relationship."},{"code":null,"e":29188,"s":28870,"text":"One-to-many − When more than one instance of an entity is associated with a relationship, it is marked as '1:N'. The following image reflects that only one instance of entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts one-to-many relationship."},{"code":null,"e":29508,"s":29188,"text":"Many-to-one − When more than one instance of entity is associated with the relationship, it is marked as 'N:1'. The following image reflects that more than one instance of an entity on the left and only one instance of an entity on the right can be associated with the relationship. It depicts many-to-one relationship."},{"code":null,"e":29828,"s":29508,"text":"Many-to-one − When more than one instance of entity is associated with the relationship, it is marked as 'N:1'. The following image reflects that more than one instance of an entity on the left and only one instance of an entity on the right can be associated with the relationship. It depicts many-to-one relationship."},{"code":null,"e":30057,"s":29828,"text":"Many-to-many − The following image reflects that more than one instance of an entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts many-to-many relationship."},{"code":null,"e":30286,"s":30057,"text":"Many-to-many − The following image reflects that more than one instance of an entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts many-to-many relationship."},{"code":null,"e":30405,"s":30286,"text":"Total Participation − Each entity is involved in the relationship. Total participation is represented by double lines."},{"code":null,"e":30524,"s":30405,"text":"Total Participation − Each entity is involved in the relationship. Total participation is represented by double lines."},{"code":null,"e":30653,"s":30524,"text":"Partial participation − Not all entities are involved in the relationship. Partial participation is represented by single lines."},{"code":null,"e":30782,"s":30653,"text":"Partial participation − Not all entities are involved in the relationship. Partial participation is represented by single lines."},{"code":null,"e":31025,"s":30782,"text":"Let us now learn how the ER Model is represented by means of an ER diagram. Any object, for example, entities, attributes of an entity, relationship sets, and attributes of relationship sets, can be represented with the help of an ER diagram."},{"code":null,"e":31131,"s":31025,"text":"Entities are represented by means of rectangles. Rectangles are named with the entity set they represent."},{"code":null,"e":31315,"s":31131,"text":"Attributes are the properties of entities. Attributes are represented by means of ellipses. Every ellipse represents one attribute and is directly connected to its entity (rectangle)."},{"code":null,"e":31540,"s":31315,"text":"If the attributes are composite, they are further divided in a tree like structure. Every node is then connected to its attribute. That is, composite attributes are represented by ellipses that are connected with an ellipse."},{"code":null,"e":31595,"s":31540,"text":"Multivalued attributes are depicted by double ellipse."},{"code":null,"e":31646,"s":31595,"text":"Derived attributes are depicted by dashed ellipse."},{"code":null,"e":31853,"s":31646,"text":"Relationships are represented by diamond-shaped box. Name of the relationship is written inside the diamond-box. All the entities (rectangles) participating in a relationship, are connected to it by a line."},{"code":null,"e":32047,"s":31853,"text":"A relationship where two entities are participating is called a binary relationship. Cardinality is the number of instance of an entity from a relation that can be associated with the relation."},{"code":null,"e":32303,"s":32047,"text":"One-to-one − When only one instance of an entity is associated with the relationship, it is marked as '1:1'. The following image reflects that only one instance of each entity should be associated with the relationship. It depicts one-to-one relationship."},{"code":null,"e":32559,"s":32303,"text":"One-to-one − When only one instance of an entity is associated with the relationship, it is marked as '1:1'. The following image reflects that only one instance of each entity should be associated with the relationship. It depicts one-to-one relationship."},{"code":null,"e":32877,"s":32559,"text":"One-to-many − When more than one instance of an entity is associated with a relationship, it is marked as '1:N'. The following image reflects that only one instance of entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts one-to-many relationship."},{"code":null,"e":33195,"s":32877,"text":"One-to-many − When more than one instance of an entity is associated with a relationship, it is marked as '1:N'. The following image reflects that only one instance of entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts one-to-many relationship."},{"code":null,"e":33515,"s":33195,"text":"Many-to-one − When more than one instance of entity is associated with the relationship, it is marked as 'N:1'. The following image reflects that more than one instance of an entity on the left and only one instance of an entity on the right can be associated with the relationship. It depicts many-to-one relationship."},{"code":null,"e":33835,"s":33515,"text":"Many-to-one − When more than one instance of entity is associated with the relationship, it is marked as 'N:1'. The following image reflects that more than one instance of an entity on the left and only one instance of an entity on the right can be associated with the relationship. It depicts many-to-one relationship."},{"code":null,"e":34064,"s":33835,"text":"Many-to-many − The following image reflects that more than one instance of an entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts many-to-many relationship."},{"code":null,"e":34293,"s":34064,"text":"Many-to-many − The following image reflects that more than one instance of an entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts many-to-many relationship."},{"code":null,"e":34412,"s":34293,"text":"Total Participation − Each entity is involved in the relationship. Total participation is represented by double lines."},{"code":null,"e":34531,"s":34412,"text":"Total Participation − Each entity is involved in the relationship. Total participation is represented by double lines."},{"code":null,"e":34660,"s":34531,"text":"Partial participation − Not all entities are involved in the relationship. Partial participation is represented by single lines."},{"code":null,"e":34789,"s":34660,"text":"Partial participation − Not all entities are involved in the relationship. Partial participation is represented by single lines."},{"code":null,"e":35033,"s":34789,"text":"The ER Model has the power of expressing database entities in a conceptual hierarchical manner. As the hierarchy goes up, it generalizes the view of entities, and as we go deep in the hierarchy, it gives us the detail of every entity included."},{"code":null,"e":35414,"s":35033,"text":"Going up in this structure is called generalization, where entities are clubbed together to represent a more generalized view. For example, a particular student named Mira can be generalized along with all the students. The entity shall be a student, and further, the student is a person. The reverse is called specialization where a person is a student, and that student is Mira."},{"code":null,"e":35797,"s":35414,"text":"As mentioned above, the process of generalizing entities, where the generalized entities contain the properties of all the generalized entities, is called generalization. In generalization, a number of entities are brought together into one generalized entity based on their similar characteristics. For example, pigeon, house sparrow, crow and dove can all be generalized as Birds."},{"code":null,"e":36218,"s":35797,"text":"Specialization is the opposite of generalization. In specialization, a group of entities is divided into sub-groups based on their characteristics. Take a group ‘Person’ for example. A person has name, date of birth, gender, etc. These properties are common in all persons, human beings. But in a company, persons can be identified as employee, employer, customer, or vendor, based on what role they play in the company."},{"code":null,"e":36363,"s":36218,"text":"Similarly, in a school database, persons can be specialized as teacher, student, or a staff, based on what role they play in school as entities."},{"code":null,"e":36570,"s":36363,"text":"We use all the above features of ER-Model in order to create classes of objects in object-oriented programming. The details of entities are generally hidden from the user; this process known as abstraction."},{"code":null,"e":36727,"s":36570,"text":"Inheritance is an important feature of Generalization and Specialization. It allows lower-level entities to inherit the attributes of higher-level entities."},{"code":null,"e":36872,"s":36727,"text":"For example, the attributes of a Person class such as name, age, and gender can be inherited by lower-level entities such as Student or Teacher."},{"code":null,"e":37102,"s":36872,"text":"Dr Edgar F. Codd, after his extensive research on the Relational Model of database systems, came up with twelve rules of his own, which according to him, a database must obey in order to be regarded as a true relational database."},{"code":null,"e":37290,"s":37102,"text":"These rules can be applied on any database system that manages stored data using only its relational capabilities. This is a foundation rule, which acts as a base for all the other rules."},{"code":null,"e":37449,"s":37290,"text":"The data stored in a database, may it be user data or metadata, must be a value of some table cell. Everything in a database must be stored in a table format."},{"code":null,"e":37680,"s":37449,"text":"Every single data element (value) is guaranteed to be accessible logically with a combination of table-name, primary-key (row value), and attribute-name (column value). No other means, such as pointers, can be used to access data."},{"code":null,"e":37910,"s":37680,"text":"The NULL values in a database must be given a systematic and uniform treatment. This is a very important rule because a NULL can be interpreted as one the following − data is missing, data is not known, or data is not applicable."},{"code":null,"e":38171,"s":37910,"text":"The structure description of the entire database must be stored in an online catalog, known as data dictionary, which can be accessed by authorized users. Users can use the same query language to access the catalog which they use to access the database itself."},{"code":null,"e":38509,"s":38171,"text":"A database can only be accessed using a language having linear syntax that supports data definition, data manipulation, and transaction management operations. This language can be used directly or by means of some application. If the database allows access to data without any help of this language, then it is considered as a violation."},{"code":null,"e":38612,"s":38509,"text":"All the views of a database, which can theoretically be updated, must also be updatable by the system."},{"code":null,"e":38826,"s":38612,"text":"A database must support high-level insertion, updation, and deletion. This must not be limited to a single row, that is, it must also support union, intersection and minus operations to yield sets of data records."},{"code":null,"e":39058,"s":38826,"text":"The data stored in a database must be independent of the applications that access the database. Any change in the physical structure of a database must not have any impact on how the data is being accessed by external applications."},{"code":null,"e":39404,"s":39058,"text":"The logical data in a database must be independent of its user’s view (application). Any change in logical data must not affect the applications using it. For example, if two tables are merged or one is split into two different tables, there should be no impact or change on the user application. This is one of the most difficult rule to apply."},{"code":null,"e":39666,"s":39404,"text":"A database must be independent of the application that uses it. All its integrity constraints can be independently modified without the need of any change in the application. This rule makes a database independent of the front-end application and its interface."},{"code":null,"e":39917,"s":39666,"text":"The end-user must not be able to see that the data is distributed over various locations. Users should always get the impression that the data is located at one site only. This rule has been regarded as the foundation of distributed database systems."},{"code":null,"e":40094,"s":39917,"text":"If a system has an interface that provides access to low-level records, then the interface must not be able to subvert the system and bypass security and integrity constraints."},{"code":null,"e":40332,"s":40094,"text":"Relational data model is the primary data model, which is used widely around the world for data storage and processing. This model is simple and it has all the properties and capabilities required to process data with storage efficiency."},{"code":null,"e":40558,"s":40332,"text":"Tables − In relational data model, relations are saved in the format of Tables. This format stores the relation among entities. A table has rows and columns, where rows represents records and columns represent the attributes."},{"code":null,"e":40659,"s":40558,"text":"Tuple − A single row of a table, which contains a single record for that relation is called a tuple."},{"code":null,"e":40815,"s":40659,"text":"Relation instance − A finite set of tuples in the relational database system represents relation instance. Relation instances do not have duplicate tuples."},{"code":null,"e":40922,"s":40815,"text":"Relation schema − A relation schema describes the relation name (table name), attributes, and their names."},{"code":null,"e":41058,"s":40922,"text":"Relation key − Each row has one or more attributes, known as relation key, which can identify the row in the relation (table) uniquely."},{"code":null,"e":41154,"s":41058,"text":"Attribute domain − Every attribute has some pre-defined value scope, known as attribute domain."},{"code":null,"e":41343,"s":41154,"text":"Every relation has some conditions that must hold for it to be a valid relation. These conditions are called Relational Integrity Constraints. There are three main integrity constraints −"},{"code":null,"e":41359,"s":41343,"text":"Key constraints"},{"code":null,"e":41378,"s":41359,"text":"Domain constraints"},{"code":null,"e":41412,"s":41378,"text":"Referential integrity constraints"},{"code":null,"e":41671,"s":41412,"text":"There must be at least one minimal subset of attributes in the relation, which can identify a tuple uniquely. This minimal subset of attributes is called key for that relation. If there are more than one such minimal subsets, these are called candidate keys."},{"code":null,"e":41700,"s":41671,"text":"Key constraints force that −"},{"code":null,"e":41796,"s":41700,"text":"in a relation with a key attribute, no two tuples can have identical values for key attributes."},{"code":null,"e":41892,"s":41796,"text":"in a relation with a key attribute, no two tuples can have identical values for key attributes."},{"code":null,"e":41934,"s":41892,"text":"a key attribute can not have NULL values."},{"code":null,"e":41976,"s":41934,"text":"a key attribute can not have NULL values."},{"code":null,"e":42036,"s":41976,"text":"Key constraints are also referred to as Entity Constraints."},{"code":null,"e":42382,"s":42036,"text":"Attributes have specific values in real-world scenario. For example, age can only be a positive integer. The same constraints have been tried to employ on the attributes of a relation. Every attribute is bound to have a specific range of values. For example, age cannot be less than zero and telephone numbers cannot contain a digit outside 0-9."},{"code":null,"e":42540,"s":42382,"text":"Referential integrity constraints work on the concept of Foreign Keys. A foreign key is a key attribute of a relation that can be referred in other relation."},{"code":null,"e":42692,"s":42540,"text":"Referential integrity constraint states that if a relation refers to a key attribute of a different or same relation, then that key element must exist."},{"code":null,"e":42914,"s":42692,"text":"Relational database systems are expected to be equipped with a query language that can assist its users to query the database instances. There are two kinds of query languages − relational algebra and relational calculus."},{"code":null,"e":43324,"s":42914,"text":"Relational algebra is a procedural query language, which takes instances of relations as input and yields instances of relations as output. It uses operators to perform queries. An operator can be either unary or binary. They accept relations as their input and yield relations as their output. Relational algebra is performed recursively on a relation and intermediate results are also considered relations."},{"code":null,"e":43390,"s":43324,"text":"The fundamental operations of relational algebra are as follows −"},{"code":null,"e":43397,"s":43390,"text":"Select"},{"code":null,"e":43405,"s":43397,"text":"Project"},{"code":null,"e":43411,"s":43405,"text":"Union"},{"code":null,"e":43425,"s":43411,"text":"Set different"},{"code":null,"e":43443,"s":43425,"text":"Cartesian product"},{"code":null,"e":43450,"s":43443,"text":"Rename"},{"code":null,"e":43514,"s":43450,"text":"We will discuss all these operations in the following sections."},{"code":null,"e":43582,"s":43514,"text":"It selects tuples that satisfy the given predicate from a relation."},{"code":null,"e":43599,"s":43582,"text":"Notation − σp(r)"},{"code":null,"e":43816,"s":43599,"text":"Where σ stands for selection predicate and r stands for relation. p is prepositional logic formula which may use connectors like and, or, and not. These terms may use relational operators like − =, ≠, ≥, < , >, ≤."},{"code":null,"e":43830,"s":43816,"text":"For example −"},{"code":null,"e":43858,"s":43830,"text":"σsubject=\"database\"(Books)\n"},{"code":null,"e":43885,"s":43858,"text":"σsubject=\"database\"(Books)"},{"code":null,"e":43949,"s":43885,"text":"Output − Selects tuples from books where subject is 'database'."},{"code":null,"e":43993,"s":43949,"text":"σsubject=\"database\" and price=\"450\"(Books)\n"},{"code":null,"e":44036,"s":43993,"text":"σsubject=\"database\" and price=\"450\"(Books)"},{"code":null,"e":44119,"s":44036,"text":"Output − Selects tuples from books where subject is 'database' and 'price' is 450."},{"code":null,"e":44182,"s":44119,"text":"σsubject=\"database\" and price < \"450\" or year > \"2010\"(Books)\n"},{"code":null,"e":44244,"s":44182,"text":"σsubject=\"database\" and price < \"450\" or year > \"2010\"(Books)"},{"code":null,"e":44363,"s":44244,"text":"Output − Selects tuples from books where subject is 'database' and 'price' is 450 or those books published after 2010."},{"code":null,"e":44417,"s":44363,"text":"It projects column(s) that satisfy a given predicate."},{"code":null,"e":44444,"s":44417,"text":"Notation − ∏A1, A2, An (r)"},{"code":null,"e":44497,"s":44444,"text":"Where A1, A2 , An are attribute names of relation r."},{"code":null,"e":44564,"s":44497,"text":"Duplicate rows are automatically eliminated, as relation is a set."},{"code":null,"e":44578,"s":44564,"text":"For example −"},{"code":null,"e":44605,"s":44578,"text":" ∏subject, author (Books)\n"},{"code":null,"e":44631,"s":44605,"text":" ∏subject, author (Books)"},{"code":null,"e":44713,"s":44631,"text":"Selects and projects columns named as subject and author from the relation Books."},{"code":null,"e":44786,"s":44713,"text":"It performs binary union between two given relations and is defined as −"},{"code":null,"e":44819,"s":44786,"text":" r ∪ s = { t | t ∈ r or t ∈ s} \n"},{"code":null,"e":44851,"s":44819,"text":" r ∪ s = { t | t ∈ r or t ∈ s} "},{"code":null,"e":44869,"s":44851,"text":"Notation − r U s "},{"code":null,"e":44958,"s":44869,"text":"Where r and s are either database relations or relation result set (temporary relation)."},{"code":null,"e":45030,"s":44958,"text":"For a union operation to be valid, the following conditions must hold −"},{"code":null,"e":45080,"s":45030,"text":"r, and s must have the same number of attributes."},{"code":null,"e":45118,"s":45080,"text":"Attribute domains must be compatible."},{"code":null,"e":45165,"s":45118,"text":"Duplicate tuples are automatically eliminated."},{"code":null,"e":45206,"s":45165,"text":" ∏ author (Books) ∪ ∏ author (Articles)\n"},{"code":null,"e":45246,"s":45206,"text":" ∏ author (Books) ∪ ∏ author (Articles)"},{"code":null,"e":45343,"s":45246,"text":"Output − Projects the names of the authors who have either written a book or an article or both."},{"code":null,"e":45463,"s":45343,"text":"The result of set difference operation is tuples, which are present in one relation but are not in the second relation."},{"code":null,"e":45480,"s":45463,"text":"Notation − r − s"},{"code":null,"e":45537,"s":45480,"text":"Finds all the tuples that are present in r but not in s."},{"code":null,"e":45578,"s":45537,"text":" ∏ author (Books) − ∏ author (Articles)\n"},{"code":null,"e":45618,"s":45578,"text":" ∏ author (Books) − ∏ author (Articles)"},{"code":null,"e":45697,"s":45618,"text":"Output − Provides the name of authors who have written books but not articles."},{"code":null,"e":45756,"s":45697,"text":"Combines information of two different relations into one. "},{"code":null,"e":45773,"s":45756,"text":"Notation − r Χ s"},{"code":null,"e":45839,"s":45773,"text":"Where r and s are relations and their output will be defined as −"},{"code":null,"e":45874,"s":45839,"text":"r Χ s = { q t | q ∈ r and t ∈ s}"},{"code":null,"e":45923,"s":45874,"text":" ∏ author = 'tutorialspoint'(Books Χ Articles) \n"},{"code":null,"e":45971,"s":45923,"text":" ∏ author = 'tutorialspoint'(Books Χ Articles) "},{"code":null,"e":46065,"s":45971,"text":"Output − Yields a relation, which shows all the books and articles written by tutorialspoint."},{"code":null,"e":46263,"s":46065,"text":"The results of relational algebra are also relations but without any name. The rename operation allows us to rename the output relation. 'rename' operation is denoted with small Greek letter rho ρ."},{"code":null,"e":46282,"s":46263,"text":"Notation − ρ x (E)"},{"code":null,"e":46340,"s":46282,"text":"Where the result of expression E is saved with name of x."},{"code":null,"e":46368,"s":46340,"text":"Additional operations are −"},{"code":null,"e":46385,"s":46368,"text":"Set intersection"},{"code":null,"e":46396,"s":46385,"text":"Assignment"},{"code":null,"e":46409,"s":46396,"text":"Natural join"},{"code":null,"e":46562,"s":46409,"text":"In contrast to Relational Algebra, Relational Calculus is a non-procedural query language, that is, it tells what to do but never explains how to do it."},{"code":null,"e":46604,"s":46562,"text":"Relational calculus exists in two forms −"},{"code":null,"e":46642,"s":46604,"text":"Filtering variable ranges over tuples"},{"code":null,"e":46670,"s":46642,"text":"Notation − {T | Condition} "},{"code":null,"e":46719,"s":46670,"text":"Returns all tuples T that satisfies a condition."},{"code":null,"e":46733,"s":46719,"text":"For example −"},{"code":null,"e":46785,"s":46733,"text":"{ T.name | Author(T) AND T.article = 'database' }\n"},{"code":null,"e":46872,"s":46785,"text":"Output − Returns tuples with 'name' from Author who has written article on 'database'."},{"code":null,"e":46953,"s":46872,"text":"TRC can be quantified. We can use Existential (∃) and Universal Quantifiers (∀)."},{"code":null,"e":46967,"s":46953,"text":"For example −"},{"code":null,"e":47029,"s":46967,"text":"{ R| ∃T ∈ Authors(T.article='database' AND R.name=T.name)}\n"},{"code":null,"e":47102,"s":47029,"text":"Output − The above query will yield the same result as the previous one."},{"code":null,"e":47229,"s":47102,"text":"In DRC, the filtering variable uses the domain of attributes instead of entire tuple values (as done in TRC, mentioned above)."},{"code":null,"e":47240,"s":47229,"text":"Notation −"},{"code":null,"e":47289,"s":47240,"text":"{ a1, a2, a3, ..., an | P (a1, a2, a3, ... ,an)}"},{"code":null,"e":47370,"s":47289,"text":"Where a1, a2 are attributes and P stands for formulae built by inner attributes."},{"code":null,"e":47384,"s":47370,"text":"For example −"},{"code":null,"e":47457,"s":47384,"text":"{< article, page, subject > | ∈ TutorialsPoint ∧ subject = 'database'}\n"},{"code":null,"e":47529,"s":47457,"text":"{< article, page, subject > | ∈ TutorialsPoint ∧ subject = 'database'}"},{"code":null,"e":47633,"s":47529,"text":"Output − Yields Article, Page, and Subject from the relation TutorialsPoint, where subject is database."},{"code":null,"e":47758,"s":47633,"text":"Just like TRC, DRC can also be written using existential and universal quantifiers. DRC also involves relational operators."},{"code":null,"e":47872,"s":47758,"text":"The expression power of Tuple Relation Calculus and Domain Relation Calculus is equivalent to Relational Algebra."},{"code":null,"e":48219,"s":47872,"text":"ER Model, when conceptualized into diagrams, gives a good overview of entity-relationship, which is easier to understand. ER diagrams can be mapped to relational schema, that is, it is possible to create relational schema using ER diagram. We cannot import all the ER constraints into relational model, but an approximate schema can be generated."},{"code":null,"e":48447,"s":48219,"text":"There are several processes and algorithms available to convert ER Diagrams into Relational Schema. Some of them are automated and some of them are manual. We may focus here on the mapping diagram contents to relational basics."},{"code":null,"e":48480,"s":48447,"text":"ER diagrams mainly comprise of −"},{"code":null,"e":48506,"s":48480,"text":"Entity and its attributes"},{"code":null,"e":48557,"s":48506,"text":"Relationship, which is association among entities."},{"code":null,"e":48612,"s":48557,"text":"An entity is a real-world object with some attributes."},{"code":null,"e":48642,"s":48612,"text":"Create table for each entity."},{"code":null,"e":48727,"s":48642,"text":"Entity's attributes should become fields of tables with their respective data types."},{"code":null,"e":48748,"s":48727,"text":"Declare primary key."},{"code":null,"e":48797,"s":48748,"text":"A relationship is an association among entities."},{"code":null,"e":48830,"s":48797,"text":"Create table for a relationship."},{"code":null,"e":48934,"s":48830,"text":"Add the primary keys of all participating Entities as fields of table with their respective data types."},{"code":null,"e":49007,"s":48934,"text":"If relationship has any attribute, add each attribute as field of table."},{"code":null,"e":49087,"s":49007,"text":"Declare a primary key composing all the primary keys of participating entities."},{"code":null,"e":49124,"s":49087,"text":"Declare all foreign key constraints."},{"code":null,"e":49205,"s":49124,"text":"A weak entity set is one which does not have any primary key associated with it."},{"code":null,"e":49239,"s":49205,"text":"Create table for weak entity set."},{"code":null,"e":49281,"s":49239,"text":"Add all its attributes to table as field."},{"code":null,"e":49328,"s":49281,"text":"Add the primary key of identifying entity set."},{"code":null,"e":49365,"s":49328,"text":"Declare all foreign key constraints."},{"code":null,"e":49448,"s":49365,"text":"ER specialization or generalization comes in the form of hierarchical entity sets."},{"code":null,"e":49493,"s":49448,"text":"Create tables for all higher-level entities."},{"code":null,"e":49538,"s":49493,"text":"Create tables for all higher-level entities."},{"code":null,"e":49578,"s":49538,"text":"Create tables for lower-level entities."},{"code":null,"e":49618,"s":49578,"text":"Create tables for lower-level entities."},{"code":null,"e":49698,"s":49618,"text":"Add primary keys of higher-level entities in the table of lower-level entities."},{"code":null,"e":49778,"s":49698,"text":"Add primary keys of higher-level entities in the table of lower-level entities."},{"code":null,"e":49851,"s":49778,"text":"In lower-level tables, add all other attributes of lower-level entities."},{"code":null,"e":49924,"s":49851,"text":"In lower-level tables, add all other attributes of lower-level entities."},{"code":null,"e":50009,"s":49924,"text":"Declare primary key of higher-level table and the primary key for lower-level table."},{"code":null,"e":50094,"s":50009,"text":"Declare primary key of higher-level table and the primary key for lower-level table."},{"code":null,"e":50127,"s":50094,"text":"Declare foreign key constraints."},{"code":null,"e":50160,"s":50127,"text":"Declare foreign key constraints."},{"code":null,"e":50348,"s":50160,"text":"SQL is a programming language for Relational Databases. It is designed over relational algebra and tuple relational calculus. SQL comes as a package with all major distributions of RDBMS."},{"code":null,"e":50594,"s":50348,"text":"SQL comprises both data definition and data manipulation languages. Using the data definition properties of SQL, one can design and modify database schema, whereas data manipulation properties allows SQL to store and retrieve data from database."},{"code":null,"e":50661,"s":50594,"text":"SQL uses the following set of commands to define database schema −"},{"code":null,"e":50713,"s":50661,"text":"Creates new databases, tables and views from RDBMS."},{"code":null,"e":50727,"s":50713,"text":"For example −"},{"code":null,"e":50808,"s":50727,"text":"Create database tutorialspoint;\nCreate table article;\nCreate view for_students;\n"},{"code":null,"e":50865,"s":50808,"text":"Drops commands, views, tables, and databases from RDBMS."},{"code":null,"e":50878,"s":50865,"text":"For example−"},{"code":null,"e":50983,"s":50878,"text":"Drop object_type object_name;\nDrop database tutorialspoint;\nDrop table article;\nDrop view for_students;\n"},{"code":null,"e":51009,"s":50983,"text":"Modifies database schema."},{"code":null,"e":51052,"s":51009,"text":"Alter object_type object_name parameters;\n"},{"code":null,"e":51065,"s":51052,"text":"For example−"},{"code":null,"e":51107,"s":51065,"text":"Alter table article add subject varchar;\n"},{"code":null,"e":51200,"s":51107,"text":"This command adds an attribute in the relation article with the name subject of string type."},{"code":null,"e":51466,"s":51200,"text":"SQL is equipped with data manipulation language (DML). DML modifies the database instance by inserting, updating and deleting its data. DML is responsible for all forms data modification in a database. SQL contains the following set of commands in its DML section −"},{"code":null,"e":51484,"s":51466,"text":"SELECT/FROM/WHERE"},{"code":null,"e":51503,"s":51484,"text":"INSERT INTO/VALUES"},{"code":null,"e":51520,"s":51503,"text":"UPDATE/SET/WHERE"},{"code":null,"e":51538,"s":51520,"text":"DELETE FROM/WHERE"},{"code":null,"e":51705,"s":51538,"text":"These basic constructs allow database programmers and users to enter data and information into the database and retrieve efficiently using a number of filter options."},{"code":null,"e":51908,"s":51705,"text":"SELECT − This is one of the fundamental query command of SQL. It is similar to the projection operation of relational algebra. It selects the attributes based on the condition described by WHERE clause."},{"code":null,"e":52111,"s":51908,"text":"SELECT − This is one of the fundamental query command of SQL. It is similar to the projection operation of relational algebra. It selects the attributes based on the condition described by WHERE clause."},{"code":null,"e":52313,"s":52111,"text":"FROM − This clause takes a relation name as an argument from which attributes are to be selected/projected. In case more than one relation names are given, this clause corresponds to Cartesian product."},{"code":null,"e":52515,"s":52313,"text":"FROM − This clause takes a relation name as an argument from which attributes are to be selected/projected. In case more than one relation names are given, this clause corresponds to Cartesian product."},{"code":null,"e":52637,"s":52515,"text":"WHERE − This clause defines predicate or conditions, which must match in order to qualify the attributes to be projected."},{"code":null,"e":52759,"s":52637,"text":"WHERE − This clause defines predicate or conditions, which must match in order to qualify the attributes to be projected."},{"code":null,"e":52773,"s":52759,"text":"For example −"},{"code":null,"e":52826,"s":52773,"text":"Select author_name\nFrom book_author\nWhere age > 50;\n"},{"code":null,"e":52931,"s":52826,"text":"This command will yield the names of authors from the relation book_author whose age is greater than 50."},{"code":null,"e":53010,"s":52931,"text":"This command is used for inserting values into the rows of a table (relation)."},{"code":null,"e":53018,"s":53010,"text":"Syntax−"},{"code":null,"e":53113,"s":53018,"text":"INSERT INTO table (column1 [, column2, column3 ... ]) VALUES (value1 [, value2, value3 ... ])\n"},{"code":null,"e":53116,"s":53113,"text":"Or"},{"code":null,"e":53167,"s":53116,"text":"INSERT INTO table VALUES (value1, [value2, ... ])\n"},{"code":null,"e":53181,"s":53167,"text":"For example −"},{"code":null,"e":53262,"s":53181,"text":"INSERT INTO tutorialspoint (Author, Subject) VALUES (\"anonymous\", \"computers\");\n"},{"code":null,"e":53354,"s":53262,"text":"This command is used for updating or modifying the values of columns in a table (relation)."},{"code":null,"e":53363,"s":53354,"text":"Syntax −"},{"code":null,"e":53452,"s":53363,"text":"UPDATE table_name SET column_name = value [, column_name = value ...] [WHERE condition]\n"},{"code":null,"e":53466,"s":53452,"text":"For example −"},{"code":null,"e":53538,"s":53466,"text":"UPDATE tutorialspoint SET Author=\"webmaster\" WHERE Author=\"anonymous\";\n"},{"code":null,"e":53614,"s":53538,"text":"This command is used for removing one or more rows from a table (relation)."},{"code":null,"e":53623,"s":53614,"text":"Syntax −"},{"code":null,"e":53666,"s":53623,"text":"DELETE FROM table_name [WHERE condition];\n"},{"code":null,"e":53680,"s":53666,"text":"For example −"},{"code":null,"e":53736,"s":53680,"text":"DELETE FROM tutorialspoints\n WHERE Author=\"unknown\";\n"},{"code":null,"e":54003,"s":53736,"text":"Functional dependency (FD) is a set of constraints between two attributes in a relation. Functional dependency says that if two tuples have same values for attributes A1, A2,..., An, then those two tuples must have to have same values for attributes B1, B2, ..., Bn."},{"code":null,"e":54199,"s":54003,"text":"Functional dependency is represented by an arrow sign (→) that is, X→Y, where X functionally determines Y. The left-hand side attributes determine the values of attributes on the right-hand side."},{"code":null,"e":54461,"s":54199,"text":"If F is a set of functional dependencies then the closure of F, denoted as F+, is the set of all functional dependencies logically implied by F. Armstrong's Axioms are a set of rules, that when applied repeatedly, generates a closure of functional dependencies."},{"code":null,"e":54562,"s":54461,"text":"Reflexive rule − If alpha is a set of attributes and beta is_subset_of alpha, then alpha holds beta."},{"code":null,"e":54663,"s":54562,"text":"Reflexive rule − If alpha is a set of attributes and beta is_subset_of alpha, then alpha holds beta."},{"code":null,"e":54830,"s":54663,"text":"Augmentation rule − If a → b holds and y is attribute set, then ay → by also holds. That is adding attributes in dependencies, does not change the basic dependencies."},{"code":null,"e":54997,"s":54830,"text":"Augmentation rule − If a → b holds and y is attribute set, then ay → by also holds. That is adding attributes in dependencies, does not change the basic dependencies."},{"code":null,"e":55161,"s":54997,"text":"Transitivity rule − Same as transitive rule in algebra, if a → b holds and b → c holds, then a → c also holds. a → b is called as a functionally that determines b."},{"code":null,"e":55325,"s":55161,"text":"Transitivity rule − Same as transitive rule in algebra, if a → b holds and b → c holds, then a → c also holds. a → b is called as a functionally that determines b."},{"code":null,"e":55463,"s":55325,"text":"Trivial − If a functional dependency (FD) X → Y holds, where Y is a subset of X, then it is called a trivial FD. Trivial FDs always hold."},{"code":null,"e":55601,"s":55463,"text":"Trivial − If a functional dependency (FD) X → Y holds, where Y is a subset of X, then it is called a trivial FD. Trivial FDs always hold."},{"code":null,"e":55703,"s":55601,"text":"Non-trivial − If an FD X → Y holds, where Y is not a subset of X, then it is called a non-trivial FD."},{"code":null,"e":55805,"s":55703,"text":"Non-trivial − If an FD X → Y holds, where Y is not a subset of X, then it is called a non-trivial FD."},{"code":null,"e":55923,"s":55805,"text":"Completely non-trivial − If an FD X → Y holds, where x intersect Y = Φ, it is said to be a completely non-trivial FD."},{"code":null,"e":56041,"s":55923,"text":"Completely non-trivial − If an FD X → Y holds, where x intersect Y = Φ, it is said to be a completely non-trivial FD."},{"code":null,"e":56221,"s":56041,"text":"If a database design is not perfect, it may contain anomalies, which are like a bad dream for any database administrator. Managing a database with anomalies is next to impossible."},{"code":null,"e":56593,"s":56221,"text":"Update anomalies − If data items are scattered and are not linked to each other properly, then it could lead to strange situations. For example, when we try to update one data item having its copies scattered over several places, a few instances get updated properly while a few others are left with old values. Such instances leave the database in an inconsistent state."},{"code":null,"e":56965,"s":56593,"text":"Update anomalies − If data items are scattered and are not linked to each other properly, then it could lead to strange situations. For example, when we try to update one data item having its copies scattered over several places, a few instances get updated properly while a few others are left with old values. Such instances leave the database in an inconsistent state."},{"code":null,"e":57113,"s":56965,"text":"Deletion anomalies − We tried to delete a record, but parts of it was left undeleted because of unawareness, the data is also saved somewhere else."},{"code":null,"e":57261,"s":57113,"text":"Deletion anomalies − We tried to delete a record, but parts of it was left undeleted because of unawareness, the data is also saved somewhere else."},{"code":null,"e":57344,"s":57261,"text":"Insert anomalies − We tried to insert data in a record that does not exist at all."},{"code":null,"e":57427,"s":57344,"text":"Insert anomalies − We tried to insert data in a record that does not exist at all."},{"code":null,"e":57529,"s":57427,"text":"Normalization is a method to remove all these anomalies and bring the database to a consistent state."},{"code":null,"e":57742,"s":57529,"text":"First Normal Form is defined in the definition of relations (tables) itself. This rule defines that all the attributes in a relation must have atomic domains. The values in an atomic domain are indivisible units."},{"code":null,"e":57823,"s":57742,"text":"We re-arrange the relation (table) as below, to convert it to First Normal Form."},{"code":null,"e":57900,"s":57823,"text":"Each attribute must contain only a single value from its pre-defined domain."},{"code":null,"e":57984,"s":57900,"text":"Before we learn about the second normal form, we need to understand the following −"},{"code":null,"e":58085,"s":57984,"text":"Prime attribute − An attribute, which is a part of the candidate-key, is known as a prime attribute."},{"code":null,"e":58186,"s":58085,"text":"Prime attribute − An attribute, which is a part of the candidate-key, is known as a prime attribute."},{"code":null,"e":58297,"s":58186,"text":"Non-prime attribute − An attribute, which is not a part of the prime-key, is said to be a non-prime attribute."},{"code":null,"e":58408,"s":58297,"text":"Non-prime attribute − An attribute, which is not a part of the prime-key, is said to be a non-prime attribute."},{"code":null,"e":58644,"s":58408,"text":"If we follow second normal form, then every non-prime attribute should be fully functionally dependent on prime key attribute. That is, if X → A holds, then there should not be any proper subset Y of X, for which Y → A also holds true."},{"code":null,"e":59084,"s":58644,"text":"We see here in Student_Project relation that the prime key attributes are Stu_ID and Proj_ID. According to the rule, non-key attributes, i.e. Stu_Name and Proj_Name must be dependent upon both and not on any of the prime key attribute individually. But we find that Stu_Name can be identified by Stu_ID and Proj_Name can be identified by Proj_ID independently. This is called partial dependency, which is not allowed in Second Normal Form."},{"code":null,"e":59186,"s":59084,"text":"We broke the relation in two as depicted in the above picture. So there exists no partial dependency."},{"code":null,"e":59295,"s":59186,"text":"For a relation to be in Third Normal Form, it must be in Second Normal form and the following must satisfy −"},{"code":null,"e":59368,"s":59295,"text":"No non-prime attribute is transitively dependent on prime key attribute."},{"code":null,"e":59476,"s":59368,"text":"For any non-trivial functional dependency, X → A, then either −\nX is a superkey or,\nA is prime attribute.\n\n"},{"code":null,"e":59498,"s":59476,"text":"A is prime attribute."},{"code":null,"e":59798,"s":59498,"text":"We find that in the above Student_detail relation, Stu_ID is the key and only prime key attribute. We find that City can be identified by Stu_ID as well as Zip itself. Neither Zip is a superkey nor is City a prime attribute. Additionally, Stu_ID → Zip → City, so there exists transitive dependency."},{"code":null,"e":59899,"s":59798,"text":"To bring this relation into third normal form, we break the relation into two relations as follows −"},{"code":null,"e":60002,"s":59899,"text":"Boyce-Codd Normal Form (BCNF) is an extension of Third Normal Form on strict terms. BCNF states that −"},{"code":null,"e":60075,"s":60002,"text":"For any non-trivial functional dependency, X → A, X must be a super-key."},{"code":null,"e":60205,"s":60075,"text":"In the above image, Stu_ID is the super-key in the relation Student_Detail and Zip is the super-key in the relation ZipCodes. So,"},{"code":null,"e":60228,"s":60205,"text":"Stu_ID → Stu_Name, Zip"},{"code":null,"e":60232,"s":60228,"text":"and"},{"code":null,"e":60243,"s":60232,"text":"Zip → City"},{"code":null,"e":60295,"s":60243,"text":"Which confirms that both the relations are in BCNF."},{"code":null,"e":60625,"s":60295,"text":"We understand the benefits of taking a Cartesian product of two relations, which gives us all the possible tuples that are paired together. But it might not be feasible for us in certain cases to take a Cartesian product where we encounter huge relations with thousands of tuples having a considerable large number of attributes."},{"code":null,"e":60815,"s":60625,"text":"Join is a combination of a Cartesian product followed by a selection process. A Join operation pairs two tuples from different relations, if and only if a given join condition is satisfied."},{"code":null,"e":60886,"s":60815,"text":"We will briefly describe various join types in the following sections."},{"code":null,"e":61028,"s":60886,"text":"Theta join combines tuples from different relations provided they satisfy the theta condition. The join condition is denoted by the symbol θ."},{"code":null,"e":61038,"s":61028,"text":"R1 ⋈θ R2\n"},{"code":null,"e":61194,"s":61038,"text":"R1 and R2 are relations having attributes (A1, A2, .., An) and (B1, B2,.. ,Bn) such that the attributes don’t have anything in common, that is R1 ∩ R2 = Φ."},{"code":null,"e":61248,"s":61194,"text":"Theta join can use all kinds of comparison operators."},{"code":null,"e":61265,"s":61248,"text":"Student_Detail ="},{"code":null,"e":61311,"s":61265,"text":"STUDENT ⋈Student.Std = Subject.Class SUBJECT\n"},{"code":null,"e":61437,"s":61311,"text":"When Theta join uses only equality comparison operator, it is said to be equijoin. The above example corresponds to equijoin."},{"code":null,"e":61722,"s":61437,"text":"Natural join does not use any comparison operator. It does not concatenate the way a Cartesian product does. We can perform a Natural Join only if there is at least one common attribute that exists between two relations. In addition, the attributes must have the same name and domain."},{"code":null,"e":61832,"s":61722,"text":"Natural join acts on those matching attributes where the values of attributes in both the relations are same."},{"code":null,"e":62234,"s":61832,"text":"Theta Join, Equijoin, and Natural Join are called inner joins. An inner join includes only those tuples with matching attributes and the rest are discarded in the resulting relation. Therefore, we need to use outer joins to include all the tuples from the participating relations in the resulting relation. There are three kinds of outer joins − left outer join, right outer join, and full outer join."},{"code":null,"e":62456,"s":62234,"text":"All the tuples from the Left relation, R, are included in the resulting relation. If there are tuples in R without any matching tuple in the Right relation S, then the S-attributes of the resulting relation are made NULL."},{"code":null,"e":62656,"s":62456,"text":"All the tuples from the Right relation, S, are included in the resulting relation. If there are tuples in S without any matching tuple in R, then the R-attributes of resulting relation are made NULL."},{"code":null,"e":62850,"s":62656,"text":"All the tuples from both participating relations are included in the resulting relation. If there are no matching tuples for both relations, their respective unmatched attributes are made NULL."},{"code":null,"e":63066,"s":62850,"text":"Databases are stored in file formats, which contain records. At physical level, the actual data is stored in electromagnetic format on some device. These storage devices can be broadly categorized into three types −"},{"code":null,"e":63536,"s":63066,"text":"Primary Storage − The memory storage that is directly accessible to the CPU comes under this category. CPU's internal memory (registers), fast memory (cache), and main memory (RAM) are directly accessible to the CPU, as they are all placed on the motherboard or CPU chipset. This storage is typically very small, ultra-fast, and volatile. Primary storage requires continuous power supply in order to maintain its state. In case of a power failure, all its data is lost."},{"code":null,"e":64006,"s":63536,"text":"Primary Storage − The memory storage that is directly accessible to the CPU comes under this category. CPU's internal memory (registers), fast memory (cache), and main memory (RAM) are directly accessible to the CPU, as they are all placed on the motherboard or CPU chipset. This storage is typically very small, ultra-fast, and volatile. Primary storage requires continuous power supply in order to maintain its state. In case of a power failure, all its data is lost."},{"code":null,"e":64307,"s":64006,"text":"Secondary Storage − Secondary storage devices are used to store data for future use or as backup. Secondary storage includes memory devices that are not a part of the CPU chipset or motherboard, for example, magnetic disks, optical disks (DVD, CD, etc.), hard disks, flash drives, and magnetic tapes."},{"code":null,"e":64608,"s":64307,"text":"Secondary Storage − Secondary storage devices are used to store data for future use or as backup. Secondary storage includes memory devices that are not a part of the CPU chipset or motherboard, for example, magnetic disks, optical disks (DVD, CD, etc.), hard disks, flash drives, and magnetic tapes."},{"code":null,"e":64927,"s":64608,"text":"Tertiary Storage − Tertiary storage is used to store huge volumes of data. Since such storage devices are external to the computer system, they are the slowest in speed. These storage devices are mostly used to take the back up of an entire system. Optical disks and magnetic tapes are widely used as tertiary storage."},{"code":null,"e":65246,"s":64927,"text":"Tertiary Storage − Tertiary storage is used to store huge volumes of data. Since such storage devices are external to the computer system, they are the slowest in speed. These storage devices are mostly used to take the back up of an entire system. Optical disks and magnetic tapes are widely used as tertiary storage."},{"code":null,"e":65626,"s":65246,"text":"A computer system has a well-defined hierarchy of memory. A CPU has direct access to it main memory as well as its inbuilt registers. The access time of the main memory is obviously less than the CPU speed. To minimize this speed mismatch, cache memory is introduced. Cache memory provides the fastest access time and it contains data that is most frequently accessed by the CPU."},{"code":null,"e":65842,"s":65626,"text":"The memory with the fastest access is the costliest one. Larger storage devices offer slow speed and they are less expensive, however they can store huge volumes of data as compared to CPU registers or cache memory."},{"code":null,"e":66316,"s":65842,"text":"Hard disk drives are the most common secondary storage devices in present computer systems. These are called magnetic disks because they use the concept of magnetization to store information. Hard disks consist of metal disks coated with magnetizable material. These disks are placed vertically on a spindle. A read/write head moves in between the disks and is used to magnetize or de-magnetize the spot under it. A magnetized spot can be recognized as 0 (zero) or 1 (one)."},{"code":null,"e":66565,"s":66316,"text":"Hard disks are formatted in a well-defined order to store data efficiently. A hard disk plate has many concentric circles on it, called tracks. Every track is further divided into sectors. A sector on a hard disk typically stores 512 bytes of data."},{"code":null,"e":66727,"s":66565,"text":"RAID stands for Redundant Array of Independent Disks, which is a technology to connect multiple secondary storage devices and use them as a single storage media."},{"code":null,"e":66880,"s":66727,"text":"RAID consists of an array of disks in which multiple disks are connected together to achieve different goals. RAID levels define the use of disk arrays."},{"code":null,"e":67190,"s":66880,"text":"RAID 0 − In this level, a striped array of disks is implemented. The data is broken down into blocks and the blocks are distributed among disks. Each disk receives a block of data to write/read in parallel. It enhances the speed and performance of the storage device. There is no parity and backup in Level 0."},{"code":null,"e":67500,"s":67190,"text":"RAID 0 − In this level, a striped array of disks is implemented. The data is broken down into blocks and the blocks are distributed among disks. Each disk receives a block of data to write/read in parallel. It enhances the speed and performance of the storage device. There is no parity and backup in Level 0."},{"code":null,"e":67727,"s":67500,"text":"RAID 1 − RAID 1 uses mirroring techniques. When data is sent to a RAID controller, it sends a copy of data to all the disks in the array. RAID level 1 is also called mirroring and provides 100% redundancy in case of a failure."},{"code":null,"e":67954,"s":67727,"text":"RAID 1 − RAID 1 uses mirroring techniques. When data is sent to a RAID controller, it sends a copy of data to all the disks in the array. RAID level 1 is also called mirroring and provides 100% redundancy in case of a failure."},{"code":null,"e":68285,"s":67954,"text":"RAID 2 − RAID 2 records Error Correction Code using Hamming distance for its data, striped on different disks. Like level 0, each data bit in a word is recorded on a separate disk and ECC codes of the data words are stored on a different set disks. Due to its complex structure and high cost, RAID 2 is not commercially available."},{"code":null,"e":68616,"s":68285,"text":"RAID 2 − RAID 2 records Error Correction Code using Hamming distance for its data, striped on different disks. Like level 0, each data bit in a word is recorded on a separate disk and ECC codes of the data words are stored on a different set disks. Due to its complex structure and high cost, RAID 2 is not commercially available."},{"code":null,"e":68798,"s":68616,"text":"RAID 3 − RAID 3 stripes the data onto multiple disks. The parity bit generated for data word is stored on a different disk. This technique makes it to overcome single disk failures."},{"code":null,"e":68980,"s":68798,"text":"RAID 3 − RAID 3 stripes the data onto multiple disks. The parity bit generated for data word is stored on a different disk. This technique makes it to overcome single disk failures."},{"code":null,"e":69280,"s":68980,"text":"RAID 4 − In this level, an entire block of data is written onto data disks and then the parity is generated and stored on a different disk. Note that level 3 uses byte-level striping, whereas level 4 uses block-level striping. Both level 3 and level 4 require at least three disks to implement RAID."},{"code":null,"e":69580,"s":69280,"text":"RAID 4 − In this level, an entire block of data is written onto data disks and then the parity is generated and stored on a different disk. Note that level 3 uses byte-level striping, whereas level 4 uses block-level striping. Both level 3 and level 4 require at least three disks to implement RAID."},{"code":null,"e":69792,"s":69580,"text":"RAID 5 − RAID 5 writes whole data blocks onto different disks, but the parity bits generated for data block stripe are distributed among all the data disks rather than storing them on a different dedicated disk."},{"code":null,"e":70004,"s":69792,"text":"RAID 5 − RAID 5 writes whole data blocks onto different disks, but the parity bits generated for data block stripe are distributed among all the data disks rather than storing them on a different dedicated disk."},{"code":null,"e":70272,"s":70004,"text":"RAID 6 − RAID 6 is an extension of level 5. In this level, two independent parities are generated and stored in distributed fashion among multiple disks. Two parities provide additional fault tolerance. This level requires at least four disk drives to implement RAID."},{"code":null,"e":70540,"s":70272,"text":"RAID 6 − RAID 6 is an extension of level 5. In this level, two independent parities are generated and stored in distributed fashion among multiple disks. Two parities provide additional fault tolerance. This level requires at least four disk drives to implement RAID."},{"code":null,"e":70785,"s":70540,"text":"Relative data and information is stored collectively in file formats. A file is a sequence of records stored in binary format. A disk drive is formatted into several blocks that can store records. File records are mapped onto those disk blocks."},{"code":null,"e":70924,"s":70785,"text":"File Organization defines how file records are mapped onto disk blocks. We have four types of File Organization to organize file records −"},{"code":null,"e":71271,"s":70924,"text":"When a file is created using Heap File Organization, the Operating System allocates memory area to that file without any further accounting details. File records can be placed anywhere in that memory area. It is the responsibility of the software to manage the records. Heap File does not support any ordering, sequencing, or indexing on its own."},{"code":null,"e":71579,"s":71271,"text":"Every file record contains a data field (attribute) to uniquely identify that record. In sequential file organization, records are placed in the file in some sequential order based on the unique key field or search key. Practically, it is not possible to store all the records sequentially in physical form."},{"code":null,"e":71770,"s":71579,"text":"Hash File Organization uses Hash function computation on some fields of the records. The output of the hash function determines the location of disk block where the records are to be placed."},{"code":null,"e":72013,"s":71770,"text":"Clustered file organization is not considered good for large databases. In this mechanism, related records from one or more relations are kept in the same disk block, that is, the ordering of records is not based on primary key or search key."},{"code":null,"e":72090,"s":72013,"text":"Operations on database files can be broadly classified into two categories −"},{"code":null,"e":72108,"s":72090,"text":"Update Operations"},{"code":null,"e":72126,"s":72108,"text":"Update Operations"},{"code":null,"e":72147,"s":72126,"text":"Retrieval Operations"},{"code":null,"e":72168,"s":72147,"text":"Retrieval Operations"},{"code":null,"e":72535,"s":72168,"text":"Update operations change the data values by insertion, deletion, or update. Retrieval operations, on the other hand, do not alter the data but retrieve them after optional conditional filtering. In both types of operations, selection plays a significant role. Other than creation and deletion of a file, there could be several operations, which can be done on files."},{"code":null,"e":72882,"s":72535,"text":"Open − A file can be opened in one of the two modes, read mode or write mode. In read mode, the operating system does not allow anyone to alter data. In other words, data is read only. Files opened in read mode can be shared among several entities. Write mode allows data modification. Files opened in write mode can be read but cannot be shared."},{"code":null,"e":73229,"s":72882,"text":"Open − A file can be opened in one of the two modes, read mode or write mode. In read mode, the operating system does not allow anyone to alter data. In other words, data is read only. Files opened in read mode can be shared among several entities. Write mode allows data modification. Files opened in write mode can be read but cannot be shared."},{"code":null,"e":73451,"s":73229,"text":"Locate − Every file has a file pointer, which tells the current position where the data is to be read or written. This pointer can be adjusted accordingly. Using find (seek) operation, it can be moved forward or backward."},{"code":null,"e":73673,"s":73451,"text":"Locate − Every file has a file pointer, which tells the current position where the data is to be read or written. This pointer can be adjusted accordingly. Using find (seek) operation, it can be moved forward or backward."},{"code":null,"e":73957,"s":73673,"text":"Read − By default, when files are opened in read mode, the file pointer points to the beginning of the file. There are options where the user can tell the operating system where to locate the file pointer at the time of opening a file. The very next data to the file pointer is read."},{"code":null,"e":74241,"s":73957,"text":"Read − By default, when files are opened in read mode, the file pointer points to the beginning of the file. There are options where the user can tell the operating system where to locate the file pointer at the time of opening a file. The very next data to the file pointer is read."},{"code":null,"e":74510,"s":74241,"text":"Write − User can select to open a file in write mode, which enables them to edit its contents. It can be deletion, insertion, or modification. The file pointer can be located at the time of opening or can be dynamically changed if the operating system allows to do so."},{"code":null,"e":74779,"s":74510,"text":"Write − User can select to open a file in write mode, which enables them to edit its contents. It can be deletion, insertion, or modification. The file pointer can be located at the time of opening or can be dynamically changed if the operating system allows to do so."},{"code":null,"e":75112,"s":74779,"text":"Close − This is the most important operation from the operating system’s point of view. When a request to close a file is generated, the operating system\n\nremoves all the locks (if in shared mode),\nsaves the data (if altered) to the secondary storage media, and\nreleases all the buffers and file handlers associated with the file.\n\n"},{"code":null,"e":75266,"s":75112,"text":"Close − This is the most important operation from the operating system’s point of view. When a request to close a file is generated, the operating system"},{"code":null,"e":75309,"s":75266,"text":"removes all the locks (if in shared mode),"},{"code":null,"e":75373,"s":75309,"text":"saves the data (if altered) to the secondary storage media, and"},{"code":null,"e":75442,"s":75373,"text":"releases all the buffers and file handlers associated with the file."},{"code":null,"e":75656,"s":75442,"text":"The organization of data inside a file plays a major role here. The process to locate the file pointer to a desired record inside a file various based on whether the records are arranged sequentially or clustered."},{"code":null,"e":75780,"s":75656,"text":"We know that data is stored in the form of records. Every record has a key field, which helps it to be recognized uniquely."},{"code":null,"e":76002,"s":75780,"text":"Indexing is a data structure technique to efficiently retrieve records from the database files based on some attributes on which the indexing has been done. Indexing in database systems is similar to what we see in books."},{"code":null,"e":76097,"s":76002,"text":"Indexing is defined based on its indexing attributes. Indexing can be of the following types −"},{"code":null,"e":76264,"s":76097,"text":"Primary Index − Primary index is defined on an ordered data file. The data file is ordered on a key field. The key field is generally the primary key of the relation."},{"code":null,"e":76431,"s":76264,"text":"Primary Index − Primary index is defined on an ordered data file. The data file is ordered on a key field. The key field is generally the primary key of the relation."},{"code":null,"e":76596,"s":76431,"text":"Secondary Index − Secondary index may be generated from a field which is a candidate key and has a unique value in every record, or a non-key with duplicate values."},{"code":null,"e":76761,"s":76596,"text":"Secondary Index − Secondary index may be generated from a field which is a candidate key and has a unique value in every record, or a non-key with duplicate values."},{"code":null,"e":76878,"s":76761,"text":"Clustering Index − Clustering index is defined on an ordered data file. The data file is ordered on a non-key field."},{"code":null,"e":76995,"s":76878,"text":"Clustering Index − Clustering index is defined on an ordered data file. The data file is ordered on a non-key field."},{"code":null,"e":77030,"s":76995,"text":"Ordered Indexing is of two types −"},{"code":null,"e":77042,"s":77030,"text":"Dense Index"},{"code":null,"e":77055,"s":77042,"text":"Sparse Index"},{"code":null,"e":77310,"s":77055,"text":"In dense index, there is an index record for every search key value in the database. This makes searching faster but requires more space to store index records itself. Index records contain search key value and a pointer to the actual record on the disk."},{"code":null,"e":77728,"s":77310,"text":"In sparse index, index records are not created for every search key. An index record here contains a search key and an actual pointer to the data on the disk. To search a record, we first proceed by index record and reach at the actual location of the data. If the data we are looking for is not where we directly reach by following the index, then the system starts sequential search until the desired data is found."},{"code":null,"e":78163,"s":77728,"text":"Index records comprise search-key values and data pointers. Multilevel index is stored on the disk along with the actual database files. As the size of the database grows, so does the size of the indices. There is an immense need to keep the index records in the main memory so as to speed up the search operations. If single-level index is used, then a large size index cannot be kept in memory which leads to multiple disk accesses."},{"code":null,"e":78396,"s":78163,"text":"Multi-level Index helps in breaking down the index into several smaller indices in order to make the outermost level so small that it can be saved in a single disk block, which can easily be accommodated anywhere in the main memory."},{"code":null,"e":78751,"s":78396,"text":"A B+ tree is a balanced binary search tree that follows a multi-level index format. The leaf nodes of a B+ tree denote actual data pointers. B+ tree ensures that all leaf nodes remain at the same height, thus balanced. Additionally, the leaf nodes are linked using a link list; therefore, a B+ tree can support random access as well as sequential access."},{"code":null,"e":78872,"s":78751,"text":"Every leaf node is at equal distance from the root node. A B+ tree is of the order n where n is fixed for every B+ tree."},{"code":null,"e":78889,"s":78872,"text":"Internal nodes −"},{"code":null,"e":78970,"s":78889,"text":"Internal (non-leaf) nodes contain at least ⌈n/2⌉ pointers, except the root node."},{"code":null,"e":79020,"s":78970,"text":"At most, an internal node can contain n pointers."},{"code":null,"e":79033,"s":79020,"text":"Leaf nodes −"},{"code":null,"e":79105,"s":79033,"text":"Leaf nodes contain at least ⌈n/2⌉ record pointers and ⌈n/2⌉ key values."},{"code":null,"e":79174,"s":79105,"text":"At most, a leaf node can contain n record pointers and n key values."},{"code":null,"e":79271,"s":79174,"text":"Every leaf node contains one block pointer P to point to next leaf node and forms a linked list."},{"code":null,"e":79344,"s":79271,"text":"B+ trees are filled from bottom and each entry is done at the leaf node."},{"code":null,"e":79417,"s":79344,"text":"B+ trees are filled from bottom and each entry is done at the leaf node."},{"code":null,"e":79650,"s":79417,"text":"If a leaf node overflows −\n\nSplit node into two parts.\nPartition at i = ⌊(m+1)/2⌋.\nFirst i entries are stored in one node.\nRest of the entries (i+1 onwards) are moved to a new node.\nith key is duplicated at the parent of the leaf.\n\n"},{"code":null,"e":79677,"s":79650,"text":"Split node into two parts."},{"code":null,"e":79704,"s":79677,"text":"Split node into two parts."},{"code":null,"e":79732,"s":79704,"text":"Partition at i = ⌊(m+1)/2⌋."},{"code":null,"e":79760,"s":79732,"text":"Partition at i = ⌊(m+1)/2⌋."},{"code":null,"e":79800,"s":79760,"text":"First i entries are stored in one node."},{"code":null,"e":79840,"s":79800,"text":"First i entries are stored in one node."},{"code":null,"e":79899,"s":79840,"text":"Rest of the entries (i+1 onwards) are moved to a new node."},{"code":null,"e":79958,"s":79899,"text":"Rest of the entries (i+1 onwards) are moved to a new node."},{"code":null,"e":80007,"s":79958,"text":"ith key is duplicated at the parent of the leaf."},{"code":null,"e":80056,"s":80007,"text":"ith key is duplicated at the parent of the leaf."},{"code":null,"e":80237,"s":80056,"text":"If a non-leaf node overflows −\n\nSplit node into two parts.\nPartition the node at i = ⌈(m+1)/2⌉.\nEntries up to i are kept in one node.\nRest of the entries are moved to a new node.\n\n"},{"code":null,"e":80268,"s":80237,"text":"If a non-leaf node overflows −"},{"code":null,"e":80295,"s":80268,"text":"Split node into two parts."},{"code":null,"e":80322,"s":80295,"text":"Split node into two parts."},{"code":null,"e":80359,"s":80322,"text":"Partition the node at i = ⌈(m+1)/2⌉."},{"code":null,"e":80396,"s":80359,"text":"Partition the node at i = ⌈(m+1)/2⌉."},{"code":null,"e":80434,"s":80396,"text":"Entries up to i are kept in one node."},{"code":null,"e":80472,"s":80434,"text":"Entries up to i are kept in one node."},{"code":null,"e":80517,"s":80472,"text":"Rest of the entries are moved to a new node."},{"code":null,"e":80562,"s":80517,"text":"Rest of the entries are moved to a new node."},{"code":null,"e":80609,"s":80562,"text":"B+ tree entries are deleted at the leaf nodes."},{"code":null,"e":80656,"s":80609,"text":"B+ tree entries are deleted at the leaf nodes."},{"code":null,"e":80786,"s":80656,"text":"The target entry is searched and deleted.\n\nIf it is an internal node, delete and replace with the entry from the left position.\n\n"},{"code":null,"e":80828,"s":80786,"text":"The target entry is searched and deleted."},{"code":null,"e":80913,"s":80828,"text":"If it is an internal node, delete and replace with the entry from the left position."},{"code":null,"e":80998,"s":80913,"text":"If it is an internal node, delete and replace with the entry from the left position."},{"code":null,"e":81109,"s":80998,"text":"After deletion, underflow is tested,\n\nIf underflow occurs, distribute the entries from the nodes left to it.\n\n"},{"code":null,"e":81146,"s":81109,"text":"After deletion, underflow is tested,"},{"code":null,"e":81217,"s":81146,"text":"If underflow occurs, distribute the entries from the nodes left to it."},{"code":null,"e":81288,"s":81217,"text":"If underflow occurs, distribute the entries from the nodes left to it."},{"code":null,"e":81378,"s":81288,"text":"If distribution is not possible from left, then\n\nDistribute from the nodes right to it.\n\n"},{"code":null,"e":81426,"s":81378,"text":"If distribution is not possible from left, then"},{"code":null,"e":81465,"s":81426,"text":"Distribute from the nodes right to it."},{"code":null,"e":81504,"s":81465,"text":"Distribute from the nodes right to it."},{"code":null,"e":81611,"s":81504,"text":"If distribution is not possible from left or from right, then\n\nMerge the node with left and right to it.\n\n"},{"code":null,"e":81673,"s":81611,"text":"If distribution is not possible from left or from right, then"},{"code":null,"e":81715,"s":81673,"text":"Merge the node with left and right to it."},{"code":null,"e":81757,"s":81715,"text":"Merge the node with left and right to it."},{"code":null,"e":82076,"s":81757,"text":"For a huge database structure, it can be almost next to impossible to search all the index values through all its level and then reach the destination data block to retrieve the desired data. Hashing is an effective technique to calculate the direct location of a data record on the disk without using index structure."},{"code":null,"e":82177,"s":82076,"text":"Hashing uses hash functions with search keys as parameters to generate the address of a data record."},{"code":null,"e":82364,"s":82177,"text":"Bucket − A hash file stores data in bucket format. Bucket is considered a unit of storage. A bucket typically stores one complete disk block, which in turn can store one or more records."},{"code":null,"e":82551,"s":82364,"text":"Bucket − A hash file stores data in bucket format. Bucket is considered a unit of storage. A bucket typically stores one complete disk block, which in turn can store one or more records."},{"code":null,"e":82751,"s":82551,"text":"Hash Function − A hash function, h, is a mapping function that maps all the set of search-keys K to the address where actual records are placed. It is a function from search keys to bucket addresses."},{"code":null,"e":82951,"s":82751,"text":"Hash Function − A hash function, h, is a mapping function that maps all the set of search-keys K to the address where actual records are placed. It is a function from search keys to bucket addresses."},{"code":null,"e":83264,"s":82951,"text":"In static hashing, when a search-key value is provided, the hash function always computes the same address. For example, if mod-4 hash function is used, then it shall generate only 5 values. The output address shall always be same for that function. The number of buckets provided remains unchanged at all times."},{"code":null,"e":83456,"s":83264,"text":"Insertion − When a record is required to be entered using static hash, the hash function h computes the bucket address for search key K, where the record will be stored.\nBucket address = h(K)"},{"code":null,"e":83626,"s":83456,"text":"Insertion − When a record is required to be entered using static hash, the hash function h computes the bucket address for search key K, where the record will be stored."},{"code":null,"e":83648,"s":83626,"text":"Bucket address = h(K)"},{"code":null,"e":83793,"s":83648,"text":"Search − When a record needs to be retrieved, the same hash function can be used to retrieve the address of the bucket where the data is stored."},{"code":null,"e":83938,"s":83793,"text":"Search − When a record needs to be retrieved, the same hash function can be used to retrieve the address of the bucket where the data is stored."},{"code":null,"e":84005,"s":83938,"text":"Delete − This is simply a search followed by a deletion operation."},{"code":null,"e":84072,"s":84005,"text":"Delete − This is simply a search followed by a deletion operation."},{"code":null,"e":84225,"s":84072,"text":"The condition of bucket-overflow is known as collision. This is a fatal state for any static hash function. In this case, overflow chaining can be used."},{"code":null,"e":84398,"s":84225,"text":"Overflow Chaining − When buckets are full, a new bucket is allocated for the same hash result and is linked after the previous one. This mechanism is called Closed Hashing."},{"code":null,"e":84571,"s":84398,"text":"Overflow Chaining − When buckets are full, a new bucket is allocated for the same hash result and is linked after the previous one. This mechanism is called Closed Hashing."},{"code":null,"e":84743,"s":84571,"text":"Linear Probing − When a hash function generates an address at which data is already stored, the next free bucket is allocated to it. This mechanism is called Open Hashing."},{"code":null,"e":84915,"s":84743,"text":"Linear Probing − When a hash function generates an address at which data is already stored, the next free bucket is allocated to it. This mechanism is called Open Hashing."},{"code":null,"e":85201,"s":84915,"text":"The problem with static hashing is that it does not expand or shrink dynamically as the size of the database grows or shrinks. Dynamic hashing provides a mechanism in which data buckets are added and removed dynamically and on-demand. Dynamic hashing is also known as extended hashing."},{"code":null,"e":85315,"s":85201,"text":"Hash function, in dynamic hashing, is made to produce a large number of values and only a few are used initially."},{"code":null,"e":85740,"s":85315,"text":"The prefix of an entire hash value is taken as a hash index. Only a portion of the hash value is used for computing bucket addresses. Every hash index has a depth value to signify how many bits are used for computing a hash function. These bits can address 2n buckets. When all these bits are consumed − that is, when all the buckets are full − then the depth value is increased linearly and twice the buckets are allocated."},{"code":null,"e":85843,"s":85740,"text":"Querying − Look at the depth value of the hash index and use those bits to compute the bucket address."},{"code":null,"e":85946,"s":85843,"text":"Querying − Look at the depth value of the hash index and use those bits to compute the bucket address."},{"code":null,"e":86001,"s":85946,"text":"Update − Perform a query as above and update the data."},{"code":null,"e":86056,"s":86001,"text":"Update − Perform a query as above and update the data."},{"code":null,"e":86131,"s":86056,"text":"Deletion − Perform a query to locate the desired data and delete the same."},{"code":null,"e":86206,"s":86131,"text":"Deletion − Perform a query to locate the desired data and delete the same."},{"code":null,"e":86477,"s":86206,"text":"Insertion − Compute the address of the bucket\n\nIf the bucket is already full.\n\nAdd more buckets.\nAdd additional bits to the hash value.\nRe-compute the hash function.\n\n\nElse\n\nAdd data to the bucket,\n\n\nIf all the buckets are full, perform the remedies of static hashing.\n\n"},{"code":null,"e":86523,"s":86477,"text":"Insertion − Compute the address of the bucket"},{"code":null,"e":86644,"s":86523,"text":"If the bucket is already full.\n\nAdd more buckets.\nAdd additional bits to the hash value.\nRe-compute the hash function.\n\n"},{"code":null,"e":86662,"s":86644,"text":"Add more buckets."},{"code":null,"e":86701,"s":86662,"text":"Add additional bits to the hash value."},{"code":null,"e":86731,"s":86701,"text":"Re-compute the hash function."},{"code":null,"e":86763,"s":86731,"text":"Else\n\nAdd data to the bucket,\n\n"},{"code":null,"e":86787,"s":86763,"text":"Add data to the bucket,"},{"code":null,"e":86856,"s":86787,"text":"If all the buckets are full, perform the remedies of static hashing."},{"code":null,"e":87024,"s":86856,"text":"Hashing is not favorable when the data is organized in some ordering and the queries require a range of data. When data is discrete and random, hash performs the best."},{"code":null,"e":87126,"s":87024,"text":"Hashing algorithms have high complexity than indexing. All hash operations are done in constant time."},{"code":null,"e":87254,"s":87126,"text":"A transaction can be defined as a group of tasks. A single task is the minimum processing unit which cannot be divided further."},{"code":null,"e":87448,"s":87254,"text":"Let’s take an example of a simple transaction. Suppose a bank employee transfers Rs 500 from A's account to B's account. This very simple and small transaction involves several low-level tasks."},{"code":null,"e":87460,"s":87448,"text":"A’s Account"},{"code":null,"e":87574,"s":87460,"text":"Open_Account(A)\nOld_Balance = A.balance\nNew_Balance = Old_Balance - 500\nA.balance = New_Balance\nClose_Account(A)\n"},{"code":null,"e":87586,"s":87574,"text":"B’s Account"},{"code":null,"e":87700,"s":87586,"text":"Open_Account(B)\nOld_Balance = B.balance\nNew_Balance = Old_Balance + 500\nB.balance = New_Balance\nClose_Account(B)\n"},{"code":null,"e":87991,"s":87700,"text":"A transaction is a very small unit of a program and it may contain several lowlevel tasks. A transaction in a database system must maintain Atomicity, Consistency, Isolation, and Durability − commonly known as ACID properties − in order to ensure accuracy, completeness, and data integrity."},{"code":null,"e":88356,"s":87991,"text":"Atomicity − This property states that a transaction must be treated as an atomic unit, that is, either all of its operations are executed or none. There must be no state in a database where a transaction is left partially completed. States should be defined either before the execution of the transaction or after the execution/abortion/failure of the transaction."},{"code":null,"e":88721,"s":88356,"text":"Atomicity − This property states that a transaction must be treated as an atomic unit, that is, either all of its operations are executed or none. There must be no state in a database where a transaction is left partially completed. States should be defined either before the execution of the transaction or after the execution/abortion/failure of the transaction."},{"code":null,"e":89044,"s":88721,"text":"Consistency − The database must remain in a consistent state after any transaction. No transaction should have any adverse effect on the data residing in the database. If the database was in a consistent state before the execution of a transaction, it must remain consistent after the execution of the transaction as well."},{"code":null,"e":89367,"s":89044,"text":"Consistency − The database must remain in a consistent state after any transaction. No transaction should have any adverse effect on the data residing in the database. If the database was in a consistent state before the execution of a transaction, it must remain consistent after the execution of the transaction as well."},{"code":null,"e":89770,"s":89367,"text":"Durability − The database should be durable enough to hold all its latest updates even if the system fails or restarts. If a transaction updates a chunk of data in a database and commits, then the database will hold the modified data. If a transaction commits but the system fails before the data could be written on to the disk, then that data will be updated once the system springs back into action."},{"code":null,"e":90173,"s":89770,"text":"Durability − The database should be durable enough to hold all its latest updates even if the system fails or restarts. If a transaction updates a chunk of data in a database and commits, then the database will hold the modified data. If a transaction commits but the system fails before the data could be written on to the disk, then that data will be updated once the system springs back into action."},{"code":null,"e":90496,"s":90173,"text":"Isolation − In a database system where more than one transaction are being executed simultaneously and in parallel, the property of isolation states that all the transactions will be carried out and executed as if it is the only transaction in the system. No transaction will affect the existence of any other transaction."},{"code":null,"e":90819,"s":90496,"text":"Isolation − In a database system where more than one transaction are being executed simultaneously and in parallel, the property of isolation states that all the transactions will be carried out and executed as if it is the only transaction in the system. No transaction will affect the existence of any other transaction."},{"code":null,"e":91031,"s":90819,"text":"When multiple transactions are being executed by the operating system in a multiprogramming environment, there are possibilities that instructions of one transactions are interleaved with some other transaction."},{"code":null,"e":91212,"s":91031,"text":"Schedule − A chronological execution sequence of a transaction is called a schedule. A schedule can have many transactions in it, each comprising of a number of instructions/tasks."},{"code":null,"e":91393,"s":91212,"text":"Schedule − A chronological execution sequence of a transaction is called a schedule. A schedule can have many transactions in it, each comprising of a number of instructions/tasks."},{"code":null,"e":91749,"s":91393,"text":"Serial Schedule − It is a schedule in which transactions are aligned in such a way that one transaction is executed first. When the first transaction completes its cycle, then the next transaction is executed. Transactions are ordered one after the other. This type of schedule is called a serial schedule, as transactions are executed in a serial manner."},{"code":null,"e":92105,"s":91749,"text":"Serial Schedule − It is a schedule in which transactions are aligned in such a way that one transaction is executed first. When the first transaction completes its cycle, then the next transaction is executed. Transactions are ordered one after the other. This type of schedule is called a serial schedule, as transactions are executed in a serial manner."},{"code":null,"e":92627,"s":92105,"text":"In a multi-transaction environment, serial schedules are considered as a benchmark. The execution sequence of an instruction in a transaction cannot be changed, but two transactions can have their instructions executed in a random fashion. This execution does no harm if two transactions are mutually independent and working on different segments of data; but in case these two transactions are working on the same data, then the results may vary. This ever-varying result may bring the database to an inconsistent state."},{"code":null,"e":92797,"s":92627,"text":"To resolve this problem, we allow parallel execution of a transaction schedule, if its transactions are either serializable or have some equivalence relation among them."},{"code":null,"e":92853,"s":92797,"text":"An equivalence schedule can be of the following types −"},{"code":null,"e":93114,"s":92853,"text":"If two schedules produce the same result after execution, they are said to be result equivalent. They may yield the same result for some value and different results for another set of values. That's why this equivalence is not generally considered significant."},{"code":null,"e":93241,"s":93114,"text":"Two schedules would be view equivalence if the transactions in both the schedules perform similar actions in a similar manner."},{"code":null,"e":93255,"s":93241,"text":"For example −"},{"code":null,"e":93333,"s":93255,"text":"If T reads the initial data in S1, then it also reads the initial data in S2."},{"code":null,"e":93411,"s":93333,"text":"If T reads the initial data in S1, then it also reads the initial data in S2."},{"code":null,"e":93501,"s":93411,"text":"If T reads the value written by J in S1, then it also reads the value written by J in S2."},{"code":null,"e":93591,"s":93501,"text":"If T reads the value written by J in S1, then it also reads the value written by J in S2."},{"code":null,"e":93709,"s":93591,"text":"If T performs the final write on the data value in S1, then it also performs the final write on the data value in S2."},{"code":null,"e":93827,"s":93709,"text":"If T performs the final write on the data value in S1, then it also performs the final write on the data value in S2."},{"code":null,"e":93902,"s":93827,"text":"Two schedules would be conflicting if they have the following properties −"},{"code":null,"e":93940,"s":93902,"text":"Both belong to separate transactions."},{"code":null,"e":93974,"s":93940,"text":"Both accesses the same data item."},{"code":null,"e":94017,"s":93974,"text":"At least one of them is \"write\" operation."},{"code":null,"e":94140,"s":94017,"text":"Two schedules having multiple transactions with conflicting operations are said to be conflict equivalent if and only if −"},{"code":null,"e":94197,"s":94140,"text":"Both the schedules contain the same set of Transactions."},{"code":null,"e":94278,"s":94197,"text":"The order of conflicting pairs of operation is maintained in both the schedules."},{"code":null,"e":94457,"s":94278,"text":"Note − View equivalent schedules are view serializable and conflict equivalent schedules are conflict serializable. All conflict serializable schedules are view serializable too."},{"code":null,"e":94525,"s":94457,"text":"A transaction in a database can be in one of the following states −"},{"code":null,"e":94632,"s":94525,"text":"Active − In this state, the transaction is being executed. This is the initial state of every transaction."},{"code":null,"e":94739,"s":94632,"text":"Active − In this state, the transaction is being executed. This is the initial state of every transaction."},{"code":null,"e":94859,"s":94739,"text":"Partially Committed − When a transaction executes its final operation, it is said to be in a partially committed state."},{"code":null,"e":94979,"s":94859,"text":"Partially Committed − When a transaction executes its final operation, it is said to be in a partially committed state."},{"code":null,"e":95151,"s":94979,"text":"Failed − A transaction is said to be in a failed state if any of the checks made by the database recovery system fails. A failed transaction can no longer proceed further."},{"code":null,"e":95323,"s":95151,"text":"Failed − A transaction is said to be in a failed state if any of the checks made by the database recovery system fails. A failed transaction can no longer proceed further."},{"code":null,"e":95782,"s":95323,"text":"Aborted − If any of the checks fails and the transaction has reached a failed state, then the recovery manager rolls back all its write operations on the database to bring the database back to its original state where it was prior to the execution of the transaction. Transactions in this state are called aborted. The database recovery module can select one of the two operations after a transaction aborts −\n\nRe-start the transaction\nKill the transaction\n\n"},{"code":null,"e":96192,"s":95782,"text":"Aborted − If any of the checks fails and the transaction has reached a failed state, then the recovery manager rolls back all its write operations on the database to bring the database back to its original state where it was prior to the execution of the transaction. Transactions in this state are called aborted. The database recovery module can select one of the two operations after a transaction aborts −"},{"code":null,"e":96217,"s":96192,"text":"Re-start the transaction"},{"code":null,"e":96238,"s":96217,"text":"Kill the transaction"},{"code":null,"e":96409,"s":96238,"text":"Committed − If a transaction executes all its operations successfully, it is said to be committed. All its effects are now permanently established on the database system."},{"code":null,"e":96580,"s":96409,"text":"Committed − If a transaction executes all its operations successfully, it is said to be committed. All its effects are now permanently established on the database system."},{"code":null,"e":96934,"s":96580,"text":"In a multiprogramming environment where multiple transactions can be executed simultaneously, it is highly important to control the concurrency of transactions. We have concurrency control protocols to ensure atomicity, isolation, and serializability of concurrent transactions. Concurrency control protocols can be broadly divided into two categories −"},{"code":null,"e":96955,"s":96934,"text":"Lock based protocols"},{"code":null,"e":96982,"s":96955,"text":"Time stamp based protocols"},{"code":null,"e":97171,"s":96982,"text":"Database systems equipped with lock-based protocols use a mechanism by which any transaction cannot read or write data until it acquires an appropriate lock on it. Locks are of two kinds −"},{"code":null,"e":97263,"s":97171,"text":"Binary Locks − A lock on a data item can be in two states; it is either locked or unlocked."},{"code":null,"e":97355,"s":97263,"text":"Binary Locks − A lock on a data item can be in two states; it is either locked or unlocked."},{"code":null,"e":97723,"s":97355,"text":"Shared/exclusive − This type of locking mechanism differentiates the locks based on their uses. If a lock is acquired on a data item to perform a write operation, it is an exclusive lock. Allowing more than one transaction to write on the same data item would lead the database into an inconsistent state. Read locks are shared because no data value is being changed."},{"code":null,"e":98091,"s":97723,"text":"Shared/exclusive − This type of locking mechanism differentiates the locks based on their uses. If a lock is acquired on a data item to perform a write operation, it is an exclusive lock. Allowing more than one transaction to write on the same data item would lead the database into an inconsistent state. Read locks are shared because no data value is being changed."},{"code":null,"e":98142,"s":98091,"text":"There are four types of lock protocols available −"},{"code":null,"e":98345,"s":98142,"text":"Simplistic lock-based protocols allow transactions to obtain a lock on every object before a 'write' operation is performed. Transactions may unlock the data item after completing the ‘write’ operation."},{"code":null,"e":98779,"s":98345,"text":"Pre-claiming protocols evaluate their operations and create a list of data items on which they need locks. Before initiating an execution, the transaction requests the system for all the locks it needs beforehand. If all the locks are granted, the transaction executes and releases all the locks when all its operations are over. If all the locks are not granted, the transaction rolls back and waits until all the locks are granted."},{"code":null,"e":99207,"s":98779,"text":"This locking protocol divides the execution phase of a transaction into three parts. In the first part, when the transaction starts executing, it seeks permission for the locks it requires. The second part is where the transaction acquires all the locks. As soon as the transaction releases its first lock, the third phase starts. In this phase, the transaction cannot demand any new locks; it only releases the acquired locks."},{"code":null,"e":99411,"s":99207,"text":"Two-phase locking has two phases, one is growing, where all the locks are being acquired by the transaction; and the second phase is shrinking, where the locks held by the transaction are being released."},{"code":null,"e":99543,"s":99411,"text":"To claim an exclusive (write) lock, a transaction must first acquire a shared (read) lock and then upgrade it to an exclusive lock."},{"code":null,"e":99853,"s":99543,"text":"The first phase of Strict-2PL is same as 2PL. After acquiring all the locks in the first phase, the transaction continues to execute normally. But in contrast to 2PL, Strict-2PL does not release a lock after using it. Strict-2PL holds all the locks until the commit point and releases all the locks at a time."},{"code":null,"e":99907,"s":99853,"text":"Strict-2PL does not have cascading abort as 2PL does."},{"code":null,"e":100057,"s":99907,"text":"The most commonly used concurrency protocol is the timestamp based protocol. This protocol uses either system time or logical counter as a timestamp."},{"code":null,"e":100255,"s":100057,"text":"Lock-based protocols manage the order between the conflicting pairs among transactions at the time of execution, whereas timestamp-based protocols start working as soon as a transaction is created."},{"code":null,"e":100609,"s":100255,"text":"Every transaction has a timestamp associated with it, and the ordering is determined by the age of the transaction. A transaction created at 0002 clock time would be older than all other transactions that come after it. For example, any transaction 'y' entering the system at 0004 is two seconds younger and the priority would be given to the older one."},{"code":null,"e":100783,"s":100609,"text":"In addition, every data item is given the latest read and write-timestamp. This lets the system know when the last ‘read and write’ operation was performed on the data item."},{"code":null,"e":101065,"s":100783,"text":"The timestamp-ordering protocol ensures serializability among transactions in their conflicting read and write operations. This is the responsibility of the protocol system that the conflicting pair of tasks should be executed according to the timestamp values of the transactions."},{"code":null,"e":101119,"s":101065,"text":"The timestamp of transaction Ti is denoted as TS(Ti)."},{"code":null,"e":101180,"s":101119,"text":"Read time-stamp of data-item X is denoted by R-timestamp(X)."},{"code":null,"e":101242,"s":101180,"text":"Write time-stamp of data-item X is denoted by W-timestamp(X)."},{"code":null,"e":101289,"s":101242,"text":"Timestamp ordering protocol works as follows −"},{"code":null,"e":101338,"s":101289,"text":"If a transaction Ti issues a read(X) operation −"},{"code":null,"e":101387,"s":101338,"text":"If a transaction Ti issues a read(X) operation −"},{"code":null,"e":101437,"s":101387,"text":"If TS(Ti) < W-timestamp(X)\n\nOperation rejected.\n\n"},{"code":null,"e":101457,"s":101437,"text":"Operation rejected."},{"code":null,"e":101508,"s":101457,"text":"If TS(Ti) >= W-timestamp(X)\n\nOperation executed.\n\n"},{"code":null,"e":101528,"s":101508,"text":"Operation executed."},{"code":null,"e":101562,"s":101528,"text":"All data-item timestamps updated."},{"code":null,"e":101612,"s":101562,"text":"If a transaction Ti issues a write(X) operation −"},{"code":null,"e":101662,"s":101612,"text":"If a transaction Ti issues a write(X) operation −"},{"code":null,"e":101689,"s":101662,"text":"If TS(Ti) < R-timestamp(X)"},{"code":null,"e":101709,"s":101689,"text":"Operation rejected."},{"code":null,"e":101736,"s":101709,"text":"If TS(Ti) < W-timestamp(X)"},{"code":null,"e":101775,"s":101736,"text":"Operation rejected and Ti rolled back."},{"code":null,"e":101806,"s":101775,"text":"Otherwise, operation executed."},{"code":null,"e":101905,"s":101806,"text":"This rule states if TS(Ti) < W-timestamp(X), then the operation is rejected and Ti is rolled back."},{"code":null,"e":101987,"s":101905,"text":"Time-stamp ordering rules can be modified to make the schedule view serializable."},{"code":null,"e":102062,"s":101987,"text":"Instead of making Ti rolled back, the 'write' operation itself is ignored."},{"code":null,"e":102252,"s":102062,"text":"In a multi-process system, deadlock is an unwanted situation that arises in a shared resource environment, where a process indefinitely waits for a resource that is held by another process."},{"code":null,"e":102667,"s":102252,"text":"For example, assume a set of transactions {T0, T1, T2, ...,Tn}. T0 needs a resource X to complete its task. Resource X is held by T1, and T1 is waiting for a resource Y, which is held by T2. T2 is waiting for resource Z, which is held by T0. Thus, all the processes wait for each other to release resources. In this situation, none of the processes can finish their task. This situation is known as a deadlock."},{"code":null,"e":102827,"s":102667,"text":"Deadlocks are not healthy for a system. In case a system is stuck in a deadlock, the transactions involved in the deadlock are either rolled back or restarted."},{"code":null,"e":103161,"s":102827,"text":"To prevent any deadlock situation in the system, the DBMS aggressively inspects all the operations, where transactions are about to execute. The DBMS inspects the operations and analyzes if they can create a deadlock situation. If it finds that a deadlock situation might occur, then that transaction is never allowed to be executed."},{"code":null,"e":103300,"s":103161,"text":"There are deadlock prevention schemes that use timestamp ordering mechanism of transactions in order to predetermine a deadlock situation."},{"code":null,"e":103490,"s":103300,"text":"In this scheme, if a transaction requests to lock a resource (data item), which is already held with a conflicting lock by another transaction, then one of the two possibilities may occur −"},{"code":null,"e":103644,"s":103490,"text":"If TS(Ti) < TS(Tj) − that is Ti, which is requesting a conflicting lock, is older than Tj − then Ti is allowed to wait until the data-item is available."},{"code":null,"e":103798,"s":103644,"text":"If TS(Ti) < TS(Tj) − that is Ti, which is requesting a conflicting lock, is older than Tj − then Ti is allowed to wait until the data-item is available."},{"code":null,"e":103937,"s":103798,"text":"If TS(Ti) > TS(tj) − that is Ti is younger than Tj − then Ti dies. Ti is restarted later with a random delay but with the same timestamp."},{"code":null,"e":104076,"s":103937,"text":"If TS(Ti) > TS(tj) − that is Ti is younger than Tj − then Ti dies. Ti is restarted later with a random delay but with the same timestamp."},{"code":null,"e":104152,"s":104076,"text":"This scheme allows the older transaction to wait but kills the younger one."},{"code":null,"e":104340,"s":104152,"text":"In this scheme, if a transaction requests to lock a resource (data item), which is already held with conflicting lock by some another transaction, one of the two possibilities may occur −"},{"code":null,"e":104491,"s":104340,"text":"If TS(Ti) < TS(Tj), then Ti forces Tj to be rolled back − that is Ti wounds Tj. Tj is restarted later with a random delay but with the same timestamp."},{"code":null,"e":104642,"s":104491,"text":"If TS(Ti) < TS(Tj), then Ti forces Tj to be rolled back − that is Ti wounds Tj. Tj is restarted later with a random delay but with the same timestamp."},{"code":null,"e":104721,"s":104642,"text":"If TS(Ti) > TS(Tj), then Ti is forced to wait until the resource is available."},{"code":null,"e":104800,"s":104721,"text":"If TS(Ti) > TS(Tj), then Ti is forced to wait until the resource is available."},{"code":null,"e":104999,"s":104800,"text":"This scheme, allows the younger transaction to wait; but when an older transaction requests an item held by a younger one, the older transaction forces the younger one to abort and release the item."},{"code":null,"e":105086,"s":104999,"text":"In both the cases, the transaction that enters the system at a later stage is aborted."},{"code":null,"e":105466,"s":105086,"text":"Aborting a transaction is not always a practical approach. Instead, deadlock avoidance mechanisms can be used to detect any deadlock situation in advance. Methods like \"wait-for graph\" are available but they are suitable for only those systems where transactions are lightweight having fewer instances of resource. In a bulky system, deadlock prevention techniques may work well."},{"code":null,"e":105843,"s":105466,"text":"This is a simple method available to track if any deadlock situation may arise. For each transaction entering into the system, a node is created. When a transaction Ti requests for a lock on an item, say X, which is held by some other transaction Tj, a directed edge is created from Ti to Tj. If Tj releases item X, the edge between them is dropped and Ti locks the data item."},{"code":null,"e":106011,"s":105843,"text":"The system maintains this wait-for graph for every transaction waiting for some data items held by others. The system keeps checking if there's any cycle in the graph."},{"code":null,"e":106066,"s":106011,"text":"Here, we can use any of the two following approaches −"},{"code":null,"e":106294,"s":106066,"text":"First, do not allow any request for an item, which is already locked by another transaction. This is not always feasible and may cause starvation, where a transaction indefinitely waits for a data item and can never acquire it."},{"code":null,"e":106522,"s":106294,"text":"First, do not allow any request for an item, which is already locked by another transaction. This is not always feasible and may cause starvation, where a transaction indefinitely waits for a data item and can never acquire it."},{"code":null,"e":106865,"s":106522,"text":"The second option is to roll back one of the transactions. It is not always feasible to roll back the younger transaction, as it may be important than the older one. With the help of some relative algorithm, a transaction is chosen, which is to be aborted. This transaction is known as the victim and the process is known as victim selection."},{"code":null,"e":107208,"s":106865,"text":"The second option is to roll back one of the transactions. It is not always feasible to roll back the younger transaction, as it may be important than the older one. With the help of some relative algorithm, a transaction is chosen, which is to be aborted. This transaction is known as the victim and the process is known as victim selection."},{"code":null,"e":107607,"s":107208,"text":"A volatile storage like RAM stores all the active logs, disk buffers, and related data. In addition, it stores all the transactions that are being currently executed. What happens if such a volatile storage crashes abruptly? It would obviously take away all the logs and active copies of the database. It makes recovery almost impossible, as everything that is required to recover the data is lost."},{"code":null,"e":107681,"s":107607,"text":"Following techniques may be adopted in case of loss of volatile storage −"},{"code":null,"e":107781,"s":107681,"text":"We can have checkpoints at multiple stages so as to save the contents of the database periodically."},{"code":null,"e":107881,"s":107781,"text":"We can have checkpoints at multiple stages so as to save the contents of the database periodically."},{"code":null,"e":108052,"s":107881,"text":"A state of active database in the volatile memory can be periodically dumped onto a stable storage, which may also contain logs and active transactions and buffer blocks."},{"code":null,"e":108223,"s":108052,"text":"A state of active database in the volatile memory can be periodically dumped onto a stable storage, which may also contain logs and active transactions and buffer blocks."},{"code":null,"e":108345,"s":108223,"text":" can be marked on a log file, whenever the database contents are dumped from a non-volatile memory to a stable one."},{"code":null,"e":108467,"s":108345,"text":" can be marked on a log file, whenever the database contents are dumped from a non-volatile memory to a stable one."},{"code":null,"e":108540,"s":108467,"text":"When the system recovers from a failure, it can restore the latest dump."},{"code":null,"e":108613,"s":108540,"text":"When the system recovers from a failure, it can restore the latest dump."},{"code":null,"e":108674,"s":108613,"text":"It can maintain a redo-list and an undo-list as checkpoints."},{"code":null,"e":108735,"s":108674,"text":"It can maintain a redo-list and an undo-list as checkpoints."},{"code":null,"e":108859,"s":108735,"text":"It can recover the system by consulting undo-redo lists to restore the state of all transactions up to the last checkpoint."},{"code":null,"e":108983,"s":108859,"text":"It can recover the system by consulting undo-redo lists to restore the state of all transactions up to the last checkpoint."},{"code":null,"e":109230,"s":108983,"text":"A catastrophic failure is one where a stable, secondary storage device gets corrupt. With the storage device, all the valuable data that is stored inside is lost. We have two different strategies to recover data from such a catastrophic failure −"},{"code":null,"e":109373,"s":109230,"text":"Remote backup &minu; Here a backup copy of the database is stored at a remote location from where it can be restored in case of a catastrophe."},{"code":null,"e":109516,"s":109373,"text":"Remote backup &minu; Here a backup copy of the database is stored at a remote location from where it can be restored in case of a catastrophe."},{"code":null,"e":109715,"s":109516,"text":"Alternatively, database backups can be taken on magnetic tapes and stored at a safer place. This backup can later be transferred onto a freshly installed database to bring it to the point of backup."},{"code":null,"e":109914,"s":109715,"text":"Alternatively, database backups can be taken on magnetic tapes and stored at a safer place. This backup can later be transferred onto a freshly installed database to bring it to the point of backup."},{"code":null,"e":110299,"s":109914,"text":"Grown-up databases are too bulky to be frequently backed up. In such cases, we have techniques where we can restore a database just by looking at its logs. So, all that we need to do here is to take a backup of all the logs at frequent intervals of time. The database can be backed up once a week, and the logs being very small can be backed up every day or as frequently as possible."},{"code":null,"e":110520,"s":110299,"text":"Remote backup provides a sense of security in case the primary location where the database is located gets destroyed. Remote backup can be offline or real-time or online. In case it is offline, it is maintained manually."},{"code":null,"e":110850,"s":110520,"text":"Online backup systems are more real-time and lifesavers for database administrators and investors. An online backup system is a mechanism where every bit of the real-time data is backed up simultaneously at two distant places. One of them is directly connected to the system and the other one is kept at a remote place as backup."},{"code":null,"e":111060,"s":110850,"text":"As soon as the primary database storage fails, the backup system senses the failure and switches the user system to the remote storage. Sometimes this is so instant that the users can’t even realize a failure."},{"code":null,"e":111421,"s":111060,"text":"DBMS is a highly complex system with hundreds of transactions being executed every second. The durability and robustness of a DBMS depends on its complex architecture and its underlying hardware and system software. If it fails or crashes amid transactions, it is expected that the system would follow some sort of algorithm or techniques to recover lost data."},{"code":null,"e":111522,"s":111421,"text":"To see where the problem has occurred, we generalize a failure into various categories, as follows −"},{"code":null,"e":111725,"s":111522,"text":"A transaction has to abort when it fails to execute or when it reaches a point from where it can’t go any further. This is called transaction failure where only a few transactions or processes are hurt."},{"code":null,"e":111770,"s":111725,"text":"Reasons for a transaction failure could be −"},{"code":null,"e":111887,"s":111770,"text":"Logical errors − Where a transaction cannot complete because it has some code error or any internal error condition."},{"code":null,"e":112004,"s":111887,"text":"Logical errors − Where a transaction cannot complete because it has some code error or any internal error condition."},{"code":null,"e":112284,"s":112004,"text":"System errors − Where the database system itself terminates an active transaction because the DBMS is not able to execute it, or it has to stop because of some system condition. For example, in case of deadlock or resource unavailability, the system aborts an active transaction."},{"code":null,"e":112564,"s":112284,"text":"System errors − Where the database system itself terminates an active transaction because the DBMS is not able to execute it, or it has to stop because of some system condition. For example, in case of deadlock or resource unavailability, the system aborts an active transaction."},{"code":null,"e":112793,"s":112564,"text":"There are problems − external to the system − that may cause the system to stop abruptly and cause the system to crash. For example, interruptions in power supply may cause the failure of underlying hardware or software failure."},{"code":null,"e":112839,"s":112793,"text":"Examples may include operating system errors."},{"code":null,"e":112968,"s":112839,"text":"In early days of technology evolution, it was a common problem where hard-disk drives or storage drives used to fail frequently."},{"code":null,"e":113128,"s":112968,"text":"Disk failures include formation of bad sectors, unreachability to the disk, disk head crash or any other failure, which destroys all or a part of disk storage."},{"code":null,"e":113243,"s":113128,"text":"We have already described the storage system. In brief, the storage structure can be divided into two categories −"},{"code":null,"e":113585,"s":113243,"text":"Volatile storage − As the name suggests, a volatile storage cannot survive system crashes. Volatile storage devices are placed very close to the CPU; normally they are embedded onto the chipset itself. For example, main memory and cache memory are examples of volatile storage. They are fast but can store only a small amount of information."},{"code":null,"e":113927,"s":113585,"text":"Volatile storage − As the name suggests, a volatile storage cannot survive system crashes. Volatile storage devices are placed very close to the CPU; normally they are embedded onto the chipset itself. For example, main memory and cache memory are examples of volatile storage. They are fast but can store only a small amount of information."},{"code":null,"e":114175,"s":113927,"text":"Non-volatile storage − These memories are made to survive system crashes. They are huge in data storage capacity, but slower in accessibility. Examples may include hard-disks, magnetic tapes, flash memory, and non-volatile (battery backed up) RAM."},{"code":null,"e":114423,"s":114175,"text":"Non-volatile storage − These memories are made to survive system crashes. They are huge in data storage capacity, but slower in accessibility. Examples may include hard-disks, magnetic tapes, flash memory, and non-volatile (battery backed up) RAM."},{"code":null,"e":114783,"s":114423,"text":"When a system crashes, it may have several transactions being executed and various files opened for them to modify the data items. Transactions are made of various operations, which are atomic in nature. But according to ACID properties of DBMS, atomicity of transactions as a whole must be maintained, that is, either all the operations are executed or none."},{"code":null,"e":114853,"s":114783,"text":"When a DBMS recovers from a crash, it should maintain the following −"},{"code":null,"e":114932,"s":114853,"text":"It should check the states of all the transactions, which were being executed."},{"code":null,"e":115011,"s":114932,"text":"It should check the states of all the transactions, which were being executed."},{"code":null,"e":115133,"s":115011,"text":"A transaction may be in the middle of some operation; the DBMS must ensure the atomicity of the transaction in this case."},{"code":null,"e":115255,"s":115133,"text":"A transaction may be in the middle of some operation; the DBMS must ensure the atomicity of the transaction in this case."},{"code":null,"e":115347,"s":115255,"text":"It should check whether the transaction can be completed now or it needs to be rolled back."},{"code":null,"e":115439,"s":115347,"text":"It should check whether the transaction can be completed now or it needs to be rolled back."},{"code":null,"e":115516,"s":115439,"text":"No transactions would be allowed to leave the DBMS in an inconsistent state."},{"code":null,"e":115593,"s":115516,"text":"No transactions would be allowed to leave the DBMS in an inconsistent state."},{"code":null,"e":115720,"s":115593,"text":"There are two types of techniques, which can help a DBMS in recovering as well as maintaining the atomicity of a transaction −"},{"code":null,"e":115844,"s":115720,"text":"Maintaining the logs of each transaction, and writing them onto some stable storage before actually modifying the database."},{"code":null,"e":115968,"s":115844,"text":"Maintaining the logs of each transaction, and writing them onto some stable storage before actually modifying the database."},{"code":null,"e":116087,"s":115968,"text":"Maintaining shadow paging, where the changes are done on a volatile memory, and later, the actual database is updated."},{"code":null,"e":116206,"s":116087,"text":"Maintaining shadow paging, where the changes are done on a volatile memory, and later, the actual database is updated."},{"code":null,"e":116435,"s":116206,"text":"Log is a sequence of records, which maintains the records of actions performed by a transaction. It is important that the logs are written prior to the actual modification and stored on a stable storage media, which is failsafe."},{"code":null,"e":116473,"s":116435,"text":"Log-based recovery works as follows −"},{"code":null,"e":116521,"s":116473,"text":"The log file is kept on a stable storage media."},{"code":null,"e":116569,"s":116521,"text":"The log file is kept on a stable storage media."},{"code":null,"e":116654,"s":116569,"text":"When a transaction enters the system and starts execution, it writes a log about it."},{"code":null,"e":116739,"s":116654,"text":"When a transaction enters the system and starts execution, it writes a log about it."},{"code":null,"e":116752,"s":116739,"text":"\n"},{"code":null,"e":116820,"s":116752,"text":"When the transaction modifies an item X, it write logs as follows −"},{"code":null,"e":116888,"s":116820,"text":"When the transaction modifies an item X, it write logs as follows −"},{"code":null,"e":116905,"s":116888,"text":"\n"},{"code":null,"e":116960,"s":116905,"text":"It reads Tn has changed the value of X, from V1 to V2."},{"code":null,"e":117001,"s":116960,"text":"When the transaction finishes, it logs −"},{"code":null,"e":117015,"s":117001,"text":"\n"},{"code":null,"e":117067,"s":117015,"text":"The database can be modified using two approaches −"},{"code":null,"e":117202,"s":117067,"text":"Deferred database modification − All logs are written on to the stable storage and the database is updated when a transaction commits."},{"code":null,"e":117337,"s":117202,"text":"Deferred database modification − All logs are written on to the stable storage and the database is updated when a transaction commits."},{"code":null,"e":117490,"s":117337,"text":"Immediate database modification − Each log follows an actual database modification. That is, the database is modified immediately after every operation."},{"code":null,"e":117643,"s":117490,"text":"Immediate database modification − Each log follows an actual database modification. That is, the database is modified immediately after every operation."},{"code":null,"e":117927,"s":117643,"text":"When more than one transaction are being executed in parallel, the logs are interleaved. At the time of recovery, it would become hard for the recovery system to backtrack all logs, and then start recovering. To ease this situation, most modern DBMS use the concept of 'checkpoints'."},{"code":null,"e":118360,"s":117927,"text":"Keeping and maintaining logs in real time and in real environment may fill out all the memory space available in the system. As time passes, the log file may grow too big to be handled at all. Checkpoint is a mechanism where all the previous logs are removed from the system and stored permanently in a storage disk. Checkpoint declares a point before which the DBMS was in consistent state, and all the transactions were committed."},{"code":null,"e":118462,"s":118360,"text":"When a system with concurrent transactions crashes and recovers, it behaves in the following manner −"},{"code":null,"e":118544,"s":118462,"text":"The recovery system reads the logs backwards from the end to the last checkpoint."},{"code":null,"e":118626,"s":118544,"text":"The recovery system reads the logs backwards from the end to the last checkpoint."},{"code":null,"e":118680,"s":118626,"text":"It maintains two lists, an undo-list and a redo-list."},{"code":null,"e":118734,"s":118680,"text":"It maintains two lists, an undo-list and a redo-list."},{"code":null,"e":118866,"s":118734,"text":"If the recovery system sees a log with and or just , it puts the transaction in the redo-list."},{"code":null,"e":118998,"s":118866,"text":"If the recovery system sees a log with and or just , it puts the transaction in the redo-list."},{"code":null,"e":119121,"s":118998,"text":"If the recovery system sees a log with but no commit or abort log found, it puts the transaction in undo-list."},{"code":null,"e":119244,"s":119121,"text":"If the recovery system sees a log with but no commit or abort log found, it puts the transaction in undo-list."},{"code":null,"e":119442,"s":119244,"text":"All the transactions in the undo-list are then undone and their logs are removed. All the transactions in the redo-list and their previous logs are removed and then redone before saving their logs."},{"code":null,"e":119479,"s":119442,"text":"\n 178 Lectures \n 14.5 hours \n"},{"code":null,"e":119498,"s":119479,"text":" Arnab Chakraborty"},{"code":null,"e":119533,"s":119498,"text":"\n 194 Lectures \n 16 hours \n"},{"code":null,"e":119552,"s":119533,"text":" Arnab Chakraborty"},{"code":null,"e":119559,"s":119552,"text":" Print"},{"code":null,"e":119570,"s":119559,"text":" Add Notes"}],"string":"[\n {\n \"code\": null,\n \"e\": 2415,\n \"s\": 2282,\n \"text\": \"Database is a collection of related data and data is a collection of facts and figures that can be processed to produce information.\"\n },\n {\n \"code\": null,\n \"e\": 2638,\n \"s\": 2415,\n \"text\": \"Mostly data represents recordable facts. Data aids in producing information, which is based on facts. For example, if we have data about marks obtained by all students, we can then conclude about toppers and average marks.\"\n },\n {\n \"code\": null,\n \"e\": 2766,\n \"s\": 2638,\n \"text\": \"A database management system stores data in such a way that it becomes easier to retrieve, manipulate, and produce information.\"\n },\n {\n \"code\": null,\n \"e\": 3004,\n \"s\": 2766,\n \"text\": \"Traditionally, data was organized in file formats. DBMS was a new concept then, and all the research was done to make it overcome the deficiencies in traditional style of data management. A modern DBMS has the following characteristics −\"\n },\n {\n \"code\": null,\n \"e\": 3246,\n \"s\": 3004,\n \"text\": \"Real-world entity − A modern DBMS is more realistic and uses real-world entities to design its architecture. It uses the behavior and attributes too. For example, a school database may use students as an entity and their age as an attribute.\"\n },\n {\n \"code\": null,\n \"e\": 3488,\n \"s\": 3246,\n \"text\": \"Real-world entity − A modern DBMS is more realistic and uses real-world entities to design its architecture. It uses the behavior and attributes too. For example, a school database may use students as an entity and their age as an attribute.\"\n },\n {\n \"code\": null,\n \"e\": 3663,\n \"s\": 3488,\n \"text\": \"Relation-based tables − DBMS allows entities and relations among them to form tables. A user can understand the architecture of a database just by looking at the table names.\"\n },\n {\n \"code\": null,\n \"e\": 3838,\n \"s\": 3663,\n \"text\": \"Relation-based tables − DBMS allows entities and relations among them to form tables. A user can understand the architecture of a database just by looking at the table names.\"\n },\n {\n \"code\": null,\n \"e\": 4118,\n \"s\": 3838,\n \"text\": \"Isolation of data and application − A database system is entirely different than its data. A database is an active entity, whereas data is said to be passive, on which the database works and organizes. DBMS also stores metadata, which is data about data, to ease its own process.\"\n },\n {\n \"code\": null,\n \"e\": 4398,\n \"s\": 4118,\n \"text\": \"Isolation of data and application − A database system is entirely different than its data. A database is an active entity, whereas data is said to be passive, on which the database works and organizes. DBMS also stores metadata, which is data about data, to ease its own process.\"\n },\n {\n \"code\": null,\n \"e\": 4632,\n \"s\": 4398,\n \"text\": \"Less redundancy − DBMS follows the rules of normalization, which splits a relation when any of its attributes is having redundancy in values. Normalization is a mathematically rich and scientific process that reduces data redundancy.\"\n },\n {\n \"code\": null,\n \"e\": 4866,\n \"s\": 4632,\n \"text\": \"Less redundancy − DBMS follows the rules of normalization, which splits a relation when any of its attributes is having redundancy in values. Normalization is a mathematically rich and scientific process that reduces data redundancy.\"\n },\n {\n \"code\": null,\n \"e\": 5189,\n \"s\": 4866,\n \"text\": \"Consistency − Consistency is a state where every relation in a database remains consistent. There exist methods and techniques, which can detect attempt of leaving database in inconsistent state. A DBMS can provide greater consistency as compared to earlier forms of data storing applications like file-processing systems.\"\n },\n {\n \"code\": null,\n \"e\": 5512,\n \"s\": 5189,\n \"text\": \"Consistency − Consistency is a state where every relation in a database remains consistent. There exist methods and techniques, which can detect attempt of leaving database in inconsistent state. A DBMS can provide greater consistency as compared to earlier forms of data storing applications like file-processing systems.\"\n },\n {\n \"code\": null,\n \"e\": 5802,\n \"s\": 5512,\n \"text\": \"Query Language − DBMS is equipped with query language, which makes it more efficient to retrieve and manipulate data. A user can apply as many and as different filtering options as required to retrieve a set of data. Traditionally it was not possible where file-processing system was used.\"\n },\n {\n \"code\": null,\n \"e\": 6092,\n \"s\": 5802,\n \"text\": \"Query Language − DBMS is equipped with query language, which makes it more efficient to retrieve and manipulate data. A user can apply as many and as different filtering options as required to retrieve a set of data. Traditionally it was not possible where file-processing system was used.\"\n },\n {\n \"code\": null,\n \"e\": 6407,\n \"s\": 6092,\n \"text\": \"ACID Properties − DBMS follows the concepts of Atomicity, Consistency, Isolation, and Durability (normally shortened as ACID). These concepts are applied on transactions, which manipulate data in a database. ACID properties help the database stay healthy in multi-transactional environments and in case of failure.\"\n },\n {\n \"code\": null,\n \"e\": 6722,\n \"s\": 6407,\n \"text\": \"ACID Properties − DBMS follows the concepts of Atomicity, Consistency, Isolation, and Durability (normally shortened as ACID). These concepts are applied on transactions, which manipulate data in a database. ACID properties help the database stay healthy in multi-transactional environments and in case of failure.\"\n },\n {\n \"code\": null,\n \"e\": 6985,\n \"s\": 6722,\n \"text\": \"Multiuser and Concurrent Access − DBMS supports multi-user environment and allows them to access and manipulate data in parallel. Though there are restrictions on transactions when users attempt to handle the same data item, but users are always unaware of them.\"\n },\n {\n \"code\": null,\n \"e\": 7248,\n \"s\": 6985,\n \"text\": \"Multiuser and Concurrent Access − DBMS supports multi-user environment and allows them to access and manipulate data in parallel. Though there are restrictions on transactions when users attempt to handle the same data item, but users are always unaware of them.\"\n },\n {\n \"code\": null,\n \"e\": 7549,\n \"s\": 7248,\n \"text\": \"Multiple views − DBMS offers multiple views for different users. A user who is in the Sales department will have a different view of database than a person working in the Production department. This feature enables the users to have a concentrate view of the database according to their requirements.\"\n },\n {\n \"code\": null,\n \"e\": 7850,\n \"s\": 7549,\n \"text\": \"Multiple views − DBMS offers multiple views for different users. A user who is in the Sales department will have a different view of database than a person working in the Production department. This feature enables the users to have a concentrate view of the database according to their requirements.\"\n },\n {\n \"code\": null,\n \"e\": 8576,\n \"s\": 7850,\n \"text\": \"Security − Features like multiple views offer security to some extent where users are unable to access data of other users and departments. DBMS offers methods to impose constraints while entering data into the database and retrieving the same at a later stage. DBMS offers many different levels of security features, which enables multiple users to have different views with different features. For example, a user in the Sales department cannot see the data that belongs to the Purchase department. Additionally, it can also be managed how much data of the Sales department should be displayed to the user. Since a DBMS is not saved on the disk as traditional file systems, it is very hard for miscreants to break the code.\"\n },\n {\n \"code\": null,\n \"e\": 9302,\n \"s\": 8576,\n \"text\": \"Security − Features like multiple views offer security to some extent where users are unable to access data of other users and departments. DBMS offers methods to impose constraints while entering data into the database and retrieving the same at a later stage. DBMS offers many different levels of security features, which enables multiple users to have different views with different features. For example, a user in the Sales department cannot see the data that belongs to the Purchase department. Additionally, it can also be managed how much data of the Sales department should be displayed to the user. Since a DBMS is not saved on the disk as traditional file systems, it is very hard for miscreants to break the code.\"\n },\n {\n \"code\": null,\n \"e\": 9506,\n \"s\": 9302,\n \"text\": \"A typical DBMS has users with different rights and permissions who use it for different purposes. Some users retrieve data and some back it up. The users of a DBMS can be broadly categorized as follows −\"\n },\n {\n \"code\": null,\n \"e\": 9923,\n \"s\": 9506,\n \"text\": \"Administrators − Administrators maintain the DBMS and are responsible for administrating the database. They are responsible to look after its usage and by whom it should be used. They create access profiles for users and apply limitations to maintain isolation and force security. Administrators also look after DBMS resources like system license, required tools, and other software and hardware related maintenance.\"\n },\n {\n \"code\": null,\n \"e\": 10340,\n \"s\": 9923,\n \"text\": \"Administrators − Administrators maintain the DBMS and are responsible for administrating the database. They are responsible to look after its usage and by whom it should be used. They create access profiles for users and apply limitations to maintain isolation and force security. Administrators also look after DBMS resources like system license, required tools, and other software and hardware related maintenance.\"\n },\n {\n \"code\": null,\n \"e\": 10602,\n \"s\": 10340,\n \"text\": \"Designers − Designers are the group of people who actually work on the designing part of the database. They keep a close watch on what data should be kept and in what format. They identify and design the whole set of entities, relations, constraints, and views.\"\n },\n {\n \"code\": null,\n \"e\": 10864,\n \"s\": 10602,\n \"text\": \"Designers − Designers are the group of people who actually work on the designing part of the database. They keep a close watch on what data should be kept and in what format. They identify and design the whole set of entities, relations, constraints, and views.\"\n },\n {\n \"code\": null,\n \"e\": 11081,\n \"s\": 10864,\n \"text\": \"End Users − End users are those who actually reap the benefits of having a DBMS. End users can range from simple viewers who pay attention to the logs or market rates to sophisticated users such as business analysts.\"\n },\n {\n \"code\": null,\n \"e\": 11298,\n \"s\": 11081,\n \"text\": \"End Users − End users are those who actually reap the benefits of having a DBMS. End users can range from simple viewers who pay attention to the logs or market rates to sophisticated users such as business analysts.\"\n },\n {\n \"code\": null,\n \"e\": 11636,\n \"s\": 11298,\n \"text\": \"The design of a DBMS depends on its architecture. It can be centralized or decentralized or hierarchical. The architecture of a DBMS can be seen as either single tier or multi-tier. An n-tier architecture divides the whole system into related but independent n modules, which can be independently modified, altered, changed, or replaced.\"\n },\n {\n \"code\": null,\n \"e\": 11937,\n \"s\": 11636,\n \"text\": \"In 1-tier architecture, the DBMS is the only entity where the user directly sits on the DBMS and uses it. Any changes done here will directly be done on the DBMS itself. It does not provide handy tools for end-users. Database designers and programmers normally prefer to use single-tier architecture.\"\n },\n {\n \"code\": null,\n \"e\": 12254,\n \"s\": 11937,\n \"text\": \"If the architecture of DBMS is 2-tier, then it must have an application through which the DBMS can be accessed. Programmers use 2-tier architecture where they access the DBMS by means of an application. Here the application tier is entirely independent of the database in terms of operation, design, and programming.\"\n },\n {\n \"code\": null,\n \"e\": 12458,\n \"s\": 12254,\n \"text\": \"A 3-tier architecture separates its tiers from each other based on the complexity of the users and how they use the data present in the database. It is the most widely used architecture to design a DBMS.\"\n },\n {\n \"code\": null,\n \"e\": 12644,\n \"s\": 12458,\n \"text\": \"Database (Data) Tier − At this tier, the database resides along with its query processing languages. We also have the relations that define the data and their constraints at this level.\"\n },\n {\n \"code\": null,\n \"e\": 12830,\n \"s\": 12644,\n \"text\": \"Database (Data) Tier − At this tier, the database resides along with its query processing languages. We also have the relations that define the data and their constraints at this level.\"\n },\n {\n \"code\": null,\n \"e\": 13308,\n \"s\": 12830,\n \"text\": \"Application (Middle) Tier − At this tier reside the application server and the programs that access the database. For a user, this application tier presents an abstracted view of the database. End-users are unaware of any existence of the database beyond the application. At the other end, the database tier is not aware of any other user beyond the application tier. Hence, the application layer sits in the middle and acts as a mediator between the end-user and the database.\"\n },\n {\n \"code\": null,\n \"e\": 13786,\n \"s\": 13308,\n \"text\": \"Application (Middle) Tier − At this tier reside the application server and the programs that access the database. For a user, this application tier presents an abstracted view of the database. End-users are unaware of any existence of the database beyond the application. At the other end, the database tier is not aware of any other user beyond the application tier. Hence, the application layer sits in the middle and acts as a mediator between the end-user and the database.\"\n },\n {\n \"code\": null,\n \"e\": 14080,\n \"s\": 13786,\n \"text\": \"User (Presentation) Tier − End-users operate on this tier and they know nothing about any existence of the database beyond this layer. At this layer, multiple views of the database can be provided by the application. All views are generated by applications that reside in the application tier.\"\n },\n {\n \"code\": null,\n \"e\": 14374,\n \"s\": 14080,\n \"text\": \"User (Presentation) Tier − End-users operate on this tier and they know nothing about any existence of the database beyond this layer. At this layer, multiple views of the database can be provided by the application. All views are generated by applications that reside in the application tier.\"\n },\n {\n \"code\": null,\n \"e\": 14511,\n \"s\": 14374,\n \"text\": \"Multiple-tier database architecture is highly modifiable, as almost all its components are independent and can be changed independently.\"\n },\n {\n \"code\": null,\n \"e\": 14767,\n \"s\": 14511,\n \"text\": \"Data models define how the logical structure of a database is modeled. Data Models are fundamental entities to introduce abstraction in a DBMS. Data models define how data is connected to each other and how they are processed and stored inside the system.\"\n },\n {\n \"code\": null,\n \"e\": 14999,\n \"s\": 14767,\n \"text\": \"The very first data model could be flat data-models, where all the data used are to be kept in the same plane. Earlier data models were not so scientific, hence they were prone to introduce lots of duplication and update anomalies.\"\n },\n {\n \"code\": null,\n \"e\": 15256,\n \"s\": 14999,\n \"text\": \"Entity-Relationship (ER) Model is based on the notion of real-world entities and relationships among them. While formulating real-world scenario into the database model, the ER Model creates entity set, relationship set, general attributes and constraints.\"\n },\n {\n \"code\": null,\n \"e\": 15319,\n \"s\": 15256,\n \"text\": \"ER Model is best used for the conceptual design of a database.\"\n },\n {\n \"code\": null,\n \"e\": 15342,\n \"s\": 15319,\n \"text\": \"ER Model is based on −\"\n },\n {\n \"code\": null,\n \"e\": 15373,\n \"s\": 15342,\n \"text\": \"Entities and their attributes.\"\n },\n {\n \"code\": null,\n \"e\": 15404,\n \"s\": 15373,\n \"text\": \"Entities and their attributes.\"\n },\n {\n \"code\": null,\n \"e\": 15434,\n \"s\": 15404,\n \"text\": \"Relationships among entities.\"\n },\n {\n \"code\": null,\n \"e\": 15464,\n \"s\": 15434,\n \"text\": \"Relationships among entities.\"\n },\n {\n \"code\": null,\n \"e\": 15500,\n \"s\": 15464,\n \"text\": \"These concepts are explained below.\"\n },\n {\n \"code\": null,\n \"e\": 15789,\n \"s\": 15500,\n \"text\": \"Entity − An entity in an ER Model is a real-world entity having properties called attributes. Every attribute is defined by its set of values called domain. For example, in a school database, a student is considered as an entity. Student has various attributes like name, age, class, etc.\"\n },\n {\n \"code\": null,\n \"e\": 16078,\n \"s\": 15789,\n \"text\": \"Entity − An entity in an ER Model is a real-world entity having properties called attributes. Every attribute is defined by its set of values called domain. For example, in a school database, a student is considered as an entity. Student has various attributes like name, age, class, etc.\"\n },\n {\n \"code\": null,\n \"e\": 16364,\n \"s\": 16078,\n \"text\": \"Relationship − The logical association among entities is called relationship. Relationships are mapped with entities in various ways. Mapping cardinalities define the number of association between two entities.\\nMapping cardinalities −\\n\\none to one\\none to many\\nmany to one\\nmany to many\\n\\n\"\n },\n {\n \"code\": null,\n \"e\": 16575,\n \"s\": 16364,\n \"text\": \"Relationship − The logical association among entities is called relationship. Relationships are mapped with entities in various ways. Mapping cardinalities define the number of association between two entities.\"\n },\n {\n \"code\": null,\n \"e\": 16599,\n \"s\": 16575,\n \"text\": \"Mapping cardinalities −\"\n },\n {\n \"code\": null,\n \"e\": 16610,\n \"s\": 16599,\n \"text\": \"one to one\"\n },\n {\n \"code\": null,\n \"e\": 16622,\n \"s\": 16610,\n \"text\": \"one to many\"\n },\n {\n \"code\": null,\n \"e\": 16634,\n \"s\": 16622,\n \"text\": \"many to one\"\n },\n {\n \"code\": null,\n \"e\": 16647,\n \"s\": 16634,\n \"text\": \"many to many\"\n },\n {\n \"code\": null,\n \"e\": 16844,\n \"s\": 16647,\n \"text\": \"The most popular data model in DBMS is the Relational Model. It is more scientific a model than others. This model is based on first-order predicate logic and defines a table as an n-ary relation.\"\n },\n {\n \"code\": null,\n \"e\": 16884,\n \"s\": 16844,\n \"text\": \"The main highlights of this model are −\"\n },\n {\n \"code\": null,\n \"e\": 16927,\n \"s\": 16884,\n \"text\": \"Data is stored in tables called relations.\"\n },\n {\n \"code\": null,\n \"e\": 16956,\n \"s\": 16927,\n \"text\": \"Relations can be normalized.\"\n },\n {\n \"code\": null,\n \"e\": 17013,\n \"s\": 16956,\n \"text\": \"In normalized relations, values saved are atomic values.\"\n },\n {\n \"code\": null,\n \"e\": 17061,\n \"s\": 17013,\n \"text\": \"Each row in a relation contains a unique value.\"\n },\n {\n \"code\": null,\n \"e\": 17123,\n \"s\": 17061,\n \"text\": \"Each column in a relation contains values from a same domain.\"\n },\n {\n \"code\": null,\n \"e\": 17380,\n \"s\": 17123,\n \"text\": \"A database schema is the skeleton structure that represents the logical view of the entire database. It defines how the data is organized and how the relations among them are associated. It formulates all the constraints that are to be applied on the data.\"\n },\n {\n \"code\": null,\n \"e\": 17667,\n \"s\": 17380,\n \"text\": \"A database schema defines its entities and the relationship among them. It contains a descriptive detail of the database, which can be depicted by means of schema diagrams. It’s the database designers who design the schema to help programmers understand the database and make it useful.\"\n },\n {\n \"code\": null,\n \"e\": 17730,\n \"s\": 17667,\n \"text\": \"A database schema can be divided broadly into two categories −\"\n },\n {\n \"code\": null,\n \"e\": 17921,\n \"s\": 17730,\n \"text\": \"Physical Database Schema − This schema pertains to the actual storage of data and its form of storage like files, indices, etc. It defines how the data will be stored in a secondary storage.\"\n },\n {\n \"code\": null,\n \"e\": 18112,\n \"s\": 17921,\n \"text\": \"Physical Database Schema − This schema pertains to the actual storage of data and its form of storage like files, indices, etc. It defines how the data will be stored in a secondary storage.\"\n },\n {\n \"code\": null,\n \"e\": 18283,\n \"s\": 18112,\n \"text\": \"Logical Database Schema − This schema defines all the logical constraints that need to be applied on the data stored. It defines tables, views, and integrity constraints.\"\n },\n {\n \"code\": null,\n \"e\": 18454,\n \"s\": 18283,\n \"text\": \"Logical Database Schema − This schema defines all the logical constraints that need to be applied on the data stored. It defines tables, views, and integrity constraints.\"\n },\n {\n \"code\": null,\n \"e\": 18762,\n \"s\": 18454,\n \"text\": \"It is important that we distinguish these two terms individually. Database schema is the skeleton of database. It is designed when the database doesn't exist at all. Once the database is operational, it is very difficult to make any changes to it. A database schema does not contain any data or information.\"\n },\n {\n \"code\": null,\n \"e\": 19114,\n \"s\": 18762,\n \"text\": \"A database instance is a state of operational database with data at any given time. It contains a snapshot of the database. Database instances tend to change with time. A DBMS ensures that its every instance (state) is in a valid state, by diligently following all the validations, constraints, and conditions that the database designers have imposed.\"\n },\n {\n \"code\": null,\n \"e\": 19295,\n \"s\": 19114,\n \"text\": \"If a database system is not multi-layered, then it becomes difficult to make any changes in the database system. Database systems are designed in multi-layers as we learnt earlier.\"\n },\n {\n \"code\": null,\n \"e\": 19741,\n \"s\": 19295,\n \"text\": \"A database system normally contains a lot of data in addition to users’ data. For example, it stores data about data, known as metadata, to locate and retrieve data easily. It is rather difficult to modify or update a set of metadata once it is stored in the database. But as a DBMS expands, it needs to change over time to satisfy the requirements of the users. If the entire data is dependent, it would become a tedious and highly complex job.\"\n },\n {\n \"code\": null,\n \"e\": 19928,\n \"s\": 19741,\n \"text\": \"Metadata itself follows a layered architecture, so that when we change data at one layer, it does not affect the data at another level. This data is independent but mapped to each other.\"\n },\n {\n \"code\": null,\n \"e\": 20136,\n \"s\": 19928,\n \"text\": \"Logical data is data about database, that is, it stores information about how data is managed inside. For example, a table (relation) stored in the database and all its constraints, applied on that relation.\"\n },\n {\n \"code\": null,\n \"e\": 20339,\n \"s\": 20136,\n \"text\": \"Logical data independence is a kind of mechanism, which liberalizes itself from actual data stored on the disk. If we do some changes on table format, it should not change the data residing on the disk.\"\n },\n {\n \"code\": null,\n \"e\": 20539,\n \"s\": 20339,\n \"text\": \"All the schemas are logical, and the actual data is stored in bit format on the disk. Physical data independence is the power to change the physical data without impacting the schema or logical data.\"\n },\n {\n \"code\": null,\n \"e\": 20728,\n \"s\": 20539,\n \"text\": \"For example, in case we want to change or upgrade the storage system itself − suppose we want to replace hard-disks with SSD − it should not have any impact on the logical data or schemas.\"\n },\n {\n \"code\": null,\n \"e\": 20934,\n \"s\": 20728,\n \"text\": \"The ER model defines the conceptual view of a database. It works around real-world entities and the associations among them. At view level, the ER model is considered a good option for designing databases.\"\n },\n {\n \"code\": null,\n \"e\": 21234,\n \"s\": 20934,\n \"text\": \"An entity can be a real-world object, either animate or inanimate, that can be easily identifiable. For example, in a school database, students, teachers, classes, and courses offered can be considered as entities. All these entities have some attributes or properties that give them their identity.\"\n },\n {\n \"code\": null,\n \"e\": 21557,\n \"s\": 21234,\n \"text\": \"An entity set is a collection of similar types of entities. An entity set may contain entities with attribute sharing similar values. For example, a Students set may contain all the students of a school; likewise a Teachers set may contain all the teachers of a school from all faculties. Entity sets need not be disjoint.\"\n },\n {\n \"code\": null,\n \"e\": 21734,\n \"s\": 21557,\n \"text\": \"Entities are represented by means of their properties, called attributes. All attributes have values. For example, a student entity may have name, class, and age as attributes.\"\n },\n {\n \"code\": null,\n \"e\": 21934,\n \"s\": 21734,\n \"text\": \"There exists a domain or range of values that can be assigned to attributes. For example, a student's name cannot be a numeric value. It has to be alphabetic. A student's age cannot be negative, etc.\"\n },\n {\n \"code\": null,\n \"e\": 22094,\n \"s\": 21934,\n \"text\": \"Simple attribute − Simple attributes are atomic values, which cannot be divided further. For example, a student's phone number is an atomic value of 10 digits.\"\n },\n {\n \"code\": null,\n \"e\": 22254,\n \"s\": 22094,\n \"text\": \"Simple attribute − Simple attributes are atomic values, which cannot be divided further. For example, a student's phone number is an atomic value of 10 digits.\"\n },\n {\n \"code\": null,\n \"e\": 22415,\n \"s\": 22254,\n \"text\": \"Composite attribute − Composite attributes are made of more than one simple attribute. For example, a student's complete name may have first_name and last_name.\"\n },\n {\n \"code\": null,\n \"e\": 22576,\n \"s\": 22415,\n \"text\": \"Composite attribute − Composite attributes are made of more than one simple attribute. For example, a student's complete name may have first_name and last_name.\"\n },\n {\n \"code\": null,\n \"e\": 22931,\n \"s\": 22576,\n \"text\": \"Derived attribute − Derived attributes are the attributes that do not exist in the physical database, but their values are derived from other attributes present in the database. For example, average_salary in a department should not be saved directly in the database, instead it can be derived. For another example, age can be derived from data_of_birth.\"\n },\n {\n \"code\": null,\n \"e\": 23286,\n \"s\": 22931,\n \"text\": \"Derived attribute − Derived attributes are the attributes that do not exist in the physical database, but their values are derived from other attributes present in the database. For example, average_salary in a department should not be saved directly in the database, instead it can be derived. For another example, age can be derived from data_of_birth.\"\n },\n {\n \"code\": null,\n \"e\": 23395,\n \"s\": 23286,\n \"text\": \"Single-value attribute − Single-value attributes contain single value. For example − Social_Security_Number.\"\n },\n {\n \"code\": null,\n \"e\": 23504,\n \"s\": 23395,\n \"text\": \"Single-value attribute − Single-value attributes contain single value. For example − Social_Security_Number.\"\n },\n {\n \"code\": null,\n \"e\": 23664,\n \"s\": 23504,\n \"text\": \"Multi-value attribute − Multi-value attributes may contain more than one values. For example, a person can have more than one phone number, email_address, etc.\"\n },\n {\n \"code\": null,\n \"e\": 23824,\n \"s\": 23664,\n \"text\": \"Multi-value attribute − Multi-value attributes may contain more than one values. For example, a person can have more than one phone number, email_address, etc.\"\n },\n {\n \"code\": null,\n \"e\": 23880,\n \"s\": 23824,\n \"text\": \"These attribute types can come together in a way like −\"\n },\n {\n \"code\": null,\n \"e\": 23912,\n \"s\": 23880,\n \"text\": \"simple single-valued attributes\"\n },\n {\n \"code\": null,\n \"e\": 23943,\n \"s\": 23912,\n \"text\": \"simple multi-valued attributes\"\n },\n {\n \"code\": null,\n \"e\": 23978,\n \"s\": 23943,\n \"text\": \"composite single-valued attributes\"\n },\n {\n \"code\": null,\n \"e\": 24012,\n \"s\": 23978,\n \"text\": \"composite multi-valued attributes\"\n },\n {\n \"code\": null,\n \"e\": 24113,\n \"s\": 24012,\n \"text\": \"Key is an attribute or collection of attributes that uniquely identifies an entity among entity set.\"\n },\n {\n \"code\": null,\n \"e\": 24198,\n \"s\": 24113,\n \"text\": \"For example, the roll_number of a student makes him/her identifiable among students.\"\n },\n {\n \"code\": null,\n \"e\": 24301,\n \"s\": 24198,\n \"text\": \"Super Key − A set of attributes (one or more) that collectively identifies an entity in an entity set.\"\n },\n {\n \"code\": null,\n \"e\": 24404,\n \"s\": 24301,\n \"text\": \"Super Key − A set of attributes (one or more) that collectively identifies an entity in an entity set.\"\n },\n {\n \"code\": null,\n \"e\": 24519,\n \"s\": 24404,\n \"text\": \"Candidate Key − A minimal super key is called a candidate key. An entity set may have more than one candidate key.\"\n },\n {\n \"code\": null,\n \"e\": 24634,\n \"s\": 24519,\n \"text\": \"Candidate Key − A minimal super key is called a candidate key. An entity set may have more than one candidate key.\"\n },\n {\n \"code\": null,\n \"e\": 24760,\n \"s\": 24634,\n \"text\": \"Primary Key − A primary key is one of the candidate keys chosen by the database designer to uniquely identify the entity set.\"\n },\n {\n \"code\": null,\n \"e\": 24886,\n \"s\": 24760,\n \"text\": \"Primary Key − A primary key is one of the candidate keys chosen by the database designer to uniquely identify the entity set.\"\n },\n {\n \"code\": null,\n \"e\": 25075,\n \"s\": 24886,\n \"text\": \"The association among entities is called a relationship. For example, an employee works_at a department, a student enrolls in a course. Here, Works_at and Enrolls are called relationships.\"\n },\n {\n \"code\": null,\n \"e\": 25251,\n \"s\": 25075,\n \"text\": \"A set of relationships of similar type is called a relationship set. Like entities, a relationship too can have attributes. These attributes are called descriptive attributes.\"\n },\n {\n \"code\": null,\n \"e\": 25346,\n \"s\": 25251,\n \"text\": \"The number of participating entities in a relationship defines the degree of the relationship.\"\n },\n {\n \"code\": null,\n \"e\": 25364,\n \"s\": 25346,\n \"text\": \"Binary = degree 2\"\n },\n {\n \"code\": null,\n \"e\": 25383,\n \"s\": 25364,\n \"text\": \"Ternary = degree 3\"\n },\n {\n \"code\": null,\n \"e\": 25398,\n \"s\": 25383,\n \"text\": \"n-ary = degree\"\n },\n {\n \"code\": null,\n \"e\": 25547,\n \"s\": 25398,\n \"text\": \"Cardinality defines the number of entities in one entity set, which can be associated with the number of entities of other set via relationship set.\"\n },\n {\n \"code\": null,\n \"e\": 25663,\n \"s\": 25547,\n \"text\": \"One-to-one − One entity from entity set A can be associated with at most one entity of entity set B and vice versa.\"\n },\n {\n \"code\": null,\n \"e\": 25779,\n \"s\": 25663,\n \"text\": \"One-to-one − One entity from entity set A can be associated with at most one entity of entity set B and vice versa.\"\n },\n {\n \"code\": null,\n \"e\": 25964,\n \"s\": 25779,\n \"text\": \"One-to-many − One entity from entity set A can be associated with more than one entities of entity set B however an entity from entity set B, can be associated with at most one entity.\"\n },\n {\n \"code\": null,\n \"e\": 26149,\n \"s\": 25964,\n \"text\": \"One-to-many − One entity from entity set A can be associated with more than one entities of entity set B however an entity from entity set B, can be associated with at most one entity.\"\n },\n {\n \"code\": null,\n \"e\": 26362,\n \"s\": 26149,\n \"text\": \"Many-to-one − More than one entities from entity set A can be associated with at most one entity of entity set B, however an entity from entity set B can be associated with more than one entity from entity set A.\"\n },\n {\n \"code\": null,\n \"e\": 26575,\n \"s\": 26362,\n \"text\": \"Many-to-one − More than one entities from entity set A can be associated with at most one entity of entity set B, however an entity from entity set B can be associated with more than one entity from entity set A.\"\n },\n {\n \"code\": null,\n \"e\": 26675,\n \"s\": 26575,\n \"text\": \"Many-to-many − One entity from A can be associated with more than one entity from B and vice versa.\"\n },\n {\n \"code\": null,\n \"e\": 26775,\n \"s\": 26675,\n \"text\": \"Many-to-many − One entity from A can be associated with more than one entity from B and vice versa.\"\n },\n {\n \"code\": null,\n \"e\": 27018,\n \"s\": 26775,\n \"text\": \"Let us now learn how the ER Model is represented by means of an ER diagram. Any object, for example, entities, attributes of an entity, relationship sets, and attributes of relationship sets, can be represented with the help of an ER diagram.\"\n },\n {\n \"code\": null,\n \"e\": 27124,\n \"s\": 27018,\n \"text\": \"Entities are represented by means of rectangles. Rectangles are named with the entity set they represent.\"\n },\n {\n \"code\": null,\n \"e\": 27308,\n \"s\": 27124,\n \"text\": \"Attributes are the properties of entities. Attributes are represented by means of ellipses. Every ellipse represents one attribute and is directly connected to its entity (rectangle).\"\n },\n {\n \"code\": null,\n \"e\": 27533,\n \"s\": 27308,\n \"text\": \"If the attributes are composite, they are further divided in a tree like structure. Every node is then connected to its attribute. That is, composite attributes are represented by ellipses that are connected with an ellipse.\"\n },\n {\n \"code\": null,\n \"e\": 27588,\n \"s\": 27533,\n \"text\": \"Multivalued attributes are depicted by double ellipse.\"\n },\n {\n \"code\": null,\n \"e\": 27639,\n \"s\": 27588,\n \"text\": \"Derived attributes are depicted by dashed ellipse.\"\n },\n {\n \"code\": null,\n \"e\": 27846,\n \"s\": 27639,\n \"text\": \"Relationships are represented by diamond-shaped box. Name of the relationship is written inside the diamond-box. All the entities (rectangles) participating in a relationship, are connected to it by a line.\"\n },\n {\n \"code\": null,\n \"e\": 28040,\n \"s\": 27846,\n \"text\": \"A relationship where two entities are participating is called a binary relationship. Cardinality is the number of instance of an entity from a relation that can be associated with the relation.\"\n },\n {\n \"code\": null,\n \"e\": 28296,\n \"s\": 28040,\n \"text\": \"One-to-one − When only one instance of an entity is associated with the relationship, it is marked as '1:1'. The following image reflects that only one instance of each entity should be associated with the relationship. It depicts one-to-one relationship.\"\n },\n {\n \"code\": null,\n \"e\": 28552,\n \"s\": 28296,\n \"text\": \"One-to-one − When only one instance of an entity is associated with the relationship, it is marked as '1:1'. The following image reflects that only one instance of each entity should be associated with the relationship. It depicts one-to-one relationship.\"\n },\n {\n \"code\": null,\n \"e\": 28870,\n \"s\": 28552,\n \"text\": \"One-to-many − When more than one instance of an entity is associated with a relationship, it is marked as '1:N'. The following image reflects that only one instance of entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts one-to-many relationship.\"\n },\n {\n \"code\": null,\n \"e\": 29188,\n \"s\": 28870,\n \"text\": \"One-to-many − When more than one instance of an entity is associated with a relationship, it is marked as '1:N'. The following image reflects that only one instance of entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts one-to-many relationship.\"\n },\n {\n \"code\": null,\n \"e\": 29508,\n \"s\": 29188,\n \"text\": \"Many-to-one − When more than one instance of entity is associated with the relationship, it is marked as 'N:1'. The following image reflects that more than one instance of an entity on the left and only one instance of an entity on the right can be associated with the relationship. It depicts many-to-one relationship.\"\n },\n {\n \"code\": null,\n \"e\": 29828,\n \"s\": 29508,\n \"text\": \"Many-to-one − When more than one instance of entity is associated with the relationship, it is marked as 'N:1'. The following image reflects that more than one instance of an entity on the left and only one instance of an entity on the right can be associated with the relationship. It depicts many-to-one relationship.\"\n },\n {\n \"code\": null,\n \"e\": 30057,\n \"s\": 29828,\n \"text\": \"Many-to-many − The following image reflects that more than one instance of an entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts many-to-many relationship.\"\n },\n {\n \"code\": null,\n \"e\": 30286,\n \"s\": 30057,\n \"text\": \"Many-to-many − The following image reflects that more than one instance of an entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts many-to-many relationship.\"\n },\n {\n \"code\": null,\n \"e\": 30405,\n \"s\": 30286,\n \"text\": \"Total Participation − Each entity is involved in the relationship. Total participation is represented by double lines.\"\n },\n {\n \"code\": null,\n \"e\": 30524,\n \"s\": 30405,\n \"text\": \"Total Participation − Each entity is involved in the relationship. Total participation is represented by double lines.\"\n },\n {\n \"code\": null,\n \"e\": 30653,\n \"s\": 30524,\n \"text\": \"Partial participation − Not all entities are involved in the relationship. Partial participation is represented by single lines.\"\n },\n {\n \"code\": null,\n \"e\": 30782,\n \"s\": 30653,\n \"text\": \"Partial participation − Not all entities are involved in the relationship. Partial participation is represented by single lines.\"\n },\n {\n \"code\": null,\n \"e\": 31025,\n \"s\": 30782,\n \"text\": \"Let us now learn how the ER Model is represented by means of an ER diagram. Any object, for example, entities, attributes of an entity, relationship sets, and attributes of relationship sets, can be represented with the help of an ER diagram.\"\n },\n {\n \"code\": null,\n \"e\": 31131,\n \"s\": 31025,\n \"text\": \"Entities are represented by means of rectangles. Rectangles are named with the entity set they represent.\"\n },\n {\n \"code\": null,\n \"e\": 31315,\n \"s\": 31131,\n \"text\": \"Attributes are the properties of entities. Attributes are represented by means of ellipses. Every ellipse represents one attribute and is directly connected to its entity (rectangle).\"\n },\n {\n \"code\": null,\n \"e\": 31540,\n \"s\": 31315,\n \"text\": \"If the attributes are composite, they are further divided in a tree like structure. Every node is then connected to its attribute. That is, composite attributes are represented by ellipses that are connected with an ellipse.\"\n },\n {\n \"code\": null,\n \"e\": 31595,\n \"s\": 31540,\n \"text\": \"Multivalued attributes are depicted by double ellipse.\"\n },\n {\n \"code\": null,\n \"e\": 31646,\n \"s\": 31595,\n \"text\": \"Derived attributes are depicted by dashed ellipse.\"\n },\n {\n \"code\": null,\n \"e\": 31853,\n \"s\": 31646,\n \"text\": \"Relationships are represented by diamond-shaped box. Name of the relationship is written inside the diamond-box. All the entities (rectangles) participating in a relationship, are connected to it by a line.\"\n },\n {\n \"code\": null,\n \"e\": 32047,\n \"s\": 31853,\n \"text\": \"A relationship where two entities are participating is called a binary relationship. Cardinality is the number of instance of an entity from a relation that can be associated with the relation.\"\n },\n {\n \"code\": null,\n \"e\": 32303,\n \"s\": 32047,\n \"text\": \"One-to-one − When only one instance of an entity is associated with the relationship, it is marked as '1:1'. The following image reflects that only one instance of each entity should be associated with the relationship. It depicts one-to-one relationship.\"\n },\n {\n \"code\": null,\n \"e\": 32559,\n \"s\": 32303,\n \"text\": \"One-to-one − When only one instance of an entity is associated with the relationship, it is marked as '1:1'. The following image reflects that only one instance of each entity should be associated with the relationship. It depicts one-to-one relationship.\"\n },\n {\n \"code\": null,\n \"e\": 32877,\n \"s\": 32559,\n \"text\": \"One-to-many − When more than one instance of an entity is associated with a relationship, it is marked as '1:N'. The following image reflects that only one instance of entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts one-to-many relationship.\"\n },\n {\n \"code\": null,\n \"e\": 33195,\n \"s\": 32877,\n \"text\": \"One-to-many − When more than one instance of an entity is associated with a relationship, it is marked as '1:N'. The following image reflects that only one instance of entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts one-to-many relationship.\"\n },\n {\n \"code\": null,\n \"e\": 33515,\n \"s\": 33195,\n \"text\": \"Many-to-one − When more than one instance of entity is associated with the relationship, it is marked as 'N:1'. The following image reflects that more than one instance of an entity on the left and only one instance of an entity on the right can be associated with the relationship. It depicts many-to-one relationship.\"\n },\n {\n \"code\": null,\n \"e\": 33835,\n \"s\": 33515,\n \"text\": \"Many-to-one − When more than one instance of entity is associated with the relationship, it is marked as 'N:1'. The following image reflects that more than one instance of an entity on the left and only one instance of an entity on the right can be associated with the relationship. It depicts many-to-one relationship.\"\n },\n {\n \"code\": null,\n \"e\": 34064,\n \"s\": 33835,\n \"text\": \"Many-to-many − The following image reflects that more than one instance of an entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts many-to-many relationship.\"\n },\n {\n \"code\": null,\n \"e\": 34293,\n \"s\": 34064,\n \"text\": \"Many-to-many − The following image reflects that more than one instance of an entity on the left and more than one instance of an entity on the right can be associated with the relationship. It depicts many-to-many relationship.\"\n },\n {\n \"code\": null,\n \"e\": 34412,\n \"s\": 34293,\n \"text\": \"Total Participation − Each entity is involved in the relationship. Total participation is represented by double lines.\"\n },\n {\n \"code\": null,\n \"e\": 34531,\n \"s\": 34412,\n \"text\": \"Total Participation − Each entity is involved in the relationship. Total participation is represented by double lines.\"\n },\n {\n \"code\": null,\n \"e\": 34660,\n \"s\": 34531,\n \"text\": \"Partial participation − Not all entities are involved in the relationship. Partial participation is represented by single lines.\"\n },\n {\n \"code\": null,\n \"e\": 34789,\n \"s\": 34660,\n \"text\": \"Partial participation − Not all entities are involved in the relationship. Partial participation is represented by single lines.\"\n },\n {\n \"code\": null,\n \"e\": 35033,\n \"s\": 34789,\n \"text\": \"The ER Model has the power of expressing database entities in a conceptual hierarchical manner. As the hierarchy goes up, it generalizes the view of entities, and as we go deep in the hierarchy, it gives us the detail of every entity included.\"\n },\n {\n \"code\": null,\n \"e\": 35414,\n \"s\": 35033,\n \"text\": \"Going up in this structure is called generalization, where entities are clubbed together to represent a more generalized view. For example, a particular student named Mira can be generalized along with all the students. The entity shall be a student, and further, the student is a person. The reverse is called specialization where a person is a student, and that student is Mira.\"\n },\n {\n \"code\": null,\n \"e\": 35797,\n \"s\": 35414,\n \"text\": \"As mentioned above, the process of generalizing entities, where the generalized entities contain the properties of all the generalized entities, is called generalization. In generalization, a number of entities are brought together into one generalized entity based on their similar characteristics. For example, pigeon, house sparrow, crow and dove can all be generalized as Birds.\"\n },\n {\n \"code\": null,\n \"e\": 36218,\n \"s\": 35797,\n \"text\": \"Specialization is the opposite of generalization. In specialization, a group of entities is divided into sub-groups based on their characteristics. Take a group ‘Person’ for example. A person has name, date of birth, gender, etc. These properties are common in all persons, human beings. But in a company, persons can be identified as employee, employer, customer, or vendor, based on what role they play in the company.\"\n },\n {\n \"code\": null,\n \"e\": 36363,\n \"s\": 36218,\n \"text\": \"Similarly, in a school database, persons can be specialized as teacher, student, or a staff, based on what role they play in school as entities.\"\n },\n {\n \"code\": null,\n \"e\": 36570,\n \"s\": 36363,\n \"text\": \"We use all the above features of ER-Model in order to create classes of objects in object-oriented programming. The details of entities are generally hidden from the user; this process known as abstraction.\"\n },\n {\n \"code\": null,\n \"e\": 36727,\n \"s\": 36570,\n \"text\": \"Inheritance is an important feature of Generalization and Specialization. It allows lower-level entities to inherit the attributes of higher-level entities.\"\n },\n {\n \"code\": null,\n \"e\": 36872,\n \"s\": 36727,\n \"text\": \"For example, the attributes of a Person class such as name, age, and gender can be inherited by lower-level entities such as Student or Teacher.\"\n },\n {\n \"code\": null,\n \"e\": 37102,\n \"s\": 36872,\n \"text\": \"Dr Edgar F. Codd, after his extensive research on the Relational Model of database systems, came up with twelve rules of his own, which according to him, a database must obey in order to be regarded as a true relational database.\"\n },\n {\n \"code\": null,\n \"e\": 37290,\n \"s\": 37102,\n \"text\": \"These rules can be applied on any database system that manages stored data using only its relational capabilities. This is a foundation rule, which acts as a base for all the other rules.\"\n },\n {\n \"code\": null,\n \"e\": 37449,\n \"s\": 37290,\n \"text\": \"The data stored in a database, may it be user data or metadata, must be a value of some table cell. Everything in a database must be stored in a table format.\"\n },\n {\n \"code\": null,\n \"e\": 37680,\n \"s\": 37449,\n \"text\": \"Every single data element (value) is guaranteed to be accessible logically with a combination of table-name, primary-key (row value), and attribute-name (column value). No other means, such as pointers, can be used to access data.\"\n },\n {\n \"code\": null,\n \"e\": 37910,\n \"s\": 37680,\n \"text\": \"The NULL values in a database must be given a systematic and uniform treatment. This is a very important rule because a NULL can be interpreted as one the following − data is missing, data is not known, or data is not applicable.\"\n },\n {\n \"code\": null,\n \"e\": 38171,\n \"s\": 37910,\n \"text\": \"The structure description of the entire database must be stored in an online catalog, known as data dictionary, which can be accessed by authorized users. Users can use the same query language to access the catalog which they use to access the database itself.\"\n },\n {\n \"code\": null,\n \"e\": 38509,\n \"s\": 38171,\n \"text\": \"A database can only be accessed using a language having linear syntax that supports data definition, data manipulation, and transaction management operations. This language can be used directly or by means of some application. If the database allows access to data without any help of this language, then it is considered as a violation.\"\n },\n {\n \"code\": null,\n \"e\": 38612,\n \"s\": 38509,\n \"text\": \"All the views of a database, which can theoretically be updated, must also be updatable by the system.\"\n },\n {\n \"code\": null,\n \"e\": 38826,\n \"s\": 38612,\n \"text\": \"A database must support high-level insertion, updation, and deletion. This must not be limited to a single row, that is, it must also support union, intersection and minus operations to yield sets of data records.\"\n },\n {\n \"code\": null,\n \"e\": 39058,\n \"s\": 38826,\n \"text\": \"The data stored in a database must be independent of the applications that access the database. Any change in the physical structure of a database must not have any impact on how the data is being accessed by external applications.\"\n },\n {\n \"code\": null,\n \"e\": 39404,\n \"s\": 39058,\n \"text\": \"The logical data in a database must be independent of its user’s view (application). Any change in logical data must not affect the applications using it. For example, if two tables are merged or one is split into two different tables, there should be no impact or change on the user application. This is one of the most difficult rule to apply.\"\n },\n {\n \"code\": null,\n \"e\": 39666,\n \"s\": 39404,\n \"text\": \"A database must be independent of the application that uses it. All its integrity constraints can be independently modified without the need of any change in the application. This rule makes a database independent of the front-end application and its interface.\"\n },\n {\n \"code\": null,\n \"e\": 39917,\n \"s\": 39666,\n \"text\": \"The end-user must not be able to see that the data is distributed over various locations. Users should always get the impression that the data is located at one site only. This rule has been regarded as the foundation of distributed database systems.\"\n },\n {\n \"code\": null,\n \"e\": 40094,\n \"s\": 39917,\n \"text\": \"If a system has an interface that provides access to low-level records, then the interface must not be able to subvert the system and bypass security and integrity constraints.\"\n },\n {\n \"code\": null,\n \"e\": 40332,\n \"s\": 40094,\n \"text\": \"Relational data model is the primary data model, which is used widely around the world for data storage and processing. This model is simple and it has all the properties and capabilities required to process data with storage efficiency.\"\n },\n {\n \"code\": null,\n \"e\": 40558,\n \"s\": 40332,\n \"text\": \"Tables − In relational data model, relations are saved in the format of Tables. This format stores the relation among entities. A table has rows and columns, where rows represents records and columns represent the attributes.\"\n },\n {\n \"code\": null,\n \"e\": 40659,\n \"s\": 40558,\n \"text\": \"Tuple − A single row of a table, which contains a single record for that relation is called a tuple.\"\n },\n {\n \"code\": null,\n \"e\": 40815,\n \"s\": 40659,\n \"text\": \"Relation instance − A finite set of tuples in the relational database system represents relation instance. Relation instances do not have duplicate tuples.\"\n },\n {\n \"code\": null,\n \"e\": 40922,\n \"s\": 40815,\n \"text\": \"Relation schema − A relation schema describes the relation name (table name), attributes, and their names.\"\n },\n {\n \"code\": null,\n \"e\": 41058,\n \"s\": 40922,\n \"text\": \"Relation key − Each row has one or more attributes, known as relation key, which can identify the row in the relation (table) uniquely.\"\n },\n {\n \"code\": null,\n \"e\": 41154,\n \"s\": 41058,\n \"text\": \"Attribute domain − Every attribute has some pre-defined value scope, known as attribute domain.\"\n },\n {\n \"code\": null,\n \"e\": 41343,\n \"s\": 41154,\n \"text\": \"Every relation has some conditions that must hold for it to be a valid relation. These conditions are called Relational Integrity Constraints. There are three main integrity constraints −\"\n },\n {\n \"code\": null,\n \"e\": 41359,\n \"s\": 41343,\n \"text\": \"Key constraints\"\n },\n {\n \"code\": null,\n \"e\": 41378,\n \"s\": 41359,\n \"text\": \"Domain constraints\"\n },\n {\n \"code\": null,\n \"e\": 41412,\n \"s\": 41378,\n \"text\": \"Referential integrity constraints\"\n },\n {\n \"code\": null,\n \"e\": 41671,\n \"s\": 41412,\n \"text\": \"There must be at least one minimal subset of attributes in the relation, which can identify a tuple uniquely. This minimal subset of attributes is called key for that relation. If there are more than one such minimal subsets, these are called candidate keys.\"\n },\n {\n \"code\": null,\n \"e\": 41700,\n \"s\": 41671,\n \"text\": \"Key constraints force that −\"\n },\n {\n \"code\": null,\n \"e\": 41796,\n \"s\": 41700,\n \"text\": \"in a relation with a key attribute, no two tuples can have identical values for key attributes.\"\n },\n {\n \"code\": null,\n \"e\": 41892,\n \"s\": 41796,\n \"text\": \"in a relation with a key attribute, no two tuples can have identical values for key attributes.\"\n },\n {\n \"code\": null,\n \"e\": 41934,\n \"s\": 41892,\n \"text\": \"a key attribute can not have NULL values.\"\n },\n {\n \"code\": null,\n \"e\": 41976,\n \"s\": 41934,\n \"text\": \"a key attribute can not have NULL values.\"\n },\n {\n \"code\": null,\n \"e\": 42036,\n \"s\": 41976,\n \"text\": \"Key constraints are also referred to as Entity Constraints.\"\n },\n {\n \"code\": null,\n \"e\": 42382,\n \"s\": 42036,\n \"text\": \"Attributes have specific values in real-world scenario. For example, age can only be a positive integer. The same constraints have been tried to employ on the attributes of a relation. Every attribute is bound to have a specific range of values. For example, age cannot be less than zero and telephone numbers cannot contain a digit outside 0-9.\"\n },\n {\n \"code\": null,\n \"e\": 42540,\n \"s\": 42382,\n \"text\": \"Referential integrity constraints work on the concept of Foreign Keys. A foreign key is a key attribute of a relation that can be referred in other relation.\"\n },\n {\n \"code\": null,\n \"e\": 42692,\n \"s\": 42540,\n \"text\": \"Referential integrity constraint states that if a relation refers to a key attribute of a different or same relation, then that key element must exist.\"\n },\n {\n \"code\": null,\n \"e\": 42914,\n \"s\": 42692,\n \"text\": \"Relational database systems are expected to be equipped with a query language that can assist its users to query the database instances. There are two kinds of query languages − relational algebra and relational calculus.\"\n },\n {\n \"code\": null,\n \"e\": 43324,\n \"s\": 42914,\n \"text\": \"Relational algebra is a procedural query language, which takes instances of relations as input and yields instances of relations as output. It uses operators to perform queries. An operator can be either unary or binary. They accept relations as their input and yield relations as their output. Relational algebra is performed recursively on a relation and intermediate results are also considered relations.\"\n },\n {\n \"code\": null,\n \"e\": 43390,\n \"s\": 43324,\n \"text\": \"The fundamental operations of relational algebra are as follows −\"\n },\n {\n \"code\": null,\n \"e\": 43397,\n \"s\": 43390,\n \"text\": \"Select\"\n },\n {\n \"code\": null,\n \"e\": 43405,\n \"s\": 43397,\n \"text\": \"Project\"\n },\n {\n \"code\": null,\n \"e\": 43411,\n \"s\": 43405,\n \"text\": \"Union\"\n },\n {\n \"code\": null,\n \"e\": 43425,\n \"s\": 43411,\n \"text\": \"Set different\"\n },\n {\n \"code\": null,\n \"e\": 43443,\n \"s\": 43425,\n \"text\": \"Cartesian product\"\n },\n {\n \"code\": null,\n \"e\": 43450,\n \"s\": 43443,\n \"text\": \"Rename\"\n },\n {\n \"code\": null,\n \"e\": 43514,\n \"s\": 43450,\n \"text\": \"We will discuss all these operations in the following sections.\"\n },\n {\n \"code\": null,\n \"e\": 43582,\n \"s\": 43514,\n \"text\": \"It selects tuples that satisfy the given predicate from a relation.\"\n },\n {\n \"code\": null,\n \"e\": 43599,\n \"s\": 43582,\n \"text\": \"Notation − σp(r)\"\n },\n {\n \"code\": null,\n \"e\": 43816,\n \"s\": 43599,\n \"text\": \"Where σ stands for selection predicate and r stands for relation. p is prepositional logic formula which may use connectors like and, or, and not. These terms may use relational operators like − =, ≠, ≥, < , >, ≤.\"\n },\n {\n \"code\": null,\n \"e\": 43830,\n \"s\": 43816,\n \"text\": \"For example −\"\n },\n {\n \"code\": null,\n \"e\": 43858,\n \"s\": 43830,\n \"text\": \"σsubject=\\\"database\\\"(Books)\\n\"\n },\n {\n \"code\": null,\n \"e\": 43885,\n \"s\": 43858,\n \"text\": \"σsubject=\\\"database\\\"(Books)\"\n },\n {\n \"code\": null,\n \"e\": 43949,\n \"s\": 43885,\n \"text\": \"Output − Selects tuples from books where subject is 'database'.\"\n },\n {\n \"code\": null,\n \"e\": 43993,\n \"s\": 43949,\n \"text\": \"σsubject=\\\"database\\\" and price=\\\"450\\\"(Books)\\n\"\n },\n {\n \"code\": null,\n \"e\": 44036,\n \"s\": 43993,\n \"text\": \"σsubject=\\\"database\\\" and price=\\\"450\\\"(Books)\"\n },\n {\n \"code\": null,\n \"e\": 44119,\n \"s\": 44036,\n \"text\": \"Output − Selects tuples from books where subject is 'database' and 'price' is 450.\"\n },\n {\n \"code\": null,\n \"e\": 44182,\n \"s\": 44119,\n \"text\": \"σsubject=\\\"database\\\" and price < \\\"450\\\" or year > \\\"2010\\\"(Books)\\n\"\n },\n {\n \"code\": null,\n \"e\": 44244,\n \"s\": 44182,\n \"text\": \"σsubject=\\\"database\\\" and price < \\\"450\\\" or year > \\\"2010\\\"(Books)\"\n },\n {\n \"code\": null,\n \"e\": 44363,\n \"s\": 44244,\n \"text\": \"Output − Selects tuples from books where subject is 'database' and 'price' is 450 or those books published after 2010.\"\n },\n {\n \"code\": null,\n \"e\": 44417,\n \"s\": 44363,\n \"text\": \"It projects column(s) that satisfy a given predicate.\"\n },\n {\n \"code\": null,\n \"e\": 44444,\n \"s\": 44417,\n \"text\": \"Notation − ∏A1, A2, An (r)\"\n },\n {\n \"code\": null,\n \"e\": 44497,\n \"s\": 44444,\n \"text\": \"Where A1, A2 , An are attribute names of relation r.\"\n },\n {\n \"code\": null,\n \"e\": 44564,\n \"s\": 44497,\n \"text\": \"Duplicate rows are automatically eliminated, as relation is a set.\"\n },\n {\n \"code\": null,\n \"e\": 44578,\n \"s\": 44564,\n \"text\": \"For example −\"\n },\n {\n \"code\": null,\n \"e\": 44605,\n \"s\": 44578,\n \"text\": \" ∏subject, author (Books)\\n\"\n },\n {\n \"code\": null,\n \"e\": 44631,\n \"s\": 44605,\n \"text\": \" ∏subject, author (Books)\"\n },\n {\n \"code\": null,\n \"e\": 44713,\n \"s\": 44631,\n \"text\": \"Selects and projects columns named as subject and author from the relation Books.\"\n },\n {\n \"code\": null,\n \"e\": 44786,\n \"s\": 44713,\n \"text\": \"It performs binary union between two given relations and is defined as −\"\n },\n {\n \"code\": null,\n \"e\": 44819,\n \"s\": 44786,\n \"text\": \" r ∪ s = { t | t ∈ r or t ∈ s} \\n\"\n },\n {\n \"code\": null,\n \"e\": 44851,\n \"s\": 44819,\n \"text\": \" r ∪ s = { t | t ∈ r or t ∈ s} \"\n },\n {\n \"code\": null,\n \"e\": 44869,\n \"s\": 44851,\n \"text\": \"Notation − r U s \"\n },\n {\n \"code\": null,\n \"e\": 44958,\n \"s\": 44869,\n \"text\": \"Where r and s are either database relations or relation result set (temporary relation).\"\n },\n {\n \"code\": null,\n \"e\": 45030,\n \"s\": 44958,\n \"text\": \"For a union operation to be valid, the following conditions must hold −\"\n },\n {\n \"code\": null,\n \"e\": 45080,\n \"s\": 45030,\n \"text\": \"r, and s must have the same number of attributes.\"\n },\n {\n \"code\": null,\n \"e\": 45118,\n \"s\": 45080,\n \"text\": \"Attribute domains must be compatible.\"\n },\n {\n \"code\": null,\n \"e\": 45165,\n \"s\": 45118,\n \"text\": \"Duplicate tuples are automatically eliminated.\"\n },\n {\n \"code\": null,\n \"e\": 45206,\n \"s\": 45165,\n \"text\": \" ∏ author (Books) ∪ ∏ author (Articles)\\n\"\n },\n {\n \"code\": null,\n \"e\": 45246,\n \"s\": 45206,\n \"text\": \" ∏ author (Books) ∪ ∏ author (Articles)\"\n },\n {\n \"code\": null,\n \"e\": 45343,\n \"s\": 45246,\n \"text\": \"Output − Projects the names of the authors who have either written a book or an article or both.\"\n },\n {\n \"code\": null,\n \"e\": 45463,\n \"s\": 45343,\n \"text\": \"The result of set difference operation is tuples, which are present in one relation but are not in the second relation.\"\n },\n {\n \"code\": null,\n \"e\": 45480,\n \"s\": 45463,\n \"text\": \"Notation − r − s\"\n },\n {\n \"code\": null,\n \"e\": 45537,\n \"s\": 45480,\n \"text\": \"Finds all the tuples that are present in r but not in s.\"\n },\n {\n \"code\": null,\n \"e\": 45578,\n \"s\": 45537,\n \"text\": \" ∏ author (Books) − ∏ author (Articles)\\n\"\n },\n {\n \"code\": null,\n \"e\": 45618,\n \"s\": 45578,\n \"text\": \" ∏ author (Books) − ∏ author (Articles)\"\n },\n {\n \"code\": null,\n \"e\": 45697,\n \"s\": 45618,\n \"text\": \"Output − Provides the name of authors who have written books but not articles.\"\n },\n {\n \"code\": null,\n \"e\": 45756,\n \"s\": 45697,\n \"text\": \"Combines information of two different relations into one. \"\n },\n {\n \"code\": null,\n \"e\": 45773,\n \"s\": 45756,\n \"text\": \"Notation − r Χ s\"\n },\n {\n \"code\": null,\n \"e\": 45839,\n \"s\": 45773,\n \"text\": \"Where r and s are relations and their output will be defined as −\"\n },\n {\n \"code\": null,\n \"e\": 45874,\n \"s\": 45839,\n \"text\": \"r Χ s = { q t | q ∈ r and t ∈ s}\"\n },\n {\n \"code\": null,\n \"e\": 45923,\n \"s\": 45874,\n \"text\": \" ∏ author = 'tutorialspoint'(Books Χ Articles) \\n\"\n },\n {\n \"code\": null,\n \"e\": 45971,\n \"s\": 45923,\n \"text\": \" ∏ author = 'tutorialspoint'(Books Χ Articles) \"\n },\n {\n \"code\": null,\n \"e\": 46065,\n \"s\": 45971,\n \"text\": \"Output − Yields a relation, which shows all the books and articles written by tutorialspoint.\"\n },\n {\n \"code\": null,\n \"e\": 46263,\n \"s\": 46065,\n \"text\": \"The results of relational algebra are also relations but without any name. The rename operation allows us to rename the output relation. 'rename' operation is denoted with small Greek letter rho ρ.\"\n },\n {\n \"code\": null,\n \"e\": 46282,\n \"s\": 46263,\n \"text\": \"Notation − ρ x (E)\"\n },\n {\n \"code\": null,\n \"e\": 46340,\n \"s\": 46282,\n \"text\": \"Where the result of expression E is saved with name of x.\"\n },\n {\n \"code\": null,\n \"e\": 46368,\n \"s\": 46340,\n \"text\": \"Additional operations are −\"\n },\n {\n \"code\": null,\n \"e\": 46385,\n \"s\": 46368,\n \"text\": \"Set intersection\"\n },\n {\n \"code\": null,\n \"e\": 46396,\n \"s\": 46385,\n \"text\": \"Assignment\"\n },\n {\n \"code\": null,\n \"e\": 46409,\n \"s\": 46396,\n \"text\": \"Natural join\"\n },\n {\n \"code\": null,\n \"e\": 46562,\n \"s\": 46409,\n \"text\": \"In contrast to Relational Algebra, Relational Calculus is a non-procedural query language, that is, it tells what to do but never explains how to do it.\"\n },\n {\n \"code\": null,\n \"e\": 46604,\n \"s\": 46562,\n \"text\": \"Relational calculus exists in two forms −\"\n },\n {\n \"code\": null,\n \"e\": 46642,\n \"s\": 46604,\n \"text\": \"Filtering variable ranges over tuples\"\n },\n {\n \"code\": null,\n \"e\": 46670,\n \"s\": 46642,\n \"text\": \"Notation − {T | Condition} \"\n },\n {\n \"code\": null,\n \"e\": 46719,\n \"s\": 46670,\n \"text\": \"Returns all tuples T that satisfies a condition.\"\n },\n {\n \"code\": null,\n \"e\": 46733,\n \"s\": 46719,\n \"text\": \"For example −\"\n },\n {\n \"code\": null,\n \"e\": 46785,\n \"s\": 46733,\n \"text\": \"{ T.name | Author(T) AND T.article = 'database' }\\n\"\n },\n {\n \"code\": null,\n \"e\": 46872,\n \"s\": 46785,\n \"text\": \"Output − Returns tuples with 'name' from Author who has written article on 'database'.\"\n },\n {\n \"code\": null,\n \"e\": 46953,\n \"s\": 46872,\n \"text\": \"TRC can be quantified. We can use Existential (∃) and Universal Quantifiers (∀).\"\n },\n {\n \"code\": null,\n \"e\": 46967,\n \"s\": 46953,\n \"text\": \"For example −\"\n },\n {\n \"code\": null,\n \"e\": 47029,\n \"s\": 46967,\n \"text\": \"{ R| ∃T ∈ Authors(T.article='database' AND R.name=T.name)}\\n\"\n },\n {\n \"code\": null,\n \"e\": 47102,\n \"s\": 47029,\n \"text\": \"Output − The above query will yield the same result as the previous one.\"\n },\n {\n \"code\": null,\n \"e\": 47229,\n \"s\": 47102,\n \"text\": \"In DRC, the filtering variable uses the domain of attributes instead of entire tuple values (as done in TRC, mentioned above).\"\n },\n {\n \"code\": null,\n \"e\": 47240,\n \"s\": 47229,\n \"text\": \"Notation −\"\n },\n {\n \"code\": null,\n \"e\": 47289,\n \"s\": 47240,\n \"text\": \"{ a1, a2, a3, ..., an | P (a1, a2, a3, ... ,an)}\"\n },\n {\n \"code\": null,\n \"e\": 47370,\n \"s\": 47289,\n \"text\": \"Where a1, a2 are attributes and P stands for formulae built by inner attributes.\"\n },\n {\n \"code\": null,\n \"e\": 47384,\n \"s\": 47370,\n \"text\": \"For example −\"\n },\n {\n \"code\": null,\n \"e\": 47457,\n \"s\": 47384,\n \"text\": \"{< article, page, subject > | ∈ TutorialsPoint ∧ subject = 'database'}\\n\"\n },\n {\n \"code\": null,\n \"e\": 47529,\n \"s\": 47457,\n \"text\": \"{< article, page, subject > | ∈ TutorialsPoint ∧ subject = 'database'}\"\n },\n {\n \"code\": null,\n \"e\": 47633,\n \"s\": 47529,\n \"text\": \"Output − Yields Article, Page, and Subject from the relation TutorialsPoint, where subject is database.\"\n },\n {\n \"code\": null,\n \"e\": 47758,\n \"s\": 47633,\n \"text\": \"Just like TRC, DRC can also be written using existential and universal quantifiers. DRC also involves relational operators.\"\n },\n {\n \"code\": null,\n \"e\": 47872,\n \"s\": 47758,\n \"text\": \"The expression power of Tuple Relation Calculus and Domain Relation Calculus is equivalent to Relational Algebra.\"\n },\n {\n \"code\": null,\n \"e\": 48219,\n \"s\": 47872,\n \"text\": \"ER Model, when conceptualized into diagrams, gives a good overview of entity-relationship, which is easier to understand. ER diagrams can be mapped to relational schema, that is, it is possible to create relational schema using ER diagram. We cannot import all the ER constraints into relational model, but an approximate schema can be generated.\"\n },\n {\n \"code\": null,\n \"e\": 48447,\n \"s\": 48219,\n \"text\": \"There are several processes and algorithms available to convert ER Diagrams into Relational Schema. Some of them are automated and some of them are manual. We may focus here on the mapping diagram contents to relational basics.\"\n },\n {\n \"code\": null,\n \"e\": 48480,\n \"s\": 48447,\n \"text\": \"ER diagrams mainly comprise of −\"\n },\n {\n \"code\": null,\n \"e\": 48506,\n \"s\": 48480,\n \"text\": \"Entity and its attributes\"\n },\n {\n \"code\": null,\n \"e\": 48557,\n \"s\": 48506,\n \"text\": \"Relationship, which is association among entities.\"\n },\n {\n \"code\": null,\n \"e\": 48612,\n \"s\": 48557,\n \"text\": \"An entity is a real-world object with some attributes.\"\n },\n {\n \"code\": null,\n \"e\": 48642,\n \"s\": 48612,\n \"text\": \"Create table for each entity.\"\n },\n {\n \"code\": null,\n \"e\": 48727,\n \"s\": 48642,\n \"text\": \"Entity's attributes should become fields of tables with their respective data types.\"\n },\n {\n \"code\": null,\n \"e\": 48748,\n \"s\": 48727,\n \"text\": \"Declare primary key.\"\n },\n {\n \"code\": null,\n \"e\": 48797,\n \"s\": 48748,\n \"text\": \"A relationship is an association among entities.\"\n },\n {\n \"code\": null,\n \"e\": 48830,\n \"s\": 48797,\n \"text\": \"Create table for a relationship.\"\n },\n {\n \"code\": null,\n \"e\": 48934,\n \"s\": 48830,\n \"text\": \"Add the primary keys of all participating Entities as fields of table with their respective data types.\"\n },\n {\n \"code\": null,\n \"e\": 49007,\n \"s\": 48934,\n \"text\": \"If relationship has any attribute, add each attribute as field of table.\"\n },\n {\n \"code\": null,\n \"e\": 49087,\n \"s\": 49007,\n \"text\": \"Declare a primary key composing all the primary keys of participating entities.\"\n },\n {\n \"code\": null,\n \"e\": 49124,\n \"s\": 49087,\n \"text\": \"Declare all foreign key constraints.\"\n },\n {\n \"code\": null,\n \"e\": 49205,\n \"s\": 49124,\n \"text\": \"A weak entity set is one which does not have any primary key associated with it.\"\n },\n {\n \"code\": null,\n \"e\": 49239,\n \"s\": 49205,\n \"text\": \"Create table for weak entity set.\"\n },\n {\n \"code\": null,\n \"e\": 49281,\n \"s\": 49239,\n \"text\": \"Add all its attributes to table as field.\"\n },\n {\n \"code\": null,\n \"e\": 49328,\n \"s\": 49281,\n \"text\": \"Add the primary key of identifying entity set.\"\n },\n {\n \"code\": null,\n \"e\": 49365,\n \"s\": 49328,\n \"text\": \"Declare all foreign key constraints.\"\n },\n {\n \"code\": null,\n \"e\": 49448,\n \"s\": 49365,\n \"text\": \"ER specialization or generalization comes in the form of hierarchical entity sets.\"\n },\n {\n \"code\": null,\n \"e\": 49493,\n \"s\": 49448,\n \"text\": \"Create tables for all higher-level entities.\"\n },\n {\n \"code\": null,\n \"e\": 49538,\n \"s\": 49493,\n \"text\": \"Create tables for all higher-level entities.\"\n },\n {\n \"code\": null,\n \"e\": 49578,\n \"s\": 49538,\n \"text\": \"Create tables for lower-level entities.\"\n },\n {\n \"code\": null,\n \"e\": 49618,\n \"s\": 49578,\n \"text\": \"Create tables for lower-level entities.\"\n },\n {\n \"code\": null,\n \"e\": 49698,\n \"s\": 49618,\n \"text\": \"Add primary keys of higher-level entities in the table of lower-level entities.\"\n },\n {\n \"code\": null,\n \"e\": 49778,\n \"s\": 49698,\n \"text\": \"Add primary keys of higher-level entities in the table of lower-level entities.\"\n },\n {\n \"code\": null,\n \"e\": 49851,\n \"s\": 49778,\n \"text\": \"In lower-level tables, add all other attributes of lower-level entities.\"\n },\n {\n \"code\": null,\n \"e\": 49924,\n \"s\": 49851,\n \"text\": \"In lower-level tables, add all other attributes of lower-level entities.\"\n },\n {\n \"code\": null,\n \"e\": 50009,\n \"s\": 49924,\n \"text\": \"Declare primary key of higher-level table and the primary key for lower-level table.\"\n },\n {\n \"code\": null,\n \"e\": 50094,\n \"s\": 50009,\n \"text\": \"Declare primary key of higher-level table and the primary key for lower-level table.\"\n },\n {\n \"code\": null,\n \"e\": 50127,\n \"s\": 50094,\n \"text\": \"Declare foreign key constraints.\"\n },\n {\n \"code\": null,\n \"e\": 50160,\n \"s\": 50127,\n \"text\": \"Declare foreign key constraints.\"\n },\n {\n \"code\": null,\n \"e\": 50348,\n \"s\": 50160,\n \"text\": \"SQL is a programming language for Relational Databases. It is designed over relational algebra and tuple relational calculus. SQL comes as a package with all major distributions of RDBMS.\"\n },\n {\n \"code\": null,\n \"e\": 50594,\n \"s\": 50348,\n \"text\": \"SQL comprises both data definition and data manipulation languages. Using the data definition properties of SQL, one can design and modify database schema, whereas data manipulation properties allows SQL to store and retrieve data from database.\"\n },\n {\n \"code\": null,\n \"e\": 50661,\n \"s\": 50594,\n \"text\": \"SQL uses the following set of commands to define database schema −\"\n },\n {\n \"code\": null,\n \"e\": 50713,\n \"s\": 50661,\n \"text\": \"Creates new databases, tables and views from RDBMS.\"\n },\n {\n \"code\": null,\n \"e\": 50727,\n \"s\": 50713,\n \"text\": \"For example −\"\n },\n {\n \"code\": null,\n \"e\": 50808,\n \"s\": 50727,\n \"text\": \"Create database tutorialspoint;\\nCreate table article;\\nCreate view for_students;\\n\"\n },\n {\n \"code\": null,\n \"e\": 50865,\n \"s\": 50808,\n \"text\": \"Drops commands, views, tables, and databases from RDBMS.\"\n },\n {\n \"code\": null,\n \"e\": 50878,\n \"s\": 50865,\n \"text\": \"For example−\"\n },\n {\n \"code\": null,\n \"e\": 50983,\n \"s\": 50878,\n \"text\": \"Drop object_type object_name;\\nDrop database tutorialspoint;\\nDrop table article;\\nDrop view for_students;\\n\"\n },\n {\n \"code\": null,\n \"e\": 51009,\n \"s\": 50983,\n \"text\": \"Modifies database schema.\"\n },\n {\n \"code\": null,\n \"e\": 51052,\n \"s\": 51009,\n \"text\": \"Alter object_type object_name parameters;\\n\"\n },\n {\n \"code\": null,\n \"e\": 51065,\n \"s\": 51052,\n \"text\": \"For example−\"\n },\n {\n \"code\": null,\n \"e\": 51107,\n \"s\": 51065,\n \"text\": \"Alter table article add subject varchar;\\n\"\n },\n {\n \"code\": null,\n \"e\": 51200,\n \"s\": 51107,\n \"text\": \"This command adds an attribute in the relation article with the name subject of string type.\"\n },\n {\n \"code\": null,\n \"e\": 51466,\n \"s\": 51200,\n \"text\": \"SQL is equipped with data manipulation language (DML). DML modifies the database instance by inserting, updating and deleting its data. DML is responsible for all forms data modification in a database. SQL contains the following set of commands in its DML section −\"\n },\n {\n \"code\": null,\n \"e\": 51484,\n \"s\": 51466,\n \"text\": \"SELECT/FROM/WHERE\"\n },\n {\n \"code\": null,\n \"e\": 51503,\n \"s\": 51484,\n \"text\": \"INSERT INTO/VALUES\"\n },\n {\n \"code\": null,\n \"e\": 51520,\n \"s\": 51503,\n \"text\": \"UPDATE/SET/WHERE\"\n },\n {\n \"code\": null,\n \"e\": 51538,\n \"s\": 51520,\n \"text\": \"DELETE FROM/WHERE\"\n },\n {\n \"code\": null,\n \"e\": 51705,\n \"s\": 51538,\n \"text\": \"These basic constructs allow database programmers and users to enter data and information into the database and retrieve efficiently using a number of filter options.\"\n },\n {\n \"code\": null,\n \"e\": 51908,\n \"s\": 51705,\n \"text\": \"SELECT − This is one of the fundamental query command of SQL. It is similar to the projection operation of relational algebra. It selects the attributes based on the condition described by WHERE clause.\"\n },\n {\n \"code\": null,\n \"e\": 52111,\n \"s\": 51908,\n \"text\": \"SELECT − This is one of the fundamental query command of SQL. It is similar to the projection operation of relational algebra. It selects the attributes based on the condition described by WHERE clause.\"\n },\n {\n \"code\": null,\n \"e\": 52313,\n \"s\": 52111,\n \"text\": \"FROM − This clause takes a relation name as an argument from which attributes are to be selected/projected. In case more than one relation names are given, this clause corresponds to Cartesian product.\"\n },\n {\n \"code\": null,\n \"e\": 52515,\n \"s\": 52313,\n \"text\": \"FROM − This clause takes a relation name as an argument from which attributes are to be selected/projected. In case more than one relation names are given, this clause corresponds to Cartesian product.\"\n },\n {\n \"code\": null,\n \"e\": 52637,\n \"s\": 52515,\n \"text\": \"WHERE − This clause defines predicate or conditions, which must match in order to qualify the attributes to be projected.\"\n },\n {\n \"code\": null,\n \"e\": 52759,\n \"s\": 52637,\n \"text\": \"WHERE − This clause defines predicate or conditions, which must match in order to qualify the attributes to be projected.\"\n },\n {\n \"code\": null,\n \"e\": 52773,\n \"s\": 52759,\n \"text\": \"For example −\"\n },\n {\n \"code\": null,\n \"e\": 52826,\n \"s\": 52773,\n \"text\": \"Select author_name\\nFrom book_author\\nWhere age > 50;\\n\"\n },\n {\n \"code\": null,\n \"e\": 52931,\n \"s\": 52826,\n \"text\": \"This command will yield the names of authors from the relation book_author whose age is greater than 50.\"\n },\n {\n \"code\": null,\n \"e\": 53010,\n \"s\": 52931,\n \"text\": \"This command is used for inserting values into the rows of a table (relation).\"\n },\n {\n \"code\": null,\n \"e\": 53018,\n \"s\": 53010,\n \"text\": \"Syntax−\"\n },\n {\n \"code\": null,\n \"e\": 53113,\n \"s\": 53018,\n \"text\": \"INSERT INTO table (column1 [, column2, column3 ... ]) VALUES (value1 [, value2, value3 ... ])\\n\"\n },\n {\n \"code\": null,\n \"e\": 53116,\n \"s\": 53113,\n \"text\": \"Or\"\n },\n {\n \"code\": null,\n \"e\": 53167,\n \"s\": 53116,\n \"text\": \"INSERT INTO table VALUES (value1, [value2, ... ])\\n\"\n },\n {\n \"code\": null,\n \"e\": 53181,\n \"s\": 53167,\n \"text\": \"For example −\"\n },\n {\n \"code\": null,\n \"e\": 53262,\n \"s\": 53181,\n \"text\": \"INSERT INTO tutorialspoint (Author, Subject) VALUES (\\\"anonymous\\\", \\\"computers\\\");\\n\"\n },\n {\n \"code\": null,\n \"e\": 53354,\n \"s\": 53262,\n \"text\": \"This command is used for updating or modifying the values of columns in a table (relation).\"\n },\n {\n \"code\": null,\n \"e\": 53363,\n \"s\": 53354,\n \"text\": \"Syntax −\"\n },\n {\n \"code\": null,\n \"e\": 53452,\n \"s\": 53363,\n \"text\": \"UPDATE table_name SET column_name = value [, column_name = value ...] [WHERE condition]\\n\"\n },\n {\n \"code\": null,\n \"e\": 53466,\n \"s\": 53452,\n \"text\": \"For example −\"\n },\n {\n \"code\": null,\n \"e\": 53538,\n \"s\": 53466,\n \"text\": \"UPDATE tutorialspoint SET Author=\\\"webmaster\\\" WHERE Author=\\\"anonymous\\\";\\n\"\n },\n {\n \"code\": null,\n \"e\": 53614,\n \"s\": 53538,\n \"text\": \"This command is used for removing one or more rows from a table (relation).\"\n },\n {\n \"code\": null,\n \"e\": 53623,\n \"s\": 53614,\n \"text\": \"Syntax −\"\n },\n {\n \"code\": null,\n \"e\": 53666,\n \"s\": 53623,\n \"text\": \"DELETE FROM table_name [WHERE condition];\\n\"\n },\n {\n \"code\": null,\n \"e\": 53680,\n \"s\": 53666,\n \"text\": \"For example −\"\n },\n {\n \"code\": null,\n \"e\": 53736,\n \"s\": 53680,\n \"text\": \"DELETE FROM tutorialspoints\\n WHERE Author=\\\"unknown\\\";\\n\"\n },\n {\n \"code\": null,\n \"e\": 54003,\n \"s\": 53736,\n \"text\": \"Functional dependency (FD) is a set of constraints between two attributes in a relation. Functional dependency says that if two tuples have same values for attributes A1, A2,..., An, then those two tuples must have to have same values for attributes B1, B2, ..., Bn.\"\n },\n {\n \"code\": null,\n \"e\": 54199,\n \"s\": 54003,\n \"text\": \"Functional dependency is represented by an arrow sign (→) that is, X→Y, where X functionally determines Y. The left-hand side attributes determine the values of attributes on the right-hand side.\"\n },\n {\n \"code\": null,\n \"e\": 54461,\n \"s\": 54199,\n \"text\": \"If F is a set of functional dependencies then the closure of F, denoted as F+, is the set of all functional dependencies logically implied by F. Armstrong's Axioms are a set of rules, that when applied repeatedly, generates a closure of functional dependencies.\"\n },\n {\n \"code\": null,\n \"e\": 54562,\n \"s\": 54461,\n \"text\": \"Reflexive rule − If alpha is a set of attributes and beta is_subset_of alpha, then alpha holds beta.\"\n },\n {\n \"code\": null,\n \"e\": 54663,\n \"s\": 54562,\n \"text\": \"Reflexive rule − If alpha is a set of attributes and beta is_subset_of alpha, then alpha holds beta.\"\n },\n {\n \"code\": null,\n \"e\": 54830,\n \"s\": 54663,\n \"text\": \"Augmentation rule − If a → b holds and y is attribute set, then ay → by also holds. That is adding attributes in dependencies, does not change the basic dependencies.\"\n },\n {\n \"code\": null,\n \"e\": 54997,\n \"s\": 54830,\n \"text\": \"Augmentation rule − If a → b holds and y is attribute set, then ay → by also holds. That is adding attributes in dependencies, does not change the basic dependencies.\"\n },\n {\n \"code\": null,\n \"e\": 55161,\n \"s\": 54997,\n \"text\": \"Transitivity rule − Same as transitive rule in algebra, if a → b holds and b → c holds, then a → c also holds. a → b is called as a functionally that determines b.\"\n },\n {\n \"code\": null,\n \"e\": 55325,\n \"s\": 55161,\n \"text\": \"Transitivity rule − Same as transitive rule in algebra, if a → b holds and b → c holds, then a → c also holds. a → b is called as a functionally that determines b.\"\n },\n {\n \"code\": null,\n \"e\": 55463,\n \"s\": 55325,\n \"text\": \"Trivial − If a functional dependency (FD) X → Y holds, where Y is a subset of X, then it is called a trivial FD. Trivial FDs always hold.\"\n },\n {\n \"code\": null,\n \"e\": 55601,\n \"s\": 55463,\n \"text\": \"Trivial − If a functional dependency (FD) X → Y holds, where Y is a subset of X, then it is called a trivial FD. Trivial FDs always hold.\"\n },\n {\n \"code\": null,\n \"e\": 55703,\n \"s\": 55601,\n \"text\": \"Non-trivial − If an FD X → Y holds, where Y is not a subset of X, then it is called a non-trivial FD.\"\n },\n {\n \"code\": null,\n \"e\": 55805,\n \"s\": 55703,\n \"text\": \"Non-trivial − If an FD X → Y holds, where Y is not a subset of X, then it is called a non-trivial FD.\"\n },\n {\n \"code\": null,\n \"e\": 55923,\n \"s\": 55805,\n \"text\": \"Completely non-trivial − If an FD X → Y holds, where x intersect Y = Φ, it is said to be a completely non-trivial FD.\"\n },\n {\n \"code\": null,\n \"e\": 56041,\n \"s\": 55923,\n \"text\": \"Completely non-trivial − If an FD X → Y holds, where x intersect Y = Φ, it is said to be a completely non-trivial FD.\"\n },\n {\n \"code\": null,\n \"e\": 56221,\n \"s\": 56041,\n \"text\": \"If a database design is not perfect, it may contain anomalies, which are like a bad dream for any database administrator. Managing a database with anomalies is next to impossible.\"\n },\n {\n \"code\": null,\n \"e\": 56593,\n \"s\": 56221,\n \"text\": \"Update anomalies − If data items are scattered and are not linked to each other properly, then it could lead to strange situations. For example, when we try to update one data item having its copies scattered over several places, a few instances get updated properly while a few others are left with old values. Such instances leave the database in an inconsistent state.\"\n },\n {\n \"code\": null,\n \"e\": 56965,\n \"s\": 56593,\n \"text\": \"Update anomalies − If data items are scattered and are not linked to each other properly, then it could lead to strange situations. For example, when we try to update one data item having its copies scattered over several places, a few instances get updated properly while a few others are left with old values. Such instances leave the database in an inconsistent state.\"\n },\n {\n \"code\": null,\n \"e\": 57113,\n \"s\": 56965,\n \"text\": \"Deletion anomalies − We tried to delete a record, but parts of it was left undeleted because of unawareness, the data is also saved somewhere else.\"\n },\n {\n \"code\": null,\n \"e\": 57261,\n \"s\": 57113,\n \"text\": \"Deletion anomalies − We tried to delete a record, but parts of it was left undeleted because of unawareness, the data is also saved somewhere else.\"\n },\n {\n \"code\": null,\n \"e\": 57344,\n \"s\": 57261,\n \"text\": \"Insert anomalies − We tried to insert data in a record that does not exist at all.\"\n },\n {\n \"code\": null,\n \"e\": 57427,\n \"s\": 57344,\n \"text\": \"Insert anomalies − We tried to insert data in a record that does not exist at all.\"\n },\n {\n \"code\": null,\n \"e\": 57529,\n \"s\": 57427,\n \"text\": \"Normalization is a method to remove all these anomalies and bring the database to a consistent state.\"\n },\n {\n \"code\": null,\n \"e\": 57742,\n \"s\": 57529,\n \"text\": \"First Normal Form is defined in the definition of relations (tables) itself. This rule defines that all the attributes in a relation must have atomic domains. The values in an atomic domain are indivisible units.\"\n },\n {\n \"code\": null,\n \"e\": 57823,\n \"s\": 57742,\n \"text\": \"We re-arrange the relation (table) as below, to convert it to First Normal Form.\"\n },\n {\n \"code\": null,\n \"e\": 57900,\n \"s\": 57823,\n \"text\": \"Each attribute must contain only a single value from its pre-defined domain.\"\n },\n {\n \"code\": null,\n \"e\": 57984,\n \"s\": 57900,\n \"text\": \"Before we learn about the second normal form, we need to understand the following −\"\n },\n {\n \"code\": null,\n \"e\": 58085,\n \"s\": 57984,\n \"text\": \"Prime attribute − An attribute, which is a part of the candidate-key, is known as a prime attribute.\"\n },\n {\n \"code\": null,\n \"e\": 58186,\n \"s\": 58085,\n \"text\": \"Prime attribute − An attribute, which is a part of the candidate-key, is known as a prime attribute.\"\n },\n {\n \"code\": null,\n \"e\": 58297,\n \"s\": 58186,\n \"text\": \"Non-prime attribute − An attribute, which is not a part of the prime-key, is said to be a non-prime attribute.\"\n },\n {\n \"code\": null,\n \"e\": 58408,\n \"s\": 58297,\n \"text\": \"Non-prime attribute − An attribute, which is not a part of the prime-key, is said to be a non-prime attribute.\"\n },\n {\n \"code\": null,\n \"e\": 58644,\n \"s\": 58408,\n \"text\": \"If we follow second normal form, then every non-prime attribute should be fully functionally dependent on prime key attribute. That is, if X → A holds, then there should not be any proper subset Y of X, for which Y → A also holds true.\"\n },\n {\n \"code\": null,\n \"e\": 59084,\n \"s\": 58644,\n \"text\": \"We see here in Student_Project relation that the prime key attributes are Stu_ID and Proj_ID. According to the rule, non-key attributes, i.e. Stu_Name and Proj_Name must be dependent upon both and not on any of the prime key attribute individually. But we find that Stu_Name can be identified by Stu_ID and Proj_Name can be identified by Proj_ID independently. This is called partial dependency, which is not allowed in Second Normal Form.\"\n },\n {\n \"code\": null,\n \"e\": 59186,\n \"s\": 59084,\n \"text\": \"We broke the relation in two as depicted in the above picture. So there exists no partial dependency.\"\n },\n {\n \"code\": null,\n \"e\": 59295,\n \"s\": 59186,\n \"text\": \"For a relation to be in Third Normal Form, it must be in Second Normal form and the following must satisfy −\"\n },\n {\n \"code\": null,\n \"e\": 59368,\n \"s\": 59295,\n \"text\": \"No non-prime attribute is transitively dependent on prime key attribute.\"\n },\n {\n \"code\": null,\n \"e\": 59476,\n \"s\": 59368,\n \"text\": \"For any non-trivial functional dependency, X → A, then either −\\nX is a superkey or,\\nA is prime attribute.\\n\\n\"\n },\n {\n \"code\": null,\n \"e\": 59498,\n \"s\": 59476,\n \"text\": \"A is prime attribute.\"\n },\n {\n \"code\": null,\n \"e\": 59798,\n \"s\": 59498,\n \"text\": \"We find that in the above Student_detail relation, Stu_ID is the key and only prime key attribute. We find that City can be identified by Stu_ID as well as Zip itself. Neither Zip is a superkey nor is City a prime attribute. Additionally, Stu_ID → Zip → City, so there exists transitive dependency.\"\n },\n {\n \"code\": null,\n \"e\": 59899,\n \"s\": 59798,\n \"text\": \"To bring this relation into third normal form, we break the relation into two relations as follows −\"\n },\n {\n \"code\": null,\n \"e\": 60002,\n \"s\": 59899,\n \"text\": \"Boyce-Codd Normal Form (BCNF) is an extension of Third Normal Form on strict terms. BCNF states that −\"\n },\n {\n \"code\": null,\n \"e\": 60075,\n \"s\": 60002,\n \"text\": \"For any non-trivial functional dependency, X → A, X must be a super-key.\"\n },\n {\n \"code\": null,\n \"e\": 60205,\n \"s\": 60075,\n \"text\": \"In the above image, Stu_ID is the super-key in the relation Student_Detail and Zip is the super-key in the relation ZipCodes. So,\"\n },\n {\n \"code\": null,\n \"e\": 60228,\n \"s\": 60205,\n \"text\": \"Stu_ID → Stu_Name, Zip\"\n },\n {\n \"code\": null,\n \"e\": 60232,\n \"s\": 60228,\n \"text\": \"and\"\n },\n {\n \"code\": null,\n \"e\": 60243,\n \"s\": 60232,\n \"text\": \"Zip → City\"\n },\n {\n \"code\": null,\n \"e\": 60295,\n \"s\": 60243,\n \"text\": \"Which confirms that both the relations are in BCNF.\"\n },\n {\n \"code\": null,\n \"e\": 60625,\n \"s\": 60295,\n \"text\": \"We understand the benefits of taking a Cartesian product of two relations, which gives us all the possible tuples that are paired together. But it might not be feasible for us in certain cases to take a Cartesian product where we encounter huge relations with thousands of tuples having a considerable large number of attributes.\"\n },\n {\n \"code\": null,\n \"e\": 60815,\n \"s\": 60625,\n \"text\": \"Join is a combination of a Cartesian product followed by a selection process. A Join operation pairs two tuples from different relations, if and only if a given join condition is satisfied.\"\n },\n {\n \"code\": null,\n \"e\": 60886,\n \"s\": 60815,\n \"text\": \"We will briefly describe various join types in the following sections.\"\n },\n {\n \"code\": null,\n \"e\": 61028,\n \"s\": 60886,\n \"text\": \"Theta join combines tuples from different relations provided they satisfy the theta condition. The join condition is denoted by the symbol θ.\"\n },\n {\n \"code\": null,\n \"e\": 61038,\n \"s\": 61028,\n \"text\": \"R1 ⋈θ R2\\n\"\n },\n {\n \"code\": null,\n \"e\": 61194,\n \"s\": 61038,\n \"text\": \"R1 and R2 are relations having attributes (A1, A2, .., An) and (B1, B2,.. ,Bn) such that the attributes don’t have anything in common, that is R1 ∩ R2 = Φ.\"\n },\n {\n \"code\": null,\n \"e\": 61248,\n \"s\": 61194,\n \"text\": \"Theta join can use all kinds of comparison operators.\"\n },\n {\n \"code\": null,\n \"e\": 61265,\n \"s\": 61248,\n \"text\": \"Student_Detail =\"\n },\n {\n \"code\": null,\n \"e\": 61311,\n \"s\": 61265,\n \"text\": \"STUDENT ⋈Student.Std = Subject.Class SUBJECT\\n\"\n },\n {\n \"code\": null,\n \"e\": 61437,\n \"s\": 61311,\n \"text\": \"When Theta join uses only equality comparison operator, it is said to be equijoin. The above example corresponds to equijoin.\"\n },\n {\n \"code\": null,\n \"e\": 61722,\n \"s\": 61437,\n \"text\": \"Natural join does not use any comparison operator. It does not concatenate the way a Cartesian product does. We can perform a Natural Join only if there is at least one common attribute that exists between two relations. In addition, the attributes must have the same name and domain.\"\n },\n {\n \"code\": null,\n \"e\": 61832,\n \"s\": 61722,\n \"text\": \"Natural join acts on those matching attributes where the values of attributes in both the relations are same.\"\n },\n {\n \"code\": null,\n \"e\": 62234,\n \"s\": 61832,\n \"text\": \"Theta Join, Equijoin, and Natural Join are called inner joins. An inner join includes only those tuples with matching attributes and the rest are discarded in the resulting relation. Therefore, we need to use outer joins to include all the tuples from the participating relations in the resulting relation. There are three kinds of outer joins − left outer join, right outer join, and full outer join.\"\n },\n {\n \"code\": null,\n \"e\": 62456,\n \"s\": 62234,\n \"text\": \"All the tuples from the Left relation, R, are included in the resulting relation. If there are tuples in R without any matching tuple in the Right relation S, then the S-attributes of the resulting relation are made NULL.\"\n },\n {\n \"code\": null,\n \"e\": 62656,\n \"s\": 62456,\n \"text\": \"All the tuples from the Right relation, S, are included in the resulting relation. If there are tuples in S without any matching tuple in R, then the R-attributes of resulting relation are made NULL.\"\n },\n {\n \"code\": null,\n \"e\": 62850,\n \"s\": 62656,\n \"text\": \"All the tuples from both participating relations are included in the resulting relation. If there are no matching tuples for both relations, their respective unmatched attributes are made NULL.\"\n },\n {\n \"code\": null,\n \"e\": 63066,\n \"s\": 62850,\n \"text\": \"Databases are stored in file formats, which contain records. At physical level, the actual data is stored in electromagnetic format on some device. These storage devices can be broadly categorized into three types −\"\n },\n {\n \"code\": null,\n \"e\": 63536,\n \"s\": 63066,\n \"text\": \"Primary Storage − The memory storage that is directly accessible to the CPU comes under this category. CPU's internal memory (registers), fast memory (cache), and main memory (RAM) are directly accessible to the CPU, as they are all placed on the motherboard or CPU chipset. This storage is typically very small, ultra-fast, and volatile. Primary storage requires continuous power supply in order to maintain its state. In case of a power failure, all its data is lost.\"\n },\n {\n \"code\": null,\n \"e\": 64006,\n \"s\": 63536,\n \"text\": \"Primary Storage − The memory storage that is directly accessible to the CPU comes under this category. CPU's internal memory (registers), fast memory (cache), and main memory (RAM) are directly accessible to the CPU, as they are all placed on the motherboard or CPU chipset. This storage is typically very small, ultra-fast, and volatile. Primary storage requires continuous power supply in order to maintain its state. In case of a power failure, all its data is lost.\"\n },\n {\n \"code\": null,\n \"e\": 64307,\n \"s\": 64006,\n \"text\": \"Secondary Storage − Secondary storage devices are used to store data for future use or as backup. Secondary storage includes memory devices that are not a part of the CPU chipset or motherboard, for example, magnetic disks, optical disks (DVD, CD, etc.), hard disks, flash drives, and magnetic tapes.\"\n },\n {\n \"code\": null,\n \"e\": 64608,\n \"s\": 64307,\n \"text\": \"Secondary Storage − Secondary storage devices are used to store data for future use or as backup. Secondary storage includes memory devices that are not a part of the CPU chipset or motherboard, for example, magnetic disks, optical disks (DVD, CD, etc.), hard disks, flash drives, and magnetic tapes.\"\n },\n {\n \"code\": null,\n \"e\": 64927,\n \"s\": 64608,\n \"text\": \"Tertiary Storage − Tertiary storage is used to store huge volumes of data. Since such storage devices are external to the computer system, they are the slowest in speed. These storage devices are mostly used to take the back up of an entire system. Optical disks and magnetic tapes are widely used as tertiary storage.\"\n },\n {\n \"code\": null,\n \"e\": 65246,\n \"s\": 64927,\n \"text\": \"Tertiary Storage − Tertiary storage is used to store huge volumes of data. Since such storage devices are external to the computer system, they are the slowest in speed. These storage devices are mostly used to take the back up of an entire system. Optical disks and magnetic tapes are widely used as tertiary storage.\"\n },\n {\n \"code\": null,\n \"e\": 65626,\n \"s\": 65246,\n \"text\": \"A computer system has a well-defined hierarchy of memory. A CPU has direct access to it main memory as well as its inbuilt registers. The access time of the main memory is obviously less than the CPU speed. To minimize this speed mismatch, cache memory is introduced. Cache memory provides the fastest access time and it contains data that is most frequently accessed by the CPU.\"\n },\n {\n \"code\": null,\n \"e\": 65842,\n \"s\": 65626,\n \"text\": \"The memory with the fastest access is the costliest one. Larger storage devices offer slow speed and they are less expensive, however they can store huge volumes of data as compared to CPU registers or cache memory.\"\n },\n {\n \"code\": null,\n \"e\": 66316,\n \"s\": 65842,\n \"text\": \"Hard disk drives are the most common secondary storage devices in present computer systems. These are called magnetic disks because they use the concept of magnetization to store information. Hard disks consist of metal disks coated with magnetizable material. These disks are placed vertically on a spindle. A read/write head moves in between the disks and is used to magnetize or de-magnetize the spot under it. A magnetized spot can be recognized as 0 (zero) or 1 (one).\"\n },\n {\n \"code\": null,\n \"e\": 66565,\n \"s\": 66316,\n \"text\": \"Hard disks are formatted in a well-defined order to store data efficiently. A hard disk plate has many concentric circles on it, called tracks. Every track is further divided into sectors. A sector on a hard disk typically stores 512 bytes of data.\"\n },\n {\n \"code\": null,\n \"e\": 66727,\n \"s\": 66565,\n \"text\": \"RAID stands for Redundant Array of Independent Disks, which is a technology to connect multiple secondary storage devices and use them as a single storage media.\"\n },\n {\n \"code\": null,\n \"e\": 66880,\n \"s\": 66727,\n \"text\": \"RAID consists of an array of disks in which multiple disks are connected together to achieve different goals. RAID levels define the use of disk arrays.\"\n },\n {\n \"code\": null,\n \"e\": 67190,\n \"s\": 66880,\n \"text\": \"RAID 0 − In this level, a striped array of disks is implemented. The data is broken down into blocks and the blocks are distributed among disks. Each disk receives a block of data to write/read in parallel. It enhances the speed and performance of the storage device. There is no parity and backup in Level 0.\"\n },\n {\n \"code\": null,\n \"e\": 67500,\n \"s\": 67190,\n \"text\": \"RAID 0 − In this level, a striped array of disks is implemented. The data is broken down into blocks and the blocks are distributed among disks. Each disk receives a block of data to write/read in parallel. It enhances the speed and performance of the storage device. There is no parity and backup in Level 0.\"\n },\n {\n \"code\": null,\n \"e\": 67727,\n \"s\": 67500,\n \"text\": \"RAID 1 − RAID 1 uses mirroring techniques. When data is sent to a RAID controller, it sends a copy of data to all the disks in the array. RAID level 1 is also called mirroring and provides 100% redundancy in case of a failure.\"\n },\n {\n \"code\": null,\n \"e\": 67954,\n \"s\": 67727,\n \"text\": \"RAID 1 − RAID 1 uses mirroring techniques. When data is sent to a RAID controller, it sends a copy of data to all the disks in the array. RAID level 1 is also called mirroring and provides 100% redundancy in case of a failure.\"\n },\n {\n \"code\": null,\n \"e\": 68285,\n \"s\": 67954,\n \"text\": \"RAID 2 − RAID 2 records Error Correction Code using Hamming distance for its data, striped on different disks. Like level 0, each data bit in a word is recorded on a separate disk and ECC codes of the data words are stored on a different set disks. Due to its complex structure and high cost, RAID 2 is not commercially available.\"\n },\n {\n \"code\": null,\n \"e\": 68616,\n \"s\": 68285,\n \"text\": \"RAID 2 − RAID 2 records Error Correction Code using Hamming distance for its data, striped on different disks. Like level 0, each data bit in a word is recorded on a separate disk and ECC codes of the data words are stored on a different set disks. Due to its complex structure and high cost, RAID 2 is not commercially available.\"\n },\n {\n \"code\": null,\n \"e\": 68798,\n \"s\": 68616,\n \"text\": \"RAID 3 − RAID 3 stripes the data onto multiple disks. The parity bit generated for data word is stored on a different disk. This technique makes it to overcome single disk failures.\"\n },\n {\n \"code\": null,\n \"e\": 68980,\n \"s\": 68798,\n \"text\": \"RAID 3 − RAID 3 stripes the data onto multiple disks. The parity bit generated for data word is stored on a different disk. This technique makes it to overcome single disk failures.\"\n },\n {\n \"code\": null,\n \"e\": 69280,\n \"s\": 68980,\n \"text\": \"RAID 4 − In this level, an entire block of data is written onto data disks and then the parity is generated and stored on a different disk. Note that level 3 uses byte-level striping, whereas level 4 uses block-level striping. Both level 3 and level 4 require at least three disks to implement RAID.\"\n },\n {\n \"code\": null,\n \"e\": 69580,\n \"s\": 69280,\n \"text\": \"RAID 4 − In this level, an entire block of data is written onto data disks and then the parity is generated and stored on a different disk. Note that level 3 uses byte-level striping, whereas level 4 uses block-level striping. Both level 3 and level 4 require at least three disks to implement RAID.\"\n },\n {\n \"code\": null,\n \"e\": 69792,\n \"s\": 69580,\n \"text\": \"RAID 5 − RAID 5 writes whole data blocks onto different disks, but the parity bits generated for data block stripe are distributed among all the data disks rather than storing them on a different dedicated disk.\"\n },\n {\n \"code\": null,\n \"e\": 70004,\n \"s\": 69792,\n \"text\": \"RAID 5 − RAID 5 writes whole data blocks onto different disks, but the parity bits generated for data block stripe are distributed among all the data disks rather than storing them on a different dedicated disk.\"\n },\n {\n \"code\": null,\n \"e\": 70272,\n \"s\": 70004,\n \"text\": \"RAID 6 − RAID 6 is an extension of level 5. In this level, two independent parities are generated and stored in distributed fashion among multiple disks. Two parities provide additional fault tolerance. This level requires at least four disk drives to implement RAID.\"\n },\n {\n \"code\": null,\n \"e\": 70540,\n \"s\": 70272,\n \"text\": \"RAID 6 − RAID 6 is an extension of level 5. In this level, two independent parities are generated and stored in distributed fashion among multiple disks. Two parities provide additional fault tolerance. This level requires at least four disk drives to implement RAID.\"\n },\n {\n \"code\": null,\n \"e\": 70785,\n \"s\": 70540,\n \"text\": \"Relative data and information is stored collectively in file formats. A file is a sequence of records stored in binary format. A disk drive is formatted into several blocks that can store records. File records are mapped onto those disk blocks.\"\n },\n {\n \"code\": null,\n \"e\": 70924,\n \"s\": 70785,\n \"text\": \"File Organization defines how file records are mapped onto disk blocks. We have four types of File Organization to organize file records −\"\n },\n {\n \"code\": null,\n \"e\": 71271,\n \"s\": 70924,\n \"text\": \"When a file is created using Heap File Organization, the Operating System allocates memory area to that file without any further accounting details. File records can be placed anywhere in that memory area. It is the responsibility of the software to manage the records. Heap File does not support any ordering, sequencing, or indexing on its own.\"\n },\n {\n \"code\": null,\n \"e\": 71579,\n \"s\": 71271,\n \"text\": \"Every file record contains a data field (attribute) to uniquely identify that record. In sequential file organization, records are placed in the file in some sequential order based on the unique key field or search key. Practically, it is not possible to store all the records sequentially in physical form.\"\n },\n {\n \"code\": null,\n \"e\": 71770,\n \"s\": 71579,\n \"text\": \"Hash File Organization uses Hash function computation on some fields of the records. The output of the hash function determines the location of disk block where the records are to be placed.\"\n },\n {\n \"code\": null,\n \"e\": 72013,\n \"s\": 71770,\n \"text\": \"Clustered file organization is not considered good for large databases. In this mechanism, related records from one or more relations are kept in the same disk block, that is, the ordering of records is not based on primary key or search key.\"\n },\n {\n \"code\": null,\n \"e\": 72090,\n \"s\": 72013,\n \"text\": \"Operations on database files can be broadly classified into two categories −\"\n },\n {\n \"code\": null,\n \"e\": 72108,\n \"s\": 72090,\n \"text\": \"Update Operations\"\n },\n {\n \"code\": null,\n \"e\": 72126,\n \"s\": 72108,\n \"text\": \"Update Operations\"\n },\n {\n \"code\": null,\n \"e\": 72147,\n \"s\": 72126,\n \"text\": \"Retrieval Operations\"\n },\n {\n \"code\": null,\n \"e\": 72168,\n \"s\": 72147,\n \"text\": \"Retrieval Operations\"\n },\n {\n \"code\": null,\n \"e\": 72535,\n \"s\": 72168,\n \"text\": \"Update operations change the data values by insertion, deletion, or update. Retrieval operations, on the other hand, do not alter the data but retrieve them after optional conditional filtering. In both types of operations, selection plays a significant role. Other than creation and deletion of a file, there could be several operations, which can be done on files.\"\n },\n {\n \"code\": null,\n \"e\": 72882,\n \"s\": 72535,\n \"text\": \"Open − A file can be opened in one of the two modes, read mode or write mode. In read mode, the operating system does not allow anyone to alter data. In other words, data is read only. Files opened in read mode can be shared among several entities. Write mode allows data modification. Files opened in write mode can be read but cannot be shared.\"\n },\n {\n \"code\": null,\n \"e\": 73229,\n \"s\": 72882,\n \"text\": \"Open − A file can be opened in one of the two modes, read mode or write mode. In read mode, the operating system does not allow anyone to alter data. In other words, data is read only. Files opened in read mode can be shared among several entities. Write mode allows data modification. Files opened in write mode can be read but cannot be shared.\"\n },\n {\n \"code\": null,\n \"e\": 73451,\n \"s\": 73229,\n \"text\": \"Locate − Every file has a file pointer, which tells the current position where the data is to be read or written. This pointer can be adjusted accordingly. Using find (seek) operation, it can be moved forward or backward.\"\n },\n {\n \"code\": null,\n \"e\": 73673,\n \"s\": 73451,\n \"text\": \"Locate − Every file has a file pointer, which tells the current position where the data is to be read or written. This pointer can be adjusted accordingly. Using find (seek) operation, it can be moved forward or backward.\"\n },\n {\n \"code\": null,\n \"e\": 73957,\n \"s\": 73673,\n \"text\": \"Read − By default, when files are opened in read mode, the file pointer points to the beginning of the file. There are options where the user can tell the operating system where to locate the file pointer at the time of opening a file. The very next data to the file pointer is read.\"\n },\n {\n \"code\": null,\n \"e\": 74241,\n \"s\": 73957,\n \"text\": \"Read − By default, when files are opened in read mode, the file pointer points to the beginning of the file. There are options where the user can tell the operating system where to locate the file pointer at the time of opening a file. The very next data to the file pointer is read.\"\n },\n {\n \"code\": null,\n \"e\": 74510,\n \"s\": 74241,\n \"text\": \"Write − User can select to open a file in write mode, which enables them to edit its contents. It can be deletion, insertion, or modification. The file pointer can be located at the time of opening or can be dynamically changed if the operating system allows to do so.\"\n },\n {\n \"code\": null,\n \"e\": 74779,\n \"s\": 74510,\n \"text\": \"Write − User can select to open a file in write mode, which enables them to edit its contents. It can be deletion, insertion, or modification. The file pointer can be located at the time of opening or can be dynamically changed if the operating system allows to do so.\"\n },\n {\n \"code\": null,\n \"e\": 75112,\n \"s\": 74779,\n \"text\": \"Close − This is the most important operation from the operating system’s point of view. When a request to close a file is generated, the operating system\\n\\nremoves all the locks (if in shared mode),\\nsaves the data (if altered) to the secondary storage media, and\\nreleases all the buffers and file handlers associated with the file.\\n\\n\"\n },\n {\n \"code\": null,\n \"e\": 75266,\n \"s\": 75112,\n \"text\": \"Close − This is the most important operation from the operating system’s point of view. When a request to close a file is generated, the operating system\"\n },\n {\n \"code\": null,\n \"e\": 75309,\n \"s\": 75266,\n \"text\": \"removes all the locks (if in shared mode),\"\n },\n {\n \"code\": null,\n \"e\": 75373,\n \"s\": 75309,\n \"text\": \"saves the data (if altered) to the secondary storage media, and\"\n },\n {\n \"code\": null,\n \"e\": 75442,\n \"s\": 75373,\n \"text\": \"releases all the buffers and file handlers associated with the file.\"\n },\n {\n \"code\": null,\n \"e\": 75656,\n \"s\": 75442,\n \"text\": \"The organization of data inside a file plays a major role here. The process to locate the file pointer to a desired record inside a file various based on whether the records are arranged sequentially or clustered.\"\n },\n {\n \"code\": null,\n \"e\": 75780,\n \"s\": 75656,\n \"text\": \"We know that data is stored in the form of records. Every record has a key field, which helps it to be recognized uniquely.\"\n },\n {\n \"code\": null,\n \"e\": 76002,\n \"s\": 75780,\n \"text\": \"Indexing is a data structure technique to efficiently retrieve records from the database files based on some attributes on which the indexing has been done. Indexing in database systems is similar to what we see in books.\"\n },\n {\n \"code\": null,\n \"e\": 76097,\n \"s\": 76002,\n \"text\": \"Indexing is defined based on its indexing attributes. Indexing can be of the following types −\"\n },\n {\n \"code\": null,\n \"e\": 76264,\n \"s\": 76097,\n \"text\": \"Primary Index − Primary index is defined on an ordered data file. The data file is ordered on a key field. The key field is generally the primary key of the relation.\"\n },\n {\n \"code\": null,\n \"e\": 76431,\n \"s\": 76264,\n \"text\": \"Primary Index − Primary index is defined on an ordered data file. The data file is ordered on a key field. The key field is generally the primary key of the relation.\"\n },\n {\n \"code\": null,\n \"e\": 76596,\n \"s\": 76431,\n \"text\": \"Secondary Index − Secondary index may be generated from a field which is a candidate key and has a unique value in every record, or a non-key with duplicate values.\"\n },\n {\n \"code\": null,\n \"e\": 76761,\n \"s\": 76596,\n \"text\": \"Secondary Index − Secondary index may be generated from a field which is a candidate key and has a unique value in every record, or a non-key with duplicate values.\"\n },\n {\n \"code\": null,\n \"e\": 76878,\n \"s\": 76761,\n \"text\": \"Clustering Index − Clustering index is defined on an ordered data file. The data file is ordered on a non-key field.\"\n },\n {\n \"code\": null,\n \"e\": 76995,\n \"s\": 76878,\n \"text\": \"Clustering Index − Clustering index is defined on an ordered data file. The data file is ordered on a non-key field.\"\n },\n {\n \"code\": null,\n \"e\": 77030,\n \"s\": 76995,\n \"text\": \"Ordered Indexing is of two types −\"\n },\n {\n \"code\": null,\n \"e\": 77042,\n \"s\": 77030,\n \"text\": \"Dense Index\"\n },\n {\n \"code\": null,\n \"e\": 77055,\n \"s\": 77042,\n \"text\": \"Sparse Index\"\n },\n {\n \"code\": null,\n \"e\": 77310,\n \"s\": 77055,\n \"text\": \"In dense index, there is an index record for every search key value in the database. This makes searching faster but requires more space to store index records itself. Index records contain search key value and a pointer to the actual record on the disk.\"\n },\n {\n \"code\": null,\n \"e\": 77728,\n \"s\": 77310,\n \"text\": \"In sparse index, index records are not created for every search key. An index record here contains a search key and an actual pointer to the data on the disk. To search a record, we first proceed by index record and reach at the actual location of the data. If the data we are looking for is not where we directly reach by following the index, then the system starts sequential search until the desired data is found.\"\n },\n {\n \"code\": null,\n \"e\": 78163,\n \"s\": 77728,\n \"text\": \"Index records comprise search-key values and data pointers. Multilevel index is stored on the disk along with the actual database files. As the size of the database grows, so does the size of the indices. There is an immense need to keep the index records in the main memory so as to speed up the search operations. If single-level index is used, then a large size index cannot be kept in memory which leads to multiple disk accesses.\"\n },\n {\n \"code\": null,\n \"e\": 78396,\n \"s\": 78163,\n \"text\": \"Multi-level Index helps in breaking down the index into several smaller indices in order to make the outermost level so small that it can be saved in a single disk block, which can easily be accommodated anywhere in the main memory.\"\n },\n {\n \"code\": null,\n \"e\": 78751,\n \"s\": 78396,\n \"text\": \"A B+ tree is a balanced binary search tree that follows a multi-level index format. The leaf nodes of a B+ tree denote actual data pointers. B+ tree ensures that all leaf nodes remain at the same height, thus balanced. Additionally, the leaf nodes are linked using a link list; therefore, a B+ tree can support random access as well as sequential access.\"\n },\n {\n \"code\": null,\n \"e\": 78872,\n \"s\": 78751,\n \"text\": \"Every leaf node is at equal distance from the root node. A B+ tree is of the order n where n is fixed for every B+ tree.\"\n },\n {\n \"code\": null,\n \"e\": 78889,\n \"s\": 78872,\n \"text\": \"Internal nodes −\"\n },\n {\n \"code\": null,\n \"e\": 78970,\n \"s\": 78889,\n \"text\": \"Internal (non-leaf) nodes contain at least ⌈n/2⌉ pointers, except the root node.\"\n },\n {\n \"code\": null,\n \"e\": 79020,\n \"s\": 78970,\n \"text\": \"At most, an internal node can contain n pointers.\"\n },\n {\n \"code\": null,\n \"e\": 79033,\n \"s\": 79020,\n \"text\": \"Leaf nodes −\"\n },\n {\n \"code\": null,\n \"e\": 79105,\n \"s\": 79033,\n \"text\": \"Leaf nodes contain at least ⌈n/2⌉ record pointers and ⌈n/2⌉ key values.\"\n },\n {\n \"code\": null,\n \"e\": 79174,\n \"s\": 79105,\n \"text\": \"At most, a leaf node can contain n record pointers and n key values.\"\n },\n {\n \"code\": null,\n \"e\": 79271,\n \"s\": 79174,\n \"text\": \"Every leaf node contains one block pointer P to point to next leaf node and forms a linked list.\"\n },\n {\n \"code\": null,\n \"e\": 79344,\n \"s\": 79271,\n \"text\": \"B+ trees are filled from bottom and each entry is done at the leaf node.\"\n },\n {\n \"code\": null,\n \"e\": 79417,\n \"s\": 79344,\n \"text\": \"B+ trees are filled from bottom and each entry is done at the leaf node.\"\n },\n {\n \"code\": null,\n \"e\": 79650,\n \"s\": 79417,\n \"text\": \"If a leaf node overflows −\\n\\nSplit node into two parts.\\nPartition at i = ⌊(m+1)/2⌋.\\nFirst i entries are stored in one node.\\nRest of the entries (i+1 onwards) are moved to a new node.\\nith key is duplicated at the parent of the leaf.\\n\\n\"\n },\n {\n \"code\": null,\n \"e\": 79677,\n \"s\": 79650,\n \"text\": \"Split node into two parts.\"\n },\n {\n \"code\": null,\n \"e\": 79704,\n \"s\": 79677,\n \"text\": \"Split node into two parts.\"\n },\n {\n \"code\": null,\n \"e\": 79732,\n \"s\": 79704,\n \"text\": \"Partition at i = ⌊(m+1)/2⌋.\"\n },\n {\n \"code\": null,\n \"e\": 79760,\n \"s\": 79732,\n \"text\": \"Partition at i = ⌊(m+1)/2⌋.\"\n },\n {\n \"code\": null,\n \"e\": 79800,\n \"s\": 79760,\n \"text\": \"First i entries are stored in one node.\"\n },\n {\n \"code\": null,\n \"e\": 79840,\n \"s\": 79800,\n \"text\": \"First i entries are stored in one node.\"\n },\n {\n \"code\": null,\n \"e\": 79899,\n \"s\": 79840,\n \"text\": \"Rest of the entries (i+1 onwards) are moved to a new node.\"\n },\n {\n \"code\": null,\n \"e\": 79958,\n \"s\": 79899,\n \"text\": \"Rest of the entries (i+1 onwards) are moved to a new node.\"\n },\n {\n \"code\": null,\n \"e\": 80007,\n \"s\": 79958,\n \"text\": \"ith key is duplicated at the parent of the leaf.\"\n },\n {\n \"code\": null,\n \"e\": 80056,\n \"s\": 80007,\n \"text\": \"ith key is duplicated at the parent of the leaf.\"\n },\n {\n \"code\": null,\n \"e\": 80237,\n \"s\": 80056,\n \"text\": \"If a non-leaf node overflows −\\n\\nSplit node into two parts.\\nPartition the node at i = ⌈(m+1)/2⌉.\\nEntries up to i are kept in one node.\\nRest of the entries are moved to a new node.\\n\\n\"\n },\n {\n \"code\": null,\n \"e\": 80268,\n \"s\": 80237,\n \"text\": \"If a non-leaf node overflows −\"\n },\n {\n \"code\": null,\n \"e\": 80295,\n \"s\": 80268,\n \"text\": \"Split node into two parts.\"\n },\n {\n \"code\": null,\n \"e\": 80322,\n \"s\": 80295,\n \"text\": \"Split node into two parts.\"\n },\n {\n \"code\": null,\n \"e\": 80359,\n \"s\": 80322,\n \"text\": \"Partition the node at i = ⌈(m+1)/2⌉.\"\n },\n {\n \"code\": null,\n \"e\": 80396,\n \"s\": 80359,\n \"text\": \"Partition the node at i = ⌈(m+1)/2⌉.\"\n },\n {\n \"code\": null,\n \"e\": 80434,\n \"s\": 80396,\n \"text\": \"Entries up to i are kept in one node.\"\n },\n {\n \"code\": null,\n \"e\": 80472,\n \"s\": 80434,\n \"text\": \"Entries up to i are kept in one node.\"\n },\n {\n \"code\": null,\n \"e\": 80517,\n \"s\": 80472,\n \"text\": \"Rest of the entries are moved to a new node.\"\n },\n {\n \"code\": null,\n \"e\": 80562,\n \"s\": 80517,\n \"text\": \"Rest of the entries are moved to a new node.\"\n },\n {\n \"code\": null,\n \"e\": 80609,\n \"s\": 80562,\n \"text\": \"B+ tree entries are deleted at the leaf nodes.\"\n },\n {\n \"code\": null,\n \"e\": 80656,\n \"s\": 80609,\n \"text\": \"B+ tree entries are deleted at the leaf nodes.\"\n },\n {\n \"code\": null,\n \"e\": 80786,\n \"s\": 80656,\n \"text\": \"The target entry is searched and deleted.\\n\\nIf it is an internal node, delete and replace with the entry from the left position.\\n\\n\"\n },\n {\n \"code\": null,\n \"e\": 80828,\n \"s\": 80786,\n \"text\": \"The target entry is searched and deleted.\"\n },\n {\n \"code\": null,\n \"e\": 80913,\n \"s\": 80828,\n \"text\": \"If it is an internal node, delete and replace with the entry from the left position.\"\n },\n {\n \"code\": null,\n \"e\": 80998,\n \"s\": 80913,\n \"text\": \"If it is an internal node, delete and replace with the entry from the left position.\"\n },\n {\n \"code\": null,\n \"e\": 81109,\n \"s\": 80998,\n \"text\": \"After deletion, underflow is tested,\\n\\nIf underflow occurs, distribute the entries from the nodes left to it.\\n\\n\"\n },\n {\n \"code\": null,\n \"e\": 81146,\n \"s\": 81109,\n \"text\": \"After deletion, underflow is tested,\"\n },\n {\n \"code\": null,\n \"e\": 81217,\n \"s\": 81146,\n \"text\": \"If underflow occurs, distribute the entries from the nodes left to it.\"\n },\n {\n \"code\": null,\n \"e\": 81288,\n \"s\": 81217,\n \"text\": \"If underflow occurs, distribute the entries from the nodes left to it.\"\n },\n {\n \"code\": null,\n \"e\": 81378,\n \"s\": 81288,\n \"text\": \"If distribution is not possible from left, then\\n\\nDistribute from the nodes right to it.\\n\\n\"\n },\n {\n \"code\": null,\n \"e\": 81426,\n \"s\": 81378,\n \"text\": \"If distribution is not possible from left, then\"\n },\n {\n \"code\": null,\n \"e\": 81465,\n \"s\": 81426,\n \"text\": \"Distribute from the nodes right to it.\"\n },\n {\n \"code\": null,\n \"e\": 81504,\n \"s\": 81465,\n \"text\": \"Distribute from the nodes right to it.\"\n },\n {\n \"code\": null,\n \"e\": 81611,\n \"s\": 81504,\n \"text\": \"If distribution is not possible from left or from right, then\\n\\nMerge the node with left and right to it.\\n\\n\"\n },\n {\n \"code\": null,\n \"e\": 81673,\n \"s\": 81611,\n \"text\": \"If distribution is not possible from left or from right, then\"\n },\n {\n \"code\": null,\n \"e\": 81715,\n \"s\": 81673,\n \"text\": \"Merge the node with left and right to it.\"\n },\n {\n \"code\": null,\n \"e\": 81757,\n \"s\": 81715,\n \"text\": \"Merge the node with left and right to it.\"\n },\n {\n \"code\": null,\n \"e\": 82076,\n \"s\": 81757,\n \"text\": \"For a huge database structure, it can be almost next to impossible to search all the index values through all its level and then reach the destination data block to retrieve the desired data. Hashing is an effective technique to calculate the direct location of a data record on the disk without using index structure.\"\n },\n {\n \"code\": null,\n \"e\": 82177,\n \"s\": 82076,\n \"text\": \"Hashing uses hash functions with search keys as parameters to generate the address of a data record.\"\n },\n {\n \"code\": null,\n \"e\": 82364,\n \"s\": 82177,\n \"text\": \"Bucket − A hash file stores data in bucket format. Bucket is considered a unit of storage. A bucket typically stores one complete disk block, which in turn can store one or more records.\"\n },\n {\n \"code\": null,\n \"e\": 82551,\n \"s\": 82364,\n \"text\": \"Bucket − A hash file stores data in bucket format. Bucket is considered a unit of storage. A bucket typically stores one complete disk block, which in turn can store one or more records.\"\n },\n {\n \"code\": null,\n \"e\": 82751,\n \"s\": 82551,\n \"text\": \"Hash Function − A hash function, h, is a mapping function that maps all the set of search-keys K to the address where actual records are placed. It is a function from search keys to bucket addresses.\"\n },\n {\n \"code\": null,\n \"e\": 82951,\n \"s\": 82751,\n \"text\": \"Hash Function − A hash function, h, is a mapping function that maps all the set of search-keys K to the address where actual records are placed. It is a function from search keys to bucket addresses.\"\n },\n {\n \"code\": null,\n \"e\": 83264,\n \"s\": 82951,\n \"text\": \"In static hashing, when a search-key value is provided, the hash function always computes the same address. For example, if mod-4 hash function is used, then it shall generate only 5 values. The output address shall always be same for that function. The number of buckets provided remains unchanged at all times.\"\n },\n {\n \"code\": null,\n \"e\": 83456,\n \"s\": 83264,\n \"text\": \"Insertion − When a record is required to be entered using static hash, the hash function h computes the bucket address for search key K, where the record will be stored.\\nBucket address = h(K)\"\n },\n {\n \"code\": null,\n \"e\": 83626,\n \"s\": 83456,\n \"text\": \"Insertion − When a record is required to be entered using static hash, the hash function h computes the bucket address for search key K, where the record will be stored.\"\n },\n {\n \"code\": null,\n \"e\": 83648,\n \"s\": 83626,\n \"text\": \"Bucket address = h(K)\"\n },\n {\n \"code\": null,\n \"e\": 83793,\n \"s\": 83648,\n \"text\": \"Search − When a record needs to be retrieved, the same hash function can be used to retrieve the address of the bucket where the data is stored.\"\n },\n {\n \"code\": null,\n \"e\": 83938,\n \"s\": 83793,\n \"text\": \"Search − When a record needs to be retrieved, the same hash function can be used to retrieve the address of the bucket where the data is stored.\"\n },\n {\n \"code\": null,\n \"e\": 84005,\n \"s\": 83938,\n \"text\": \"Delete − This is simply a search followed by a deletion operation.\"\n },\n {\n \"code\": null,\n \"e\": 84072,\n \"s\": 84005,\n \"text\": \"Delete − This is simply a search followed by a deletion operation.\"\n },\n {\n \"code\": null,\n \"e\": 84225,\n \"s\": 84072,\n \"text\": \"The condition of bucket-overflow is known as collision. This is a fatal state for any static hash function. In this case, overflow chaining can be used.\"\n },\n {\n \"code\": null,\n \"e\": 84398,\n \"s\": 84225,\n \"text\": \"Overflow Chaining − When buckets are full, a new bucket is allocated for the same hash result and is linked after the previous one. This mechanism is called Closed Hashing.\"\n },\n {\n \"code\": null,\n \"e\": 84571,\n \"s\": 84398,\n \"text\": \"Overflow Chaining − When buckets are full, a new bucket is allocated for the same hash result and is linked after the previous one. This mechanism is called Closed Hashing.\"\n },\n {\n \"code\": null,\n \"e\": 84743,\n \"s\": 84571,\n \"text\": \"Linear Probing − When a hash function generates an address at which data is already stored, the next free bucket is allocated to it. This mechanism is called Open Hashing.\"\n },\n {\n \"code\": null,\n \"e\": 84915,\n \"s\": 84743,\n \"text\": \"Linear Probing − When a hash function generates an address at which data is already stored, the next free bucket is allocated to it. This mechanism is called Open Hashing.\"\n },\n {\n \"code\": null,\n \"e\": 85201,\n \"s\": 84915,\n \"text\": \"The problem with static hashing is that it does not expand or shrink dynamically as the size of the database grows or shrinks. Dynamic hashing provides a mechanism in which data buckets are added and removed dynamically and on-demand. Dynamic hashing is also known as extended hashing.\"\n },\n {\n \"code\": null,\n \"e\": 85315,\n \"s\": 85201,\n \"text\": \"Hash function, in dynamic hashing, is made to produce a large number of values and only a few are used initially.\"\n },\n {\n \"code\": null,\n \"e\": 85740,\n \"s\": 85315,\n \"text\": \"The prefix of an entire hash value is taken as a hash index. Only a portion of the hash value is used for computing bucket addresses. Every hash index has a depth value to signify how many bits are used for computing a hash function. These bits can address 2n buckets. When all these bits are consumed − that is, when all the buckets are full − then the depth value is increased linearly and twice the buckets are allocated.\"\n },\n {\n \"code\": null,\n \"e\": 85843,\n \"s\": 85740,\n \"text\": \"Querying − Look at the depth value of the hash index and use those bits to compute the bucket address.\"\n },\n {\n \"code\": null,\n \"e\": 85946,\n \"s\": 85843,\n \"text\": \"Querying − Look at the depth value of the hash index and use those bits to compute the bucket address.\"\n },\n {\n \"code\": null,\n \"e\": 86001,\n \"s\": 85946,\n \"text\": \"Update − Perform a query as above and update the data.\"\n },\n {\n \"code\": null,\n \"e\": 86056,\n \"s\": 86001,\n \"text\": \"Update − Perform a query as above and update the data.\"\n },\n {\n \"code\": null,\n \"e\": 86131,\n \"s\": 86056,\n \"text\": \"Deletion − Perform a query to locate the desired data and delete the same.\"\n },\n {\n \"code\": null,\n \"e\": 86206,\n \"s\": 86131,\n \"text\": \"Deletion − Perform a query to locate the desired data and delete the same.\"\n },\n {\n \"code\": null,\n \"e\": 86477,\n \"s\": 86206,\n \"text\": \"Insertion − Compute the address of the bucket\\n\\nIf the bucket is already full.\\n\\nAdd more buckets.\\nAdd additional bits to the hash value.\\nRe-compute the hash function.\\n\\n\\nElse\\n\\nAdd data to the bucket,\\n\\n\\nIf all the buckets are full, perform the remedies of static hashing.\\n\\n\"\n },\n {\n \"code\": null,\n \"e\": 86523,\n \"s\": 86477,\n \"text\": \"Insertion − Compute the address of the bucket\"\n },\n {\n \"code\": null,\n \"e\": 86644,\n \"s\": 86523,\n \"text\": \"If the bucket is already full.\\n\\nAdd more buckets.\\nAdd additional bits to the hash value.\\nRe-compute the hash function.\\n\\n\"\n },\n {\n \"code\": null,\n \"e\": 86662,\n \"s\": 86644,\n \"text\": \"Add more buckets.\"\n },\n {\n \"code\": null,\n \"e\": 86701,\n \"s\": 86662,\n \"text\": \"Add additional bits to the hash value.\"\n },\n {\n \"code\": null,\n \"e\": 86731,\n \"s\": 86701,\n \"text\": \"Re-compute the hash function.\"\n },\n {\n \"code\": null,\n \"e\": 86763,\n \"s\": 86731,\n \"text\": \"Else\\n\\nAdd data to the bucket,\\n\\n\"\n },\n {\n \"code\": null,\n \"e\": 86787,\n \"s\": 86763,\n \"text\": \"Add data to the bucket,\"\n },\n {\n \"code\": null,\n \"e\": 86856,\n \"s\": 86787,\n \"text\": \"If all the buckets are full, perform the remedies of static hashing.\"\n },\n {\n \"code\": null,\n \"e\": 87024,\n \"s\": 86856,\n \"text\": \"Hashing is not favorable when the data is organized in some ordering and the queries require a range of data. When data is discrete and random, hash performs the best.\"\n },\n {\n \"code\": null,\n \"e\": 87126,\n \"s\": 87024,\n \"text\": \"Hashing algorithms have high complexity than indexing. All hash operations are done in constant time.\"\n },\n {\n \"code\": null,\n \"e\": 87254,\n \"s\": 87126,\n \"text\": \"A transaction can be defined as a group of tasks. A single task is the minimum processing unit which cannot be divided further.\"\n },\n {\n \"code\": null,\n \"e\": 87448,\n \"s\": 87254,\n \"text\": \"Let’s take an example of a simple transaction. Suppose a bank employee transfers Rs 500 from A's account to B's account. This very simple and small transaction involves several low-level tasks.\"\n },\n {\n \"code\": null,\n \"e\": 87460,\n \"s\": 87448,\n \"text\": \"A’s Account\"\n },\n {\n \"code\": null,\n \"e\": 87574,\n \"s\": 87460,\n \"text\": \"Open_Account(A)\\nOld_Balance = A.balance\\nNew_Balance = Old_Balance - 500\\nA.balance = New_Balance\\nClose_Account(A)\\n\"\n },\n {\n \"code\": null,\n \"e\": 87586,\n \"s\": 87574,\n \"text\": \"B’s Account\"\n },\n {\n \"code\": null,\n \"e\": 87700,\n \"s\": 87586,\n \"text\": \"Open_Account(B)\\nOld_Balance = B.balance\\nNew_Balance = Old_Balance + 500\\nB.balance = New_Balance\\nClose_Account(B)\\n\"\n },\n {\n \"code\": null,\n \"e\": 87991,\n \"s\": 87700,\n \"text\": \"A transaction is a very small unit of a program and it may contain several lowlevel tasks. A transaction in a database system must maintain Atomicity, Consistency, Isolation, and Durability − commonly known as ACID properties − in order to ensure accuracy, completeness, and data integrity.\"\n },\n {\n \"code\": null,\n \"e\": 88356,\n \"s\": 87991,\n \"text\": \"Atomicity − This property states that a transaction must be treated as an atomic unit, that is, either all of its operations are executed or none. There must be no state in a database where a transaction is left partially completed. States should be defined either before the execution of the transaction or after the execution/abortion/failure of the transaction.\"\n },\n {\n \"code\": null,\n \"e\": 88721,\n \"s\": 88356,\n \"text\": \"Atomicity − This property states that a transaction must be treated as an atomic unit, that is, either all of its operations are executed or none. There must be no state in a database where a transaction is left partially completed. States should be defined either before the execution of the transaction or after the execution/abortion/failure of the transaction.\"\n },\n {\n \"code\": null,\n \"e\": 89044,\n \"s\": 88721,\n \"text\": \"Consistency − The database must remain in a consistent state after any transaction. No transaction should have any adverse effect on the data residing in the database. If the database was in a consistent state before the execution of a transaction, it must remain consistent after the execution of the transaction as well.\"\n },\n {\n \"code\": null,\n \"e\": 89367,\n \"s\": 89044,\n \"text\": \"Consistency − The database must remain in a consistent state after any transaction. No transaction should have any adverse effect on the data residing in the database. If the database was in a consistent state before the execution of a transaction, it must remain consistent after the execution of the transaction as well.\"\n },\n {\n \"code\": null,\n \"e\": 89770,\n \"s\": 89367,\n \"text\": \"Durability − The database should be durable enough to hold all its latest updates even if the system fails or restarts. If a transaction updates a chunk of data in a database and commits, then the database will hold the modified data. If a transaction commits but the system fails before the data could be written on to the disk, then that data will be updated once the system springs back into action.\"\n },\n {\n \"code\": null,\n \"e\": 90173,\n \"s\": 89770,\n \"text\": \"Durability − The database should be durable enough to hold all its latest updates even if the system fails or restarts. If a transaction updates a chunk of data in a database and commits, then the database will hold the modified data. If a transaction commits but the system fails before the data could be written on to the disk, then that data will be updated once the system springs back into action.\"\n },\n {\n \"code\": null,\n \"e\": 90496,\n \"s\": 90173,\n \"text\": \"Isolation − In a database system where more than one transaction are being executed simultaneously and in parallel, the property of isolation states that all the transactions will be carried out and executed as if it is the only transaction in the system. No transaction will affect the existence of any other transaction.\"\n },\n {\n \"code\": null,\n \"e\": 90819,\n \"s\": 90496,\n \"text\": \"Isolation − In a database system where more than one transaction are being executed simultaneously and in parallel, the property of isolation states that all the transactions will be carried out and executed as if it is the only transaction in the system. No transaction will affect the existence of any other transaction.\"\n },\n {\n \"code\": null,\n \"e\": 91031,\n \"s\": 90819,\n \"text\": \"When multiple transactions are being executed by the operating system in a multiprogramming environment, there are possibilities that instructions of one transactions are interleaved with some other transaction.\"\n },\n {\n \"code\": null,\n \"e\": 91212,\n \"s\": 91031,\n \"text\": \"Schedule − A chronological execution sequence of a transaction is called a schedule. A schedule can have many transactions in it, each comprising of a number of instructions/tasks.\"\n },\n {\n \"code\": null,\n \"e\": 91393,\n \"s\": 91212,\n \"text\": \"Schedule − A chronological execution sequence of a transaction is called a schedule. A schedule can have many transactions in it, each comprising of a number of instructions/tasks.\"\n },\n {\n \"code\": null,\n \"e\": 91749,\n \"s\": 91393,\n \"text\": \"Serial Schedule − It is a schedule in which transactions are aligned in such a way that one transaction is executed first. When the first transaction completes its cycle, then the next transaction is executed. Transactions are ordered one after the other. This type of schedule is called a serial schedule, as transactions are executed in a serial manner.\"\n },\n {\n \"code\": null,\n \"e\": 92105,\n \"s\": 91749,\n \"text\": \"Serial Schedule − It is a schedule in which transactions are aligned in such a way that one transaction is executed first. When the first transaction completes its cycle, then the next transaction is executed. Transactions are ordered one after the other. This type of schedule is called a serial schedule, as transactions are executed in a serial manner.\"\n },\n {\n \"code\": null,\n \"e\": 92627,\n \"s\": 92105,\n \"text\": \"In a multi-transaction environment, serial schedules are considered as a benchmark. The execution sequence of an instruction in a transaction cannot be changed, but two transactions can have their instructions executed in a random fashion. This execution does no harm if two transactions are mutually independent and working on different segments of data; but in case these two transactions are working on the same data, then the results may vary. This ever-varying result may bring the database to an inconsistent state.\"\n },\n {\n \"code\": null,\n \"e\": 92797,\n \"s\": 92627,\n \"text\": \"To resolve this problem, we allow parallel execution of a transaction schedule, if its transactions are either serializable or have some equivalence relation among them.\"\n },\n {\n \"code\": null,\n \"e\": 92853,\n \"s\": 92797,\n \"text\": \"An equivalence schedule can be of the following types −\"\n },\n {\n \"code\": null,\n \"e\": 93114,\n \"s\": 92853,\n \"text\": \"If two schedules produce the same result after execution, they are said to be result equivalent. They may yield the same result for some value and different results for another set of values. That's why this equivalence is not generally considered significant.\"\n },\n {\n \"code\": null,\n \"e\": 93241,\n \"s\": 93114,\n \"text\": \"Two schedules would be view equivalence if the transactions in both the schedules perform similar actions in a similar manner.\"\n },\n {\n \"code\": null,\n \"e\": 93255,\n \"s\": 93241,\n \"text\": \"For example −\"\n },\n {\n \"code\": null,\n \"e\": 93333,\n \"s\": 93255,\n \"text\": \"If T reads the initial data in S1, then it also reads the initial data in S2.\"\n },\n {\n \"code\": null,\n \"e\": 93411,\n \"s\": 93333,\n \"text\": \"If T reads the initial data in S1, then it also reads the initial data in S2.\"\n },\n {\n \"code\": null,\n \"e\": 93501,\n \"s\": 93411,\n \"text\": \"If T reads the value written by J in S1, then it also reads the value written by J in S2.\"\n },\n {\n \"code\": null,\n \"e\": 93591,\n \"s\": 93501,\n \"text\": \"If T reads the value written by J in S1, then it also reads the value written by J in S2.\"\n },\n {\n \"code\": null,\n \"e\": 93709,\n \"s\": 93591,\n \"text\": \"If T performs the final write on the data value in S1, then it also performs the final write on the data value in S2.\"\n },\n {\n \"code\": null,\n \"e\": 93827,\n \"s\": 93709,\n \"text\": \"If T performs the final write on the data value in S1, then it also performs the final write on the data value in S2.\"\n },\n {\n \"code\": null,\n \"e\": 93902,\n \"s\": 93827,\n \"text\": \"Two schedules would be conflicting if they have the following properties −\"\n },\n {\n \"code\": null,\n \"e\": 93940,\n \"s\": 93902,\n \"text\": \"Both belong to separate transactions.\"\n },\n {\n \"code\": null,\n \"e\": 93974,\n \"s\": 93940,\n \"text\": \"Both accesses the same data item.\"\n },\n {\n \"code\": null,\n \"e\": 94017,\n \"s\": 93974,\n \"text\": \"At least one of them is \\\"write\\\" operation.\"\n },\n {\n \"code\": null,\n \"e\": 94140,\n \"s\": 94017,\n \"text\": \"Two schedules having multiple transactions with conflicting operations are said to be conflict equivalent if and only if −\"\n },\n {\n \"code\": null,\n \"e\": 94197,\n \"s\": 94140,\n \"text\": \"Both the schedules contain the same set of Transactions.\"\n },\n {\n \"code\": null,\n \"e\": 94278,\n \"s\": 94197,\n \"text\": \"The order of conflicting pairs of operation is maintained in both the schedules.\"\n },\n {\n \"code\": null,\n \"e\": 94457,\n \"s\": 94278,\n \"text\": \"Note − View equivalent schedules are view serializable and conflict equivalent schedules are conflict serializable. All conflict serializable schedules are view serializable too.\"\n },\n {\n \"code\": null,\n \"e\": 94525,\n \"s\": 94457,\n \"text\": \"A transaction in a database can be in one of the following states −\"\n },\n {\n \"code\": null,\n \"e\": 94632,\n \"s\": 94525,\n \"text\": \"Active − In this state, the transaction is being executed. This is the initial state of every transaction.\"\n },\n {\n \"code\": null,\n \"e\": 94739,\n \"s\": 94632,\n \"text\": \"Active − In this state, the transaction is being executed. This is the initial state of every transaction.\"\n },\n {\n \"code\": null,\n \"e\": 94859,\n \"s\": 94739,\n \"text\": \"Partially Committed − When a transaction executes its final operation, it is said to be in a partially committed state.\"\n },\n {\n \"code\": null,\n \"e\": 94979,\n \"s\": 94859,\n \"text\": \"Partially Committed − When a transaction executes its final operation, it is said to be in a partially committed state.\"\n },\n {\n \"code\": null,\n \"e\": 95151,\n \"s\": 94979,\n \"text\": \"Failed − A transaction is said to be in a failed state if any of the checks made by the database recovery system fails. A failed transaction can no longer proceed further.\"\n },\n {\n \"code\": null,\n \"e\": 95323,\n \"s\": 95151,\n \"text\": \"Failed − A transaction is said to be in a failed state if any of the checks made by the database recovery system fails. A failed transaction can no longer proceed further.\"\n },\n {\n \"code\": null,\n \"e\": 95782,\n \"s\": 95323,\n \"text\": \"Aborted − If any of the checks fails and the transaction has reached a failed state, then the recovery manager rolls back all its write operations on the database to bring the database back to its original state where it was prior to the execution of the transaction. Transactions in this state are called aborted. The database recovery module can select one of the two operations after a transaction aborts −\\n\\nRe-start the transaction\\nKill the transaction\\n\\n\"\n },\n {\n \"code\": null,\n \"e\": 96192,\n \"s\": 95782,\n \"text\": \"Aborted − If any of the checks fails and the transaction has reached a failed state, then the recovery manager rolls back all its write operations on the database to bring the database back to its original state where it was prior to the execution of the transaction. Transactions in this state are called aborted. The database recovery module can select one of the two operations after a transaction aborts −\"\n },\n {\n \"code\": null,\n \"e\": 96217,\n \"s\": 96192,\n \"text\": \"Re-start the transaction\"\n },\n {\n \"code\": null,\n \"e\": 96238,\n \"s\": 96217,\n \"text\": \"Kill the transaction\"\n },\n {\n \"code\": null,\n \"e\": 96409,\n \"s\": 96238,\n \"text\": \"Committed − If a transaction executes all its operations successfully, it is said to be committed. All its effects are now permanently established on the database system.\"\n },\n {\n \"code\": null,\n \"e\": 96580,\n \"s\": 96409,\n \"text\": \"Committed − If a transaction executes all its operations successfully, it is said to be committed. All its effects are now permanently established on the database system.\"\n },\n {\n \"code\": null,\n \"e\": 96934,\n \"s\": 96580,\n \"text\": \"In a multiprogramming environment where multiple transactions can be executed simultaneously, it is highly important to control the concurrency of transactions. We have concurrency control protocols to ensure atomicity, isolation, and serializability of concurrent transactions. Concurrency control protocols can be broadly divided into two categories −\"\n },\n {\n \"code\": null,\n \"e\": 96955,\n \"s\": 96934,\n \"text\": \"Lock based protocols\"\n },\n {\n \"code\": null,\n \"e\": 96982,\n \"s\": 96955,\n \"text\": \"Time stamp based protocols\"\n },\n {\n \"code\": null,\n \"e\": 97171,\n \"s\": 96982,\n \"text\": \"Database systems equipped with lock-based protocols use a mechanism by which any transaction cannot read or write data until it acquires an appropriate lock on it. Locks are of two kinds −\"\n },\n {\n \"code\": null,\n \"e\": 97263,\n \"s\": 97171,\n \"text\": \"Binary Locks − A lock on a data item can be in two states; it is either locked or unlocked.\"\n },\n {\n \"code\": null,\n \"e\": 97355,\n \"s\": 97263,\n \"text\": \"Binary Locks − A lock on a data item can be in two states; it is either locked or unlocked.\"\n },\n {\n \"code\": null,\n \"e\": 97723,\n \"s\": 97355,\n \"text\": \"Shared/exclusive − This type of locking mechanism differentiates the locks based on their uses. If a lock is acquired on a data item to perform a write operation, it is an exclusive lock. Allowing more than one transaction to write on the same data item would lead the database into an inconsistent state. Read locks are shared because no data value is being changed.\"\n },\n {\n \"code\": null,\n \"e\": 98091,\n \"s\": 97723,\n \"text\": \"Shared/exclusive − This type of locking mechanism differentiates the locks based on their uses. If a lock is acquired on a data item to perform a write operation, it is an exclusive lock. Allowing more than one transaction to write on the same data item would lead the database into an inconsistent state. Read locks are shared because no data value is being changed.\"\n },\n {\n \"code\": null,\n \"e\": 98142,\n \"s\": 98091,\n \"text\": \"There are four types of lock protocols available −\"\n },\n {\n \"code\": null,\n \"e\": 98345,\n \"s\": 98142,\n \"text\": \"Simplistic lock-based protocols allow transactions to obtain a lock on every object before a 'write' operation is performed. Transactions may unlock the data item after completing the ‘write’ operation.\"\n },\n {\n \"code\": null,\n \"e\": 98779,\n \"s\": 98345,\n \"text\": \"Pre-claiming protocols evaluate their operations and create a list of data items on which they need locks. Before initiating an execution, the transaction requests the system for all the locks it needs beforehand. If all the locks are granted, the transaction executes and releases all the locks when all its operations are over. If all the locks are not granted, the transaction rolls back and waits until all the locks are granted.\"\n },\n {\n \"code\": null,\n \"e\": 99207,\n \"s\": 98779,\n \"text\": \"This locking protocol divides the execution phase of a transaction into three parts. In the first part, when the transaction starts executing, it seeks permission for the locks it requires. The second part is where the transaction acquires all the locks. As soon as the transaction releases its first lock, the third phase starts. In this phase, the transaction cannot demand any new locks; it only releases the acquired locks.\"\n },\n {\n \"code\": null,\n \"e\": 99411,\n \"s\": 99207,\n \"text\": \"Two-phase locking has two phases, one is growing, where all the locks are being acquired by the transaction; and the second phase is shrinking, where the locks held by the transaction are being released.\"\n },\n {\n \"code\": null,\n \"e\": 99543,\n \"s\": 99411,\n \"text\": \"To claim an exclusive (write) lock, a transaction must first acquire a shared (read) lock and then upgrade it to an exclusive lock.\"\n },\n {\n \"code\": null,\n \"e\": 99853,\n \"s\": 99543,\n \"text\": \"The first phase of Strict-2PL is same as 2PL. After acquiring all the locks in the first phase, the transaction continues to execute normally. But in contrast to 2PL, Strict-2PL does not release a lock after using it. Strict-2PL holds all the locks until the commit point and releases all the locks at a time.\"\n },\n {\n \"code\": null,\n \"e\": 99907,\n \"s\": 99853,\n \"text\": \"Strict-2PL does not have cascading abort as 2PL does.\"\n },\n {\n \"code\": null,\n \"e\": 100057,\n \"s\": 99907,\n \"text\": \"The most commonly used concurrency protocol is the timestamp based protocol. This protocol uses either system time or logical counter as a timestamp.\"\n },\n {\n \"code\": null,\n \"e\": 100255,\n \"s\": 100057,\n \"text\": \"Lock-based protocols manage the order between the conflicting pairs among transactions at the time of execution, whereas timestamp-based protocols start working as soon as a transaction is created.\"\n },\n {\n \"code\": null,\n \"e\": 100609,\n \"s\": 100255,\n \"text\": \"Every transaction has a timestamp associated with it, and the ordering is determined by the age of the transaction. A transaction created at 0002 clock time would be older than all other transactions that come after it. For example, any transaction 'y' entering the system at 0004 is two seconds younger and the priority would be given to the older one.\"\n },\n {\n \"code\": null,\n \"e\": 100783,\n \"s\": 100609,\n \"text\": \"In addition, every data item is given the latest read and write-timestamp. This lets the system know when the last ‘read and write’ operation was performed on the data item.\"\n },\n {\n \"code\": null,\n \"e\": 101065,\n \"s\": 100783,\n \"text\": \"The timestamp-ordering protocol ensures serializability among transactions in their conflicting read and write operations. This is the responsibility of the protocol system that the conflicting pair of tasks should be executed according to the timestamp values of the transactions.\"\n },\n {\n \"code\": null,\n \"e\": 101119,\n \"s\": 101065,\n \"text\": \"The timestamp of transaction Ti is denoted as TS(Ti).\"\n },\n {\n \"code\": null,\n \"e\": 101180,\n \"s\": 101119,\n \"text\": \"Read time-stamp of data-item X is denoted by R-timestamp(X).\"\n },\n {\n \"code\": null,\n \"e\": 101242,\n \"s\": 101180,\n \"text\": \"Write time-stamp of data-item X is denoted by W-timestamp(X).\"\n },\n {\n \"code\": null,\n \"e\": 101289,\n \"s\": 101242,\n \"text\": \"Timestamp ordering protocol works as follows −\"\n },\n {\n \"code\": null,\n \"e\": 101338,\n \"s\": 101289,\n \"text\": \"If a transaction Ti issues a read(X) operation −\"\n },\n {\n \"code\": null,\n \"e\": 101387,\n \"s\": 101338,\n \"text\": \"If a transaction Ti issues a read(X) operation −\"\n },\n {\n \"code\": null,\n \"e\": 101437,\n \"s\": 101387,\n \"text\": \"If TS(Ti) < W-timestamp(X)\\n\\nOperation rejected.\\n\\n\"\n },\n {\n \"code\": null,\n \"e\": 101457,\n \"s\": 101437,\n \"text\": \"Operation rejected.\"\n },\n {\n \"code\": null,\n \"e\": 101508,\n \"s\": 101457,\n \"text\": \"If TS(Ti) >= W-timestamp(X)\\n\\nOperation executed.\\n\\n\"\n },\n {\n \"code\": null,\n \"e\": 101528,\n \"s\": 101508,\n \"text\": \"Operation executed.\"\n },\n {\n \"code\": null,\n \"e\": 101562,\n \"s\": 101528,\n \"text\": \"All data-item timestamps updated.\"\n },\n {\n \"code\": null,\n \"e\": 101612,\n \"s\": 101562,\n \"text\": \"If a transaction Ti issues a write(X) operation −\"\n },\n {\n \"code\": null,\n \"e\": 101662,\n \"s\": 101612,\n \"text\": \"If a transaction Ti issues a write(X) operation −\"\n },\n {\n \"code\": null,\n \"e\": 101689,\n \"s\": 101662,\n \"text\": \"If TS(Ti) < R-timestamp(X)\"\n },\n {\n \"code\": null,\n \"e\": 101709,\n \"s\": 101689,\n \"text\": \"Operation rejected.\"\n },\n {\n \"code\": null,\n \"e\": 101736,\n \"s\": 101709,\n \"text\": \"If TS(Ti) < W-timestamp(X)\"\n },\n {\n \"code\": null,\n \"e\": 101775,\n \"s\": 101736,\n \"text\": \"Operation rejected and Ti rolled back.\"\n },\n {\n \"code\": null,\n \"e\": 101806,\n \"s\": 101775,\n \"text\": \"Otherwise, operation executed.\"\n },\n {\n \"code\": null,\n \"e\": 101905,\n \"s\": 101806,\n \"text\": \"This rule states if TS(Ti) < W-timestamp(X), then the operation is rejected and Ti is rolled back.\"\n },\n {\n \"code\": null,\n \"e\": 101987,\n \"s\": 101905,\n \"text\": \"Time-stamp ordering rules can be modified to make the schedule view serializable.\"\n },\n {\n \"code\": null,\n \"e\": 102062,\n \"s\": 101987,\n \"text\": \"Instead of making Ti rolled back, the 'write' operation itself is ignored.\"\n },\n {\n \"code\": null,\n \"e\": 102252,\n \"s\": 102062,\n \"text\": \"In a multi-process system, deadlock is an unwanted situation that arises in a shared resource environment, where a process indefinitely waits for a resource that is held by another process.\"\n },\n {\n \"code\": null,\n \"e\": 102667,\n \"s\": 102252,\n \"text\": \"For example, assume a set of transactions {T0, T1, T2, ...,Tn}. T0 needs a resource X to complete its task. Resource X is held by T1, and T1 is waiting for a resource Y, which is held by T2. T2 is waiting for resource Z, which is held by T0. Thus, all the processes wait for each other to release resources. In this situation, none of the processes can finish their task. This situation is known as a deadlock.\"\n },\n {\n \"code\": null,\n \"e\": 102827,\n \"s\": 102667,\n \"text\": \"Deadlocks are not healthy for a system. In case a system is stuck in a deadlock, the transactions involved in the deadlock are either rolled back or restarted.\"\n },\n {\n \"code\": null,\n \"e\": 103161,\n \"s\": 102827,\n \"text\": \"To prevent any deadlock situation in the system, the DBMS aggressively inspects all the operations, where transactions are about to execute. The DBMS inspects the operations and analyzes if they can create a deadlock situation. If it finds that a deadlock situation might occur, then that transaction is never allowed to be executed.\"\n },\n {\n \"code\": null,\n \"e\": 103300,\n \"s\": 103161,\n \"text\": \"There are deadlock prevention schemes that use timestamp ordering mechanism of transactions in order to predetermine a deadlock situation.\"\n },\n {\n \"code\": null,\n \"e\": 103490,\n \"s\": 103300,\n \"text\": \"In this scheme, if a transaction requests to lock a resource (data item), which is already held with a conflicting lock by another transaction, then one of the two possibilities may occur −\"\n },\n {\n \"code\": null,\n \"e\": 103644,\n \"s\": 103490,\n \"text\": \"If TS(Ti) < TS(Tj) − that is Ti, which is requesting a conflicting lock, is older than Tj − then Ti is allowed to wait until the data-item is available.\"\n },\n {\n \"code\": null,\n \"e\": 103798,\n \"s\": 103644,\n \"text\": \"If TS(Ti) < TS(Tj) − that is Ti, which is requesting a conflicting lock, is older than Tj − then Ti is allowed to wait until the data-item is available.\"\n },\n {\n \"code\": null,\n \"e\": 103937,\n \"s\": 103798,\n \"text\": \"If TS(Ti) > TS(tj) − that is Ti is younger than Tj − then Ti dies. Ti is restarted later with a random delay but with the same timestamp.\"\n },\n {\n \"code\": null,\n \"e\": 104076,\n \"s\": 103937,\n \"text\": \"If TS(Ti) > TS(tj) − that is Ti is younger than Tj − then Ti dies. Ti is restarted later with a random delay but with the same timestamp.\"\n },\n {\n \"code\": null,\n \"e\": 104152,\n \"s\": 104076,\n \"text\": \"This scheme allows the older transaction to wait but kills the younger one.\"\n },\n {\n \"code\": null,\n \"e\": 104340,\n \"s\": 104152,\n \"text\": \"In this scheme, if a transaction requests to lock a resource (data item), which is already held with conflicting lock by some another transaction, one of the two possibilities may occur −\"\n },\n {\n \"code\": null,\n \"e\": 104491,\n \"s\": 104340,\n \"text\": \"If TS(Ti) < TS(Tj), then Ti forces Tj to be rolled back − that is Ti wounds Tj. Tj is restarted later with a random delay but with the same timestamp.\"\n },\n {\n \"code\": null,\n \"e\": 104642,\n \"s\": 104491,\n \"text\": \"If TS(Ti) < TS(Tj), then Ti forces Tj to be rolled back − that is Ti wounds Tj. Tj is restarted later with a random delay but with the same timestamp.\"\n },\n {\n \"code\": null,\n \"e\": 104721,\n \"s\": 104642,\n \"text\": \"If TS(Ti) > TS(Tj), then Ti is forced to wait until the resource is available.\"\n },\n {\n \"code\": null,\n \"e\": 104800,\n \"s\": 104721,\n \"text\": \"If TS(Ti) > TS(Tj), then Ti is forced to wait until the resource is available.\"\n },\n {\n \"code\": null,\n \"e\": 104999,\n \"s\": 104800,\n \"text\": \"This scheme, allows the younger transaction to wait; but when an older transaction requests an item held by a younger one, the older transaction forces the younger one to abort and release the item.\"\n },\n {\n \"code\": null,\n \"e\": 105086,\n \"s\": 104999,\n \"text\": \"In both the cases, the transaction that enters the system at a later stage is aborted.\"\n },\n {\n \"code\": null,\n \"e\": 105466,\n \"s\": 105086,\n \"text\": \"Aborting a transaction is not always a practical approach. Instead, deadlock avoidance mechanisms can be used to detect any deadlock situation in advance. Methods like \\\"wait-for graph\\\" are available but they are suitable for only those systems where transactions are lightweight having fewer instances of resource. In a bulky system, deadlock prevention techniques may work well.\"\n },\n {\n \"code\": null,\n \"e\": 105843,\n \"s\": 105466,\n \"text\": \"This is a simple method available to track if any deadlock situation may arise. For each transaction entering into the system, a node is created. When a transaction Ti requests for a lock on an item, say X, which is held by some other transaction Tj, a directed edge is created from Ti to Tj. If Tj releases item X, the edge between them is dropped and Ti locks the data item.\"\n },\n {\n \"code\": null,\n \"e\": 106011,\n \"s\": 105843,\n \"text\": \"The system maintains this wait-for graph for every transaction waiting for some data items held by others. The system keeps checking if there's any cycle in the graph.\"\n },\n {\n \"code\": null,\n \"e\": 106066,\n \"s\": 106011,\n \"text\": \"Here, we can use any of the two following approaches −\"\n },\n {\n \"code\": null,\n \"e\": 106294,\n \"s\": 106066,\n \"text\": \"First, do not allow any request for an item, which is already locked by another transaction. This is not always feasible and may cause starvation, where a transaction indefinitely waits for a data item and can never acquire it.\"\n },\n {\n \"code\": null,\n \"e\": 106522,\n \"s\": 106294,\n \"text\": \"First, do not allow any request for an item, which is already locked by another transaction. This is not always feasible and may cause starvation, where a transaction indefinitely waits for a data item and can never acquire it.\"\n },\n {\n \"code\": null,\n \"e\": 106865,\n \"s\": 106522,\n \"text\": \"The second option is to roll back one of the transactions. It is not always feasible to roll back the younger transaction, as it may be important than the older one. With the help of some relative algorithm, a transaction is chosen, which is to be aborted. This transaction is known as the victim and the process is known as victim selection.\"\n },\n {\n \"code\": null,\n \"e\": 107208,\n \"s\": 106865,\n \"text\": \"The second option is to roll back one of the transactions. It is not always feasible to roll back the younger transaction, as it may be important than the older one. With the help of some relative algorithm, a transaction is chosen, which is to be aborted. This transaction is known as the victim and the process is known as victim selection.\"\n },\n {\n \"code\": null,\n \"e\": 107607,\n \"s\": 107208,\n \"text\": \"A volatile storage like RAM stores all the active logs, disk buffers, and related data. In addition, it stores all the transactions that are being currently executed. What happens if such a volatile storage crashes abruptly? It would obviously take away all the logs and active copies of the database. It makes recovery almost impossible, as everything that is required to recover the data is lost.\"\n },\n {\n \"code\": null,\n \"e\": 107681,\n \"s\": 107607,\n \"text\": \"Following techniques may be adopted in case of loss of volatile storage −\"\n },\n {\n \"code\": null,\n \"e\": 107781,\n \"s\": 107681,\n \"text\": \"We can have checkpoints at multiple stages so as to save the contents of the database periodically.\"\n },\n {\n \"code\": null,\n \"e\": 107881,\n \"s\": 107781,\n \"text\": \"We can have checkpoints at multiple stages so as to save the contents of the database periodically.\"\n },\n {\n \"code\": null,\n \"e\": 108052,\n \"s\": 107881,\n \"text\": \"A state of active database in the volatile memory can be periodically dumped onto a stable storage, which may also contain logs and active transactions and buffer blocks.\"\n },\n {\n \"code\": null,\n \"e\": 108223,\n \"s\": 108052,\n \"text\": \"A state of active database in the volatile memory can be periodically dumped onto a stable storage, which may also contain logs and active transactions and buffer blocks.\"\n },\n {\n \"code\": null,\n \"e\": 108345,\n \"s\": 108223,\n \"text\": \" can be marked on a log file, whenever the database contents are dumped from a non-volatile memory to a stable one.\"\n },\n {\n \"code\": null,\n \"e\": 108467,\n \"s\": 108345,\n \"text\": \" can be marked on a log file, whenever the database contents are dumped from a non-volatile memory to a stable one.\"\n },\n {\n \"code\": null,\n \"e\": 108540,\n \"s\": 108467,\n \"text\": \"When the system recovers from a failure, it can restore the latest dump.\"\n },\n {\n \"code\": null,\n \"e\": 108613,\n \"s\": 108540,\n \"text\": \"When the system recovers from a failure, it can restore the latest dump.\"\n },\n {\n \"code\": null,\n \"e\": 108674,\n \"s\": 108613,\n \"text\": \"It can maintain a redo-list and an undo-list as checkpoints.\"\n },\n {\n \"code\": null,\n \"e\": 108735,\n \"s\": 108674,\n \"text\": \"It can maintain a redo-list and an undo-list as checkpoints.\"\n },\n {\n \"code\": null,\n \"e\": 108859,\n \"s\": 108735,\n \"text\": \"It can recover the system by consulting undo-redo lists to restore the state of all transactions up to the last checkpoint.\"\n },\n {\n \"code\": null,\n \"e\": 108983,\n \"s\": 108859,\n \"text\": \"It can recover the system by consulting undo-redo lists to restore the state of all transactions up to the last checkpoint.\"\n },\n {\n \"code\": null,\n \"e\": 109230,\n \"s\": 108983,\n \"text\": \"A catastrophic failure is one where a stable, secondary storage device gets corrupt. With the storage device, all the valuable data that is stored inside is lost. We have two different strategies to recover data from such a catastrophic failure −\"\n },\n {\n \"code\": null,\n \"e\": 109373,\n \"s\": 109230,\n \"text\": \"Remote backup &minu; Here a backup copy of the database is stored at a remote location from where it can be restored in case of a catastrophe.\"\n },\n {\n \"code\": null,\n \"e\": 109516,\n \"s\": 109373,\n \"text\": \"Remote backup &minu; Here a backup copy of the database is stored at a remote location from where it can be restored in case of a catastrophe.\"\n },\n {\n \"code\": null,\n \"e\": 109715,\n \"s\": 109516,\n \"text\": \"Alternatively, database backups can be taken on magnetic tapes and stored at a safer place. This backup can later be transferred onto a freshly installed database to bring it to the point of backup.\"\n },\n {\n \"code\": null,\n \"e\": 109914,\n \"s\": 109715,\n \"text\": \"Alternatively, database backups can be taken on magnetic tapes and stored at a safer place. This backup can later be transferred onto a freshly installed database to bring it to the point of backup.\"\n },\n {\n \"code\": null,\n \"e\": 110299,\n \"s\": 109914,\n \"text\": \"Grown-up databases are too bulky to be frequently backed up. In such cases, we have techniques where we can restore a database just by looking at its logs. So, all that we need to do here is to take a backup of all the logs at frequent intervals of time. The database can be backed up once a week, and the logs being very small can be backed up every day or as frequently as possible.\"\n },\n {\n \"code\": null,\n \"e\": 110520,\n \"s\": 110299,\n \"text\": \"Remote backup provides a sense of security in case the primary location where the database is located gets destroyed. Remote backup can be offline or real-time or online. In case it is offline, it is maintained manually.\"\n },\n {\n \"code\": null,\n \"e\": 110850,\n \"s\": 110520,\n \"text\": \"Online backup systems are more real-time and lifesavers for database administrators and investors. An online backup system is a mechanism where every bit of the real-time data is backed up simultaneously at two distant places. One of them is directly connected to the system and the other one is kept at a remote place as backup.\"\n },\n {\n \"code\": null,\n \"e\": 111060,\n \"s\": 110850,\n \"text\": \"As soon as the primary database storage fails, the backup system senses the failure and switches the user system to the remote storage. Sometimes this is so instant that the users can’t even realize a failure.\"\n },\n {\n \"code\": null,\n \"e\": 111421,\n \"s\": 111060,\n \"text\": \"DBMS is a highly complex system with hundreds of transactions being executed every second. The durability and robustness of a DBMS depends on its complex architecture and its underlying hardware and system software. If it fails or crashes amid transactions, it is expected that the system would follow some sort of algorithm or techniques to recover lost data.\"\n },\n {\n \"code\": null,\n \"e\": 111522,\n \"s\": 111421,\n \"text\": \"To see where the problem has occurred, we generalize a failure into various categories, as follows −\"\n },\n {\n \"code\": null,\n \"e\": 111725,\n \"s\": 111522,\n \"text\": \"A transaction has to abort when it fails to execute or when it reaches a point from where it can’t go any further. This is called transaction failure where only a few transactions or processes are hurt.\"\n },\n {\n \"code\": null,\n \"e\": 111770,\n \"s\": 111725,\n \"text\": \"Reasons for a transaction failure could be −\"\n },\n {\n \"code\": null,\n \"e\": 111887,\n \"s\": 111770,\n \"text\": \"Logical errors − Where a transaction cannot complete because it has some code error or any internal error condition.\"\n },\n {\n \"code\": null,\n \"e\": 112004,\n \"s\": 111887,\n \"text\": \"Logical errors − Where a transaction cannot complete because it has some code error or any internal error condition.\"\n },\n {\n \"code\": null,\n \"e\": 112284,\n \"s\": 112004,\n \"text\": \"System errors − Where the database system itself terminates an active transaction because the DBMS is not able to execute it, or it has to stop because of some system condition. For example, in case of deadlock or resource unavailability, the system aborts an active transaction.\"\n },\n {\n \"code\": null,\n \"e\": 112564,\n \"s\": 112284,\n \"text\": \"System errors − Where the database system itself terminates an active transaction because the DBMS is not able to execute it, or it has to stop because of some system condition. For example, in case of deadlock or resource unavailability, the system aborts an active transaction.\"\n },\n {\n \"code\": null,\n \"e\": 112793,\n \"s\": 112564,\n \"text\": \"There are problems − external to the system − that may cause the system to stop abruptly and cause the system to crash. For example, interruptions in power supply may cause the failure of underlying hardware or software failure.\"\n },\n {\n \"code\": null,\n \"e\": 112839,\n \"s\": 112793,\n \"text\": \"Examples may include operating system errors.\"\n },\n {\n \"code\": null,\n \"e\": 112968,\n \"s\": 112839,\n \"text\": \"In early days of technology evolution, it was a common problem where hard-disk drives or storage drives used to fail frequently.\"\n },\n {\n \"code\": null,\n \"e\": 113128,\n \"s\": 112968,\n \"text\": \"Disk failures include formation of bad sectors, unreachability to the disk, disk head crash or any other failure, which destroys all or a part of disk storage.\"\n },\n {\n \"code\": null,\n \"e\": 113243,\n \"s\": 113128,\n \"text\": \"We have already described the storage system. In brief, the storage structure can be divided into two categories −\"\n },\n {\n \"code\": null,\n \"e\": 113585,\n \"s\": 113243,\n \"text\": \"Volatile storage − As the name suggests, a volatile storage cannot survive system crashes. Volatile storage devices are placed very close to the CPU; normally they are embedded onto the chipset itself. For example, main memory and cache memory are examples of volatile storage. They are fast but can store only a small amount of information.\"\n },\n {\n \"code\": null,\n \"e\": 113927,\n \"s\": 113585,\n \"text\": \"Volatile storage − As the name suggests, a volatile storage cannot survive system crashes. Volatile storage devices are placed very close to the CPU; normally they are embedded onto the chipset itself. For example, main memory and cache memory are examples of volatile storage. They are fast but can store only a small amount of information.\"\n },\n {\n \"code\": null,\n \"e\": 114175,\n \"s\": 113927,\n \"text\": \"Non-volatile storage − These memories are made to survive system crashes. They are huge in data storage capacity, but slower in accessibility. Examples may include hard-disks, magnetic tapes, flash memory, and non-volatile (battery backed up) RAM.\"\n },\n {\n \"code\": null,\n \"e\": 114423,\n \"s\": 114175,\n \"text\": \"Non-volatile storage − These memories are made to survive system crashes. They are huge in data storage capacity, but slower in accessibility. Examples may include hard-disks, magnetic tapes, flash memory, and non-volatile (battery backed up) RAM.\"\n },\n {\n \"code\": null,\n \"e\": 114783,\n \"s\": 114423,\n \"text\": \"When a system crashes, it may have several transactions being executed and various files opened for them to modify the data items. Transactions are made of various operations, which are atomic in nature. But according to ACID properties of DBMS, atomicity of transactions as a whole must be maintained, that is, either all the operations are executed or none.\"\n },\n {\n \"code\": null,\n \"e\": 114853,\n \"s\": 114783,\n \"text\": \"When a DBMS recovers from a crash, it should maintain the following −\"\n },\n {\n \"code\": null,\n \"e\": 114932,\n \"s\": 114853,\n \"text\": \"It should check the states of all the transactions, which were being executed.\"\n },\n {\n \"code\": null,\n \"e\": 115011,\n \"s\": 114932,\n \"text\": \"It should check the states of all the transactions, which were being executed.\"\n },\n {\n \"code\": null,\n \"e\": 115133,\n \"s\": 115011,\n \"text\": \"A transaction may be in the middle of some operation; the DBMS must ensure the atomicity of the transaction in this case.\"\n },\n {\n \"code\": null,\n \"e\": 115255,\n \"s\": 115133,\n \"text\": \"A transaction may be in the middle of some operation; the DBMS must ensure the atomicity of the transaction in this case.\"\n },\n {\n \"code\": null,\n \"e\": 115347,\n \"s\": 115255,\n \"text\": \"It should check whether the transaction can be completed now or it needs to be rolled back.\"\n },\n {\n \"code\": null,\n \"e\": 115439,\n \"s\": 115347,\n \"text\": \"It should check whether the transaction can be completed now or it needs to be rolled back.\"\n },\n {\n \"code\": null,\n \"e\": 115516,\n \"s\": 115439,\n \"text\": \"No transactions would be allowed to leave the DBMS in an inconsistent state.\"\n },\n {\n \"code\": null,\n \"e\": 115593,\n \"s\": 115516,\n \"text\": \"No transactions would be allowed to leave the DBMS in an inconsistent state.\"\n },\n {\n \"code\": null,\n \"e\": 115720,\n \"s\": 115593,\n \"text\": \"There are two types of techniques, which can help a DBMS in recovering as well as maintaining the atomicity of a transaction −\"\n },\n {\n \"code\": null,\n \"e\": 115844,\n \"s\": 115720,\n \"text\": \"Maintaining the logs of each transaction, and writing them onto some stable storage before actually modifying the database.\"\n },\n {\n \"code\": null,\n \"e\": 115968,\n \"s\": 115844,\n \"text\": \"Maintaining the logs of each transaction, and writing them onto some stable storage before actually modifying the database.\"\n },\n {\n \"code\": null,\n \"e\": 116087,\n \"s\": 115968,\n \"text\": \"Maintaining shadow paging, where the changes are done on a volatile memory, and later, the actual database is updated.\"\n },\n {\n \"code\": null,\n \"e\": 116206,\n \"s\": 116087,\n \"text\": \"Maintaining shadow paging, where the changes are done on a volatile memory, and later, the actual database is updated.\"\n },\n {\n \"code\": null,\n \"e\": 116435,\n \"s\": 116206,\n \"text\": \"Log is a sequence of records, which maintains the records of actions performed by a transaction. It is important that the logs are written prior to the actual modification and stored on a stable storage media, which is failsafe.\"\n },\n {\n \"code\": null,\n \"e\": 116473,\n \"s\": 116435,\n \"text\": \"Log-based recovery works as follows −\"\n },\n {\n \"code\": null,\n \"e\": 116521,\n \"s\": 116473,\n \"text\": \"The log file is kept on a stable storage media.\"\n },\n {\n \"code\": null,\n \"e\": 116569,\n \"s\": 116521,\n \"text\": \"The log file is kept on a stable storage media.\"\n },\n {\n \"code\": null,\n \"e\": 116654,\n \"s\": 116569,\n \"text\": \"When a transaction enters the system and starts execution, it writes a log about it.\"\n },\n {\n \"code\": null,\n \"e\": 116739,\n \"s\": 116654,\n \"text\": \"When a transaction enters the system and starts execution, it writes a log about it.\"\n },\n {\n \"code\": null,\n \"e\": 116752,\n \"s\": 116739,\n \"text\": \"\\n\"\n },\n {\n \"code\": null,\n \"e\": 116820,\n \"s\": 116752,\n \"text\": \"When the transaction modifies an item X, it write logs as follows −\"\n },\n {\n \"code\": null,\n \"e\": 116888,\n \"s\": 116820,\n \"text\": \"When the transaction modifies an item X, it write logs as follows −\"\n },\n {\n \"code\": null,\n \"e\": 116905,\n \"s\": 116888,\n \"text\": \"\\n\"\n },\n {\n \"code\": null,\n \"e\": 116960,\n \"s\": 116905,\n \"text\": \"It reads Tn has changed the value of X, from V1 to V2.\"\n },\n {\n \"code\": null,\n \"e\": 117001,\n \"s\": 116960,\n \"text\": \"When the transaction finishes, it logs −\"\n },\n {\n \"code\": null,\n \"e\": 117015,\n \"s\": 117001,\n \"text\": \"\\n\"\n },\n {\n \"code\": null,\n \"e\": 117067,\n \"s\": 117015,\n \"text\": \"The database can be modified using two approaches −\"\n },\n {\n \"code\": null,\n \"e\": 117202,\n \"s\": 117067,\n \"text\": \"Deferred database modification − All logs are written on to the stable storage and the database is updated when a transaction commits.\"\n },\n {\n \"code\": null,\n \"e\": 117337,\n \"s\": 117202,\n \"text\": \"Deferred database modification − All logs are written on to the stable storage and the database is updated when a transaction commits.\"\n },\n {\n \"code\": null,\n \"e\": 117490,\n \"s\": 117337,\n \"text\": \"Immediate database modification − Each log follows an actual database modification. That is, the database is modified immediately after every operation.\"\n },\n {\n \"code\": null,\n \"e\": 117643,\n \"s\": 117490,\n \"text\": \"Immediate database modification − Each log follows an actual database modification. That is, the database is modified immediately after every operation.\"\n },\n {\n \"code\": null,\n \"e\": 117927,\n \"s\": 117643,\n \"text\": \"When more than one transaction are being executed in parallel, the logs are interleaved. At the time of recovery, it would become hard for the recovery system to backtrack all logs, and then start recovering. To ease this situation, most modern DBMS use the concept of 'checkpoints'.\"\n },\n {\n \"code\": null,\n \"e\": 118360,\n \"s\": 117927,\n \"text\": \"Keeping and maintaining logs in real time and in real environment may fill out all the memory space available in the system. As time passes, the log file may grow too big to be handled at all. Checkpoint is a mechanism where all the previous logs are removed from the system and stored permanently in a storage disk. Checkpoint declares a point before which the DBMS was in consistent state, and all the transactions were committed.\"\n },\n {\n \"code\": null,\n \"e\": 118462,\n \"s\": 118360,\n \"text\": \"When a system with concurrent transactions crashes and recovers, it behaves in the following manner −\"\n },\n {\n \"code\": null,\n \"e\": 118544,\n \"s\": 118462,\n \"text\": \"The recovery system reads the logs backwards from the end to the last checkpoint.\"\n },\n {\n \"code\": null,\n \"e\": 118626,\n \"s\": 118544,\n \"text\": \"The recovery system reads the logs backwards from the end to the last checkpoint.\"\n },\n {\n \"code\": null,\n \"e\": 118680,\n \"s\": 118626,\n \"text\": \"It maintains two lists, an undo-list and a redo-list.\"\n },\n {\n \"code\": null,\n \"e\": 118734,\n \"s\": 118680,\n \"text\": \"It maintains two lists, an undo-list and a redo-list.\"\n },\n {\n \"code\": null,\n \"e\": 118866,\n \"s\": 118734,\n \"text\": \"If the recovery system sees a log with and or just , it puts the transaction in the redo-list.\"\n },\n {\n \"code\": null,\n \"e\": 118998,\n \"s\": 118866,\n \"text\": \"If the recovery system sees a log with and or just , it puts the transaction in the redo-list.\"\n },\n {\n \"code\": null,\n \"e\": 119121,\n \"s\": 118998,\n \"text\": \"If the recovery system sees a log with but no commit or abort log found, it puts the transaction in undo-list.\"\n },\n {\n \"code\": null,\n \"e\": 119244,\n \"s\": 119121,\n \"text\": \"If the recovery system sees a log with but no commit or abort log found, it puts the transaction in undo-list.\"\n },\n {\n \"code\": null,\n \"e\": 119442,\n \"s\": 119244,\n \"text\": \"All the transactions in the undo-list are then undone and their logs are removed. All the transactions in the redo-list and their previous logs are removed and then redone before saving their logs.\"\n },\n {\n \"code\": null,\n \"e\": 119479,\n \"s\": 119442,\n \"text\": \"\\n 178 Lectures \\n 14.5 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 119498,\n \"s\": 119479,\n \"text\": \" Arnab Chakraborty\"\n },\n {\n \"code\": null,\n \"e\": 119533,\n \"s\": 119498,\n \"text\": \"\\n 194 Lectures \\n 16 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 119552,\n \"s\": 119533,\n \"text\": \" Arnab Chakraborty\"\n },\n {\n \"code\": null,\n \"e\": 119559,\n \"s\": 119552,\n \"text\": \" Print\"\n },\n {\n \"code\": null,\n \"e\": 119570,\n \"s\": 119559,\n \"text\": \" Add Notes\"\n }\n]"}}},{"rowIdx":134,"cells":{"title":{"kind":"string","value":"Node.js querystring.parse() Method"},"text":{"kind":"string","value":"08 Oct, 2021\nThe querystring.parse() method is used to parse a URL query string into an object that contains the key and pair values of the query URL. The object returned does not inherit prototypes from the JavaScript object, therefore usual Object methods will not work. During parsing, the UTF-8 encoding format is assumed unless there is an alternative character encoding format. To decode alternative character encoding, the decodeURIComponent option has to be specified. \nSyntax: \nquerystring.parse( str[, sep[, eq[, options]]]) )\n\nParameters: This function accepts four parameters as mentioned above and described below: \nstr: It is a String that specifies the URL query that has to be parsed.\nsep: It is a String that specifies the substring used to delimit the key and value pairs in the specified query string. The default value is “&”.\neq: It is a String that specifies the substring used to delimit keys and values in the specified query string. The default value is “=”.\noptions: It is an object which can be used to modify the behavior of the method. It has the following parameters: decodeURIComponent: It is a function that would be used to decode percent-encoded characters in the query string. The default value is querystring.unescape().maxKeys: It is a number which specifies the maximum number of keys that should be parsed from the query string. A value of “0” would remove all the counting limits. The default value is “1000”.\ndecodeURIComponent: It is a function that would be used to decode percent-encoded characters in the query string. The default value is querystring.unescape().\nmaxKeys: It is a number which specifies the maximum number of keys that should be parsed from the query string. A value of “0” would remove all the counting limits. The default value is “1000”.\nReturn Value: It returns an object that has the key and value pairs parsed from the query string.\nBelow examples illustrate the querystring.parse() method in Node.js:\nExample 1:\nNode.js\n// Import the querystring moduleconst querystring = require(\"querystring\"); // Specify the URL query string// to be parsedlet urlQuery = \"username=user1&units=kgs&units=pounds&permission=false\"; // Use the parse() method on the stringlet parsedObject = querystring.parse(urlQuery); console.log(\"Parsed Query:\", parsedObject); // Use the parse() method on the string// with sep as `&&` and eq as `-`urlQuery = \"username-user1&&units-kgs&&units-pounds&&permission-false\";parsedObject = querystring.parse(urlQuery, \"&&\", \"-\"); console.log(\"\\nParsed Query:\", parsedObject);\nOutput:\nParsed Query: [Object: null prototype] {\n username: 'user1',\n units: [ 'kgs', 'pounds' ],\n permission: 'false'\n}\n\nParsed Query: [Object: null prototype] {\n username: 'user1',\n units: [ 'kgs', 'pounds' ],\n permission: 'false'\n}\n\nExample 2:\nNode.js\n// Import the querystring moduleconst querystring = require(\"querystring\"); // Specify the URL query string// to be parsedlet urlQuery = \"user=admin&articles=1&articles=2&articles=3&access=true\"; // Use the parse() method on the string// with default valueslet parsedObject = querystring.parse(urlQuery, \"&\", \"=\"); console.log(\"Parsed Query:\", parsedObject); // Use the parse() method on the string// with maxKeys set to 1parsedObject = querystring.parse(urlQuery, \"&\", \"=\", { maxKeys: 1 }); console.log(\"\\nParsed Query:\", parsedObject); // Use the parse() method on the string// with maxKeys set to 2parsedObject = querystring.parse(urlQuery, \"&\", \"=\", { maxKeys: 2 }); console.log(\"\\nParsed Query:\", parsedObject); // Use the parse() method on the string// with maxKeys set to 0 (no limits)parsedObject = querystring.parse(urlQuery, \"&\", \"=\", { maxKeys: 0 }); console.log(\"\\nParsed Query:\", parsedObject);\nOutput:\nParsed Query: [Object: null prototype] {\n user: 'admin',\n articles: [ '1', '2', '3' ],\n access: 'true'\n}\n\nParsed Query: [Object: null prototype] { user: 'admin' }\n\nParsed Query: [Object: null prototype] \n { user: 'admin', articles: '1' }\n\nParsed Query: [Object: null prototype] {\n user: 'admin',\n articles: [ '1', '2', '3' ],\n access: 'true'\n}\n\nReference: https://nodejs.org/api/querystring.html#querystring_querystring_parse_str_sep_eq_options \nNode.js- querystring-Module\nNode.js\nWeb Technologies\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nHow to update Node.js and NPM to next version ?\nNode.js fs.readFileSync() Method\nNode.js fs.writeFile() Method\nHow to update NPM ?\nDifference between promise and async await in Node.js\nTop 10 Projects For Beginners To Practice HTML and CSS Skills\nDifference between var, let and const keywords in JavaScript\nHow to insert spaces/tabs in text using HTML/CSS?\nHow to fetch data from an API in ReactJS ?\nDifferences between Functional Components and Class Components in React"},"parsed":{"kind":"list like","value":[{"code":null,"e":28,"s":0,"text":"\n08 Oct, 2021"},{"code":null,"e":493,"s":28,"text":"The querystring.parse() method is used to parse a URL query string into an object that contains the key and pair values of the query URL. The object returned does not inherit prototypes from the JavaScript object, therefore usual Object methods will not work. During parsing, the UTF-8 encoding format is assumed unless there is an alternative character encoding format. To decode alternative character encoding, the decodeURIComponent option has to be specified. "},{"code":null,"e":502,"s":493,"text":"Syntax: "},{"code":null,"e":553,"s":502,"text":"querystring.parse( str[, sep[, eq[, options]]]) )\n"},{"code":null,"e":644,"s":553,"text":"Parameters: This function accepts four parameters as mentioned above and described below: "},{"code":null,"e":716,"s":644,"text":"str: It is a String that specifies the URL query that has to be parsed."},{"code":null,"e":862,"s":716,"text":"sep: It is a String that specifies the substring used to delimit the key and value pairs in the specified query string. The default value is “&”."},{"code":null,"e":999,"s":862,"text":"eq: It is a String that specifies the substring used to delimit keys and values in the specified query string. The default value is “=”."},{"code":null,"e":1465,"s":999,"text":"options: It is an object which can be used to modify the behavior of the method. It has the following parameters: decodeURIComponent: It is a function that would be used to decode percent-encoded characters in the query string. The default value is querystring.unescape().maxKeys: It is a number which specifies the maximum number of keys that should be parsed from the query string. A value of “0” would remove all the counting limits. The default value is “1000”."},{"code":null,"e":1624,"s":1465,"text":"decodeURIComponent: It is a function that would be used to decode percent-encoded characters in the query string. The default value is querystring.unescape()."},{"code":null,"e":1818,"s":1624,"text":"maxKeys: It is a number which specifies the maximum number of keys that should be parsed from the query string. A value of “0” would remove all the counting limits. The default value is “1000”."},{"code":null,"e":1916,"s":1818,"text":"Return Value: It returns an object that has the key and value pairs parsed from the query string."},{"code":null,"e":1985,"s":1916,"text":"Below examples illustrate the querystring.parse() method in Node.js:"},{"code":null,"e":1996,"s":1985,"text":"Example 1:"},{"code":null,"e":2004,"s":1996,"text":"Node.js"},{"code":"// Import the querystring moduleconst querystring = require(\"querystring\"); // Specify the URL query string// to be parsedlet urlQuery = \"username=user1&units=kgs&units=pounds&permission=false\"; // Use the parse() method on the stringlet parsedObject = querystring.parse(urlQuery); console.log(\"Parsed Query:\", parsedObject); // Use the parse() method on the string// with sep as `&&` and eq as `-`urlQuery = \"username-user1&&units-kgs&&units-pounds&&permission-false\";parsedObject = querystring.parse(urlQuery, \"&&\", \"-\"); console.log(\"\\nParsed Query:\", parsedObject);","e":2583,"s":2004,"text":null},{"code":null,"e":2591,"s":2583,"text":"Output:"},{"code":null,"e":2825,"s":2591,"text":"Parsed Query: [Object: null prototype] {\n username: 'user1',\n units: [ 'kgs', 'pounds' ],\n permission: 'false'\n}\n\nParsed Query: [Object: null prototype] {\n username: 'user1',\n units: [ 'kgs', 'pounds' ],\n permission: 'false'\n}\n"},{"code":null,"e":2836,"s":2825,"text":"Example 2:"},{"code":null,"e":2844,"s":2836,"text":"Node.js"},{"code":"// Import the querystring moduleconst querystring = require(\"querystring\"); // Specify the URL query string// to be parsedlet urlQuery = \"user=admin&articles=1&articles=2&articles=3&access=true\"; // Use the parse() method on the string// with default valueslet parsedObject = querystring.parse(urlQuery, \"&\", \"=\"); console.log(\"Parsed Query:\", parsedObject); // Use the parse() method on the string// with maxKeys set to 1parsedObject = querystring.parse(urlQuery, \"&\", \"=\", { maxKeys: 1 }); console.log(\"\\nParsed Query:\", parsedObject); // Use the parse() method on the string// with maxKeys set to 2parsedObject = querystring.parse(urlQuery, \"&\", \"=\", { maxKeys: 2 }); console.log(\"\\nParsed Query:\", parsedObject); // Use the parse() method on the string// with maxKeys set to 0 (no limits)parsedObject = querystring.parse(urlQuery, \"&\", \"=\", { maxKeys: 0 }); console.log(\"\\nParsed Query:\", parsedObject);","e":3769,"s":2844,"text":null},{"code":null,"e":3777,"s":3769,"text":"Output:"},{"code":null,"e":4141,"s":3777,"text":"Parsed Query: [Object: null prototype] {\n user: 'admin',\n articles: [ '1', '2', '3' ],\n access: 'true'\n}\n\nParsed Query: [Object: null prototype] { user: 'admin' }\n\nParsed Query: [Object: null prototype] \n { user: 'admin', articles: '1' }\n\nParsed Query: [Object: null prototype] {\n user: 'admin',\n articles: [ '1', '2', '3' ],\n access: 'true'\n}\n"},{"code":null,"e":4242,"s":4141,"text":"Reference: https://nodejs.org/api/querystring.html#querystring_querystring_parse_str_sep_eq_options "},{"code":null,"e":4270,"s":4242,"text":"Node.js- querystring-Module"},{"code":null,"e":4278,"s":4270,"text":"Node.js"},{"code":null,"e":4295,"s":4278,"text":"Web Technologies"},{"code":null,"e":4393,"s":4295,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":4441,"s":4393,"text":"How to update Node.js and NPM to next version ?"},{"code":null,"e":4474,"s":4441,"text":"Node.js fs.readFileSync() Method"},{"code":null,"e":4504,"s":4474,"text":"Node.js fs.writeFile() Method"},{"code":null,"e":4524,"s":4504,"text":"How to update NPM ?"},{"code":null,"e":4578,"s":4524,"text":"Difference between promise and async await in Node.js"},{"code":null,"e":4640,"s":4578,"text":"Top 10 Projects For Beginners To Practice HTML and CSS Skills"},{"code":null,"e":4701,"s":4640,"text":"Difference between var, let and const keywords in JavaScript"},{"code":null,"e":4751,"s":4701,"text":"How to insert spaces/tabs in text using HTML/CSS?"},{"code":null,"e":4794,"s":4751,"text":"How to fetch data from an API in ReactJS ?"}],"string":"[\n {\n \"code\": null,\n \"e\": 28,\n \"s\": 0,\n \"text\": \"\\n08 Oct, 2021\"\n },\n {\n \"code\": null,\n \"e\": 493,\n \"s\": 28,\n \"text\": \"The querystring.parse() method is used to parse a URL query string into an object that contains the key and pair values of the query URL. The object returned does not inherit prototypes from the JavaScript object, therefore usual Object methods will not work. During parsing, the UTF-8 encoding format is assumed unless there is an alternative character encoding format. To decode alternative character encoding, the decodeURIComponent option has to be specified. \"\n },\n {\n \"code\": null,\n \"e\": 502,\n \"s\": 493,\n \"text\": \"Syntax: \"\n },\n {\n \"code\": null,\n \"e\": 553,\n \"s\": 502,\n \"text\": \"querystring.parse( str[, sep[, eq[, options]]]) )\\n\"\n },\n {\n \"code\": null,\n \"e\": 644,\n \"s\": 553,\n \"text\": \"Parameters: This function accepts four parameters as mentioned above and described below: \"\n },\n {\n \"code\": null,\n \"e\": 716,\n \"s\": 644,\n \"text\": \"str: It is a String that specifies the URL query that has to be parsed.\"\n },\n {\n \"code\": null,\n \"e\": 862,\n \"s\": 716,\n \"text\": \"sep: It is a String that specifies the substring used to delimit the key and value pairs in the specified query string. The default value is “&”.\"\n },\n {\n \"code\": null,\n \"e\": 999,\n \"s\": 862,\n \"text\": \"eq: It is a String that specifies the substring used to delimit keys and values in the specified query string. The default value is “=”.\"\n },\n {\n \"code\": null,\n \"e\": 1465,\n \"s\": 999,\n \"text\": \"options: It is an object which can be used to modify the behavior of the method. It has the following parameters: decodeURIComponent: It is a function that would be used to decode percent-encoded characters in the query string. The default value is querystring.unescape().maxKeys: It is a number which specifies the maximum number of keys that should be parsed from the query string. A value of “0” would remove all the counting limits. The default value is “1000”.\"\n },\n {\n \"code\": null,\n \"e\": 1624,\n \"s\": 1465,\n \"text\": \"decodeURIComponent: It is a function that would be used to decode percent-encoded characters in the query string. The default value is querystring.unescape().\"\n },\n {\n \"code\": null,\n \"e\": 1818,\n \"s\": 1624,\n \"text\": \"maxKeys: It is a number which specifies the maximum number of keys that should be parsed from the query string. A value of “0” would remove all the counting limits. The default value is “1000”.\"\n },\n {\n \"code\": null,\n \"e\": 1916,\n \"s\": 1818,\n \"text\": \"Return Value: It returns an object that has the key and value pairs parsed from the query string.\"\n },\n {\n \"code\": null,\n \"e\": 1985,\n \"s\": 1916,\n \"text\": \"Below examples illustrate the querystring.parse() method in Node.js:\"\n },\n {\n \"code\": null,\n \"e\": 1996,\n \"s\": 1985,\n \"text\": \"Example 1:\"\n },\n {\n \"code\": null,\n \"e\": 2004,\n \"s\": 1996,\n \"text\": \"Node.js\"\n },\n {\n \"code\": \"// Import the querystring moduleconst querystring = require(\\\"querystring\\\"); // Specify the URL query string// to be parsedlet urlQuery = \\\"username=user1&units=kgs&units=pounds&permission=false\\\"; // Use the parse() method on the stringlet parsedObject = querystring.parse(urlQuery); console.log(\\\"Parsed Query:\\\", parsedObject); // Use the parse() method on the string// with sep as `&&` and eq as `-`urlQuery = \\\"username-user1&&units-kgs&&units-pounds&&permission-false\\\";parsedObject = querystring.parse(urlQuery, \\\"&&\\\", \\\"-\\\"); console.log(\\\"\\\\nParsed Query:\\\", parsedObject);\",\n \"e\": 2583,\n \"s\": 2004,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 2591,\n \"s\": 2583,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 2825,\n \"s\": 2591,\n \"text\": \"Parsed Query: [Object: null prototype] {\\n username: 'user1',\\n units: [ 'kgs', 'pounds' ],\\n permission: 'false'\\n}\\n\\nParsed Query: [Object: null prototype] {\\n username: 'user1',\\n units: [ 'kgs', 'pounds' ],\\n permission: 'false'\\n}\\n\"\n },\n {\n \"code\": null,\n \"e\": 2836,\n \"s\": 2825,\n \"text\": \"Example 2:\"\n },\n {\n \"code\": null,\n \"e\": 2844,\n \"s\": 2836,\n \"text\": \"Node.js\"\n },\n {\n \"code\": \"// Import the querystring moduleconst querystring = require(\\\"querystring\\\"); // Specify the URL query string// to be parsedlet urlQuery = \\\"user=admin&articles=1&articles=2&articles=3&access=true\\\"; // Use the parse() method on the string// with default valueslet parsedObject = querystring.parse(urlQuery, \\\"&\\\", \\\"=\\\"); console.log(\\\"Parsed Query:\\\", parsedObject); // Use the parse() method on the string// with maxKeys set to 1parsedObject = querystring.parse(urlQuery, \\\"&\\\", \\\"=\\\", { maxKeys: 1 }); console.log(\\\"\\\\nParsed Query:\\\", parsedObject); // Use the parse() method on the string// with maxKeys set to 2parsedObject = querystring.parse(urlQuery, \\\"&\\\", \\\"=\\\", { maxKeys: 2 }); console.log(\\\"\\\\nParsed Query:\\\", parsedObject); // Use the parse() method on the string// with maxKeys set to 0 (no limits)parsedObject = querystring.parse(urlQuery, \\\"&\\\", \\\"=\\\", { maxKeys: 0 }); console.log(\\\"\\\\nParsed Query:\\\", parsedObject);\",\n \"e\": 3769,\n \"s\": 2844,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 3777,\n \"s\": 3769,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 4141,\n \"s\": 3777,\n \"text\": \"Parsed Query: [Object: null prototype] {\\n user: 'admin',\\n articles: [ '1', '2', '3' ],\\n access: 'true'\\n}\\n\\nParsed Query: [Object: null prototype] { user: 'admin' }\\n\\nParsed Query: [Object: null prototype] \\n { user: 'admin', articles: '1' }\\n\\nParsed Query: [Object: null prototype] {\\n user: 'admin',\\n articles: [ '1', '2', '3' ],\\n access: 'true'\\n}\\n\"\n },\n {\n \"code\": null,\n \"e\": 4242,\n \"s\": 4141,\n \"text\": \"Reference: https://nodejs.org/api/querystring.html#querystring_querystring_parse_str_sep_eq_options \"\n },\n {\n \"code\": null,\n \"e\": 4270,\n \"s\": 4242,\n \"text\": \"Node.js- querystring-Module\"\n },\n {\n \"code\": null,\n \"e\": 4278,\n \"s\": 4270,\n \"text\": \"Node.js\"\n },\n {\n \"code\": null,\n \"e\": 4295,\n \"s\": 4278,\n \"text\": \"Web Technologies\"\n },\n {\n \"code\": null,\n \"e\": 4393,\n \"s\": 4295,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 4441,\n \"s\": 4393,\n \"text\": \"How to update Node.js and NPM to next version ?\"\n },\n {\n \"code\": null,\n \"e\": 4474,\n \"s\": 4441,\n \"text\": \"Node.js fs.readFileSync() Method\"\n },\n {\n \"code\": null,\n \"e\": 4504,\n \"s\": 4474,\n \"text\": \"Node.js fs.writeFile() Method\"\n },\n {\n \"code\": null,\n \"e\": 4524,\n \"s\": 4504,\n \"text\": \"How to update NPM ?\"\n },\n {\n \"code\": null,\n \"e\": 4578,\n \"s\": 4524,\n \"text\": \"Difference between promise and async await in Node.js\"\n },\n {\n \"code\": null,\n \"e\": 4640,\n \"s\": 4578,\n \"text\": \"Top 10 Projects For Beginners To Practice HTML and CSS Skills\"\n },\n {\n \"code\": null,\n \"e\": 4701,\n \"s\": 4640,\n \"text\": \"Difference between var, let and const keywords in JavaScript\"\n },\n {\n \"code\": null,\n \"e\": 4751,\n \"s\": 4701,\n \"text\": \"How to insert spaces/tabs in text using HTML/CSS?\"\n },\n {\n \"code\": null,\n \"e\": 4794,\n \"s\": 4751,\n \"text\": \"How to fetch data from an API in ReactJS ?\"\n }\n]"}}},{"rowIdx":135,"cells":{"title":{"kind":"string","value":"LCA in a tree using Binary Lifting Technique"},"text":{"kind":"string","value":"04 Sep, 2021\nGiven a binary tree, the task is to find the Lowest Common Ancestor of the given two nodes in the tree. Let G be a tree then LCA of two nodes u and v is defined as the node w in the tree which is an ancestor of both u and v and is farthest from the root node.If one node is the ancestor of another one than that particular node is the LCA of those two nodes.Example: \nInput: \nOutput: The LCA of 6 and 9 is 1. The LCA of 5 and 9 is 1. The LCA of 6 and 8 is 3. The LCA of 6 and 1 is 1. \nApproach: The article describes an approach known as Binary Lifting to find the Lowest Common Ancestor of two nodes in a tree. There can be many approaches to solve the LCA problem. We are discussing the Binary Lifting Technique, the others can be read from here and here. Binary Lifting is a dynamic programming approach where we pre-compute an array memo[1, n][1, log(n)] where memo[i][j] contains 2^j-th ancestor of node i. For computing the values of memo[][], the following recursion may be used \nmemo state: \n memo[i][j] = i-th node’s 2^(j)th ancestor in the path \nmemo initialization: \n memo[i][j] = memo[i][0] (first parent (2^0) of each node is given)\nmemo trans:\n memo[i][j] = memo[ memo [i][j – 1]]\nmeaning: A(i,2^j)=A( A(i , 2^(j-1) ) , 2^(j-1) ) \nTo find the (2^j)-th ancestor of i, recursively find i-th node’s 2^(j-1)th ancestor’s 2^(j-1)th ancestor. (2^(j) = 2^(j-1) + 2^(j-1))\nSo:\nmemo[i][j] = parent[i] if j = 0 and memo[i][j] = memo[memo[i][j – 1]][j – 1] if j > 0. \nWe first check whether a node is an ancestor of other or not and if one node is ancestor of other then it is the LCA of these two nodes otherwise we find a node which is not the common ancestor of both u and v and is highest(i.e. a node x such that x is not the common ancestor of u and v but memo[x][0] is) in the tree. After finding such a node (let it be x), we print the first ancestor of x i.e. memo[x][0] which will be the required LCA.Below is the implementation of the above approach: \nC++\nJava\nPython3\nC#\nJavascript\n// C++ implementation of the approach#include using namespace std; // Pre-processing to calculate values of memo[][]void dfs(int u, int p, int **memo, int *lev, int log, vector *g){ // Using recursion formula to calculate // the values of memo[][] memo[u][0] = p; for (int i = 1; i <= log; i++) memo[u][i] = memo[memo[u][i - 1]][i - 1]; for (int v : g[u]) { if (v != p) { lev[v] = lev[u] + 1; dfs(v, u, memo, lev, log, g); } }} // Function to return the LCA of nodes u and vint lca(int u, int v, int log, int *lev, int **memo){ // The node which is present farthest // from the root node is taken as u // If v is farther from root node // then swap the two if (lev[u] < lev[v]) swap(u, v); // Finding the ancestor of u // which is at same level as v for (int i = log; i >= 0; i--) if ((lev[u] - pow(2, i)) >= lev[v]) u = memo[u][i]; // If v is the ancestor of u // then v is the LCA of u and v if (u == v) return u; // Finding the node closest to the root which is // not the common ancestor of u and v i.e. a node // x such that x is not the common ancestor of u // and v but memo[x][0] is for (int i = log; i >= 0; i--) { if (memo[u][i] != memo[v][i]) { u = memo[u][i]; v = memo[v][i]; } } // Returning the first ancestor // of above found node return memo[u][0];} // Driver Codeint main(){ // Number of nodes int n = 9; // vector to store tree vector g[n + 1]; int log = (int)ceil(log2(n)); int **memo = new int *[n + 1]; for (int i = 0; i < n + 1; i++) memo[i] = new int[log + 1]; // Stores the level of each node int *lev = new int[n + 1]; // Initialising memo values with -1 for (int i = 0; i <= n; i++) memset(memo[i], -1, sizeof memo[i]); // Add edges g[1].push_back(2); g[2].push_back(1); g[1].push_back(3); g[3].push_back(1); g[1].push_back(4); g[4].push_back(1); g[2].push_back(5); g[5].push_back(2); g[3].push_back(6); g[6].push_back(3); g[3].push_back(7); g[7].push_back(3); g[3].push_back(8); g[8].push_back(3); g[4].push_back(9); g[9].push_back(4); dfs(1, 1, memo, lev, log, g); cout << \"The LCA of 6 and 9 is \" << lca(6, 9, log, lev, memo) << endl; cout << \"The LCA of 5 and 9 is \" << lca(5, 9, log, lev, memo) << endl; cout << \"The LCA of 6 and 8 is \" << lca(6, 8, log, lev, memo) << endl; cout << \"The LCA of 6 and 1 is \" << lca(6, 1, log, lev, memo) << endl; return 0;} // This code is contributed by// sanjeev2552\n// Java implementation of the approachimport java.util.*;public class GFG { // ArrayList to store tree static ArrayList g[]; static int memo[][], lev[], log; // Pre-processing to calculate values of memo[][] static void dfs(int u, int p) { // Using recursion formula to calculate // the values of memo[][] memo[u][0] = p; for (int i = 1; i <= log; i++) memo[u][i] = memo[memo[u][i - 1]][i - 1]; for (int v : g[u]) { if (v != p) { // Calculating the level of each node lev[v] = lev[u] + 1; dfs(v, u); } } } // Function to return the LCA of nodes u and v static int lca(int u, int v) { // The node which is present farthest // from the root node is taken as u // If v is farther from root node // then swap the two if (lev[u] < lev[v]) { int temp = u; u = v; v = temp; } // Finding the ancestor of u // which is at same level as v for (int i = log; i >= 0; i--) { if ((lev[u] - (int)Math.pow(2, i)) >= lev[v]) u = memo[u][i]; } // If v is the ancestor of u // then v is the LCA of u and v if (u == v) return u; // Finding the node closest to the root which is // not the common ancestor of u and v i.e. a node // x such that x is not the common ancestor of u // and v but memo[x][0] is for (int i = log; i >= 0; i--) { if (memo[u][i] != memo[v][i]) { u = memo[u][i]; v = memo[v][i]; } } // Returning the first ancestor // of above found node return memo[u][0]; } // Driver code public static void main(String args[]) { // Number of nodes int n = 9; g = new ArrayList[n + 1]; // log(n) with base 2 log = (int)Math.ceil(Math.log(n) / Math.log(2)); memo = new int[n + 1][log + 1]; // Stores the level of each node lev = new int[n + 1]; // Initialising memo values with -1 for (int i = 0; i <= n; i++) Arrays.fill(memo[i], -1); for (int i = 0; i <= n; i++) g[i] = new ArrayList<>(); // Add edges g[1].add(2); g[2].add(1); g[1].add(3); g[3].add(1); g[1].add(4); g[4].add(1); g[2].add(5); g[5].add(2); g[3].add(6); g[6].add(3); g[3].add(7); g[7].add(3); g[3].add(8); g[8].add(3); g[4].add(9); g[9].add(4); dfs(1, 1); System.out.println(\"The LCA of 6 and 9 is \" + lca(6, 9)); System.out.println(\"The LCA of 5 and 9 is \" + lca(5, 9)); System.out.println(\"The LCA of 6 and 8 is \" + lca(6, 8)); System.out.println(\"The LCA of 6 and 1 is \" + lca(6, 1)); }}\n# Python3 implementation of the above approachimport math # Pre-processing to calculate values of memo[][]def dfs(u, p, memo, lev, log, g): # Using recursion formula to calculate # the values of memo[][] memo[u][0] = p for i in range(1, log + 1): memo[u][i] = memo[memo[u][i - 1]][i - 1] for v in g[u]: if v != p: lev[v] = lev[u] + 1 dfs(v, u, memo, lev, log, g) # Function to return the LCA of nodes u and vdef lca(u, v, log, lev, memo): # The node which is present farthest # from the root node is taken as u # If v is farther from root node # then swap the two if lev[u] < lev[v]: swap(u, v) # Finding the ancestor of u # which is at same level as v for i in range(log, -1, -1): if (lev[u] - pow(2, i)) >= lev[v]: u = memo[u][i] # If v is the ancestor of u # then v is the LCA of u and v if u == v: return v # Finding the node closest to the # root which is not the common ancestor # of u and v i.e. a node x such that x # is not the common ancestor of u # and v but memo[x][0] is for i in range(log, -1, -1): if memo[u][i] != memo[v][i]: u = memo[u][i] v = memo[v][i] # Returning the first ancestor # of above found node return memo[u][0] # Driver code # Number of nodesn = 9 log = math.ceil(math.log(n, 2))g = [[] for i in range(n + 1)] memo = [[-1 for i in range(log + 1)] for j in range(n + 1)] # Stores the level of each node lev = [0 for i in range(n + 1)] # Add edgesg[1].append(2)g[2].append(1)g[1].append(3)g[3].append(1)g[1].append(4)g[4].append(1)g[2].append(5)g[5].append(2)g[3].append(6)g[6].append(3)g[3].append(7)g[7].append(3)g[3].append(8)g[8].append(3)g[4].append(9)g[9].append(4) dfs(1, 1, memo, lev, log, g) print(\"The LCA of 6 and 9 is\", lca(6, 9, log, lev, memo))print(\"The LCA of 5 and 9 is\", lca(5, 9, log, lev, memo))print(\"The LCA of 6 and 8 is\", lca(6, 8, log, lev, memo))print(\"The LCA of 6 and 1 is\", lca(6, 1, log, lev, memo)) # This code is contributed by Bhaskar\n// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // List to store tree static List []g; static int [,]memo; static int []lev; static int log; // Pre-processing to calculate // values of memo[,] static void dfs(int u, int p) { // Using recursion formula to // calculate the values of memo[,] memo[u, 0] = p; for (int i = 1; i <= log; i++) memo[u, i] = memo[memo[u, i - 1], i - 1]; foreach (int v in g[u]) { if (v != p) { // Calculating the level of each node lev[v] = lev[u] + 1; dfs(v, u); } } } // Function to return the LCA of // nodes u and v static int lca(int u, int v) { // The node which is present farthest // from the root node is taken as u // If v is farther from root node // then swap the two if (lev[u] < lev[v]) { int temp = u; u = v; v = temp; } // Finding the ancestor of u // which is at same level as v for (int i = log; i >= 0; i--) { if ((lev[u] - (int)Math.Pow(2, i)) >= lev[v]) u = memo[u, i]; } // If v is the ancestor of u // then v is the LCA of u and v if (u == v) return u; // Finding the node closest to the root // which is not the common ancestor of // u and v i.e. a node x such that // x is not the common ancestor of u // and v but memo[x,0] is for (int i = log; i >= 0; i--) { if (memo[u, i] != memo[v, i]) { u = memo[u, i]; v = memo[v, i]; } } // Returning the first ancestor // of above found node return memo[u, 0]; } // Driver code public static void Main(String []args) { // Number of nodes int n = 9; g = new List[n + 1]; // log(n) with base 2 log = (int)Math.Ceiling(Math.Log(n) / Math.Log(2)); memo = new int[n + 1, log + 1]; // Stores the level of each node lev = new int[n + 1]; // Initialising memo values with -1 for (int i = 0; i <= n; i++) for (int j = 0; j <= log; j++) memo[i, j] = -1; for (int i = 0; i <= n; i++) g[i] = new List(); // Add edges g[1].Add(2); g[2].Add(1); g[1].Add(3); g[3].Add(1); g[1].Add(4); g[4].Add(1); g[2].Add(5); g[5].Add(2); g[3].Add(6); g[6].Add(3); g[3].Add(7); g[7].Add(3); g[3].Add(8); g[8].Add(3); g[4].Add(9); g[9].Add(4); dfs(1, 1); Console.WriteLine(\"The LCA of 6 and 9 is \" + lca(6, 9)); Console.WriteLine(\"The LCA of 5 and 9 is \" + lca(5, 9)); Console.WriteLine(\"The LCA of 6 and 8 is \" + lca(6, 8)); Console.WriteLine(\"The LCA of 6 and 1 is \" + lca(6, 1)); }} // This code is contributed by PrinciRaj1992\n\nThe LCA of 6 and 9 is 1\nThe LCA of 5 and 9 is 1\nThe LCA of 6 and 8 is 3\nThe LCA of 6 and 1 is 1\n \nTime Complexity: The time taken in pre-processing is O(NlogN) and every query takes O(logN) time. So the overall time complexity of the solution is O(NlogN).Auxiliary Space: O(NlogN) \nprinciraj1992\nsanjeev2552\nbpandey23012002\ndarkhash\ndecode2207\npankajsharmagfg\ngaurav2146\nBinary Tree\nLCA\nData Structures\nDynamic Programming\nTree\nData Structures\nDynamic Programming\nTree\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},"parsed":{"kind":"list like","value":[{"code":null,"e":52,"s":24,"text":"\n04 Sep, 2021"},{"code":null,"e":421,"s":52,"text":"Given a binary tree, the task is to find the Lowest Common Ancestor of the given two nodes in the tree. Let G be a tree then LCA of two nodes u and v is defined as the node w in the tree which is an ancestor of both u and v and is farthest from the root node.If one node is the ancestor of another one than that particular node is the LCA of those two nodes.Example: "},{"code":null,"e":430,"s":421,"text":"Input: "},{"code":null,"e":540,"s":430,"text":"Output: The LCA of 6 and 9 is 1. The LCA of 5 and 9 is 1. The LCA of 6 and 8 is 3. The LCA of 6 and 1 is 1. "},{"code":null,"e":1043,"s":540,"text":"Approach: The article describes an approach known as Binary Lifting to find the Lowest Common Ancestor of two nodes in a tree. There can be many approaches to solve the LCA problem. We are discussing the Binary Lifting Technique, the others can be read from here and here. Binary Lifting is a dynamic programming approach where we pre-compute an array memo[1, n][1, log(n)] where memo[i][j] contains 2^j-th ancestor of node i. For computing the values of memo[][], the following recursion may be used "},{"code":null,"e":1057,"s":1043,"text":"memo state: "},{"code":null,"e":1116,"s":1057,"text":" memo[i][j] = i-th node’s 2^(j)th ancestor in the path "},{"code":null,"e":1139,"s":1116,"text":"memo initialization: "},{"code":null,"e":1209,"s":1139,"text":" memo[i][j] = memo[i][0] (first parent (2^0) of each node is given)"},{"code":null,"e":1221,"s":1209,"text":"memo trans:"},{"code":null,"e":1260,"s":1221,"text":" memo[i][j] = memo[ memo [i][j – 1]]"},{"code":null,"e":1310,"s":1260,"text":"meaning: A(i,2^j)=A( A(i , 2^(j-1) ) , 2^(j-1) ) "},{"code":null,"e":1444,"s":1310,"text":"To find the (2^j)-th ancestor of i, recursively find i-th node’s 2^(j-1)th ancestor’s 2^(j-1)th ancestor. (2^(j) = 2^(j-1) + 2^(j-1))"},{"code":null,"e":1448,"s":1444,"text":"So:"},{"code":null,"e":1537,"s":1448,"text":"memo[i][j] = parent[i] if j = 0 and memo[i][j] = memo[memo[i][j – 1]][j – 1] if j > 0. "},{"code":null,"e":2032,"s":1537,"text":"We first check whether a node is an ancestor of other or not and if one node is ancestor of other then it is the LCA of these two nodes otherwise we find a node which is not the common ancestor of both u and v and is highest(i.e. a node x such that x is not the common ancestor of u and v but memo[x][0] is) in the tree. After finding such a node (let it be x), we print the first ancestor of x i.e. memo[x][0] which will be the required LCA.Below is the implementation of the above approach: "},{"code":null,"e":2036,"s":2032,"text":"C++"},{"code":null,"e":2041,"s":2036,"text":"Java"},{"code":null,"e":2049,"s":2041,"text":"Python3"},{"code":null,"e":2052,"s":2049,"text":"C#"},{"code":null,"e":2063,"s":2052,"text":"Javascript"},{"code":"// C++ implementation of the approach#include using namespace std; // Pre-processing to calculate values of memo[][]void dfs(int u, int p, int **memo, int *lev, int log, vector *g){ // Using recursion formula to calculate // the values of memo[][] memo[u][0] = p; for (int i = 1; i <= log; i++) memo[u][i] = memo[memo[u][i - 1]][i - 1]; for (int v : g[u]) { if (v != p) { lev[v] = lev[u] + 1; dfs(v, u, memo, lev, log, g); } }} // Function to return the LCA of nodes u and vint lca(int u, int v, int log, int *lev, int **memo){ // The node which is present farthest // from the root node is taken as u // If v is farther from root node // then swap the two if (lev[u] < lev[v]) swap(u, v); // Finding the ancestor of u // which is at same level as v for (int i = log; i >= 0; i--) if ((lev[u] - pow(2, i)) >= lev[v]) u = memo[u][i]; // If v is the ancestor of u // then v is the LCA of u and v if (u == v) return u; // Finding the node closest to the root which is // not the common ancestor of u and v i.e. a node // x such that x is not the common ancestor of u // and v but memo[x][0] is for (int i = log; i >= 0; i--) { if (memo[u][i] != memo[v][i]) { u = memo[u][i]; v = memo[v][i]; } } // Returning the first ancestor // of above found node return memo[u][0];} // Driver Codeint main(){ // Number of nodes int n = 9; // vector to store tree vector g[n + 1]; int log = (int)ceil(log2(n)); int **memo = new int *[n + 1]; for (int i = 0; i < n + 1; i++) memo[i] = new int[log + 1]; // Stores the level of each node int *lev = new int[n + 1]; // Initialising memo values with -1 for (int i = 0; i <= n; i++) memset(memo[i], -1, sizeof memo[i]); // Add edges g[1].push_back(2); g[2].push_back(1); g[1].push_back(3); g[3].push_back(1); g[1].push_back(4); g[4].push_back(1); g[2].push_back(5); g[5].push_back(2); g[3].push_back(6); g[6].push_back(3); g[3].push_back(7); g[7].push_back(3); g[3].push_back(8); g[8].push_back(3); g[4].push_back(9); g[9].push_back(4); dfs(1, 1, memo, lev, log, g); cout << \"The LCA of 6 and 9 is \" << lca(6, 9, log, lev, memo) << endl; cout << \"The LCA of 5 and 9 is \" << lca(5, 9, log, lev, memo) << endl; cout << \"The LCA of 6 and 8 is \" << lca(6, 8, log, lev, memo) << endl; cout << \"The LCA of 6 and 1 is \" << lca(6, 1, log, lev, memo) << endl; return 0;} // This code is contributed by// sanjeev2552","e":4757,"s":2063,"text":null},{"code":"// Java implementation of the approachimport java.util.*;public class GFG { // ArrayList to store tree static ArrayList g[]; static int memo[][], lev[], log; // Pre-processing to calculate values of memo[][] static void dfs(int u, int p) { // Using recursion formula to calculate // the values of memo[][] memo[u][0] = p; for (int i = 1; i <= log; i++) memo[u][i] = memo[memo[u][i - 1]][i - 1]; for (int v : g[u]) { if (v != p) { // Calculating the level of each node lev[v] = lev[u] + 1; dfs(v, u); } } } // Function to return the LCA of nodes u and v static int lca(int u, int v) { // The node which is present farthest // from the root node is taken as u // If v is farther from root node // then swap the two if (lev[u] < lev[v]) { int temp = u; u = v; v = temp; } // Finding the ancestor of u // which is at same level as v for (int i = log; i >= 0; i--) { if ((lev[u] - (int)Math.pow(2, i)) >= lev[v]) u = memo[u][i]; } // If v is the ancestor of u // then v is the LCA of u and v if (u == v) return u; // Finding the node closest to the root which is // not the common ancestor of u and v i.e. a node // x such that x is not the common ancestor of u // and v but memo[x][0] is for (int i = log; i >= 0; i--) { if (memo[u][i] != memo[v][i]) { u = memo[u][i]; v = memo[v][i]; } } // Returning the first ancestor // of above found node return memo[u][0]; } // Driver code public static void main(String args[]) { // Number of nodes int n = 9; g = new ArrayList[n + 1]; // log(n) with base 2 log = (int)Math.ceil(Math.log(n) / Math.log(2)); memo = new int[n + 1][log + 1]; // Stores the level of each node lev = new int[n + 1]; // Initialising memo values with -1 for (int i = 0; i <= n; i++) Arrays.fill(memo[i], -1); for (int i = 0; i <= n; i++) g[i] = new ArrayList<>(); // Add edges g[1].add(2); g[2].add(1); g[1].add(3); g[3].add(1); g[1].add(4); g[4].add(1); g[2].add(5); g[5].add(2); g[3].add(6); g[6].add(3); g[3].add(7); g[7].add(3); g[3].add(8); g[8].add(3); g[4].add(9); g[9].add(4); dfs(1, 1); System.out.println(\"The LCA of 6 and 9 is \" + lca(6, 9)); System.out.println(\"The LCA of 5 and 9 is \" + lca(5, 9)); System.out.println(\"The LCA of 6 and 8 is \" + lca(6, 8)); System.out.println(\"The LCA of 6 and 1 is \" + lca(6, 1)); }}","e":7719,"s":4757,"text":null},{"code":"# Python3 implementation of the above approachimport math # Pre-processing to calculate values of memo[][]def dfs(u, p, memo, lev, log, g): # Using recursion formula to calculate # the values of memo[][] memo[u][0] = p for i in range(1, log + 1): memo[u][i] = memo[memo[u][i - 1]][i - 1] for v in g[u]: if v != p: lev[v] = lev[u] + 1 dfs(v, u, memo, lev, log, g) # Function to return the LCA of nodes u and vdef lca(u, v, log, lev, memo): # The node which is present farthest # from the root node is taken as u # If v is farther from root node # then swap the two if lev[u] < lev[v]: swap(u, v) # Finding the ancestor of u # which is at same level as v for i in range(log, -1, -1): if (lev[u] - pow(2, i)) >= lev[v]: u = memo[u][i] # If v is the ancestor of u # then v is the LCA of u and v if u == v: return v # Finding the node closest to the # root which is not the common ancestor # of u and v i.e. a node x such that x # is not the common ancestor of u # and v but memo[x][0] is for i in range(log, -1, -1): if memo[u][i] != memo[v][i]: u = memo[u][i] v = memo[v][i] # Returning the first ancestor # of above found node return memo[u][0] # Driver code # Number of nodesn = 9 log = math.ceil(math.log(n, 2))g = [[] for i in range(n + 1)] memo = [[-1 for i in range(log + 1)] for j in range(n + 1)] # Stores the level of each node lev = [0 for i in range(n + 1)] # Add edgesg[1].append(2)g[2].append(1)g[1].append(3)g[3].append(1)g[1].append(4)g[4].append(1)g[2].append(5)g[5].append(2)g[3].append(6)g[6].append(3)g[3].append(7)g[7].append(3)g[3].append(8)g[8].append(3)g[4].append(9)g[9].append(4) dfs(1, 1, memo, lev, log, g) print(\"The LCA of 6 and 9 is\", lca(6, 9, log, lev, memo))print(\"The LCA of 5 and 9 is\", lca(5, 9, log, lev, memo))print(\"The LCA of 6 and 8 is\", lca(6, 8, log, lev, memo))print(\"The LCA of 6 and 1 is\", lca(6, 1, log, lev, memo)) # This code is contributed by Bhaskar","e":9882,"s":7719,"text":null},{"code":"// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // List to store tree static List []g; static int [,]memo; static int []lev; static int log; // Pre-processing to calculate // values of memo[,] static void dfs(int u, int p) { // Using recursion formula to // calculate the values of memo[,] memo[u, 0] = p; for (int i = 1; i <= log; i++) memo[u, i] = memo[memo[u, i - 1], i - 1]; foreach (int v in g[u]) { if (v != p) { // Calculating the level of each node lev[v] = lev[u] + 1; dfs(v, u); } } } // Function to return the LCA of // nodes u and v static int lca(int u, int v) { // The node which is present farthest // from the root node is taken as u // If v is farther from root node // then swap the two if (lev[u] < lev[v]) { int temp = u; u = v; v = temp; } // Finding the ancestor of u // which is at same level as v for (int i = log; i >= 0; i--) { if ((lev[u] - (int)Math.Pow(2, i)) >= lev[v]) u = memo[u, i]; } // If v is the ancestor of u // then v is the LCA of u and v if (u == v) return u; // Finding the node closest to the root // which is not the common ancestor of // u and v i.e. a node x such that // x is not the common ancestor of u // and v but memo[x,0] is for (int i = log; i >= 0; i--) { if (memo[u, i] != memo[v, i]) { u = memo[u, i]; v = memo[v, i]; } } // Returning the first ancestor // of above found node return memo[u, 0]; } // Driver code public static void Main(String []args) { // Number of nodes int n = 9; g = new List[n + 1]; // log(n) with base 2 log = (int)Math.Ceiling(Math.Log(n) / Math.Log(2)); memo = new int[n + 1, log + 1]; // Stores the level of each node lev = new int[n + 1]; // Initialising memo values with -1 for (int i = 0; i <= n; i++) for (int j = 0; j <= log; j++) memo[i, j] = -1; for (int i = 0; i <= n; i++) g[i] = new List(); // Add edges g[1].Add(2); g[2].Add(1); g[1].Add(3); g[3].Add(1); g[1].Add(4); g[4].Add(1); g[2].Add(5); g[5].Add(2); g[3].Add(6); g[6].Add(3); g[3].Add(7); g[7].Add(3); g[3].Add(8); g[8].Add(3); g[4].Add(9); g[9].Add(4); dfs(1, 1); Console.WriteLine(\"The LCA of 6 and 9 is \" + lca(6, 9)); Console.WriteLine(\"The LCA of 5 and 9 is \" + lca(5, 9)); Console.WriteLine(\"The LCA of 6 and 8 is \" + lca(6, 8)); Console.WriteLine(\"The LCA of 6 and 1 is \" + lca(6, 1)); }} // This code is contributed by PrinciRaj1992","e":13219,"s":9882,"text":null},{"code":"","e":16067,"s":13219,"text":null},{"code":null,"e":16163,"s":16067,"text":"The LCA of 6 and 9 is 1\nThe LCA of 5 and 9 is 1\nThe LCA of 6 and 8 is 3\nThe LCA of 6 and 1 is 1"},{"code":null,"e":16350,"s":16165,"text":"Time Complexity: The time taken in pre-processing is O(NlogN) and every query takes O(logN) time. So the overall time complexity of the solution is O(NlogN).Auxiliary Space: O(NlogN) "},{"code":null,"e":16364,"s":16350,"text":"princiraj1992"},{"code":null,"e":16376,"s":16364,"text":"sanjeev2552"},{"code":null,"e":16392,"s":16376,"text":"bpandey23012002"},{"code":null,"e":16401,"s":16392,"text":"darkhash"},{"code":null,"e":16412,"s":16401,"text":"decode2207"},{"code":null,"e":16428,"s":16412,"text":"pankajsharmagfg"},{"code":null,"e":16439,"s":16428,"text":"gaurav2146"},{"code":null,"e":16451,"s":16439,"text":"Binary Tree"},{"code":null,"e":16455,"s":16451,"text":"LCA"},{"code":null,"e":16471,"s":16455,"text":"Data Structures"},{"code":null,"e":16491,"s":16471,"text":"Dynamic Programming"},{"code":null,"e":16496,"s":16491,"text":"Tree"},{"code":null,"e":16512,"s":16496,"text":"Data Structures"},{"code":null,"e":16532,"s":16512,"text":"Dynamic Programming"},{"code":null,"e":16537,"s":16532,"text":"Tree"}],"string":"[\n {\n \"code\": null,\n \"e\": 52,\n \"s\": 24,\n \"text\": \"\\n04 Sep, 2021\"\n },\n {\n \"code\": null,\n \"e\": 421,\n \"s\": 52,\n \"text\": \"Given a binary tree, the task is to find the Lowest Common Ancestor of the given two nodes in the tree. Let G be a tree then LCA of two nodes u and v is defined as the node w in the tree which is an ancestor of both u and v and is farthest from the root node.If one node is the ancestor of another one than that particular node is the LCA of those two nodes.Example: \"\n },\n {\n \"code\": null,\n \"e\": 430,\n \"s\": 421,\n \"text\": \"Input: \"\n },\n {\n \"code\": null,\n \"e\": 540,\n \"s\": 430,\n \"text\": \"Output: The LCA of 6 and 9 is 1. The LCA of 5 and 9 is 1. The LCA of 6 and 8 is 3. The LCA of 6 and 1 is 1. \"\n },\n {\n \"code\": null,\n \"e\": 1043,\n \"s\": 540,\n \"text\": \"Approach: The article describes an approach known as Binary Lifting to find the Lowest Common Ancestor of two nodes in a tree. There can be many approaches to solve the LCA problem. We are discussing the Binary Lifting Technique, the others can be read from here and here. Binary Lifting is a dynamic programming approach where we pre-compute an array memo[1, n][1, log(n)] where memo[i][j] contains 2^j-th ancestor of node i. For computing the values of memo[][], the following recursion may be used \"\n },\n {\n \"code\": null,\n \"e\": 1057,\n \"s\": 1043,\n \"text\": \"memo state: \"\n },\n {\n \"code\": null,\n \"e\": 1116,\n \"s\": 1057,\n \"text\": \" memo[i][j] = i-th node’s 2^(j)th ancestor in the path \"\n },\n {\n \"code\": null,\n \"e\": 1139,\n \"s\": 1116,\n \"text\": \"memo initialization: \"\n },\n {\n \"code\": null,\n \"e\": 1209,\n \"s\": 1139,\n \"text\": \" memo[i][j] = memo[i][0] (first parent (2^0) of each node is given)\"\n },\n {\n \"code\": null,\n \"e\": 1221,\n \"s\": 1209,\n \"text\": \"memo trans:\"\n },\n {\n \"code\": null,\n \"e\": 1260,\n \"s\": 1221,\n \"text\": \" memo[i][j] = memo[ memo [i][j – 1]]\"\n },\n {\n \"code\": null,\n \"e\": 1310,\n \"s\": 1260,\n \"text\": \"meaning: A(i,2^j)=A( A(i , 2^(j-1) ) , 2^(j-1) ) \"\n },\n {\n \"code\": null,\n \"e\": 1444,\n \"s\": 1310,\n \"text\": \"To find the (2^j)-th ancestor of i, recursively find i-th node’s 2^(j-1)th ancestor’s 2^(j-1)th ancestor. (2^(j) = 2^(j-1) + 2^(j-1))\"\n },\n {\n \"code\": null,\n \"e\": 1448,\n \"s\": 1444,\n \"text\": \"So:\"\n },\n {\n \"code\": null,\n \"e\": 1537,\n \"s\": 1448,\n \"text\": \"memo[i][j] = parent[i] if j = 0 and memo[i][j] = memo[memo[i][j – 1]][j – 1] if j > 0. \"\n },\n {\n \"code\": null,\n \"e\": 2032,\n \"s\": 1537,\n \"text\": \"We first check whether a node is an ancestor of other or not and if one node is ancestor of other then it is the LCA of these two nodes otherwise we find a node which is not the common ancestor of both u and v and is highest(i.e. a node x such that x is not the common ancestor of u and v but memo[x][0] is) in the tree. After finding such a node (let it be x), we print the first ancestor of x i.e. memo[x][0] which will be the required LCA.Below is the implementation of the above approach: \"\n },\n {\n \"code\": null,\n \"e\": 2036,\n \"s\": 2032,\n \"text\": \"C++\"\n },\n {\n \"code\": null,\n \"e\": 2041,\n \"s\": 2036,\n \"text\": \"Java\"\n },\n {\n \"code\": null,\n \"e\": 2049,\n \"s\": 2041,\n \"text\": \"Python3\"\n },\n {\n \"code\": null,\n \"e\": 2052,\n \"s\": 2049,\n \"text\": \"C#\"\n },\n {\n \"code\": null,\n \"e\": 2063,\n \"s\": 2052,\n \"text\": \"Javascript\"\n },\n {\n \"code\": \"// C++ implementation of the approach#include using namespace std; // Pre-processing to calculate values of memo[][]void dfs(int u, int p, int **memo, int *lev, int log, vector *g){ // Using recursion formula to calculate // the values of memo[][] memo[u][0] = p; for (int i = 1; i <= log; i++) memo[u][i] = memo[memo[u][i - 1]][i - 1]; for (int v : g[u]) { if (v != p) { lev[v] = lev[u] + 1; dfs(v, u, memo, lev, log, g); } }} // Function to return the LCA of nodes u and vint lca(int u, int v, int log, int *lev, int **memo){ // The node which is present farthest // from the root node is taken as u // If v is farther from root node // then swap the two if (lev[u] < lev[v]) swap(u, v); // Finding the ancestor of u // which is at same level as v for (int i = log; i >= 0; i--) if ((lev[u] - pow(2, i)) >= lev[v]) u = memo[u][i]; // If v is the ancestor of u // then v is the LCA of u and v if (u == v) return u; // Finding the node closest to the root which is // not the common ancestor of u and v i.e. a node // x such that x is not the common ancestor of u // and v but memo[x][0] is for (int i = log; i >= 0; i--) { if (memo[u][i] != memo[v][i]) { u = memo[u][i]; v = memo[v][i]; } } // Returning the first ancestor // of above found node return memo[u][0];} // Driver Codeint main(){ // Number of nodes int n = 9; // vector to store tree vector g[n + 1]; int log = (int)ceil(log2(n)); int **memo = new int *[n + 1]; for (int i = 0; i < n + 1; i++) memo[i] = new int[log + 1]; // Stores the level of each node int *lev = new int[n + 1]; // Initialising memo values with -1 for (int i = 0; i <= n; i++) memset(memo[i], -1, sizeof memo[i]); // Add edges g[1].push_back(2); g[2].push_back(1); g[1].push_back(3); g[3].push_back(1); g[1].push_back(4); g[4].push_back(1); g[2].push_back(5); g[5].push_back(2); g[3].push_back(6); g[6].push_back(3); g[3].push_back(7); g[7].push_back(3); g[3].push_back(8); g[8].push_back(3); g[4].push_back(9); g[9].push_back(4); dfs(1, 1, memo, lev, log, g); cout << \\\"The LCA of 6 and 9 is \\\" << lca(6, 9, log, lev, memo) << endl; cout << \\\"The LCA of 5 and 9 is \\\" << lca(5, 9, log, lev, memo) << endl; cout << \\\"The LCA of 6 and 8 is \\\" << lca(6, 8, log, lev, memo) << endl; cout << \\\"The LCA of 6 and 1 is \\\" << lca(6, 1, log, lev, memo) << endl; return 0;} // This code is contributed by// sanjeev2552\",\n \"e\": 4757,\n \"s\": 2063,\n \"text\": null\n },\n {\n \"code\": \"// Java implementation of the approachimport java.util.*;public class GFG { // ArrayList to store tree static ArrayList g[]; static int memo[][], lev[], log; // Pre-processing to calculate values of memo[][] static void dfs(int u, int p) { // Using recursion formula to calculate // the values of memo[][] memo[u][0] = p; for (int i = 1; i <= log; i++) memo[u][i] = memo[memo[u][i - 1]][i - 1]; for (int v : g[u]) { if (v != p) { // Calculating the level of each node lev[v] = lev[u] + 1; dfs(v, u); } } } // Function to return the LCA of nodes u and v static int lca(int u, int v) { // The node which is present farthest // from the root node is taken as u // If v is farther from root node // then swap the two if (lev[u] < lev[v]) { int temp = u; u = v; v = temp; } // Finding the ancestor of u // which is at same level as v for (int i = log; i >= 0; i--) { if ((lev[u] - (int)Math.pow(2, i)) >= lev[v]) u = memo[u][i]; } // If v is the ancestor of u // then v is the LCA of u and v if (u == v) return u; // Finding the node closest to the root which is // not the common ancestor of u and v i.e. a node // x such that x is not the common ancestor of u // and v but memo[x][0] is for (int i = log; i >= 0; i--) { if (memo[u][i] != memo[v][i]) { u = memo[u][i]; v = memo[v][i]; } } // Returning the first ancestor // of above found node return memo[u][0]; } // Driver code public static void main(String args[]) { // Number of nodes int n = 9; g = new ArrayList[n + 1]; // log(n) with base 2 log = (int)Math.ceil(Math.log(n) / Math.log(2)); memo = new int[n + 1][log + 1]; // Stores the level of each node lev = new int[n + 1]; // Initialising memo values with -1 for (int i = 0; i <= n; i++) Arrays.fill(memo[i], -1); for (int i = 0; i <= n; i++) g[i] = new ArrayList<>(); // Add edges g[1].add(2); g[2].add(1); g[1].add(3); g[3].add(1); g[1].add(4); g[4].add(1); g[2].add(5); g[5].add(2); g[3].add(6); g[6].add(3); g[3].add(7); g[7].add(3); g[3].add(8); g[8].add(3); g[4].add(9); g[9].add(4); dfs(1, 1); System.out.println(\\\"The LCA of 6 and 9 is \\\" + lca(6, 9)); System.out.println(\\\"The LCA of 5 and 9 is \\\" + lca(5, 9)); System.out.println(\\\"The LCA of 6 and 8 is \\\" + lca(6, 8)); System.out.println(\\\"The LCA of 6 and 1 is \\\" + lca(6, 1)); }}\",\n \"e\": 7719,\n \"s\": 4757,\n \"text\": null\n },\n {\n \"code\": \"# Python3 implementation of the above approachimport math # Pre-processing to calculate values of memo[][]def dfs(u, p, memo, lev, log, g): # Using recursion formula to calculate # the values of memo[][] memo[u][0] = p for i in range(1, log + 1): memo[u][i] = memo[memo[u][i - 1]][i - 1] for v in g[u]: if v != p: lev[v] = lev[u] + 1 dfs(v, u, memo, lev, log, g) # Function to return the LCA of nodes u and vdef lca(u, v, log, lev, memo): # The node which is present farthest # from the root node is taken as u # If v is farther from root node # then swap the two if lev[u] < lev[v]: swap(u, v) # Finding the ancestor of u # which is at same level as v for i in range(log, -1, -1): if (lev[u] - pow(2, i)) >= lev[v]: u = memo[u][i] # If v is the ancestor of u # then v is the LCA of u and v if u == v: return v # Finding the node closest to the # root which is not the common ancestor # of u and v i.e. a node x such that x # is not the common ancestor of u # and v but memo[x][0] is for i in range(log, -1, -1): if memo[u][i] != memo[v][i]: u = memo[u][i] v = memo[v][i] # Returning the first ancestor # of above found node return memo[u][0] # Driver code # Number of nodesn = 9 log = math.ceil(math.log(n, 2))g = [[] for i in range(n + 1)] memo = [[-1 for i in range(log + 1)] for j in range(n + 1)] # Stores the level of each node lev = [0 for i in range(n + 1)] # Add edgesg[1].append(2)g[2].append(1)g[1].append(3)g[3].append(1)g[1].append(4)g[4].append(1)g[2].append(5)g[5].append(2)g[3].append(6)g[6].append(3)g[3].append(7)g[7].append(3)g[3].append(8)g[8].append(3)g[4].append(9)g[9].append(4) dfs(1, 1, memo, lev, log, g) print(\\\"The LCA of 6 and 9 is\\\", lca(6, 9, log, lev, memo))print(\\\"The LCA of 5 and 9 is\\\", lca(5, 9, log, lev, memo))print(\\\"The LCA of 6 and 8 is\\\", lca(6, 8, log, lev, memo))print(\\\"The LCA of 6 and 1 is\\\", lca(6, 1, log, lev, memo)) # This code is contributed by Bhaskar\",\n \"e\": 9882,\n \"s\": 7719,\n \"text\": null\n },\n {\n \"code\": \"// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // List to store tree static List []g; static int [,]memo; static int []lev; static int log; // Pre-processing to calculate // values of memo[,] static void dfs(int u, int p) { // Using recursion formula to // calculate the values of memo[,] memo[u, 0] = p; for (int i = 1; i <= log; i++) memo[u, i] = memo[memo[u, i - 1], i - 1]; foreach (int v in g[u]) { if (v != p) { // Calculating the level of each node lev[v] = lev[u] + 1; dfs(v, u); } } } // Function to return the LCA of // nodes u and v static int lca(int u, int v) { // The node which is present farthest // from the root node is taken as u // If v is farther from root node // then swap the two if (lev[u] < lev[v]) { int temp = u; u = v; v = temp; } // Finding the ancestor of u // which is at same level as v for (int i = log; i >= 0; i--) { if ((lev[u] - (int)Math.Pow(2, i)) >= lev[v]) u = memo[u, i]; } // If v is the ancestor of u // then v is the LCA of u and v if (u == v) return u; // Finding the node closest to the root // which is not the common ancestor of // u and v i.e. a node x such that // x is not the common ancestor of u // and v but memo[x,0] is for (int i = log; i >= 0; i--) { if (memo[u, i] != memo[v, i]) { u = memo[u, i]; v = memo[v, i]; } } // Returning the first ancestor // of above found node return memo[u, 0]; } // Driver code public static void Main(String []args) { // Number of nodes int n = 9; g = new List[n + 1]; // log(n) with base 2 log = (int)Math.Ceiling(Math.Log(n) / Math.Log(2)); memo = new int[n + 1, log + 1]; // Stores the level of each node lev = new int[n + 1]; // Initialising memo values with -1 for (int i = 0; i <= n; i++) for (int j = 0; j <= log; j++) memo[i, j] = -1; for (int i = 0; i <= n; i++) g[i] = new List(); // Add edges g[1].Add(2); g[2].Add(1); g[1].Add(3); g[3].Add(1); g[1].Add(4); g[4].Add(1); g[2].Add(5); g[5].Add(2); g[3].Add(6); g[6].Add(3); g[3].Add(7); g[7].Add(3); g[3].Add(8); g[8].Add(3); g[4].Add(9); g[9].Add(4); dfs(1, 1); Console.WriteLine(\\\"The LCA of 6 and 9 is \\\" + lca(6, 9)); Console.WriteLine(\\\"The LCA of 5 and 9 is \\\" + lca(5, 9)); Console.WriteLine(\\\"The LCA of 6 and 8 is \\\" + lca(6, 8)); Console.WriteLine(\\\"The LCA of 6 and 1 is \\\" + lca(6, 1)); }} // This code is contributed by PrinciRaj1992\",\n \"e\": 13219,\n \"s\": 9882,\n \"text\": null\n },\n {\n \"code\": \"\",\n \"e\": 16067,\n \"s\": 13219,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 16163,\n \"s\": 16067,\n \"text\": \"The LCA of 6 and 9 is 1\\nThe LCA of 5 and 9 is 1\\nThe LCA of 6 and 8 is 3\\nThe LCA of 6 and 1 is 1\"\n },\n {\n \"code\": null,\n \"e\": 16350,\n \"s\": 16165,\n \"text\": \"Time Complexity: The time taken in pre-processing is O(NlogN) and every query takes O(logN) time. So the overall time complexity of the solution is O(NlogN).Auxiliary Space: O(NlogN) \"\n },\n {\n \"code\": null,\n \"e\": 16364,\n \"s\": 16350,\n \"text\": \"princiraj1992\"\n },\n {\n \"code\": null,\n \"e\": 16376,\n \"s\": 16364,\n \"text\": \"sanjeev2552\"\n },\n {\n \"code\": null,\n \"e\": 16392,\n \"s\": 16376,\n \"text\": \"bpandey23012002\"\n },\n {\n \"code\": null,\n \"e\": 16401,\n \"s\": 16392,\n \"text\": \"darkhash\"\n },\n {\n \"code\": null,\n \"e\": 16412,\n \"s\": 16401,\n \"text\": \"decode2207\"\n },\n {\n \"code\": null,\n \"e\": 16428,\n \"s\": 16412,\n \"text\": \"pankajsharmagfg\"\n },\n {\n \"code\": null,\n \"e\": 16439,\n \"s\": 16428,\n \"text\": \"gaurav2146\"\n },\n {\n \"code\": null,\n \"e\": 16451,\n \"s\": 16439,\n \"text\": \"Binary Tree\"\n },\n {\n \"code\": null,\n \"e\": 16455,\n \"s\": 16451,\n \"text\": \"LCA\"\n },\n {\n \"code\": null,\n \"e\": 16471,\n \"s\": 16455,\n \"text\": \"Data Structures\"\n },\n {\n \"code\": null,\n \"e\": 16491,\n \"s\": 16471,\n \"text\": \"Dynamic Programming\"\n },\n {\n \"code\": null,\n \"e\": 16496,\n \"s\": 16491,\n \"text\": \"Tree\"\n },\n {\n \"code\": null,\n \"e\": 16512,\n \"s\": 16496,\n \"text\": \"Data Structures\"\n },\n {\n \"code\": null,\n \"e\": 16532,\n \"s\": 16512,\n \"text\": \"Dynamic Programming\"\n },\n {\n \"code\": null,\n \"e\": 16537,\n \"s\": 16532,\n \"text\": \"Tree\"\n }\n]"}}},{"rowIdx":136,"cells":{"title":{"kind":"string","value":"PyQt5 – setChecked() method for Check Box"},"text":{"kind":"string","value":"22 Apr, 2020\nsetChecked method is used to change the state of check box. By default it is un-checked after clicking on the check box widget its states get changed into checked, but with the help of setChecked method we can do it directly without clicking it.\nSyntax : checkbox.setChecked(True)\nArgument : It takes bool as argument.\nAction performed : It will change the state of check box.\nBelow is the implementation.\n# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating the check-box checkbox = QCheckBox('Check Box', self) # setting geometry of check box checkbox.setGeometry(200, 150, 100, 30) # setting check box state to checked checkbox.setChecked(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())\nOutput :\nPython-gui\nPython-PyQt\nPython\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nPython Dictionary\nDifferent ways to create Pandas Dataframe\nEnumerate() in Python\nRead a file line by line in Python\nPython String | replace()\nHow to Install PIP on Windows ?\n*args and **kwargs in Python\nPython Classes and Objects\nPython OOPs Concepts\nIterate over a list in Python"},"parsed":{"kind":"list like","value":[{"code":null,"e":28,"s":0,"text":"\n22 Apr, 2020"},{"code":null,"e":274,"s":28,"text":"setChecked method is used to change the state of check box. By default it is un-checked after clicking on the check box widget its states get changed into checked, but with the help of setChecked method we can do it directly without clicking it."},{"code":null,"e":309,"s":274,"text":"Syntax : checkbox.setChecked(True)"},{"code":null,"e":347,"s":309,"text":"Argument : It takes bool as argument."},{"code":null,"e":405,"s":347,"text":"Action performed : It will change the state of check box."},{"code":null,"e":434,"s":405,"text":"Below is the implementation."},{"code":"# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating the check-box checkbox = QCheckBox('Check Box', self) # setting geometry of check box checkbox.setGeometry(200, 150, 100, 30) # setting check box state to checked checkbox.setChecked(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())","e":1345,"s":434,"text":null},{"code":null,"e":1354,"s":1345,"text":"Output :"},{"code":null,"e":1365,"s":1354,"text":"Python-gui"},{"code":null,"e":1377,"s":1365,"text":"Python-PyQt"},{"code":null,"e":1384,"s":1377,"text":"Python"},{"code":null,"e":1482,"s":1384,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":1500,"s":1482,"text":"Python Dictionary"},{"code":null,"e":1542,"s":1500,"text":"Different ways to create Pandas Dataframe"},{"code":null,"e":1564,"s":1542,"text":"Enumerate() in Python"},{"code":null,"e":1599,"s":1564,"text":"Read a file line by line in Python"},{"code":null,"e":1625,"s":1599,"text":"Python String | replace()"},{"code":null,"e":1657,"s":1625,"text":"How to Install PIP on Windows ?"},{"code":null,"e":1686,"s":1657,"text":"*args and **kwargs in Python"},{"code":null,"e":1713,"s":1686,"text":"Python Classes and Objects"},{"code":null,"e":1734,"s":1713,"text":"Python OOPs Concepts"}],"string":"[\n {\n \"code\": null,\n \"e\": 28,\n \"s\": 0,\n \"text\": \"\\n22 Apr, 2020\"\n },\n {\n \"code\": null,\n \"e\": 274,\n \"s\": 28,\n \"text\": \"setChecked method is used to change the state of check box. By default it is un-checked after clicking on the check box widget its states get changed into checked, but with the help of setChecked method we can do it directly without clicking it.\"\n },\n {\n \"code\": null,\n \"e\": 309,\n \"s\": 274,\n \"text\": \"Syntax : checkbox.setChecked(True)\"\n },\n {\n \"code\": null,\n \"e\": 347,\n \"s\": 309,\n \"text\": \"Argument : It takes bool as argument.\"\n },\n {\n \"code\": null,\n \"e\": 405,\n \"s\": 347,\n \"text\": \"Action performed : It will change the state of check box.\"\n },\n {\n \"code\": null,\n \"e\": 434,\n \"s\": 405,\n \"text\": \"Below is the implementation.\"\n },\n {\n \"code\": \"# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\\\"Python \\\") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating the check-box checkbox = QCheckBox('Check Box', self) # setting geometry of check box checkbox.setGeometry(200, 150, 100, 30) # setting check box state to checked checkbox.setChecked(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())\",\n \"e\": 1345,\n \"s\": 434,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 1354,\n \"s\": 1345,\n \"text\": \"Output :\"\n },\n {\n \"code\": null,\n \"e\": 1365,\n \"s\": 1354,\n \"text\": \"Python-gui\"\n },\n {\n \"code\": null,\n \"e\": 1377,\n \"s\": 1365,\n \"text\": \"Python-PyQt\"\n },\n {\n \"code\": null,\n \"e\": 1384,\n \"s\": 1377,\n \"text\": \"Python\"\n },\n {\n \"code\": null,\n \"e\": 1482,\n \"s\": 1384,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 1500,\n \"s\": 1482,\n \"text\": \"Python Dictionary\"\n },\n {\n \"code\": null,\n \"e\": 1542,\n \"s\": 1500,\n \"text\": \"Different ways to create Pandas Dataframe\"\n },\n {\n \"code\": null,\n \"e\": 1564,\n \"s\": 1542,\n \"text\": \"Enumerate() in Python\"\n },\n {\n \"code\": null,\n \"e\": 1599,\n \"s\": 1564,\n \"text\": \"Read a file line by line in Python\"\n },\n {\n \"code\": null,\n \"e\": 1625,\n \"s\": 1599,\n \"text\": \"Python String | replace()\"\n },\n {\n \"code\": null,\n \"e\": 1657,\n \"s\": 1625,\n \"text\": \"How to Install PIP on Windows ?\"\n },\n {\n \"code\": null,\n \"e\": 1686,\n \"s\": 1657,\n \"text\": \"*args and **kwargs in Python\"\n },\n {\n \"code\": null,\n \"e\": 1713,\n \"s\": 1686,\n \"text\": \"Python Classes and Objects\"\n },\n {\n \"code\": null,\n \"e\": 1734,\n \"s\": 1713,\n \"text\": \"Python OOPs Concepts\"\n }\n]"}}},{"rowIdx":137,"cells":{"title":{"kind":"string","value":"How to use php serialize() and unserialize() Function"},"text":{"kind":"string","value":"30 Sep, 2019\nIn PHP, the complex data can not be transported or can not be stored. If you want to execute continuously a complex set of data beyond a single script then this serialize() and unserialize() functions are handy to deal with those complex data structures. The serialize() function is just given a compatible shape to a complex data structure that the PHP can handle that data after that you can reverse the work by using the unserialize() function.\nMost often, we need to store a complex array in the database or in a file from PHP. Some of us might have surely searched for some built-in function to accomplish this task. Complex arrays are arrays with elements of more than one data-types or array. But, we already have a handy solution to handle this situation.\nSerialize() Function: The serialize() is an inbuilt function PHP that is used to serialize the given array. The serialize() function accepts a single parameter which is the data we want to serialize and returns a serialized string.\nSyntax:serialize( $values_in_form_of_array )\nserialize( $values_in_form_of_array )\nBelow program illustrate the Serialize() function.Program: \n \nOutput:a:4:{i:0;s:5:\"hello\";i:1;i:42;i:2;a:2:{i:\n0;i:1;i:1;s:3:\"two\";}i:3;s:5:\"apple\";}\na:4:{i:0;s:5:\"hello\";i:1;i:42;i:2;a:2:{i:\n0;i:1;i:1;s:3:\"two\";}i:3;s:5:\"apple\";}\nUnserialize() Function: The unserialize() is an inbuilt function php that is used to unserialize the given serialized array to get back to the original value of the complex array, $myvar.\nSyntax:unserialize( $serialized_array )\nunserialize( $serialized_array )\nBelow program illustrate both serialize() and unserialize() functions:Program: \n \nOutput:Array\n(\n [0] => hello\n [1] => 42\n [2] => Array\n (\n [0] => 1\n [1] => two\n )\n\n [3] => apple\n)\n\nArray\n(\n [0] => hello\n [1] => 42\n [2] => Array\n (\n [0] => 1\n [1] => two\n )\n\n [3] => apple\n)\n\nNote: For more depth knowledge you can check PHP | Serializing Data article.\nPHP-basics\nPicked\nPHP\nWeb Technologies\nPHP\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nHow to execute PHP code using command line ?\nHow to Insert Form Data into Database using PHP ?\nPHP in_array() Function\nHow to delete an array element based on key in PHP?\nHow to pop an alert message box using PHP ?\nTop 10 Projects For Beginners To Practice HTML and CSS Skills\nInstallation of Node.js on Linux\nDifference between var, let and const keywords in JavaScript\nHow to insert spaces/tabs in text using HTML/CSS?\nHow to fetch data from an API in ReactJS ?"},"parsed":{"kind":"list like","value":[{"code":null,"e":28,"s":0,"text":"\n30 Sep, 2019"},{"code":null,"e":476,"s":28,"text":"In PHP, the complex data can not be transported or can not be stored. If you want to execute continuously a complex set of data beyond a single script then this serialize() and unserialize() functions are handy to deal with those complex data structures. The serialize() function is just given a compatible shape to a complex data structure that the PHP can handle that data after that you can reverse the work by using the unserialize() function."},{"code":null,"e":792,"s":476,"text":"Most often, we need to store a complex array in the database or in a file from PHP. Some of us might have surely searched for some built-in function to accomplish this task. Complex arrays are arrays with elements of more than one data-types or array. But, we already have a handy solution to handle this situation."},{"code":null,"e":1024,"s":792,"text":"Serialize() Function: The serialize() is an inbuilt function PHP that is used to serialize the given array. The serialize() function accepts a single parameter which is the data we want to serialize and returns a serialized string."},{"code":null,"e":1069,"s":1024,"text":"Syntax:serialize( $values_in_form_of_array )"},{"code":null,"e":1107,"s":1069,"text":"serialize( $values_in_form_of_array )"},{"code":null,"e":1370,"s":1107,"text":"Below program illustrate the Serialize() function.Program: "},{"code":" ","e":1575,"s":1370,"text":null},{"code":null,"e":1663,"s":1575,"text":"Output:a:4:{i:0;s:5:\"hello\";i:1;i:42;i:2;a:2:{i:\n0;i:1;i:1;s:3:\"two\";}i:3;s:5:\"apple\";}"},{"code":null,"e":1744,"s":1663,"text":"a:4:{i:0;s:5:\"hello\";i:1;i:42;i:2;a:2:{i:\n0;i:1;i:1;s:3:\"two\";}i:3;s:5:\"apple\";}"},{"code":null,"e":1932,"s":1744,"text":"Unserialize() Function: The unserialize() is an inbuilt function php that is used to unserialize the given serialized array to get back to the original value of the complex array, $myvar."},{"code":null,"e":1972,"s":1932,"text":"Syntax:unserialize( $serialized_array )"},{"code":null,"e":2005,"s":1972,"text":"unserialize( $serialized_array )"},{"code":null,"e":2370,"s":2005,"text":"Below program illustrate both serialize() and unserialize() functions:Program: "},{"code":" ","e":2657,"s":2370,"text":null},{"code":null,"e":2805,"s":2657,"text":"Output:Array\n(\n [0] => hello\n [1] => 42\n [2] => Array\n (\n [0] => 1\n [1] => two\n )\n\n [3] => apple\n)\n"},{"code":null,"e":2946,"s":2805,"text":"Array\n(\n [0] => hello\n [1] => 42\n [2] => Array\n (\n [0] => 1\n [1] => two\n )\n\n [3] => apple\n)\n"},{"code":null,"e":3023,"s":2946,"text":"Note: For more depth knowledge you can check PHP | Serializing Data article."},{"code":null,"e":3034,"s":3023,"text":"PHP-basics"},{"code":null,"e":3041,"s":3034,"text":"Picked"},{"code":null,"e":3045,"s":3041,"text":"PHP"},{"code":null,"e":3062,"s":3045,"text":"Web Technologies"},{"code":null,"e":3066,"s":3062,"text":"PHP"},{"code":null,"e":3164,"s":3066,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":3209,"s":3164,"text":"How to execute PHP code using command line ?"},{"code":null,"e":3259,"s":3209,"text":"How to Insert Form Data into Database using PHP ?"},{"code":null,"e":3283,"s":3259,"text":"PHP in_array() Function"},{"code":null,"e":3335,"s":3283,"text":"How to delete an array element based on key in PHP?"},{"code":null,"e":3379,"s":3335,"text":"How to pop an alert message box using PHP ?"},{"code":null,"e":3441,"s":3379,"text":"Top 10 Projects For Beginners To Practice HTML and CSS Skills"},{"code":null,"e":3474,"s":3441,"text":"Installation of Node.js on Linux"},{"code":null,"e":3535,"s":3474,"text":"Difference between var, let and const keywords in JavaScript"},{"code":null,"e":3585,"s":3535,"text":"How to insert spaces/tabs in text using HTML/CSS?"}],"string":"[\n {\n \"code\": null,\n \"e\": 28,\n \"s\": 0,\n \"text\": \"\\n30 Sep, 2019\"\n },\n {\n \"code\": null,\n \"e\": 476,\n \"s\": 28,\n \"text\": \"In PHP, the complex data can not be transported or can not be stored. If you want to execute continuously a complex set of data beyond a single script then this serialize() and unserialize() functions are handy to deal with those complex data structures. The serialize() function is just given a compatible shape to a complex data structure that the PHP can handle that data after that you can reverse the work by using the unserialize() function.\"\n },\n {\n \"code\": null,\n \"e\": 792,\n \"s\": 476,\n \"text\": \"Most often, we need to store a complex array in the database or in a file from PHP. Some of us might have surely searched for some built-in function to accomplish this task. Complex arrays are arrays with elements of more than one data-types or array. But, we already have a handy solution to handle this situation.\"\n },\n {\n \"code\": null,\n \"e\": 1024,\n \"s\": 792,\n \"text\": \"Serialize() Function: The serialize() is an inbuilt function PHP that is used to serialize the given array. The serialize() function accepts a single parameter which is the data we want to serialize and returns a serialized string.\"\n },\n {\n \"code\": null,\n \"e\": 1069,\n \"s\": 1024,\n \"text\": \"Syntax:serialize( $values_in_form_of_array )\"\n },\n {\n \"code\": null,\n \"e\": 1107,\n \"s\": 1069,\n \"text\": \"serialize( $values_in_form_of_array )\"\n },\n {\n \"code\": null,\n \"e\": 1370,\n \"s\": 1107,\n \"text\": \"Below program illustrate the Serialize() function.Program: \"\n },\n {\n \"code\": \" \",\n \"e\": 1575,\n \"s\": 1370,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 1663,\n \"s\": 1575,\n \"text\": \"Output:a:4:{i:0;s:5:\\\"hello\\\";i:1;i:42;i:2;a:2:{i:\\n0;i:1;i:1;s:3:\\\"two\\\";}i:3;s:5:\\\"apple\\\";}\"\n },\n {\n \"code\": null,\n \"e\": 1744,\n \"s\": 1663,\n \"text\": \"a:4:{i:0;s:5:\\\"hello\\\";i:1;i:42;i:2;a:2:{i:\\n0;i:1;i:1;s:3:\\\"two\\\";}i:3;s:5:\\\"apple\\\";}\"\n },\n {\n \"code\": null,\n \"e\": 1932,\n \"s\": 1744,\n \"text\": \"Unserialize() Function: The unserialize() is an inbuilt function php that is used to unserialize the given serialized array to get back to the original value of the complex array, $myvar.\"\n },\n {\n \"code\": null,\n \"e\": 1972,\n \"s\": 1932,\n \"text\": \"Syntax:unserialize( $serialized_array )\"\n },\n {\n \"code\": null,\n \"e\": 2005,\n \"s\": 1972,\n \"text\": \"unserialize( $serialized_array )\"\n },\n {\n \"code\": null,\n \"e\": 2370,\n \"s\": 2005,\n \"text\": \"Below program illustrate both serialize() and unserialize() functions:Program: \"\n },\n {\n \"code\": \" \",\n \"e\": 2657,\n \"s\": 2370,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 2805,\n \"s\": 2657,\n \"text\": \"Output:Array\\n(\\n [0] => hello\\n [1] => 42\\n [2] => Array\\n (\\n [0] => 1\\n [1] => two\\n )\\n\\n [3] => apple\\n)\\n\"\n },\n {\n \"code\": null,\n \"e\": 2946,\n \"s\": 2805,\n \"text\": \"Array\\n(\\n [0] => hello\\n [1] => 42\\n [2] => Array\\n (\\n [0] => 1\\n [1] => two\\n )\\n\\n [3] => apple\\n)\\n\"\n },\n {\n \"code\": null,\n \"e\": 3023,\n \"s\": 2946,\n \"text\": \"Note: For more depth knowledge you can check PHP | Serializing Data article.\"\n },\n {\n \"code\": null,\n \"e\": 3034,\n \"s\": 3023,\n \"text\": \"PHP-basics\"\n },\n {\n \"code\": null,\n \"e\": 3041,\n \"s\": 3034,\n \"text\": \"Picked\"\n },\n {\n \"code\": null,\n \"e\": 3045,\n \"s\": 3041,\n \"text\": \"PHP\"\n },\n {\n \"code\": null,\n \"e\": 3062,\n \"s\": 3045,\n \"text\": \"Web Technologies\"\n },\n {\n \"code\": null,\n \"e\": 3066,\n \"s\": 3062,\n \"text\": \"PHP\"\n },\n {\n \"code\": null,\n \"e\": 3164,\n \"s\": 3066,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 3209,\n \"s\": 3164,\n \"text\": \"How to execute PHP code using command line ?\"\n },\n {\n \"code\": null,\n \"e\": 3259,\n \"s\": 3209,\n \"text\": \"How to Insert Form Data into Database using PHP ?\"\n },\n {\n \"code\": null,\n \"e\": 3283,\n \"s\": 3259,\n \"text\": \"PHP in_array() Function\"\n },\n {\n \"code\": null,\n \"e\": 3335,\n \"s\": 3283,\n \"text\": \"How to delete an array element based on key in PHP?\"\n },\n {\n \"code\": null,\n \"e\": 3379,\n \"s\": 3335,\n \"text\": \"How to pop an alert message box using PHP ?\"\n },\n {\n \"code\": null,\n \"e\": 3441,\n \"s\": 3379,\n \"text\": \"Top 10 Projects For Beginners To Practice HTML and CSS Skills\"\n },\n {\n \"code\": null,\n \"e\": 3474,\n \"s\": 3441,\n \"text\": \"Installation of Node.js on Linux\"\n },\n {\n \"code\": null,\n \"e\": 3535,\n \"s\": 3474,\n \"text\": \"Difference between var, let and const keywords in JavaScript\"\n },\n {\n \"code\": null,\n \"e\": 3585,\n \"s\": 3535,\n \"text\": \"How to insert spaces/tabs in text using HTML/CSS?\"\n }\n]"}}},{"rowIdx":138,"cells":{"title":{"kind":"string","value":"How to copy text to the clipboard in React.js ?"},"text":{"kind":"string","value":"12 Mar, 2021\nThe following example covers how to copy text to the clipboard in React JS using useState() hook.\nPrerequisite:\nBasic knowledge of npm & create-react-app command.\nBasic knowledge of styled-components.\nBasic Knowledge of useState() React hooks.\nBasic Setup: You will start a new project using create-react-app using the following command:\nnpx create-react-app react-copy-text\nNow go to your react-copy-text folder by typing the given command in the terminal.\ncd react-copy-text\nRequired module: Install the dependencies required in this project by typing the given command in the terminal.\nnpm install --save styled-components\nnpm install --save react-copy-to-clipboard\nNow create the components folder in src then go to the components folder and create two files Clipboard.js and Styles.js.\nProject Structure: The file structure in the project will look like this.\nExample: We create a state with the first element copyText as an initial state having a value of the empty string and the second element as function setCopyText() for updating the state. Then a function is created by the name handleCopyText which sets the state value to the text we enter the input field. Another function copyToClipboard is created to copy the updated state value to the clipboard.\nWhen we enter a text in our input field, handleCopyText function gets triggered through onChange event which sets the state to that entered value. Now when we click on the button ‘Copy to Clipboard’, the function copyToClipboard gets triggered through onClick event which copies the state value to the clipboard with copy() function. Now we can copy our text anywhere by just clicking Ctrl+V key.\nClipboard.js\nimport React,{useState} from 'react'import copy from \"copy-to-clipboard\"; import { Heading, Input1, Input2, Container, Button } from './Styles' const Clipboard = () => { const [copyText, setCopyText] = useState(''); const handleCopyText = (e) => { setCopyText(e.target.value); } const copyToClipboard = () => { copy(copyText); alert(`You have copied \"${copyText}\"`); } return (
GeeksForGeeks
)} export default Clipboard;\nStyles.js\nimport styled from 'styled-components'; export const Container = styled.div` width: 600px; margin: 40px auto; position: relative;`export const Heading = styled.h1` text-align: center; color: green;`; export const Input1 = styled.input` height: 50px; width: 100%; padding: 0; font-size: 25px;`export const Input2 = styled.input` height: 50px; width: 100%; padding: 0; font-size: 25px; margin-top: 70px;` export const Button = styled.button` padding: 20px; font-size: 20px; position: relative; left: 30%; margin-top: 10px; cursor: pointer;`;\nApp.js\nimport Clipboard from './components/Clipboard' function App() { return ( );} export default App;\nStep to Run Application: Run the application using the following command from the root directory of the project:\nnpm start\nOutput: Now open your browser and go to http://localhost:3000/, you will see the following output:\nReact-Questions\nReactJS\nWeb Technologies\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nAxios in React: A Guide for Beginners\nReactJS useNavigate() Hook\nHow to install bootstrap in React.js ?\nHow to create a multi-page website using React.js ?\nHow to do crud operations in ReactJS ?\nInstallation of Node.js on Linux\nTop 10 Projects For Beginners To Practice HTML and CSS Skills\nDifference between var, let and const keywords in JavaScript\nHow to insert spaces/tabs in text using HTML/CSS?\nDifferences between Functional Components and Class Components in React"},"parsed":{"kind":"list like","value":[{"code":null,"e":52,"s":24,"text":"\n12 Mar, 2021"},{"code":null,"e":150,"s":52,"text":"The following example covers how to copy text to the clipboard in React JS using useState() hook."},{"code":null,"e":164,"s":150,"text":"Prerequisite:"},{"code":null,"e":215,"s":164,"text":"Basic knowledge of npm & create-react-app command."},{"code":null,"e":253,"s":215,"text":"Basic knowledge of styled-components."},{"code":null,"e":296,"s":253,"text":"Basic Knowledge of useState() React hooks."},{"code":null,"e":390,"s":296,"text":"Basic Setup: You will start a new project using create-react-app using the following command:"},{"code":null,"e":427,"s":390,"text":"npx create-react-app react-copy-text"},{"code":null,"e":510,"s":427,"text":"Now go to your react-copy-text folder by typing the given command in the terminal."},{"code":null,"e":529,"s":510,"text":"cd react-copy-text"},{"code":null,"e":641,"s":529,"text":"Required module: Install the dependencies required in this project by typing the given command in the terminal."},{"code":null,"e":721,"s":641,"text":"npm install --save styled-components\nnpm install --save react-copy-to-clipboard"},{"code":null,"e":843,"s":721,"text":"Now create the components folder in src then go to the components folder and create two files Clipboard.js and Styles.js."},{"code":null,"e":917,"s":843,"text":"Project Structure: The file structure in the project will look like this."},{"code":null,"e":1317,"s":917,"text":"Example: We create a state with the first element copyText as an initial state having a value of the empty string and the second element as function setCopyText() for updating the state. Then a function is created by the name handleCopyText which sets the state value to the text we enter the input field. Another function copyToClipboard is created to copy the updated state value to the clipboard."},{"code":null,"e":1714,"s":1317,"text":"When we enter a text in our input field, handleCopyText function gets triggered through onChange event which sets the state to that entered value. Now when we click on the button ‘Copy to Clipboard’, the function copyToClipboard gets triggered through onClick event which copies the state value to the clipboard with copy() function. Now we can copy our text anywhere by just clicking Ctrl+V key."},{"code":null,"e":1727,"s":1714,"text":"Clipboard.js"},{"code":"import React,{useState} from 'react'import copy from \"copy-to-clipboard\"; import { Heading, Input1, Input2, Container, Button } from './Styles' const Clipboard = () => { const [copyText, setCopyText] = useState(''); const handleCopyText = (e) => { setCopyText(e.target.value); } const copyToClipboard = () => { copy(copyText); alert(`You have copied \"${copyText}\"`); } return (
GeeksForGeeks
)} export default Clipboard;","e":2691,"s":1727,"text":null},{"code":null,"e":2701,"s":2691,"text":"Styles.js"},{"code":"import styled from 'styled-components'; export const Container = styled.div` width: 600px; margin: 40px auto; position: relative;`export const Heading = styled.h1` text-align: center; color: green;`; export const Input1 = styled.input` height: 50px; width: 100%; padding: 0; font-size: 25px;`export const Input2 = styled.input` height: 50px; width: 100%; padding: 0; font-size: 25px; margin-top: 70px;` export const Button = styled.button` padding: 20px; font-size: 20px; position: relative; left: 30%; margin-top: 10px; cursor: pointer;`;","e":3284,"s":2701,"text":null},{"code":null,"e":3291,"s":3284,"text":"App.js"},{"code":"import Clipboard from './components/Clipboard' function App() { return ( );} export default App;","e":3409,"s":3291,"text":null},{"code":null,"e":3522,"s":3409,"text":"Step to Run Application: Run the application using the following command from the root directory of the project:"},{"code":null,"e":3532,"s":3522,"text":"npm start"},{"code":null,"e":3631,"s":3532,"text":"Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"},{"code":null,"e":3647,"s":3631,"text":"React-Questions"},{"code":null,"e":3655,"s":3647,"text":"ReactJS"},{"code":null,"e":3672,"s":3655,"text":"Web Technologies"},{"code":null,"e":3770,"s":3672,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":3808,"s":3770,"text":"Axios in React: A Guide for Beginners"},{"code":null,"e":3835,"s":3808,"text":"ReactJS useNavigate() Hook"},{"code":null,"e":3874,"s":3835,"text":"How to install bootstrap in React.js ?"},{"code":null,"e":3926,"s":3874,"text":"How to create a multi-page website using React.js ?"},{"code":null,"e":3965,"s":3926,"text":"How to do crud operations in ReactJS ?"},{"code":null,"e":3998,"s":3965,"text":"Installation of Node.js on Linux"},{"code":null,"e":4060,"s":3998,"text":"Top 10 Projects For Beginners To Practice HTML and CSS Skills"},{"code":null,"e":4121,"s":4060,"text":"Difference between var, let and const keywords in JavaScript"},{"code":null,"e":4171,"s":4121,"text":"How to insert spaces/tabs in text using HTML/CSS?"}],"string":"[\n {\n \"code\": null,\n \"e\": 52,\n \"s\": 24,\n \"text\": \"\\n12 Mar, 2021\"\n },\n {\n \"code\": null,\n \"e\": 150,\n \"s\": 52,\n \"text\": \"The following example covers how to copy text to the clipboard in React JS using useState() hook.\"\n },\n {\n \"code\": null,\n \"e\": 164,\n \"s\": 150,\n \"text\": \"Prerequisite:\"\n },\n {\n \"code\": null,\n \"e\": 215,\n \"s\": 164,\n \"text\": \"Basic knowledge of npm & create-react-app command.\"\n },\n {\n \"code\": null,\n \"e\": 253,\n \"s\": 215,\n \"text\": \"Basic knowledge of styled-components.\"\n },\n {\n \"code\": null,\n \"e\": 296,\n \"s\": 253,\n \"text\": \"Basic Knowledge of useState() React hooks.\"\n },\n {\n \"code\": null,\n \"e\": 390,\n \"s\": 296,\n \"text\": \"Basic Setup: You will start a new project using create-react-app using the following command:\"\n },\n {\n \"code\": null,\n \"e\": 427,\n \"s\": 390,\n \"text\": \"npx create-react-app react-copy-text\"\n },\n {\n \"code\": null,\n \"e\": 510,\n \"s\": 427,\n \"text\": \"Now go to your react-copy-text folder by typing the given command in the terminal.\"\n },\n {\n \"code\": null,\n \"e\": 529,\n \"s\": 510,\n \"text\": \"cd react-copy-text\"\n },\n {\n \"code\": null,\n \"e\": 641,\n \"s\": 529,\n \"text\": \"Required module: Install the dependencies required in this project by typing the given command in the terminal.\"\n },\n {\n \"code\": null,\n \"e\": 721,\n \"s\": 641,\n \"text\": \"npm install --save styled-components\\nnpm install --save react-copy-to-clipboard\"\n },\n {\n \"code\": null,\n \"e\": 843,\n \"s\": 721,\n \"text\": \"Now create the components folder in src then go to the components folder and create two files Clipboard.js and Styles.js.\"\n },\n {\n \"code\": null,\n \"e\": 917,\n \"s\": 843,\n \"text\": \"Project Structure: The file structure in the project will look like this.\"\n },\n {\n \"code\": null,\n \"e\": 1317,\n \"s\": 917,\n \"text\": \"Example: We create a state with the first element copyText as an initial state having a value of the empty string and the second element as function setCopyText() for updating the state. Then a function is created by the name handleCopyText which sets the state value to the text we enter the input field. Another function copyToClipboard is created to copy the updated state value to the clipboard.\"\n },\n {\n \"code\": null,\n \"e\": 1714,\n \"s\": 1317,\n \"text\": \"When we enter a text in our input field, handleCopyText function gets triggered through onChange event which sets the state to that entered value. Now when we click on the button ‘Copy to Clipboard’, the function copyToClipboard gets triggered through onClick event which copies the state value to the clipboard with copy() function. Now we can copy our text anywhere by just clicking Ctrl+V key.\"\n },\n {\n \"code\": null,\n \"e\": 1727,\n \"s\": 1714,\n \"text\": \"Clipboard.js\"\n },\n {\n \"code\": \"import React,{useState} from 'react'import copy from \\\"copy-to-clipboard\\\"; import { Heading, Input1, Input2, Container, Button } from './Styles' const Clipboard = () => { const [copyText, setCopyText] = useState(''); const handleCopyText = (e) => { setCopyText(e.target.value); } const copyToClipboard = () => { copy(copyText); alert(`You have copied \\\"${copyText}\\\"`); } return (
GeeksForGeeks
)} export default Clipboard;\",\n \"e\": 2691,\n \"s\": 1727,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 2701,\n \"s\": 2691,\n \"text\": \"Styles.js\"\n },\n {\n \"code\": \"import styled from 'styled-components'; export const Container = styled.div` width: 600px; margin: 40px auto; position: relative;`export const Heading = styled.h1` text-align: center; color: green;`; export const Input1 = styled.input` height: 50px; width: 100%; padding: 0; font-size: 25px;`export const Input2 = styled.input` height: 50px; width: 100%; padding: 0; font-size: 25px; margin-top: 70px;` export const Button = styled.button` padding: 20px; font-size: 20px; position: relative; left: 30%; margin-top: 10px; cursor: pointer;`;\",\n \"e\": 3284,\n \"s\": 2701,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 3291,\n \"s\": 3284,\n \"text\": \"App.js\"\n },\n {\n \"code\": \"import Clipboard from './components/Clipboard' function App() { return ( );} export default App;\",\n \"e\": 3409,\n \"s\": 3291,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 3522,\n \"s\": 3409,\n \"text\": \"Step to Run Application: Run the application using the following command from the root directory of the project:\"\n },\n {\n \"code\": null,\n \"e\": 3532,\n \"s\": 3522,\n \"text\": \"npm start\"\n },\n {\n \"code\": null,\n \"e\": 3631,\n \"s\": 3532,\n \"text\": \"Output: Now open your browser and go to http://localhost:3000/, you will see the following output:\"\n },\n {\n \"code\": null,\n \"e\": 3647,\n \"s\": 3631,\n \"text\": \"React-Questions\"\n },\n {\n \"code\": null,\n \"e\": 3655,\n \"s\": 3647,\n \"text\": \"ReactJS\"\n },\n {\n \"code\": null,\n \"e\": 3672,\n \"s\": 3655,\n \"text\": \"Web Technologies\"\n },\n {\n \"code\": null,\n \"e\": 3770,\n \"s\": 3672,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 3808,\n \"s\": 3770,\n \"text\": \"Axios in React: A Guide for Beginners\"\n },\n {\n \"code\": null,\n \"e\": 3835,\n \"s\": 3808,\n \"text\": \"ReactJS useNavigate() Hook\"\n },\n {\n \"code\": null,\n \"e\": 3874,\n \"s\": 3835,\n \"text\": \"How to install bootstrap in React.js ?\"\n },\n {\n \"code\": null,\n \"e\": 3926,\n \"s\": 3874,\n \"text\": \"How to create a multi-page website using React.js ?\"\n },\n {\n \"code\": null,\n \"e\": 3965,\n \"s\": 3926,\n \"text\": \"How to do crud operations in ReactJS ?\"\n },\n {\n \"code\": null,\n \"e\": 3998,\n \"s\": 3965,\n \"text\": \"Installation of Node.js on Linux\"\n },\n {\n \"code\": null,\n \"e\": 4060,\n \"s\": 3998,\n \"text\": \"Top 10 Projects For Beginners To Practice HTML and CSS Skills\"\n },\n {\n \"code\": null,\n \"e\": 4121,\n \"s\": 4060,\n \"text\": \"Difference between var, let and const keywords in JavaScript\"\n },\n {\n \"code\": null,\n \"e\": 4171,\n \"s\": 4121,\n \"text\": \"How to insert spaces/tabs in text using HTML/CSS?\"\n }\n]"}}},{"rowIdx":139,"cells":{"title":{"kind":"string","value":"VueJS - Directives"},"text":{"kind":"string","value":"Directives are instruction for VueJS to do things in a certain way. We have already seen directives such as v-if, v-show, v-else, v-for, v-bind , v-model, v-on, etc.\nIn this chapter, we will take a look at custom directives. We will create global directives similar to how we did for components.\nVue.directive('nameofthedirective', {\n bind(e1, binding, vnode) {\n }\n})\n\nWe need to create a directive using Vue.directive. It takes the name of the directive as shown above. Let us consider an example to show the details of the working of directives.\n\n \n VueJs Instance\n \n \n \n
\n
VueJS Directive
\n
\n \n \n\nIn this example, we have created a custom directive changestyle as shown in the following piece of code.\nVue.directive(\"changestyle\",{\n bind(e1,binding, vnode) {\n console.log(e1);\n e1.style.color = \"red\";\n e1.style.fontSize = \"30px\";\n }\n});\nWe are assigning the following changestyle to a div.\n
VueJS Directive
\nIf we see in the browser, it will display the text VueJs Directive in red color and the fontsize is increased to 30px.\nWe have used the bind method, which is a part of the directive. It takes three arguments e1, the element to which the custom directive needs to be applied. Binding is like arguments passed to the custom directive, e.g. v-changestyle = ”{color:’green’}”, where green will be read in the binding argument and vnode is the element, i.e. nodename.\nIn the next example, we have consoled all the arguments and its shows what details each of them give.\nFollowing is an example with a value passed to the custom directive.\n\n \n VueJs Instance\n \n \n \n
\n
VueJS Directive
\n
\n \n \n\nThe color of the text is changed to green. The value is passed using the following piece of code.\n
VueJS Directive
\nAnd it is accessed using the following piece of code.\nVue.directive(\"changestyle\",{\n bind(e1,binding, vnode) {\n console.log(e1);\n console.log(binding.value.color);\n console.log(vnode);\n e1.style.color=binding.value.color;\n e1.style.fontSize = \"30px\";\n }\n});\nVueJS supports filters that help with text formatting. It is used along with v-bind and interpolations ({{}}). We need a pipe symbol at the end of JavaScript expression for filters.\n\n \n VueJs Instance\n \n \n \n
\n
\n Letter count is : {{name | countletters}}\n
\n \n \n\nIn the above example, we have created a simple filter countletters. Countletters filter counts the numbers of characters entered in the textbox. To make use of filters, we need to use the filter property and define the filter used, by the following piece of code.\nfilters : {\n countletters : function(value) {\n return value.length;\n }\n}\nWe are defining the method countletters and returning the length of the string entered.\nTo use filter in the display, we have used the pipe operator and the name of the filter, i.e. countletters.\nLetter count is : {{name | countletters}}\nFollowing is the display in the browser.\nWe can also pass arguments to the filter using the following piece of code.\nLetter count is : {{name | countletters('a1', 'a2')}}\nNow, the countletters will have three params, i.e. message, a1, and a2.\nWe can also pass multiple filters to the interpolation using the following piece of code.\nLetter count is : {{name | countlettersA, countlettersB}}\nIn the filter property countlettersA and countlettersB will be the two methods and the countlettersA will pass the details to countlettersB."},"parsed":{"kind":"list like","value":[{"code":null,"e":2236,"s":2070,"text":"Directives are instruction for VueJS to do things in a certain way. We have already seen directives such as v-if, v-show, v-else, v-for, v-bind , v-model, v-on, etc."},{"code":null,"e":2366,"s":2236,"text":"In this chapter, we will take a look at custom directives. We will create global directives similar to how we did for components."},{"code":null,"e":2443,"s":2366,"text":"Vue.directive('nameofthedirective', {\n bind(e1, binding, vnode) {\n }\n})\n"},{"code":null,"e":2622,"s":2443,"text":"We need to create a directive using Vue.directive. It takes the name of the directive as shown above. Let us consider an example to show the details of the working of directives."},{"code":null,"e":3297,"s":2622,"text":"\n \n VueJs Instance\n \n \n \n
\n
VueJS Directive
\n
\n \n \n"},{"code":null,"e":3402,"s":3297,"text":"In this example, we have created a custom directive changestyle as shown in the following piece of code."},{"code":null,"e":3557,"s":3402,"text":"Vue.directive(\"changestyle\",{\n bind(e1,binding, vnode) {\n console.log(e1);\n e1.style.color = \"red\";\n e1.style.fontSize = \"30px\";\n }\n});"},{"code":null,"e":3610,"s":3557,"text":"We are assigning the following changestyle to a div."},{"code":null,"e":3651,"s":3610,"text":"
VueJS Directive
"},{"code":null,"e":3770,"s":3651,"text":"If we see in the browser, it will display the text VueJs Directive in red color and the fontsize is increased to 30px."},{"code":null,"e":4114,"s":3770,"text":"We have used the bind method, which is a part of the directive. It takes three arguments e1, the element to which the custom directive needs to be applied. Binding is like arguments passed to the custom directive, e.g. v-changestyle = ”{color:’green’}”, where green will be read in the binding argument and vnode is the element, i.e. nodename."},{"code":null,"e":4216,"s":4114,"text":"In the next example, we have consoled all the arguments and its shows what details each of them give."},{"code":null,"e":4285,"s":4216,"text":"Following is an example with a value passed to the custom directive."},{"code":null,"e":5076,"s":4285,"text":"\n \n VueJs Instance\n \n \n \n
\n
VueJS Directive
\n
\n \n \n"},{"code":null,"e":5174,"s":5076,"text":"The color of the text is changed to green. The value is passed using the following piece of code."},{"code":null,"e":5522,"s":5174,"text":"
VueJS Directive
\nAnd it is accessed using the following piece of code.\nVue.directive(\"changestyle\",{\n bind(e1,binding, vnode) {\n console.log(e1);\n console.log(binding.value.color);\n console.log(vnode);\n e1.style.color=binding.value.color;\n e1.style.fontSize = \"30px\";\n }\n});"},{"code":null,"e":5704,"s":5522,"text":"VueJS supports filters that help with text formatting. It is used along with v-bind and interpolations ({{}}). We need a pipe symbol at the end of JavaScript expression for filters."},{"code":null,"e":6405,"s":5704,"text":"\n \n VueJs Instance\n \n \n \n
\n
\n Letter count is : {{name | countletters}}\n
\n \n \n"},{"code":null,"e":6669,"s":6405,"text":"In the above example, we have created a simple filter countletters. Countletters filter counts the numbers of characters entered in the textbox. To make use of filters, we need to use the filter property and define the filter used, by the following piece of code."},{"code":null,"e":6751,"s":6669,"text":"filters : {\n countletters : function(value) {\n return value.length;\n }\n}"},{"code":null,"e":6839,"s":6751,"text":"We are defining the method countletters and returning the length of the string entered."},{"code":null,"e":6947,"s":6839,"text":"To use filter in the display, we have used the pipe operator and the name of the filter, i.e. countletters."},{"code":null,"e":7035,"s":6947,"text":"Letter count is : {{name | countletters}}"},{"code":null,"e":7076,"s":7035,"text":"Following is the display in the browser."},{"code":null,"e":7152,"s":7076,"text":"We can also pass arguments to the filter using the following piece of code."},{"code":null,"e":7252,"s":7152,"text":"Letter count is : {{name | countletters('a1', 'a2')}}"},{"code":null,"e":7324,"s":7252,"text":"Now, the countletters will have three params, i.e. message, a1, and a2."},{"code":null,"e":7414,"s":7324,"text":"We can also pass multiple filters to the interpolation using the following piece of code."},{"code":null,"e":7518,"s":7414,"text":"Letter count is : {{name | countlettersA, countlettersB}}"}],"string":"[\n {\n \"code\": null,\n \"e\": 2236,\n \"s\": 2070,\n \"text\": \"Directives are instruction for VueJS to do things in a certain way. We have already seen directives such as v-if, v-show, v-else, v-for, v-bind , v-model, v-on, etc.\"\n },\n {\n \"code\": null,\n \"e\": 2366,\n \"s\": 2236,\n \"text\": \"In this chapter, we will take a look at custom directives. We will create global directives similar to how we did for components.\"\n },\n {\n \"code\": null,\n \"e\": 2443,\n \"s\": 2366,\n \"text\": \"Vue.directive('nameofthedirective', {\\n bind(e1, binding, vnode) {\\n }\\n})\\n\"\n },\n {\n \"code\": null,\n \"e\": 2622,\n \"s\": 2443,\n \"text\": \"We need to create a directive using Vue.directive. It takes the name of the directive as shown above. Let us consider an example to show the details of the working of directives.\"\n },\n {\n \"code\": null,\n \"e\": 3297,\n \"s\": 2622,\n \"text\": \"\\n \\n VueJs Instance\\n \\n \\n \\n
\\n
VueJS Directive
\\n
\\n \\n \\n\"\n },\n {\n \"code\": null,\n \"e\": 3402,\n \"s\": 3297,\n \"text\": \"In this example, we have created a custom directive changestyle as shown in the following piece of code.\"\n },\n {\n \"code\": null,\n \"e\": 3557,\n \"s\": 3402,\n \"text\": \"Vue.directive(\\\"changestyle\\\",{\\n bind(e1,binding, vnode) {\\n console.log(e1);\\n e1.style.color = \\\"red\\\";\\n e1.style.fontSize = \\\"30px\\\";\\n }\\n});\"\n },\n {\n \"code\": null,\n \"e\": 3610,\n \"s\": 3557,\n \"text\": \"We are assigning the following changestyle to a div.\"\n },\n {\n \"code\": null,\n \"e\": 3651,\n \"s\": 3610,\n \"text\": \"
VueJS Directive
\"\n },\n {\n \"code\": null,\n \"e\": 3770,\n \"s\": 3651,\n \"text\": \"If we see in the browser, it will display the text VueJs Directive in red color and the fontsize is increased to 30px.\"\n },\n {\n \"code\": null,\n \"e\": 4114,\n \"s\": 3770,\n \"text\": \"We have used the bind method, which is a part of the directive. It takes three arguments e1, the element to which the custom directive needs to be applied. Binding is like arguments passed to the custom directive, e.g. v-changestyle = ”{color:’green’}”, where green will be read in the binding argument and vnode is the element, i.e. nodename.\"\n },\n {\n \"code\": null,\n \"e\": 4216,\n \"s\": 4114,\n \"text\": \"In the next example, we have consoled all the arguments and its shows what details each of them give.\"\n },\n {\n \"code\": null,\n \"e\": 4285,\n \"s\": 4216,\n \"text\": \"Following is an example with a value passed to the custom directive.\"\n },\n {\n \"code\": null,\n \"e\": 5076,\n \"s\": 4285,\n \"text\": \"\\n \\n VueJs Instance\\n \\n \\n \\n
\\n
VueJS Directive
\\n
\\n \\n \\n\"\n },\n {\n \"code\": null,\n \"e\": 5174,\n \"s\": 5076,\n \"text\": \"The color of the text is changed to green. The value is passed using the following piece of code.\"\n },\n {\n \"code\": null,\n \"e\": 5522,\n \"s\": 5174,\n \"text\": \"
VueJS Directive
\\nAnd it is accessed using the following piece of code.\\nVue.directive(\\\"changestyle\\\",{\\n bind(e1,binding, vnode) {\\n console.log(e1);\\n console.log(binding.value.color);\\n console.log(vnode);\\n e1.style.color=binding.value.color;\\n e1.style.fontSize = \\\"30px\\\";\\n }\\n});\"\n },\n {\n \"code\": null,\n \"e\": 5704,\n \"s\": 5522,\n \"text\": \"VueJS supports filters that help with text formatting. It is used along with v-bind and interpolations ({{}}). We need a pipe symbol at the end of JavaScript expression for filters.\"\n },\n {\n \"code\": null,\n \"e\": 6405,\n \"s\": 5704,\n \"text\": \"\\n \\n VueJs Instance\\n \\n \\n \\n
\\n
\\n Letter count is : {{name | countletters}}\\n
\\n \\n \\n\"\n },\n {\n \"code\": null,\n \"e\": 6669,\n \"s\": 6405,\n \"text\": \"In the above example, we have created a simple filter countletters. Countletters filter counts the numbers of characters entered in the textbox. To make use of filters, we need to use the filter property and define the filter used, by the following piece of code.\"\n },\n {\n \"code\": null,\n \"e\": 6751,\n \"s\": 6669,\n \"text\": \"filters : {\\n countletters : function(value) {\\n return value.length;\\n }\\n}\"\n },\n {\n \"code\": null,\n \"e\": 6839,\n \"s\": 6751,\n \"text\": \"We are defining the method countletters and returning the length of the string entered.\"\n },\n {\n \"code\": null,\n \"e\": 6947,\n \"s\": 6839,\n \"text\": \"To use filter in the display, we have used the pipe operator and the name of the filter, i.e. countletters.\"\n },\n {\n \"code\": null,\n \"e\": 7035,\n \"s\": 6947,\n \"text\": \"Letter count is : {{name | countletters}}\"\n },\n {\n \"code\": null,\n \"e\": 7076,\n \"s\": 7035,\n \"text\": \"Following is the display in the browser.\"\n },\n {\n \"code\": null,\n \"e\": 7152,\n \"s\": 7076,\n \"text\": \"We can also pass arguments to the filter using the following piece of code.\"\n },\n {\n \"code\": null,\n \"e\": 7252,\n \"s\": 7152,\n \"text\": \"Letter count is : {{name | countletters('a1', 'a2')}}\"\n },\n {\n \"code\": null,\n \"e\": 7324,\n \"s\": 7252,\n \"text\": \"Now, the countletters will have three params, i.e. message, a1, and a2.\"\n },\n {\n \"code\": null,\n \"e\": 7414,\n \"s\": 7324,\n \"text\": \"We can also pass multiple filters to the interpolation using the following piece of code.\"\n },\n {\n \"code\": null,\n \"e\": 7518,\n \"s\": 7414,\n \"text\": \"Letter count is : {{name | countlettersA, countlettersB}}\"\n }\n]"}}},{"rowIdx":140,"cells":{"title":{"kind":"string","value":"Top 50 IP addressing interview questions and answers"},"text":{"kind":"string","value":"15 Sep, 2021\n1. What is IP address?\nIP address is an address having information about how to reach a specific host, especially outside the LAN. An IP address is 32 bit unique address having an address space of 232. Generally, there are two notations in which IP address is written, dotted decimal notation and hexadecimal notation. For more details, please refer introduction of Classful IP addressing.\n2. What are the different classes of IP addresses and give the range of each class?\nIP address is an address having information about how to reach a specific host, especially outside the LAN. An IP address is 32-bit unique address having an address space of 232.\nFor more details, please refer introduction of Classful IP addressing.\n3. What is subnet mask?\nA subnet mask is a 32-bit number that is used to identify the subnet of an IP address. The subnet mask is a combination of 1’s and 0’s. 1’s represents network and subnet ID while 0’s represents the host ID. In this case, the subnet mask is,\n11111111.11111111.11111111.11000000 \nor\n255.255.255.192 \nSo, in order to get the network to which the destination address belongs, we have to bitwise & with a subnet mask.\n 11111111.11111111.11111111.11000000\n&& 11001000.00000001.00000010.00010100\n-----------------------------------------------------\n 11001000.00000001.00000010.00000000 \nThe address belongs to,\n11001000.00000001.00000010.00000000 \nor\n200.1.2.0 \nFor more details, please refer Role of Subnet Mask article.\n4. Why CIDR is used?\nThe problem with this classful addressing method is that millions of class A addresses are wasted, many of the class B addresses are wasted, whereas, number of addresses available in class C is so small that it cannot cater to the needs of organizations. Class D addresses are used for multicast routing and are therefore available as a single block only. Class E addresses are reserved. Since there are these problems, Classful networking was replaced by Classless Inter-Domain Routing (CIDR). For more details, please refer CIDR full-form to the article.\n5. What is the LOOPBACK address?\nLoopback Address is used to let a system send a message to itself to make sure that the TCP/IP stack is installed correctly on the machine. For more details, please refer Local Broadcast and Loopback address article.\n6. What is a Default Gateway?\nIn organizational systems, a gateway is a node that routes the traffic from a workstation to another network segment. The default gateway commonly connects the internal networks and the outside network (Internet). In such a situation, the gateway node could also act as a proxy server and a firewall. The gateway is also associated with both a router, which uses headers and forwarding tables to determine where packets are sent and a switch, which provides the actual path for the packet in and out of the gateway. \nFor more details, please refer to Working of different layers in the Computer network article. \n7. Why Hop limit field is used?\nHop Limit: Hop Limit field is the same as TTL in IPv4 packets. It indicates the maximum number of intermediate nodes IPv6 packet is allowed to travel. Its value gets decremented by one, by each node that forwards the packet and the packet is discarded if the value decreases to 0. This is used to discard the packets that are stuck in an infinite loop because of some routing error.\nFor more details, please refer to Internet Protocol version 6 (IPv6) Header article.\n8. What protocol is used by PING?\nICMP (Internet Control Message Protocol) is used by PING. For more details, please refer to the Difference between Ping and Traceroute article.\n9. What is used of Tracert?\nTraceroute is a widely used command-line utility available in almost all operating systems. It shows you the complete route to a destination address. It also shows the time is taken (or delays) between intermediate routers. For more details, please refer to the Difference between Ping and Traceroute article.\n10. Name the ports used by FTP protocol?\nBasically, FTP protocol uses two ports:\nControl connection: For sending control information like user identification, password, commands to change the remote directory, commands to retrieve and store files, etc., FTP makes use of connections. The control connection is initiated on port number 21.\nData connection: For sending the actual file, FTP makes use of a data connection. A data connection is initiated on port number 20. For more details, please refer to File Transfer Protocol (FTP) in the Application Layer article.\n11. What is MAC address?\nMAC Addresses are unique 48-bit hardware numbers of computers, which are embedded into a network card (known as Network Interface Card) during the time of manufacturing. The MAC Address is also known as the Physical Address of a network device. In IEEE 802 standard, the Data Link Layer is divided into two sublayers – \nLogical Link Control(LLC) SublayerMedia Access Control(MAC) Sublayer\nLogical Link Control(LLC) Sublayer\nMedia Access Control(MAC) Sublayer\nThe MAC address is used by the Media Access Control (MAC) sublayer of the Data-Link Layer. MAC Address is unique worldwide since millions of network devices exist and we need to uniquely identify each. \nFor more details, please refer to Introduction of MAC Address in Computer Network article.\n12. Explain ARP?\nAddress Resolution Protocol is a communication protocol used for discovering physical addresses associated with a given network address. Typically, ARP is a network layer to data link layer mapping process, which is used to discover MAC addresses for a given Internet Protocol Address.In order to send the data to the destination, having an IP address is necessary but not sufficient; we also need the physical address of the destination machine. ARP is used to get the physical address (MAC address) of the destination machine.\nBefore sending the IP packet, the MAC address of the destination must be known. If not so, then the sender broadcasts the ARP-discovery packet requesting the MAC address of the intended destination. Since ARP-discovery is broadcast, every host inside that network will get this message but the packet will be discarded by everyone except that intended receiver host whose IP is associated. Now, this receiver will send a unicast packet with its MAC address (ARP-reply) to the sender of the ARP-discovery packet. After the original sender receives the ARP-reply, it updates ARP-cache and starts sending a unicast message to the destination.\nFor more details, please refer to the How Address Resolution Protocol works article.\n13. What is MTU?\nA maximum transmission unit also called MTU, is a term used in networking and operating systems. It defines the largest size of the packet that can be transmitted as a single entity in a network connection. The size of the MTU dictates the amount of data that can be transmitted in bytes over a network. For more details, please refer What is MTU article.\n14. If a class B network on the Internet has a subnet mask of 255.255.248.0, what is the maximum number of hosts per subnet?The binary representation of the subnet mask is 11111111.11111111.11111000. 00000000. There are 21 bits set in a subnet. So 11 (32-21) bits are left for host ids. The total possible value of host ids is 2^11 = 2048. Out of these 2048 values, 2 addresses are reserved. The address with all bits as 1 is reserved as broadcast address and the address with all host id bits as 0 is used as a network address of the subnet.In general, the number of addresses usable for addressing specific hosts in each network is always 2^N – 2 where N is the number of bits for host id. So the answer is 2046.\n15. What is IP multicast?\nMulticasting has one/more senders and one/more recipients participate in data transfer traffic. In multicasting, traffic reclines between the boundaries of unicast and broadcast. Its server’s direct single copies of data streams and that are then simulated and routed to hosts that request it. IP multicast requires the support of some other protocols such as Internet Group Management Protocol (IGMP), Multicast routing for its work. And also, in Classful IP, addressing Class D is reserved for multicast groups.\n16. Difference between public and private IP addresses?\nPublic IP address–A public IP address is an Internet Protocol address, encrypted by various servers/devices. That’s when you connect these devices with your internet connection. This is the same IP address we show on our homepage. So why the second page? Well, not all people speak the IP language. We want to make it as easy as possible for everyone to get the information they need. Some even call this their external IP address. A public Internet Protocol address is an Internet Protocol address accessed over the Internet. Like the postal address used to deliver mail to your home, the public Internet Protocol address is a different international Internet Protocol address assigned to a computer device. The web server, email server, and any server device that has direct access to the Internet are those who will enter the public Internet Protocol address. Internet Address Protocol is unique worldwide and is only supplied with a unique device.Private IP address–Everything that connects to your Internet network has a private IP address. This includes computers, smartphones, and tablets but also any Bluetooth-enabled devices such as speakers, printers, or smart TVs. With the growing internet of things, the number of private IP addresses you have at home is likely to increase. Your router needs a way to identify these things separately, and most things need a way to get to know each other. Therefore, your router generates private IP addresses that are unique identifiers for each device that separates the network.\nPublic IP address–A public IP address is an Internet Protocol address, encrypted by various servers/devices. That’s when you connect these devices with your internet connection. This is the same IP address we show on our homepage. So why the second page? Well, not all people speak the IP language. We want to make it as easy as possible for everyone to get the information they need. Some even call this their external IP address. A public Internet Protocol address is an Internet Protocol address accessed over the Internet. Like the postal address used to deliver mail to your home, the public Internet Protocol address is a different international Internet Protocol address assigned to a computer device. The web server, email server, and any server device that has direct access to the Internet are those who will enter the public Internet Protocol address. Internet Address Protocol is unique worldwide and is only supplied with a unique device.\nPrivate IP address–Everything that connects to your Internet network has a private IP address. This includes computers, smartphones, and tablets but also any Bluetooth-enabled devices such as speakers, printers, or smart TVs. With the growing internet of things, the number of private IP addresses you have at home is likely to increase. Your router needs a way to identify these things separately, and most things need a way to get to know each other. Therefore, your router generates private IP addresses that are unique identifiers for each device that separates the network.\n17. Can you explain what subnetting?\nWhen a bigger network is divided into smaller networks, in order to maintain security, then that is known as Subnetting. so, maintenance is easier for smaller networks. For more details please read an introduction to a subnetting article.\n18. Do you know what is Network Address Translation?\nTo access the Internet, one public IP address is needed, but we can use a private IP address on our private network. The idea of NAT is to allow multiple devices to access the Internet through a single public address. To achieve this, the translation of a private IP address to a public IP address is required. Network Address Translation (NAT) is a process in which one or more local IP addresses is translated into one or more Global IP addresses and vice versa in order to provide Internet access to the local hosts. Also, it does the translation of port numbers i.e. masks the port number of the host with another port number in the packet that will be routed to the destination. It then makes the corresponding entries of IP address and port number in the NAT table. NAT generally operates on a router or firewall. For more details, please refer to Network Address Translation.\n19. An organization requires a range of IP addresses to assign one to each of its 1500 computers. The organization has approached an Internet Service Provider (ISP) for this task. The ISP uses CIDR and serves the requests from the available IP address space 202.61.0.0/17. The ISP wants to assign address space to the organization which will minimize the number of routing entries in the ISP’s router using route aggregation. To calculate the address spaces are potential candidates from which the ISP can allow any one of the organizations?\nSubnet Mask for the given IP address:\n202.61.0.0/17 \n⇒ 11111111 11111111 10000000 00000000\n⇒ 255.255.128.0 \nNow, since we need 1500 hosts, so, bits for host address,\n= ceiling (log2 (1500)) \n= ceiling (10.55) \n= 11 bits for host address \nSo, the last 11 bits will be for host addresses:\n00000000.00000000 → 00000111.11111111 (0.0 → 7.255)\n\n00001000.00000000 → 00010000.00000000 (8.0 - 15.255)\n\n00001111.11111111 → 00010111.11111111 (16.0 - 23.255) \nSequences are 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 96, 104, 112, 120.\nHence, 64 and 104 are present in the sequence, so 202.61.104.0 / 21 and 202.61.64.0 / 21 are the possible IP addresses.\n20. Explain the difference between Static and Dynamic IP?\nFor more details, please refer to Difference between Static and Dynamic IP addresses.\n21. How will my computer get its IP Address?\nTo get IP address :\nClick on start ->Programs->Accessories->Command prompt.Type ipconfig on command prompt and press enter key.\nClick on start ->Programs->Accessories->Command prompt.\nType ipconfig on command prompt and press enter key.\nBy using these steps, you can get your PC IP address, Subnet Mask, and default gateway details.\n22. What are the features of Gateway?\nGateways provide a wide variety of features. Some of which are:\nGateways work as a network bridge for data transmission as it makes the transmission of data possible to transmit with more ease and does not demand high storage capacity.\nGateways create a structural temporary storeroom for the data transmitted by the server and data requests made by the user end.\nGateways made the transmission more feasible as it queued up all the data and divide it into small packets of data rather than sending it bulk. Data transmitted through Gateway is divided into various useful and small packets each having its individual significance and a role to play while processing data.\nGateways made the data more secure if the modifications to the gateway could be done which then could create more reliability over smart devices.\nGateways optimize the data for search engines, applications, and servers by implanting better readability to the content so that a machine could understand and optimize data with ease. For more details, please refer to the Introduction of Gateways.\n23. Is Ipv6 Backward Compatible With Ipv4?\nNo, IPv6 is not backward compatible with IPv4 protocol. For more details, please refer to the Internet protocol version 6 article.\n24. Is It Possible To Have An Ipv4 And An Ipv6 Addresses Simultaneously?\nYes, it is possible to have an IPv4 and IPv6 addresses simultaneously. For more details, please refer to the Internet protocol version 6 and the difference between IPv4 and IPv6 articles.\n25. What is TTL?\nThe lifespan or lifetime of data that is being sent. Once after that specified time is over or elapsed, the data will be discarded Or it can also be stated as the number of hops that packet is set to exist in the network, after which that packet is discarded. The purpose of the TTL field is to avoid a situation in which an undeliverable datagram keeps circulating in the network. For more details, please refer to the difference between RTT and TTL article.\n26. If the TTL field has the value of 10. How many routers (max) can process this datagram?\nTTL stands for Time to Live. This field specifies the life of the IP packet based on the number of hops it makes ( number of routers it goes through). TTL field is decremented by one each time the datagram is processed by a router. When the value is 0, the packet is automatically destroyed. For more details, please refer to the difference between RTT and TTL articles.\n27. If the value in the protocol field is 17, the transport layer protocol used is which protocol?\nIf the value in the protocol field is 17, the transport layer protocol uses UDP (User Datagram Protocol). For more details, please refer to UDP article.\n28. What happens in classless addressing, if there are no classes but addresses are still granted?\nIn classless addressing, there are no classes but addresses are still granted in blocks. The total number of addresses in a block of classless IP addresses = 2(32 – CIDR_value). For more details, please refer to the introduction of Classful IP addressing.\n29. Suppose two IPv6 nodes want to interoperate using IPv6 datagrams, but they are connected to each other by intervening IPv4 routers. Then what is the best solution?\nIf two IPv6 nodes want to interoperate using IPv6 datagrams, they are connected to each other by intervening IPv4 routers. Then tunneling is the best solution. For more details, please refer to Internet protocol version 6 article.\n30. What is IANA?\nIANA, the Internet Assigned Numbers Authority, is an administrative function of the Internet that keeps track of IP addresses, domain names, and protocol parameter identifiers that are used by Internet standards. Some of these identifiers are parameters, such as those used by Internet protocols (like TCP, ICMP or UDP) to specify functions and behaviour; some of them represent Internet addresses and others represent domain names. Regardless of the type of identifier, the IANA function (IANA for short below) ensures that values are managed for uniqueness and made available in publicly accessible registries.\n31. What is DHCP?\nDHCP is an abbreviation for Dynamic Host Configuration Protocol. It is an application layer protocol used by hosts for obtaining network setup information. The DHCP is controlled by a DHCP server that dynamically distributes network configuration parameters such as IP addresses, subnet mask, and gateway address. For more details, please refer to Dynamic Host Configuration Protocol (DHCP) article.\n32. How can you manage a network using a router?\nRouters have built-in console that lets you configure different settings, like security and data logging.We can assign restrictions to computers, such as what resources they are allowed to access, or what particular time of the day they can browse the internet.We can even put restrictions on what websites are not viewable across the entire network. For more details, please refer to the introduction of a Router.\n33. What is ipconfig?\nIPCONFIG stands for Internet Protocol Configuration. This is a command-line application that displays all the current TCP/IP (Transmission Control Protocol/Internet Protocol) network configuration, refreshes the DHCP (Dynamic Host Configuration Protocol) and DNS (Domain Name Server). It also displays an IP address, subnet mask, and a default gateway for all adapters. It is available for Microsoft Windows, ReactOS, and Apple macOS. ReactOS version was developed by Ged Murphy and licensed under the General Public License. For more details, please refer to ipconfig full form article.\n34. When you move the NIC cards from one PC to another PC, does the MAC address get transferred as well?\nYes, if we move the NIC cards from one PC to another PC, then the MAC address also gets transferred, because the MAC address is hard-wired into the NIC circuit, not the personal computer. This also means that a PC can have a different MAC address when another one replaces the NIC card. \n35. Explain clustering support?\nClustering support refers to the ability of a network operating system to connect multiple servers in a fault-tolerant group. The main purpose of this is the in the event that one server fails, all processing will continue on with the next server in the cluster.\n36. What is Brouter?\n Brouter – It is also known as the bridging router is a device that combines features of both bridge and router. It can work either at the data link layer or a network layer. Working as a router, it is capable of routing packets across networks, and working as the bridge, it is capable of filtering local area network traffic. For more details, please refer to the difference between Router and Brouter article.\n37. Explain the features of VPN?\nVPN also ensures security by providing an encrypted tunnel between client and vpn server.VPN is used to bypass many blocked sites.VPN facilitates anonymous browsing by hiding your ip address.Also, the most appropriate Search engine optimization(SEO) is done by analyzing the data from VPN providers which provide country-wise states for browsing a particular product. This method of SEO is used widely by many internet marketing managers to form new strategies.For more details, please refer to Virtual Private Network.\nVPN also ensures security by providing an encrypted tunnel between client and vpn server.\nVPN is used to bypass many blocked sites.\nVPN facilitates anonymous browsing by hiding your ip address.\nAlso, the most appropriate Search engine optimization(SEO) is done by analyzing the data from VPN providers which provide country-wise states for browsing a particular product. This method of SEO is used widely by many internet marketing managers to form new strategies.For more details, please refer to Virtual Private Network.\n38. What are the important differences between MAC address and IP address?\n39. What is 127.0.0.1?\nIn IPv4, IP addresses that start with decimal 127 or that has 01111111 in the first octet are loopback addresses(127.X.X.X). Typically 127.0.0.1 is used as the local loopback address.This leads to the wastage of many potential IP addresses. But in IPv6 ::1 is used as local loopback address and therefore there isn’t any wastage of addresses.\n40. What is a DNS?\nDNS is a host name to IP address translation service. DNS is a distributed database implemented in a hierarchy of name servers. It is an application layer protocol for message exchange between clients and servers. For more details, please refer to DNS in the application layer.\n41. What is the use of a proxy server?\nProxy server refers to a server that acts as an intermediary between the request made by clients, and a particular server for some services or requests for some resources. There are different types of proxy servers available that are put into use according to the purpose of a request made by the clients to the servers. The basic purpose of Proxy servers is to protect the direct connection of Internet clients and internet resources. The proxy server also prevents the identification of the client’s IP address when the client makes any request is made to any other servers. For more details, please refer to Proxy server article.\n42. What is the difference between ipconfig and ifconfig commands?\nIPCONFIG stands for Internet Protocol Configuration. This is a command-line application that displays all the current TCP/IP (Transmission Control Protocol/Internet Protocol) network configuration, refreshes the DHCP (Dynamic Host Configuration Protocol) and DNS (Domain Name Server). It also displays IP address, subnet mask, and default gateway for all adapters. It is available for Microsoft Windows, ReactOS, and Apple macOS. ReactOS version was developed by Ged Murphy and licensed under the General Public License.\nifconfig(interface configuration) command is used to configure the kernel-resident network interfaces. It is used at boot time to set up the interfaces as necessary. After that, it is usually used when needed during debugging or when you need system tuning. Also, this command is used to assign the IP address and netmask to an interface or to enable or disable a given interface. For more details, please refer to\n43. What is the importance of APIPA in networking?\nAutomatic Private IP Addressing is important in networking because communication can be established properly if you don’t get a response from DHCP Server. APIPA regulates the service, by which the response and status of the main DHCP server at a specific period of time. Apart from that, it can be used as a backup to DHCP because when DHCP stops working, APIPA has the ability to assign IP to the networking hosts.It stops unwanted broadcasting. It uses ARP(Address Resolution Protocol) to confirm the address isn’t currently in use. For more details, please refer to What is APIPA.\n44. What is the difference between Firewall and Antivirus?\n45. What is SLIP?\nSLIP stands for Serial Line Internet Protocol. It is a TCP/IP implementation which was described under RFC 1055 (Request for Comments). SLIP establishes point-to-point serial connections which can be used in dial-up connections, serial ports and routers. It frames the encapsulated IP packets across a serial line for establishing connection while using line speed between 12000 bps and 19.2 Kbps. SLIP was introduced in 1984 when Rick Adams used it to connect 4.2 Berkeley Unix and Sun Microsystems workstations. It soon caught up with the rest of the world as a credible TCP/IP implementation. It has now become obsolete after being replaced by PPP (Point to Point Protocol) which solves many deficiencies present in it. For more details, please refer to\n46. What is Kerberos protocol?\nKerberos provides a centralized authentication server whose function is to authenticate users to servers and servers to users. In Kerberos Authentication server and database is used for client authentication. Kerberos runs as a third-party trusted server known as the Key Distribution Center (KDC). Each user and service on the network is a principal.\nThe main components of Kerberos are:\nAuthentication Server (AS):The Authentication Server performs the initial authentication and ticket for Ticket Granting Service.\nDatabase:The Authentication Server verifies the access rights of users in the database.\nTicket Granting Server (TGS):The Ticket Granting Server issues the ticket for the Server.\nFor more details, please refer to Kerberos article.\n47. What is HSRP?\nHot Standby Router Protocol (HSRP) is a CISCO proprietary protocol, which provides redundancy for a local subnet. In HSRP, two or more routers give an illusion of a virtual router.\nHSRP allows you to configure two or more routers as standby routers and only a single router as an active router at a time. All the routers in a single HSRP group share a single MAC address and IP address, which acts as a default gateway to the local network. The Active router is responsible for forwarding the traffic. If it fails, the Standby router takes up all the responsibilities of the active router and forwards the traffic.\nFor more details, please refer to HSRP protocol.\n48. Why is the MAC address called the Physical address?\nThe MAC address is a physical address (also called a hardware address) because it physically identifies an item of hardware. MAC addresses use three types of number systems and all use the same format, only the size of the identifier differs. The addresses can be “Universally Managed” or “Locally Managed”. For more details, please refer to Introduction of MAC Address in Computer Network article.\n49. Process of DHCP(DORA)?\nIn DHCP, the client and the server exchange mainly 4 DHCP messages in order to make a connection. This process is known as DORA process (discovery, offer, request, and acknowledgment), but there are 8 DHCP messages in the process. For more details, please refer to Dynamic Host Configuration Protocol (DHCP) article.\n50. What is ‘APIPA’?\nAPIPA stands for Automatic Private IP Addressing (APIPA). It is a feature or characteristic in operating systems (eg. Windows) which enables computers to self-configure an IP address and subnet mask automatically when their DHCP(Dynamic Host Configuration Protocol) server isn’t reachable. The IP address range for APIPA is (169.254.0.1 to 169.254.255.254) having 65, 534 usable IP addresses, with the subnet mask of 255.255.0.0. For more details please read What is APIPA article.\n \nanikakapoor\ninterview-questions\nComputer Networks\nComputer Networks\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},"parsed":{"kind":"list like","value":[{"code":null,"e":28,"s":0,"text":"\n15 Sep, 2021"},{"code":null,"e":51,"s":28,"text":"1. What is IP address?"},{"code":null,"e":419,"s":51,"text":"IP address is an address having information about how to reach a specific host, especially outside the LAN. An IP address is 32 bit unique address having an address space of 232. Generally, there are two notations in which IP address is written, dotted decimal notation and hexadecimal notation. For more details, please refer introduction of Classful IP addressing."},{"code":null,"e":503,"s":419,"text":"2. What are the different classes of IP addresses and give the range of each class?"},{"code":null,"e":683,"s":503,"text":"IP address is an address having information about how to reach a specific host, especially outside the LAN. An IP address is 32-bit unique address having an address space of 232."},{"code":null,"e":754,"s":683,"text":"For more details, please refer introduction of Classful IP addressing."},{"code":null,"e":778,"s":754,"text":"3. What is subnet mask?"},{"code":null,"e":1019,"s":778,"text":"A subnet mask is a 32-bit number that is used to identify the subnet of an IP address. The subnet mask is a combination of 1’s and 0’s. 1’s represents network and subnet ID while 0’s represents the host ID. In this case, the subnet mask is,"},{"code":null,"e":1076,"s":1019,"text":"11111111.11111111.11111111.11000000 \nor\n255.255.255.192 "},{"code":null,"e":1191,"s":1076,"text":"So, in order to get the network to which the destination address belongs, we have to bitwise & with a subnet mask."},{"code":null,"e":1366,"s":1191,"text":" 11111111.11111111.11111111.11000000\n&& 11001000.00000001.00000010.00010100\n-----------------------------------------------------\n 11001000.00000001.00000010.00000000 "},{"code":null,"e":1390,"s":1366,"text":"The address belongs to,"},{"code":null,"e":1441,"s":1390,"text":"11001000.00000001.00000010.00000000 \nor\n200.1.2.0 "},{"code":null,"e":1501,"s":1441,"text":"For more details, please refer Role of Subnet Mask article."},{"code":null,"e":1522,"s":1501,"text":"4. Why CIDR is used?"},{"code":null,"e":2079,"s":1522,"text":"The problem with this classful addressing method is that millions of class A addresses are wasted, many of the class B addresses are wasted, whereas, number of addresses available in class C is so small that it cannot cater to the needs of organizations. Class D addresses are used for multicast routing and are therefore available as a single block only. Class E addresses are reserved. Since there are these problems, Classful networking was replaced by Classless Inter-Domain Routing (CIDR). For more details, please refer CIDR full-form to the article."},{"code":null,"e":2112,"s":2079,"text":"5. What is the LOOPBACK address?"},{"code":null,"e":2329,"s":2112,"text":"Loopback Address is used to let a system send a message to itself to make sure that the TCP/IP stack is installed correctly on the machine. For more details, please refer Local Broadcast and Loopback address article."},{"code":null,"e":2359,"s":2329,"text":"6. What is a Default Gateway?"},{"code":null,"e":2876,"s":2359,"text":"In organizational systems, a gateway is a node that routes the traffic from a workstation to another network segment. The default gateway commonly connects the internal networks and the outside network (Internet). In such a situation, the gateway node could also act as a proxy server and a firewall. The gateway is also associated with both a router, which uses headers and forwarding tables to determine where packets are sent and a switch, which provides the actual path for the packet in and out of the gateway. "},{"code":null,"e":2972,"s":2876,"text":"For more details, please refer to Working of different layers in the Computer network article. "},{"code":null,"e":3005,"s":2972,"text":"7. Why Hop limit field is used?"},{"code":null,"e":3388,"s":3005,"text":"Hop Limit: Hop Limit field is the same as TTL in IPv4 packets. It indicates the maximum number of intermediate nodes IPv6 packet is allowed to travel. Its value gets decremented by one, by each node that forwards the packet and the packet is discarded if the value decreases to 0. This is used to discard the packets that are stuck in an infinite loop because of some routing error."},{"code":null,"e":3473,"s":3388,"text":"For more details, please refer to Internet Protocol version 6 (IPv6) Header article."},{"code":null,"e":3507,"s":3473,"text":"8. What protocol is used by PING?"},{"code":null,"e":3651,"s":3507,"text":"ICMP (Internet Control Message Protocol) is used by PING. For more details, please refer to the Difference between Ping and Traceroute article."},{"code":null,"e":3679,"s":3651,"text":"9. What is used of Tracert?"},{"code":null,"e":3989,"s":3679,"text":"Traceroute is a widely used command-line utility available in almost all operating systems. It shows you the complete route to a destination address. It also shows the time is taken (or delays) between intermediate routers. For more details, please refer to the Difference between Ping and Traceroute article."},{"code":null,"e":4030,"s":3989,"text":"10. Name the ports used by FTP protocol?"},{"code":null,"e":4070,"s":4030,"text":"Basically, FTP protocol uses two ports:"},{"code":null,"e":4328,"s":4070,"text":"Control connection: For sending control information like user identification, password, commands to change the remote directory, commands to retrieve and store files, etc., FTP makes use of connections. The control connection is initiated on port number 21."},{"code":null,"e":4557,"s":4328,"text":"Data connection: For sending the actual file, FTP makes use of a data connection. A data connection is initiated on port number 20. For more details, please refer to File Transfer Protocol (FTP) in the Application Layer article."},{"code":null,"e":4582,"s":4557,"text":"11. What is MAC address?"},{"code":null,"e":4902,"s":4582,"text":"MAC Addresses are unique 48-bit hardware numbers of computers, which are embedded into a network card (known as Network Interface Card) during the time of manufacturing. The MAC Address is also known as the Physical Address of a network device. In IEEE 802 standard, the Data Link Layer is divided into two sublayers – "},{"code":null,"e":4971,"s":4902,"text":"Logical Link Control(LLC) SublayerMedia Access Control(MAC) Sublayer"},{"code":null,"e":5006,"s":4971,"text":"Logical Link Control(LLC) Sublayer"},{"code":null,"e":5041,"s":5006,"text":"Media Access Control(MAC) Sublayer"},{"code":null,"e":5244,"s":5041,"text":"The MAC address is used by the Media Access Control (MAC) sublayer of the Data-Link Layer. MAC Address is unique worldwide since millions of network devices exist and we need to uniquely identify each. "},{"code":null,"e":5335,"s":5244,"text":"For more details, please refer to Introduction of MAC Address in Computer Network article."},{"code":null,"e":5352,"s":5335,"text":"12. Explain ARP?"},{"code":null,"e":5881,"s":5352,"text":"Address Resolution Protocol is a communication protocol used for discovering physical addresses associated with a given network address. Typically, ARP is a network layer to data link layer mapping process, which is used to discover MAC addresses for a given Internet Protocol Address.In order to send the data to the destination, having an IP address is necessary but not sufficient; we also need the physical address of the destination machine. ARP is used to get the physical address (MAC address) of the destination machine."},{"code":null,"e":6521,"s":5881,"text":"Before sending the IP packet, the MAC address of the destination must be known. If not so, then the sender broadcasts the ARP-discovery packet requesting the MAC address of the intended destination. Since ARP-discovery is broadcast, every host inside that network will get this message but the packet will be discarded by everyone except that intended receiver host whose IP is associated. Now, this receiver will send a unicast packet with its MAC address (ARP-reply) to the sender of the ARP-discovery packet. After the original sender receives the ARP-reply, it updates ARP-cache and starts sending a unicast message to the destination."},{"code":null,"e":6606,"s":6521,"text":"For more details, please refer to the How Address Resolution Protocol works article."},{"code":null,"e":6624,"s":6606,"text":"13. What is MTU?"},{"code":null,"e":6980,"s":6624,"text":"A maximum transmission unit also called MTU, is a term used in networking and operating systems. It defines the largest size of the packet that can be transmitted as a single entity in a network connection. The size of the MTU dictates the amount of data that can be transmitted in bytes over a network. For more details, please refer What is MTU article."},{"code":null,"e":7695,"s":6980,"text":"14. If a class B network on the Internet has a subnet mask of 255.255.248.0, what is the maximum number of hosts per subnet?The binary representation of the subnet mask is 11111111.11111111.11111000. 00000000. There are 21 bits set in a subnet. So 11 (32-21) bits are left for host ids. The total possible value of host ids is 2^11 = 2048. Out of these 2048 values, 2 addresses are reserved. The address with all bits as 1 is reserved as broadcast address and the address with all host id bits as 0 is used as a network address of the subnet.In general, the number of addresses usable for addressing specific hosts in each network is always 2^N – 2 where N is the number of bits for host id. So the answer is 2046."},{"code":null,"e":7721,"s":7695,"text":"15. What is IP multicast?"},{"code":null,"e":8235,"s":7721,"text":"Multicasting has one/more senders and one/more recipients participate in data transfer traffic. In multicasting, traffic reclines between the boundaries of unicast and broadcast. Its server’s direct single copies of data streams and that are then simulated and routed to hosts that request it. IP multicast requires the support of some other protocols such as Internet Group Management Protocol (IGMP), Multicast routing for its work. And also, in Classful IP, addressing Class D is reserved for multicast groups."},{"code":null,"e":8291,"s":8235,"text":"16. Difference between public and private IP addresses?"},{"code":null,"e":9821,"s":8291,"text":"Public IP address–A public IP address is an Internet Protocol address, encrypted by various servers/devices. That’s when you connect these devices with your internet connection. This is the same IP address we show on our homepage. So why the second page? Well, not all people speak the IP language. We want to make it as easy as possible for everyone to get the information they need. Some even call this their external IP address. A public Internet Protocol address is an Internet Protocol address accessed over the Internet. Like the postal address used to deliver mail to your home, the public Internet Protocol address is a different international Internet Protocol address assigned to a computer device. The web server, email server, and any server device that has direct access to the Internet are those who will enter the public Internet Protocol address. Internet Address Protocol is unique worldwide and is only supplied with a unique device.Private IP address–Everything that connects to your Internet network has a private IP address. This includes computers, smartphones, and tablets but also any Bluetooth-enabled devices such as speakers, printers, or smart TVs. With the growing internet of things, the number of private IP addresses you have at home is likely to increase. Your router needs a way to identify these things separately, and most things need a way to get to know each other. Therefore, your router generates private IP addresses that are unique identifiers for each device that separates the network."},{"code":null,"e":10773,"s":9821,"text":"Public IP address–A public IP address is an Internet Protocol address, encrypted by various servers/devices. That’s when you connect these devices with your internet connection. This is the same IP address we show on our homepage. So why the second page? Well, not all people speak the IP language. We want to make it as easy as possible for everyone to get the information they need. Some even call this their external IP address. A public Internet Protocol address is an Internet Protocol address accessed over the Internet. Like the postal address used to deliver mail to your home, the public Internet Protocol address is a different international Internet Protocol address assigned to a computer device. The web server, email server, and any server device that has direct access to the Internet are those who will enter the public Internet Protocol address. Internet Address Protocol is unique worldwide and is only supplied with a unique device."},{"code":null,"e":11352,"s":10773,"text":"Private IP address–Everything that connects to your Internet network has a private IP address. This includes computers, smartphones, and tablets but also any Bluetooth-enabled devices such as speakers, printers, or smart TVs. With the growing internet of things, the number of private IP addresses you have at home is likely to increase. Your router needs a way to identify these things separately, and most things need a way to get to know each other. Therefore, your router generates private IP addresses that are unique identifiers for each device that separates the network."},{"code":null,"e":11389,"s":11352,"text":"17. Can you explain what subnetting?"},{"code":null,"e":11628,"s":11389,"text":"When a bigger network is divided into smaller networks, in order to maintain security, then that is known as Subnetting. so, maintenance is easier for smaller networks. For more details please read an introduction to a subnetting article."},{"code":null,"e":11681,"s":11628,"text":"18. Do you know what is Network Address Translation?"},{"code":null,"e":12564,"s":11681,"text":"To access the Internet, one public IP address is needed, but we can use a private IP address on our private network. The idea of NAT is to allow multiple devices to access the Internet through a single public address. To achieve this, the translation of a private IP address to a public IP address is required. Network Address Translation (NAT) is a process in which one or more local IP addresses is translated into one or more Global IP addresses and vice versa in order to provide Internet access to the local hosts. Also, it does the translation of port numbers i.e. masks the port number of the host with another port number in the packet that will be routed to the destination. It then makes the corresponding entries of IP address and port number in the NAT table. NAT generally operates on a router or firewall. For more details, please refer to Network Address Translation."},{"code":null,"e":13106,"s":12564,"text":"19. An organization requires a range of IP addresses to assign one to each of its 1500 computers. The organization has approached an Internet Service Provider (ISP) for this task. The ISP uses CIDR and serves the requests from the available IP address space 202.61.0.0/17. The ISP wants to assign address space to the organization which will minimize the number of routing entries in the ISP’s router using route aggregation. To calculate the address spaces are potential candidates from which the ISP can allow any one of the organizations?"},{"code":null,"e":13144,"s":13106,"text":"Subnet Mask for the given IP address:"},{"code":null,"e":13214,"s":13144,"text":"202.61.0.0/17 \n⇒ 11111111 11111111 10000000 00000000\n⇒ 255.255.128.0 "},{"code":null,"e":13272,"s":13214,"text":"Now, since we need 1500 hosts, so, bits for host address,"},{"code":null,"e":13344,"s":13272,"text":"= ceiling (log2 (1500)) \n= ceiling (10.55) \n= 11 bits for host address "},{"code":null,"e":13393,"s":13344,"text":"So, the last 11 bits will be for host addresses:"},{"code":null,"e":13557,"s":13393,"text":"00000000.00000000 → 00000111.11111111 (0.0 → 7.255)\n\n00001000.00000000 → 00010000.00000000 (8.0 - 15.255)\n\n00001111.11111111 → 00010111.11111111 (16.0 - 23.255) "},{"code":null,"e":13632,"s":13557,"text":"Sequences are 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 96, 104, 112, 120."},{"code":null,"e":13752,"s":13632,"text":"Hence, 64 and 104 are present in the sequence, so 202.61.104.0 / 21 and 202.61.64.0 / 21 are the possible IP addresses."},{"code":null,"e":13810,"s":13752,"text":"20. Explain the difference between Static and Dynamic IP?"},{"code":null,"e":13896,"s":13810,"text":"For more details, please refer to Difference between Static and Dynamic IP addresses."},{"code":null,"e":13941,"s":13896,"text":"21. How will my computer get its IP Address?"},{"code":null,"e":13961,"s":13941,"text":"To get IP address :"},{"code":null,"e":14069,"s":13961,"text":"Click on start ->Programs->Accessories->Command prompt.Type ipconfig on command prompt and press enter key."},{"code":null,"e":14125,"s":14069,"text":"Click on start ->Programs->Accessories->Command prompt."},{"code":null,"e":14178,"s":14125,"text":"Type ipconfig on command prompt and press enter key."},{"code":null,"e":14274,"s":14178,"text":"By using these steps, you can get your PC IP address, Subnet Mask, and default gateway details."},{"code":null,"e":14312,"s":14274,"text":"22. What are the features of Gateway?"},{"code":null,"e":14376,"s":14312,"text":"Gateways provide a wide variety of features. Some of which are:"},{"code":null,"e":14548,"s":14376,"text":"Gateways work as a network bridge for data transmission as it makes the transmission of data possible to transmit with more ease and does not demand high storage capacity."},{"code":null,"e":14676,"s":14548,"text":"Gateways create a structural temporary storeroom for the data transmitted by the server and data requests made by the user end."},{"code":null,"e":14984,"s":14676,"text":"Gateways made the transmission more feasible as it queued up all the data and divide it into small packets of data rather than sending it bulk. Data transmitted through Gateway is divided into various useful and small packets each having its individual significance and a role to play while processing data."},{"code":null,"e":15130,"s":14984,"text":"Gateways made the data more secure if the modifications to the gateway could be done which then could create more reliability over smart devices."},{"code":null,"e":15379,"s":15130,"text":"Gateways optimize the data for search engines, applications, and servers by implanting better readability to the content so that a machine could understand and optimize data with ease. For more details, please refer to the Introduction of Gateways."},{"code":null,"e":15422,"s":15379,"text":"23. Is Ipv6 Backward Compatible With Ipv4?"},{"code":null,"e":15554,"s":15422,"text":"No, IPv6 is not backward compatible with IPv4 protocol. For more details, please refer to the Internet protocol version 6 article."},{"code":null,"e":15627,"s":15554,"text":"24. Is It Possible To Have An Ipv4 And An Ipv6 Addresses Simultaneously?"},{"code":null,"e":15816,"s":15627,"text":"Yes, it is possible to have an IPv4 and IPv6 addresses simultaneously. For more details, please refer to the Internet protocol version 6 and the difference between IPv4 and IPv6 articles."},{"code":null,"e":15833,"s":15816,"text":"25. What is TTL?"},{"code":null,"e":16293,"s":15833,"text":"The lifespan or lifetime of data that is being sent. Once after that specified time is over or elapsed, the data will be discarded Or it can also be stated as the number of hops that packet is set to exist in the network, after which that packet is discarded. The purpose of the TTL field is to avoid a situation in which an undeliverable datagram keeps circulating in the network. For more details, please refer to the difference between RTT and TTL article."},{"code":null,"e":16385,"s":16293,"text":"26. If the TTL field has the value of 10. How many routers (max) can process this datagram?"},{"code":null,"e":16756,"s":16385,"text":"TTL stands for Time to Live. This field specifies the life of the IP packet based on the number of hops it makes ( number of routers it goes through). TTL field is decremented by one each time the datagram is processed by a router. When the value is 0, the packet is automatically destroyed. For more details, please refer to the difference between RTT and TTL articles."},{"code":null,"e":16855,"s":16756,"text":"27. If the value in the protocol field is 17, the transport layer protocol used is which protocol?"},{"code":null,"e":17008,"s":16855,"text":"If the value in the protocol field is 17, the transport layer protocol uses UDP (User Datagram Protocol). For more details, please refer to UDP article."},{"code":null,"e":17108,"s":17008,"text":"28. What happens in classless addressing, if there are no classes but addresses are still granted?"},{"code":null,"e":17365,"s":17108,"text":"In classless addressing, there are no classes but addresses are still granted in blocks. The total number of addresses in a block of classless IP addresses = 2(32 – CIDR_value). For more details, please refer to the introduction of Classful IP addressing."},{"code":null,"e":17534,"s":17365,"text":"29. Suppose two IPv6 nodes want to interoperate using IPv6 datagrams, but they are connected to each other by intervening IPv4 routers. Then what is the best solution?"},{"code":null,"e":17767,"s":17534,"text":"If two IPv6 nodes want to interoperate using IPv6 datagrams, they are connected to each other by intervening IPv4 routers. Then tunneling is the best solution. For more details, please refer to Internet protocol version 6 article."},{"code":null,"e":17785,"s":17767,"text":"30. What is IANA?"},{"code":null,"e":18398,"s":17785,"text":"IANA, the Internet Assigned Numbers Authority, is an administrative function of the Internet that keeps track of IP addresses, domain names, and protocol parameter identifiers that are used by Internet standards. Some of these identifiers are parameters, such as those used by Internet protocols (like TCP, ICMP or UDP) to specify functions and behaviour; some of them represent Internet addresses and others represent domain names. Regardless of the type of identifier, the IANA function (IANA for short below) ensures that values are managed for uniqueness and made available in publicly accessible registries."},{"code":null,"e":18416,"s":18398,"text":"31. What is DHCP?"},{"code":null,"e":18817,"s":18416,"text":"DHCP is an abbreviation for Dynamic Host Configuration Protocol. It is an application layer protocol used by hosts for obtaining network setup information. The DHCP is controlled by a DHCP server that dynamically distributes network configuration parameters such as IP addresses, subnet mask, and gateway address. For more details, please refer to Dynamic Host Configuration Protocol (DHCP) article."},{"code":null,"e":18866,"s":18817,"text":"32. How can you manage a network using a router?"},{"code":null,"e":19281,"s":18866,"text":"Routers have built-in console that lets you configure different settings, like security and data logging.We can assign restrictions to computers, such as what resources they are allowed to access, or what particular time of the day they can browse the internet.We can even put restrictions on what websites are not viewable across the entire network. For more details, please refer to the introduction of a Router."},{"code":null,"e":19303,"s":19281,"text":"33. What is ipconfig?"},{"code":null,"e":19891,"s":19303,"text":"IPCONFIG stands for Internet Protocol Configuration. This is a command-line application that displays all the current TCP/IP (Transmission Control Protocol/Internet Protocol) network configuration, refreshes the DHCP (Dynamic Host Configuration Protocol) and DNS (Domain Name Server). It also displays an IP address, subnet mask, and a default gateway for all adapters. It is available for Microsoft Windows, ReactOS, and Apple macOS. ReactOS version was developed by Ged Murphy and licensed under the General Public License. For more details, please refer to ipconfig full form article."},{"code":null,"e":19996,"s":19891,"text":"34. When you move the NIC cards from one PC to another PC, does the MAC address get transferred as well?"},{"code":null,"e":20284,"s":19996,"text":"Yes, if we move the NIC cards from one PC to another PC, then the MAC address also gets transferred, because the MAC address is hard-wired into the NIC circuit, not the personal computer. This also means that a PC can have a different MAC address when another one replaces the NIC card. "},{"code":null,"e":20316,"s":20284,"text":"35. Explain clustering support?"},{"code":null,"e":20579,"s":20316,"text":"Clustering support refers to the ability of a network operating system to connect multiple servers in a fault-tolerant group. The main purpose of this is the in the event that one server fails, all processing will continue on with the next server in the cluster."},{"code":null,"e":20600,"s":20579,"text":"36. What is Brouter?"},{"code":null,"e":21013,"s":20600,"text":" Brouter – It is also known as the bridging router is a device that combines features of both bridge and router. It can work either at the data link layer or a network layer. Working as a router, it is capable of routing packets across networks, and working as the bridge, it is capable of filtering local area network traffic. For more details, please refer to the difference between Router and Brouter article."},{"code":null,"e":21046,"s":21013,"text":"37. Explain the features of VPN?"},{"code":null,"e":21566,"s":21046,"text":"VPN also ensures security by providing an encrypted tunnel between client and vpn server.VPN is used to bypass many blocked sites.VPN facilitates anonymous browsing by hiding your ip address.Also, the most appropriate Search engine optimization(SEO) is done by analyzing the data from VPN providers which provide country-wise states for browsing a particular product. This method of SEO is used widely by many internet marketing managers to form new strategies.For more details, please refer to Virtual Private Network."},{"code":null,"e":21656,"s":21566,"text":"VPN also ensures security by providing an encrypted tunnel between client and vpn server."},{"code":null,"e":21698,"s":21656,"text":"VPN is used to bypass many blocked sites."},{"code":null,"e":21760,"s":21698,"text":"VPN facilitates anonymous browsing by hiding your ip address."},{"code":null,"e":22089,"s":21760,"text":"Also, the most appropriate Search engine optimization(SEO) is done by analyzing the data from VPN providers which provide country-wise states for browsing a particular product. This method of SEO is used widely by many internet marketing managers to form new strategies.For more details, please refer to Virtual Private Network."},{"code":null,"e":22164,"s":22089,"text":"38. What are the important differences between MAC address and IP address?"},{"code":null,"e":22187,"s":22164,"text":"39. What is 127.0.0.1?"},{"code":null,"e":22530,"s":22187,"text":"In IPv4, IP addresses that start with decimal 127 or that has 01111111 in the first octet are loopback addresses(127.X.X.X). Typically 127.0.0.1 is used as the local loopback address.This leads to the wastage of many potential IP addresses. But in IPv6 ::1 is used as local loopback address and therefore there isn’t any wastage of addresses."},{"code":null,"e":22549,"s":22530,"text":"40. What is a DNS?"},{"code":null,"e":22827,"s":22549,"text":"DNS is a host name to IP address translation service. DNS is a distributed database implemented in a hierarchy of name servers. It is an application layer protocol for message exchange between clients and servers. For more details, please refer to DNS in the application layer."},{"code":null,"e":22866,"s":22827,"text":"41. What is the use of a proxy server?"},{"code":null,"e":23499,"s":22866,"text":"Proxy server refers to a server that acts as an intermediary between the request made by clients, and a particular server for some services or requests for some resources. There are different types of proxy servers available that are put into use according to the purpose of a request made by the clients to the servers. The basic purpose of Proxy servers is to protect the direct connection of Internet clients and internet resources. The proxy server also prevents the identification of the client’s IP address when the client makes any request is made to any other servers. For more details, please refer to Proxy server article."},{"code":null,"e":23566,"s":23499,"text":"42. What is the difference between ipconfig and ifconfig commands?"},{"code":null,"e":24087,"s":23566,"text":"IPCONFIG stands for Internet Protocol Configuration. This is a command-line application that displays all the current TCP/IP (Transmission Control Protocol/Internet Protocol) network configuration, refreshes the DHCP (Dynamic Host Configuration Protocol) and DNS (Domain Name Server). It also displays IP address, subnet mask, and default gateway for all adapters. It is available for Microsoft Windows, ReactOS, and Apple macOS. ReactOS version was developed by Ged Murphy and licensed under the General Public License."},{"code":null,"e":24502,"s":24087,"text":"ifconfig(interface configuration) command is used to configure the kernel-resident network interfaces. It is used at boot time to set up the interfaces as necessary. After that, it is usually used when needed during debugging or when you need system tuning. Also, this command is used to assign the IP address and netmask to an interface or to enable or disable a given interface. For more details, please refer to"},{"code":null,"e":24553,"s":24502,"text":"43. What is the importance of APIPA in networking?"},{"code":null,"e":25137,"s":24553,"text":"Automatic Private IP Addressing is important in networking because communication can be established properly if you don’t get a response from DHCP Server. APIPA regulates the service, by which the response and status of the main DHCP server at a specific period of time. Apart from that, it can be used as a backup to DHCP because when DHCP stops working, APIPA has the ability to assign IP to the networking hosts.It stops unwanted broadcasting. It uses ARP(Address Resolution Protocol) to confirm the address isn’t currently in use. For more details, please refer to What is APIPA."},{"code":null,"e":25196,"s":25137,"text":"44. What is the difference between Firewall and Antivirus?"},{"code":null,"e":25214,"s":25196,"text":"45. What is SLIP?"},{"code":null,"e":25972,"s":25214,"text":"SLIP stands for Serial Line Internet Protocol. It is a TCP/IP implementation which was described under RFC 1055 (Request for Comments). SLIP establishes point-to-point serial connections which can be used in dial-up connections, serial ports and routers. It frames the encapsulated IP packets across a serial line for establishing connection while using line speed between 12000 bps and 19.2 Kbps. SLIP was introduced in 1984 when Rick Adams used it to connect 4.2 Berkeley Unix and Sun Microsystems workstations. It soon caught up with the rest of the world as a credible TCP/IP implementation. It has now become obsolete after being replaced by PPP (Point to Point Protocol) which solves many deficiencies present in it. For more details, please refer to"},{"code":null,"e":26004,"s":25972,"text":"46. What is Kerberos protocol?"},{"code":null,"e":26356,"s":26004,"text":"Kerberos provides a centralized authentication server whose function is to authenticate users to servers and servers to users. In Kerberos Authentication server and database is used for client authentication. Kerberos runs as a third-party trusted server known as the Key Distribution Center (KDC). Each user and service on the network is a principal."},{"code":null,"e":26393,"s":26356,"text":"The main components of Kerberos are:"},{"code":null,"e":26522,"s":26393,"text":"Authentication Server (AS):The Authentication Server performs the initial authentication and ticket for Ticket Granting Service."},{"code":null,"e":26610,"s":26522,"text":"Database:The Authentication Server verifies the access rights of users in the database."},{"code":null,"e":26700,"s":26610,"text":"Ticket Granting Server (TGS):The Ticket Granting Server issues the ticket for the Server."},{"code":null,"e":26752,"s":26700,"text":"For more details, please refer to Kerberos article."},{"code":null,"e":26771,"s":26752,"text":"47. What is HSRP?"},{"code":null,"e":26952,"s":26771,"text":"Hot Standby Router Protocol (HSRP) is a CISCO proprietary protocol, which provides redundancy for a local subnet. In HSRP, two or more routers give an illusion of a virtual router."},{"code":null,"e":27386,"s":26952,"text":"HSRP allows you to configure two or more routers as standby routers and only a single router as an active router at a time. All the routers in a single HSRP group share a single MAC address and IP address, which acts as a default gateway to the local network. The Active router is responsible for forwarding the traffic. If it fails, the Standby router takes up all the responsibilities of the active router and forwards the traffic."},{"code":null,"e":27435,"s":27386,"text":"For more details, please refer to HSRP protocol."},{"code":null,"e":27491,"s":27435,"text":"48. Why is the MAC address called the Physical address?"},{"code":null,"e":27890,"s":27491,"text":"The MAC address is a physical address (also called a hardware address) because it physically identifies an item of hardware. MAC addresses use three types of number systems and all use the same format, only the size of the identifier differs. The addresses can be “Universally Managed” or “Locally Managed”. For more details, please refer to Introduction of MAC Address in Computer Network article."},{"code":null,"e":27917,"s":27890,"text":"49. Process of DHCP(DORA)?"},{"code":null,"e":28236,"s":27917,"text":"In DHCP, the client and the server exchange mainly 4 DHCP messages in order to make a connection. This process is known as DORA process (discovery, offer, request, and acknowledgment), but there are 8 DHCP messages in the process. For more details, please refer to Dynamic Host Configuration Protocol (DHCP) article."},{"code":null,"e":28258,"s":28236,"text":"50. What is ‘APIPA’?"},{"code":null,"e":28741,"s":28258,"text":"APIPA stands for Automatic Private IP Addressing (APIPA). It is a feature or characteristic in operating systems (eg. Windows) which enables computers to self-configure an IP address and subnet mask automatically when their DHCP(Dynamic Host Configuration Protocol) server isn’t reachable. The IP address range for APIPA is (169.254.0.1 to 169.254.255.254) having 65, 534 usable IP addresses, with the subnet mask of 255.255.0.0. For more details please read What is APIPA article."},{"code":null,"e":28755,"s":28743,"text":"anikakapoor"},{"code":null,"e":28775,"s":28755,"text":"interview-questions"},{"code":null,"e":28793,"s":28775,"text":"Computer Networks"},{"code":null,"e":28811,"s":28793,"text":"Computer Networks"}],"string":"[\n {\n \"code\": null,\n \"e\": 28,\n \"s\": 0,\n \"text\": \"\\n15 Sep, 2021\"\n },\n {\n \"code\": null,\n \"e\": 51,\n \"s\": 28,\n \"text\": \"1. What is IP address?\"\n },\n {\n \"code\": null,\n \"e\": 419,\n \"s\": 51,\n \"text\": \"IP address is an address having information about how to reach a specific host, especially outside the LAN. An IP address is 32 bit unique address having an address space of 232. Generally, there are two notations in which IP address is written, dotted decimal notation and hexadecimal notation. For more details, please refer introduction of Classful IP addressing.\"\n },\n {\n \"code\": null,\n \"e\": 503,\n \"s\": 419,\n \"text\": \"2. What are the different classes of IP addresses and give the range of each class?\"\n },\n {\n \"code\": null,\n \"e\": 683,\n \"s\": 503,\n \"text\": \"IP address is an address having information about how to reach a specific host, especially outside the LAN. An IP address is 32-bit unique address having an address space of 232.\"\n },\n {\n \"code\": null,\n \"e\": 754,\n \"s\": 683,\n \"text\": \"For more details, please refer introduction of Classful IP addressing.\"\n },\n {\n \"code\": null,\n \"e\": 778,\n \"s\": 754,\n \"text\": \"3. What is subnet mask?\"\n },\n {\n \"code\": null,\n \"e\": 1019,\n \"s\": 778,\n \"text\": \"A subnet mask is a 32-bit number that is used to identify the subnet of an IP address. The subnet mask is a combination of 1’s and 0’s. 1’s represents network and subnet ID while 0’s represents the host ID. In this case, the subnet mask is,\"\n },\n {\n \"code\": null,\n \"e\": 1076,\n \"s\": 1019,\n \"text\": \"11111111.11111111.11111111.11000000 \\nor\\n255.255.255.192 \"\n },\n {\n \"code\": null,\n \"e\": 1191,\n \"s\": 1076,\n \"text\": \"So, in order to get the network to which the destination address belongs, we have to bitwise & with a subnet mask.\"\n },\n {\n \"code\": null,\n \"e\": 1366,\n \"s\": 1191,\n \"text\": \" 11111111.11111111.11111111.11000000\\n&& 11001000.00000001.00000010.00010100\\n-----------------------------------------------------\\n 11001000.00000001.00000010.00000000 \"\n },\n {\n \"code\": null,\n \"e\": 1390,\n \"s\": 1366,\n \"text\": \"The address belongs to,\"\n },\n {\n \"code\": null,\n \"e\": 1441,\n \"s\": 1390,\n \"text\": \"11001000.00000001.00000010.00000000 \\nor\\n200.1.2.0 \"\n },\n {\n \"code\": null,\n \"e\": 1501,\n \"s\": 1441,\n \"text\": \"For more details, please refer Role of Subnet Mask article.\"\n },\n {\n \"code\": null,\n \"e\": 1522,\n \"s\": 1501,\n \"text\": \"4. Why CIDR is used?\"\n },\n {\n \"code\": null,\n \"e\": 2079,\n \"s\": 1522,\n \"text\": \"The problem with this classful addressing method is that millions of class A addresses are wasted, many of the class B addresses are wasted, whereas, number of addresses available in class C is so small that it cannot cater to the needs of organizations. Class D addresses are used for multicast routing and are therefore available as a single block only. Class E addresses are reserved. Since there are these problems, Classful networking was replaced by Classless Inter-Domain Routing (CIDR). For more details, please refer CIDR full-form to the article.\"\n },\n {\n \"code\": null,\n \"e\": 2112,\n \"s\": 2079,\n \"text\": \"5. What is the LOOPBACK address?\"\n },\n {\n \"code\": null,\n \"e\": 2329,\n \"s\": 2112,\n \"text\": \"Loopback Address is used to let a system send a message to itself to make sure that the TCP/IP stack is installed correctly on the machine. For more details, please refer Local Broadcast and Loopback address article.\"\n },\n {\n \"code\": null,\n \"e\": 2359,\n \"s\": 2329,\n \"text\": \"6. What is a Default Gateway?\"\n },\n {\n \"code\": null,\n \"e\": 2876,\n \"s\": 2359,\n \"text\": \"In organizational systems, a gateway is a node that routes the traffic from a workstation to another network segment. The default gateway commonly connects the internal networks and the outside network (Internet). In such a situation, the gateway node could also act as a proxy server and a firewall. The gateway is also associated with both a router, which uses headers and forwarding tables to determine where packets are sent and a switch, which provides the actual path for the packet in and out of the gateway. \"\n },\n {\n \"code\": null,\n \"e\": 2972,\n \"s\": 2876,\n \"text\": \"For more details, please refer to Working of different layers in the Computer network article. \"\n },\n {\n \"code\": null,\n \"e\": 3005,\n \"s\": 2972,\n \"text\": \"7. Why Hop limit field is used?\"\n },\n {\n \"code\": null,\n \"e\": 3388,\n \"s\": 3005,\n \"text\": \"Hop Limit: Hop Limit field is the same as TTL in IPv4 packets. It indicates the maximum number of intermediate nodes IPv6 packet is allowed to travel. Its value gets decremented by one, by each node that forwards the packet and the packet is discarded if the value decreases to 0. This is used to discard the packets that are stuck in an infinite loop because of some routing error.\"\n },\n {\n \"code\": null,\n \"e\": 3473,\n \"s\": 3388,\n \"text\": \"For more details, please refer to Internet Protocol version 6 (IPv6) Header article.\"\n },\n {\n \"code\": null,\n \"e\": 3507,\n \"s\": 3473,\n \"text\": \"8. What protocol is used by PING?\"\n },\n {\n \"code\": null,\n \"e\": 3651,\n \"s\": 3507,\n \"text\": \"ICMP (Internet Control Message Protocol) is used by PING. For more details, please refer to the Difference between Ping and Traceroute article.\"\n },\n {\n \"code\": null,\n \"e\": 3679,\n \"s\": 3651,\n \"text\": \"9. What is used of Tracert?\"\n },\n {\n \"code\": null,\n \"e\": 3989,\n \"s\": 3679,\n \"text\": \"Traceroute is a widely used command-line utility available in almost all operating systems. It shows you the complete route to a destination address. It also shows the time is taken (or delays) between intermediate routers. For more details, please refer to the Difference between Ping and Traceroute article.\"\n },\n {\n \"code\": null,\n \"e\": 4030,\n \"s\": 3989,\n \"text\": \"10. Name the ports used by FTP protocol?\"\n },\n {\n \"code\": null,\n \"e\": 4070,\n \"s\": 4030,\n \"text\": \"Basically, FTP protocol uses two ports:\"\n },\n {\n \"code\": null,\n \"e\": 4328,\n \"s\": 4070,\n \"text\": \"Control connection: For sending control information like user identification, password, commands to change the remote directory, commands to retrieve and store files, etc., FTP makes use of connections. The control connection is initiated on port number 21.\"\n },\n {\n \"code\": null,\n \"e\": 4557,\n \"s\": 4328,\n \"text\": \"Data connection: For sending the actual file, FTP makes use of a data connection. A data connection is initiated on port number 20. For more details, please refer to File Transfer Protocol (FTP) in the Application Layer article.\"\n },\n {\n \"code\": null,\n \"e\": 4582,\n \"s\": 4557,\n \"text\": \"11. What is MAC address?\"\n },\n {\n \"code\": null,\n \"e\": 4902,\n \"s\": 4582,\n \"text\": \"MAC Addresses are unique 48-bit hardware numbers of computers, which are embedded into a network card (known as Network Interface Card) during the time of manufacturing. The MAC Address is also known as the Physical Address of a network device. In IEEE 802 standard, the Data Link Layer is divided into two sublayers – \"\n },\n {\n \"code\": null,\n \"e\": 4971,\n \"s\": 4902,\n \"text\": \"Logical Link Control(LLC) SublayerMedia Access Control(MAC) Sublayer\"\n },\n {\n \"code\": null,\n \"e\": 5006,\n \"s\": 4971,\n \"text\": \"Logical Link Control(LLC) Sublayer\"\n },\n {\n \"code\": null,\n \"e\": 5041,\n \"s\": 5006,\n \"text\": \"Media Access Control(MAC) Sublayer\"\n },\n {\n \"code\": null,\n \"e\": 5244,\n \"s\": 5041,\n \"text\": \"The MAC address is used by the Media Access Control (MAC) sublayer of the Data-Link Layer. MAC Address is unique worldwide since millions of network devices exist and we need to uniquely identify each. \"\n },\n {\n \"code\": null,\n \"e\": 5335,\n \"s\": 5244,\n \"text\": \"For more details, please refer to Introduction of MAC Address in Computer Network article.\"\n },\n {\n \"code\": null,\n \"e\": 5352,\n \"s\": 5335,\n \"text\": \"12. Explain ARP?\"\n },\n {\n \"code\": null,\n \"e\": 5881,\n \"s\": 5352,\n \"text\": \"Address Resolution Protocol is a communication protocol used for discovering physical addresses associated with a given network address. Typically, ARP is a network layer to data link layer mapping process, which is used to discover MAC addresses for a given Internet Protocol Address.In order to send the data to the destination, having an IP address is necessary but not sufficient; we also need the physical address of the destination machine. ARP is used to get the physical address (MAC address) of the destination machine.\"\n },\n {\n \"code\": null,\n \"e\": 6521,\n \"s\": 5881,\n \"text\": \"Before sending the IP packet, the MAC address of the destination must be known. If not so, then the sender broadcasts the ARP-discovery packet requesting the MAC address of the intended destination. Since ARP-discovery is broadcast, every host inside that network will get this message but the packet will be discarded by everyone except that intended receiver host whose IP is associated. Now, this receiver will send a unicast packet with its MAC address (ARP-reply) to the sender of the ARP-discovery packet. After the original sender receives the ARP-reply, it updates ARP-cache and starts sending a unicast message to the destination.\"\n },\n {\n \"code\": null,\n \"e\": 6606,\n \"s\": 6521,\n \"text\": \"For more details, please refer to the How Address Resolution Protocol works article.\"\n },\n {\n \"code\": null,\n \"e\": 6624,\n \"s\": 6606,\n \"text\": \"13. What is MTU?\"\n },\n {\n \"code\": null,\n \"e\": 6980,\n \"s\": 6624,\n \"text\": \"A maximum transmission unit also called MTU, is a term used in networking and operating systems. It defines the largest size of the packet that can be transmitted as a single entity in a network connection. The size of the MTU dictates the amount of data that can be transmitted in bytes over a network. For more details, please refer What is MTU article.\"\n },\n {\n \"code\": null,\n \"e\": 7695,\n \"s\": 6980,\n \"text\": \"14. If a class B network on the Internet has a subnet mask of 255.255.248.0, what is the maximum number of hosts per subnet?The binary representation of the subnet mask is 11111111.11111111.11111000. 00000000. There are 21 bits set in a subnet. So 11 (32-21) bits are left for host ids. The total possible value of host ids is 2^11 = 2048. Out of these 2048 values, 2 addresses are reserved. The address with all bits as 1 is reserved as broadcast address and the address with all host id bits as 0 is used as a network address of the subnet.In general, the number of addresses usable for addressing specific hosts in each network is always 2^N – 2 where N is the number of bits for host id. So the answer is 2046.\"\n },\n {\n \"code\": null,\n \"e\": 7721,\n \"s\": 7695,\n \"text\": \"15. What is IP multicast?\"\n },\n {\n \"code\": null,\n \"e\": 8235,\n \"s\": 7721,\n \"text\": \"Multicasting has one/more senders and one/more recipients participate in data transfer traffic. In multicasting, traffic reclines between the boundaries of unicast and broadcast. Its server’s direct single copies of data streams and that are then simulated and routed to hosts that request it. IP multicast requires the support of some other protocols such as Internet Group Management Protocol (IGMP), Multicast routing for its work. And also, in Classful IP, addressing Class D is reserved for multicast groups.\"\n },\n {\n \"code\": null,\n \"e\": 8291,\n \"s\": 8235,\n \"text\": \"16. Difference between public and private IP addresses?\"\n },\n {\n \"code\": null,\n \"e\": 9821,\n \"s\": 8291,\n \"text\": \"Public IP address–A public IP address is an Internet Protocol address, encrypted by various servers/devices. That’s when you connect these devices with your internet connection. This is the same IP address we show on our homepage. So why the second page? Well, not all people speak the IP language. We want to make it as easy as possible for everyone to get the information they need. Some even call this their external IP address. A public Internet Protocol address is an Internet Protocol address accessed over the Internet. Like the postal address used to deliver mail to your home, the public Internet Protocol address is a different international Internet Protocol address assigned to a computer device. The web server, email server, and any server device that has direct access to the Internet are those who will enter the public Internet Protocol address. Internet Address Protocol is unique worldwide and is only supplied with a unique device.Private IP address–Everything that connects to your Internet network has a private IP address. This includes computers, smartphones, and tablets but also any Bluetooth-enabled devices such as speakers, printers, or smart TVs. With the growing internet of things, the number of private IP addresses you have at home is likely to increase. Your router needs a way to identify these things separately, and most things need a way to get to know each other. Therefore, your router generates private IP addresses that are unique identifiers for each device that separates the network.\"\n },\n {\n \"code\": null,\n \"e\": 10773,\n \"s\": 9821,\n \"text\": \"Public IP address–A public IP address is an Internet Protocol address, encrypted by various servers/devices. That’s when you connect these devices with your internet connection. This is the same IP address we show on our homepage. So why the second page? Well, not all people speak the IP language. We want to make it as easy as possible for everyone to get the information they need. Some even call this their external IP address. A public Internet Protocol address is an Internet Protocol address accessed over the Internet. Like the postal address used to deliver mail to your home, the public Internet Protocol address is a different international Internet Protocol address assigned to a computer device. The web server, email server, and any server device that has direct access to the Internet are those who will enter the public Internet Protocol address. Internet Address Protocol is unique worldwide and is only supplied with a unique device.\"\n },\n {\n \"code\": null,\n \"e\": 11352,\n \"s\": 10773,\n \"text\": \"Private IP address–Everything that connects to your Internet network has a private IP address. This includes computers, smartphones, and tablets but also any Bluetooth-enabled devices such as speakers, printers, or smart TVs. With the growing internet of things, the number of private IP addresses you have at home is likely to increase. Your router needs a way to identify these things separately, and most things need a way to get to know each other. Therefore, your router generates private IP addresses that are unique identifiers for each device that separates the network.\"\n },\n {\n \"code\": null,\n \"e\": 11389,\n \"s\": 11352,\n \"text\": \"17. Can you explain what subnetting?\"\n },\n {\n \"code\": null,\n \"e\": 11628,\n \"s\": 11389,\n \"text\": \"When a bigger network is divided into smaller networks, in order to maintain security, then that is known as Subnetting. so, maintenance is easier for smaller networks. For more details please read an introduction to a subnetting article.\"\n },\n {\n \"code\": null,\n \"e\": 11681,\n \"s\": 11628,\n \"text\": \"18. Do you know what is Network Address Translation?\"\n },\n {\n \"code\": null,\n \"e\": 12564,\n \"s\": 11681,\n \"text\": \"To access the Internet, one public IP address is needed, but we can use a private IP address on our private network. The idea of NAT is to allow multiple devices to access the Internet through a single public address. To achieve this, the translation of a private IP address to a public IP address is required. Network Address Translation (NAT) is a process in which one or more local IP addresses is translated into one or more Global IP addresses and vice versa in order to provide Internet access to the local hosts. Also, it does the translation of port numbers i.e. masks the port number of the host with another port number in the packet that will be routed to the destination. It then makes the corresponding entries of IP address and port number in the NAT table. NAT generally operates on a router or firewall. For more details, please refer to Network Address Translation.\"\n },\n {\n \"code\": null,\n \"e\": 13106,\n \"s\": 12564,\n \"text\": \"19. An organization requires a range of IP addresses to assign one to each of its 1500 computers. The organization has approached an Internet Service Provider (ISP) for this task. The ISP uses CIDR and serves the requests from the available IP address space 202.61.0.0/17. The ISP wants to assign address space to the organization which will minimize the number of routing entries in the ISP’s router using route aggregation. To calculate the address spaces are potential candidates from which the ISP can allow any one of the organizations?\"\n },\n {\n \"code\": null,\n \"e\": 13144,\n \"s\": 13106,\n \"text\": \"Subnet Mask for the given IP address:\"\n },\n {\n \"code\": null,\n \"e\": 13214,\n \"s\": 13144,\n \"text\": \"202.61.0.0/17 \\n⇒ 11111111 11111111 10000000 00000000\\n⇒ 255.255.128.0 \"\n },\n {\n \"code\": null,\n \"e\": 13272,\n \"s\": 13214,\n \"text\": \"Now, since we need 1500 hosts, so, bits for host address,\"\n },\n {\n \"code\": null,\n \"e\": 13344,\n \"s\": 13272,\n \"text\": \"= ceiling (log2 (1500)) \\n= ceiling (10.55) \\n= 11 bits for host address \"\n },\n {\n \"code\": null,\n \"e\": 13393,\n \"s\": 13344,\n \"text\": \"So, the last 11 bits will be for host addresses:\"\n },\n {\n \"code\": null,\n \"e\": 13557,\n \"s\": 13393,\n \"text\": \"00000000.00000000 → 00000111.11111111 (0.0 → 7.255)\\n\\n00001000.00000000 → 00010000.00000000 (8.0 - 15.255)\\n\\n00001111.11111111 → 00010111.11111111 (16.0 - 23.255) \"\n },\n {\n \"code\": null,\n \"e\": 13632,\n \"s\": 13557,\n \"text\": \"Sequences are 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 96, 104, 112, 120.\"\n },\n {\n \"code\": null,\n \"e\": 13752,\n \"s\": 13632,\n \"text\": \"Hence, 64 and 104 are present in the sequence, so 202.61.104.0 / 21 and 202.61.64.0 / 21 are the possible IP addresses.\"\n },\n {\n \"code\": null,\n \"e\": 13810,\n \"s\": 13752,\n \"text\": \"20. Explain the difference between Static and Dynamic IP?\"\n },\n {\n \"code\": null,\n \"e\": 13896,\n \"s\": 13810,\n \"text\": \"For more details, please refer to Difference between Static and Dynamic IP addresses.\"\n },\n {\n \"code\": null,\n \"e\": 13941,\n \"s\": 13896,\n \"text\": \"21. How will my computer get its IP Address?\"\n },\n {\n \"code\": null,\n \"e\": 13961,\n \"s\": 13941,\n \"text\": \"To get IP address :\"\n },\n {\n \"code\": null,\n \"e\": 14069,\n \"s\": 13961,\n \"text\": \"Click on start ->Programs->Accessories->Command prompt.Type ipconfig on command prompt and press enter key.\"\n },\n {\n \"code\": null,\n \"e\": 14125,\n \"s\": 14069,\n \"text\": \"Click on start ->Programs->Accessories->Command prompt.\"\n },\n {\n \"code\": null,\n \"e\": 14178,\n \"s\": 14125,\n \"text\": \"Type ipconfig on command prompt and press enter key.\"\n },\n {\n \"code\": null,\n \"e\": 14274,\n \"s\": 14178,\n \"text\": \"By using these steps, you can get your PC IP address, Subnet Mask, and default gateway details.\"\n },\n {\n \"code\": null,\n \"e\": 14312,\n \"s\": 14274,\n \"text\": \"22. What are the features of Gateway?\"\n },\n {\n \"code\": null,\n \"e\": 14376,\n \"s\": 14312,\n \"text\": \"Gateways provide a wide variety of features. Some of which are:\"\n },\n {\n \"code\": null,\n \"e\": 14548,\n \"s\": 14376,\n \"text\": \"Gateways work as a network bridge for data transmission as it makes the transmission of data possible to transmit with more ease and does not demand high storage capacity.\"\n },\n {\n \"code\": null,\n \"e\": 14676,\n \"s\": 14548,\n \"text\": \"Gateways create a structural temporary storeroom for the data transmitted by the server and data requests made by the user end.\"\n },\n {\n \"code\": null,\n \"e\": 14984,\n \"s\": 14676,\n \"text\": \"Gateways made the transmission more feasible as it queued up all the data and divide it into small packets of data rather than sending it bulk. Data transmitted through Gateway is divided into various useful and small packets each having its individual significance and a role to play while processing data.\"\n },\n {\n \"code\": null,\n \"e\": 15130,\n \"s\": 14984,\n \"text\": \"Gateways made the data more secure if the modifications to the gateway could be done which then could create more reliability over smart devices.\"\n },\n {\n \"code\": null,\n \"e\": 15379,\n \"s\": 15130,\n \"text\": \"Gateways optimize the data for search engines, applications, and servers by implanting better readability to the content so that a machine could understand and optimize data with ease. For more details, please refer to the Introduction of Gateways.\"\n },\n {\n \"code\": null,\n \"e\": 15422,\n \"s\": 15379,\n \"text\": \"23. Is Ipv6 Backward Compatible With Ipv4?\"\n },\n {\n \"code\": null,\n \"e\": 15554,\n \"s\": 15422,\n \"text\": \"No, IPv6 is not backward compatible with IPv4 protocol. For more details, please refer to the Internet protocol version 6 article.\"\n },\n {\n \"code\": null,\n \"e\": 15627,\n \"s\": 15554,\n \"text\": \"24. Is It Possible To Have An Ipv4 And An Ipv6 Addresses Simultaneously?\"\n },\n {\n \"code\": null,\n \"e\": 15816,\n \"s\": 15627,\n \"text\": \"Yes, it is possible to have an IPv4 and IPv6 addresses simultaneously. For more details, please refer to the Internet protocol version 6 and the difference between IPv4 and IPv6 articles.\"\n },\n {\n \"code\": null,\n \"e\": 15833,\n \"s\": 15816,\n \"text\": \"25. What is TTL?\"\n },\n {\n \"code\": null,\n \"e\": 16293,\n \"s\": 15833,\n \"text\": \"The lifespan or lifetime of data that is being sent. Once after that specified time is over or elapsed, the data will be discarded Or it can also be stated as the number of hops that packet is set to exist in the network, after which that packet is discarded. The purpose of the TTL field is to avoid a situation in which an undeliverable datagram keeps circulating in the network. For more details, please refer to the difference between RTT and TTL article.\"\n },\n {\n \"code\": null,\n \"e\": 16385,\n \"s\": 16293,\n \"text\": \"26. If the TTL field has the value of 10. How many routers (max) can process this datagram?\"\n },\n {\n \"code\": null,\n \"e\": 16756,\n \"s\": 16385,\n \"text\": \"TTL stands for Time to Live. This field specifies the life of the IP packet based on the number of hops it makes ( number of routers it goes through). TTL field is decremented by one each time the datagram is processed by a router. When the value is 0, the packet is automatically destroyed. For more details, please refer to the difference between RTT and TTL articles.\"\n },\n {\n \"code\": null,\n \"e\": 16855,\n \"s\": 16756,\n \"text\": \"27. If the value in the protocol field is 17, the transport layer protocol used is which protocol?\"\n },\n {\n \"code\": null,\n \"e\": 17008,\n \"s\": 16855,\n \"text\": \"If the value in the protocol field is 17, the transport layer protocol uses UDP (User Datagram Protocol). For more details, please refer to UDP article.\"\n },\n {\n \"code\": null,\n \"e\": 17108,\n \"s\": 17008,\n \"text\": \"28. What happens in classless addressing, if there are no classes but addresses are still granted?\"\n },\n {\n \"code\": null,\n \"e\": 17365,\n \"s\": 17108,\n \"text\": \"In classless addressing, there are no classes but addresses are still granted in blocks. The total number of addresses in a block of classless IP addresses = 2(32 – CIDR_value). For more details, please refer to the introduction of Classful IP addressing.\"\n },\n {\n \"code\": null,\n \"e\": 17534,\n \"s\": 17365,\n \"text\": \"29. Suppose two IPv6 nodes want to interoperate using IPv6 datagrams, but they are connected to each other by intervening IPv4 routers. Then what is the best solution?\"\n },\n {\n \"code\": null,\n \"e\": 17767,\n \"s\": 17534,\n \"text\": \"If two IPv6 nodes want to interoperate using IPv6 datagrams, they are connected to each other by intervening IPv4 routers. Then tunneling is the best solution. For more details, please refer to Internet protocol version 6 article.\"\n },\n {\n \"code\": null,\n \"e\": 17785,\n \"s\": 17767,\n \"text\": \"30. What is IANA?\"\n },\n {\n \"code\": null,\n \"e\": 18398,\n \"s\": 17785,\n \"text\": \"IANA, the Internet Assigned Numbers Authority, is an administrative function of the Internet that keeps track of IP addresses, domain names, and protocol parameter identifiers that are used by Internet standards. Some of these identifiers are parameters, such as those used by Internet protocols (like TCP, ICMP or UDP) to specify functions and behaviour; some of them represent Internet addresses and others represent domain names. Regardless of the type of identifier, the IANA function (IANA for short below) ensures that values are managed for uniqueness and made available in publicly accessible registries.\"\n },\n {\n \"code\": null,\n \"e\": 18416,\n \"s\": 18398,\n \"text\": \"31. What is DHCP?\"\n },\n {\n \"code\": null,\n \"e\": 18817,\n \"s\": 18416,\n \"text\": \"DHCP is an abbreviation for Dynamic Host Configuration Protocol. It is an application layer protocol used by hosts for obtaining network setup information. The DHCP is controlled by a DHCP server that dynamically distributes network configuration parameters such as IP addresses, subnet mask, and gateway address. For more details, please refer to Dynamic Host Configuration Protocol (DHCP) article.\"\n },\n {\n \"code\": null,\n \"e\": 18866,\n \"s\": 18817,\n \"text\": \"32. How can you manage a network using a router?\"\n },\n {\n \"code\": null,\n \"e\": 19281,\n \"s\": 18866,\n \"text\": \"Routers have built-in console that lets you configure different settings, like security and data logging.We can assign restrictions to computers, such as what resources they are allowed to access, or what particular time of the day they can browse the internet.We can even put restrictions on what websites are not viewable across the entire network. For more details, please refer to the introduction of a Router.\"\n },\n {\n \"code\": null,\n \"e\": 19303,\n \"s\": 19281,\n \"text\": \"33. What is ipconfig?\"\n },\n {\n \"code\": null,\n \"e\": 19891,\n \"s\": 19303,\n \"text\": \"IPCONFIG stands for Internet Protocol Configuration. This is a command-line application that displays all the current TCP/IP (Transmission Control Protocol/Internet Protocol) network configuration, refreshes the DHCP (Dynamic Host Configuration Protocol) and DNS (Domain Name Server). It also displays an IP address, subnet mask, and a default gateway for all adapters. It is available for Microsoft Windows, ReactOS, and Apple macOS. ReactOS version was developed by Ged Murphy and licensed under the General Public License. For more details, please refer to ipconfig full form article.\"\n },\n {\n \"code\": null,\n \"e\": 19996,\n \"s\": 19891,\n \"text\": \"34. When you move the NIC cards from one PC to another PC, does the MAC address get transferred as well?\"\n },\n {\n \"code\": null,\n \"e\": 20284,\n \"s\": 19996,\n \"text\": \"Yes, if we move the NIC cards from one PC to another PC, then the MAC address also gets transferred, because the MAC address is hard-wired into the NIC circuit, not the personal computer. This also means that a PC can have a different MAC address when another one replaces the NIC card. \"\n },\n {\n \"code\": null,\n \"e\": 20316,\n \"s\": 20284,\n \"text\": \"35. Explain clustering support?\"\n },\n {\n \"code\": null,\n \"e\": 20579,\n \"s\": 20316,\n \"text\": \"Clustering support refers to the ability of a network operating system to connect multiple servers in a fault-tolerant group. The main purpose of this is the in the event that one server fails, all processing will continue on with the next server in the cluster.\"\n },\n {\n \"code\": null,\n \"e\": 20600,\n \"s\": 20579,\n \"text\": \"36. What is Brouter?\"\n },\n {\n \"code\": null,\n \"e\": 21013,\n \"s\": 20600,\n \"text\": \" Brouter – It is also known as the bridging router is a device that combines features of both bridge and router. It can work either at the data link layer or a network layer. Working as a router, it is capable of routing packets across networks, and working as the bridge, it is capable of filtering local area network traffic. For more details, please refer to the difference between Router and Brouter article.\"\n },\n {\n \"code\": null,\n \"e\": 21046,\n \"s\": 21013,\n \"text\": \"37. Explain the features of VPN?\"\n },\n {\n \"code\": null,\n \"e\": 21566,\n \"s\": 21046,\n \"text\": \"VPN also ensures security by providing an encrypted tunnel between client and vpn server.VPN is used to bypass many blocked sites.VPN facilitates anonymous browsing by hiding your ip address.Also, the most appropriate Search engine optimization(SEO) is done by analyzing the data from VPN providers which provide country-wise states for browsing a particular product. This method of SEO is used widely by many internet marketing managers to form new strategies.For more details, please refer to Virtual Private Network.\"\n },\n {\n \"code\": null,\n \"e\": 21656,\n \"s\": 21566,\n \"text\": \"VPN also ensures security by providing an encrypted tunnel between client and vpn server.\"\n },\n {\n \"code\": null,\n \"e\": 21698,\n \"s\": 21656,\n \"text\": \"VPN is used to bypass many blocked sites.\"\n },\n {\n \"code\": null,\n \"e\": 21760,\n \"s\": 21698,\n \"text\": \"VPN facilitates anonymous browsing by hiding your ip address.\"\n },\n {\n \"code\": null,\n \"e\": 22089,\n \"s\": 21760,\n \"text\": \"Also, the most appropriate Search engine optimization(SEO) is done by analyzing the data from VPN providers which provide country-wise states for browsing a particular product. This method of SEO is used widely by many internet marketing managers to form new strategies.For more details, please refer to Virtual Private Network.\"\n },\n {\n \"code\": null,\n \"e\": 22164,\n \"s\": 22089,\n \"text\": \"38. What are the important differences between MAC address and IP address?\"\n },\n {\n \"code\": null,\n \"e\": 22187,\n \"s\": 22164,\n \"text\": \"39. What is 127.0.0.1?\"\n },\n {\n \"code\": null,\n \"e\": 22530,\n \"s\": 22187,\n \"text\": \"In IPv4, IP addresses that start with decimal 127 or that has 01111111 in the first octet are loopback addresses(127.X.X.X). Typically 127.0.0.1 is used as the local loopback address.This leads to the wastage of many potential IP addresses. But in IPv6 ::1 is used as local loopback address and therefore there isn’t any wastage of addresses.\"\n },\n {\n \"code\": null,\n \"e\": 22549,\n \"s\": 22530,\n \"text\": \"40. What is a DNS?\"\n },\n {\n \"code\": null,\n \"e\": 22827,\n \"s\": 22549,\n \"text\": \"DNS is a host name to IP address translation service. DNS is a distributed database implemented in a hierarchy of name servers. It is an application layer protocol for message exchange between clients and servers. For more details, please refer to DNS in the application layer.\"\n },\n {\n \"code\": null,\n \"e\": 22866,\n \"s\": 22827,\n \"text\": \"41. What is the use of a proxy server?\"\n },\n {\n \"code\": null,\n \"e\": 23499,\n \"s\": 22866,\n \"text\": \"Proxy server refers to a server that acts as an intermediary between the request made by clients, and a particular server for some services or requests for some resources. There are different types of proxy servers available that are put into use according to the purpose of a request made by the clients to the servers. The basic purpose of Proxy servers is to protect the direct connection of Internet clients and internet resources. The proxy server also prevents the identification of the client’s IP address when the client makes any request is made to any other servers. For more details, please refer to Proxy server article.\"\n },\n {\n \"code\": null,\n \"e\": 23566,\n \"s\": 23499,\n \"text\": \"42. What is the difference between ipconfig and ifconfig commands?\"\n },\n {\n \"code\": null,\n \"e\": 24087,\n \"s\": 23566,\n \"text\": \"IPCONFIG stands for Internet Protocol Configuration. This is a command-line application that displays all the current TCP/IP (Transmission Control Protocol/Internet Protocol) network configuration, refreshes the DHCP (Dynamic Host Configuration Protocol) and DNS (Domain Name Server). It also displays IP address, subnet mask, and default gateway for all adapters. It is available for Microsoft Windows, ReactOS, and Apple macOS. ReactOS version was developed by Ged Murphy and licensed under the General Public License.\"\n },\n {\n \"code\": null,\n \"e\": 24502,\n \"s\": 24087,\n \"text\": \"ifconfig(interface configuration) command is used to configure the kernel-resident network interfaces. It is used at boot time to set up the interfaces as necessary. After that, it is usually used when needed during debugging or when you need system tuning. Also, this command is used to assign the IP address and netmask to an interface or to enable or disable a given interface. For more details, please refer to\"\n },\n {\n \"code\": null,\n \"e\": 24553,\n \"s\": 24502,\n \"text\": \"43. What is the importance of APIPA in networking?\"\n },\n {\n \"code\": null,\n \"e\": 25137,\n \"s\": 24553,\n \"text\": \"Automatic Private IP Addressing is important in networking because communication can be established properly if you don’t get a response from DHCP Server. APIPA regulates the service, by which the response and status of the main DHCP server at a specific period of time. Apart from that, it can be used as a backup to DHCP because when DHCP stops working, APIPA has the ability to assign IP to the networking hosts.It stops unwanted broadcasting. It uses ARP(Address Resolution Protocol) to confirm the address isn’t currently in use. For more details, please refer to What is APIPA.\"\n },\n {\n \"code\": null,\n \"e\": 25196,\n \"s\": 25137,\n \"text\": \"44. What is the difference between Firewall and Antivirus?\"\n },\n {\n \"code\": null,\n \"e\": 25214,\n \"s\": 25196,\n \"text\": \"45. What is SLIP?\"\n },\n {\n \"code\": null,\n \"e\": 25972,\n \"s\": 25214,\n \"text\": \"SLIP stands for Serial Line Internet Protocol. It is a TCP/IP implementation which was described under RFC 1055 (Request for Comments). SLIP establishes point-to-point serial connections which can be used in dial-up connections, serial ports and routers. It frames the encapsulated IP packets across a serial line for establishing connection while using line speed between 12000 bps and 19.2 Kbps. SLIP was introduced in 1984 when Rick Adams used it to connect 4.2 Berkeley Unix and Sun Microsystems workstations. It soon caught up with the rest of the world as a credible TCP/IP implementation. It has now become obsolete after being replaced by PPP (Point to Point Protocol) which solves many deficiencies present in it. For more details, please refer to\"\n },\n {\n \"code\": null,\n \"e\": 26004,\n \"s\": 25972,\n \"text\": \"46. What is Kerberos protocol?\"\n },\n {\n \"code\": null,\n \"e\": 26356,\n \"s\": 26004,\n \"text\": \"Kerberos provides a centralized authentication server whose function is to authenticate users to servers and servers to users. In Kerberos Authentication server and database is used for client authentication. Kerberos runs as a third-party trusted server known as the Key Distribution Center (KDC). Each user and service on the network is a principal.\"\n },\n {\n \"code\": null,\n \"e\": 26393,\n \"s\": 26356,\n \"text\": \"The main components of Kerberos are:\"\n },\n {\n \"code\": null,\n \"e\": 26522,\n \"s\": 26393,\n \"text\": \"Authentication Server (AS):The Authentication Server performs the initial authentication and ticket for Ticket Granting Service.\"\n },\n {\n \"code\": null,\n \"e\": 26610,\n \"s\": 26522,\n \"text\": \"Database:The Authentication Server verifies the access rights of users in the database.\"\n },\n {\n \"code\": null,\n \"e\": 26700,\n \"s\": 26610,\n \"text\": \"Ticket Granting Server (TGS):The Ticket Granting Server issues the ticket for the Server.\"\n },\n {\n \"code\": null,\n \"e\": 26752,\n \"s\": 26700,\n \"text\": \"For more details, please refer to Kerberos article.\"\n },\n {\n \"code\": null,\n \"e\": 26771,\n \"s\": 26752,\n \"text\": \"47. What is HSRP?\"\n },\n {\n \"code\": null,\n \"e\": 26952,\n \"s\": 26771,\n \"text\": \"Hot Standby Router Protocol (HSRP) is a CISCO proprietary protocol, which provides redundancy for a local subnet. In HSRP, two or more routers give an illusion of a virtual router.\"\n },\n {\n \"code\": null,\n \"e\": 27386,\n \"s\": 26952,\n \"text\": \"HSRP allows you to configure two or more routers as standby routers and only a single router as an active router at a time. All the routers in a single HSRP group share a single MAC address and IP address, which acts as a default gateway to the local network. The Active router is responsible for forwarding the traffic. If it fails, the Standby router takes up all the responsibilities of the active router and forwards the traffic.\"\n },\n {\n \"code\": null,\n \"e\": 27435,\n \"s\": 27386,\n \"text\": \"For more details, please refer to HSRP protocol.\"\n },\n {\n \"code\": null,\n \"e\": 27491,\n \"s\": 27435,\n \"text\": \"48. Why is the MAC address called the Physical address?\"\n },\n {\n \"code\": null,\n \"e\": 27890,\n \"s\": 27491,\n \"text\": \"The MAC address is a physical address (also called a hardware address) because it physically identifies an item of hardware. MAC addresses use three types of number systems and all use the same format, only the size of the identifier differs. The addresses can be “Universally Managed” or “Locally Managed”. For more details, please refer to Introduction of MAC Address in Computer Network article.\"\n },\n {\n \"code\": null,\n \"e\": 27917,\n \"s\": 27890,\n \"text\": \"49. Process of DHCP(DORA)?\"\n },\n {\n \"code\": null,\n \"e\": 28236,\n \"s\": 27917,\n \"text\": \"In DHCP, the client and the server exchange mainly 4 DHCP messages in order to make a connection. This process is known as DORA process (discovery, offer, request, and acknowledgment), but there are 8 DHCP messages in the process. For more details, please refer to Dynamic Host Configuration Protocol (DHCP) article.\"\n },\n {\n \"code\": null,\n \"e\": 28258,\n \"s\": 28236,\n \"text\": \"50. What is ‘APIPA’?\"\n },\n {\n \"code\": null,\n \"e\": 28741,\n \"s\": 28258,\n \"text\": \"APIPA stands for Automatic Private IP Addressing (APIPA). It is a feature or characteristic in operating systems (eg. Windows) which enables computers to self-configure an IP address and subnet mask automatically when their DHCP(Dynamic Host Configuration Protocol) server isn’t reachable. The IP address range for APIPA is (169.254.0.1 to 169.254.255.254) having 65, 534 usable IP addresses, with the subnet mask of 255.255.0.0. For more details please read What is APIPA article.\"\n },\n {\n \"code\": null,\n \"e\": 28755,\n \"s\": 28743,\n \"text\": \"anikakapoor\"\n },\n {\n \"code\": null,\n \"e\": 28775,\n \"s\": 28755,\n \"text\": \"interview-questions\"\n },\n {\n \"code\": null,\n \"e\": 28793,\n \"s\": 28775,\n \"text\": \"Computer Networks\"\n },\n {\n \"code\": null,\n \"e\": 28811,\n \"s\": 28793,\n \"text\": \"Computer Networks\"\n }\n]"}}},{"rowIdx":141,"cells":{"title":{"kind":"string","value":"Difference between var, let and const keywords in JavaScript"},"text":{"kind":"string","value":"15 Dec, 2021\nIn JavaScript, users can declare a variable using 3 keywords that are var, let, and const. In this article, we will see the differences between the var, let, and const keywords. We will discuss the scope and other required concepts about each keyword.\nvar keyword in JavaScript: The var is the oldest keyword to declare a variable in JavaScript. \nScope: Global scoped or function scoped. The scope of the var keyword is the global or function scope. It means variables defined outside the function can be accessed globally, and variables defined inside a particular function can be accessed within the function. \nExample 1: Variable ‘a’ is declared globally. So, the scope of the variable ‘a’ is global, and it can be accessible everywhere in the program. The output shown is in the console.\nJavascript\n\nOutput: \n10\n10\nExample 2: The variable ‘a’ is declared inside the function. If the user tries to access it outside the function, it will display the error. Users can declare the 2 variables with the same name using the var keyword. Also, the user can reassign the value into the var variable. The output shown in the console.\nJavascript\n\nOutput:\n10\nReferenceError: a is not defined\nExample 3: User can re-declare variable using var and user can update var variable. The output is shown in the console.\nJavascript\n\nOutput:\n7\nExample 4: If users use the var variable before the declaration, it initializes with the undefined value. The output is shown in the console.\nJavascript\n\nOutput:\n9\n10\nExample 2: The code returns an error because we are accessing the let variable outside the function block. The output is shown in the console.\nJavascript\n\nOutput:\n9\nReferenceError: b is not defined\nExample 3: Users cannot re-declare the variable defined with the let keyword but can update it.\nJavascript\n\nOutput:\nUncaught SyntaxError: Identifier 'a' has already been declared\nExample 4: Users can declare the variable with the same name in different blocks using the let keyword.\nJavascript\n\nOutput:\n9 \n10\nExample 5: If users use the let variable before the declaration, it does not initialize with undefined just like a var variable and return an error.\nJavascript\n\nOutput:\nUncaught ReferenceError: Cannot access 'a' before initialization\nconst keyword in JavaScript: The const keyword has all the properties that are the same as the let keyword, except the user cannot update it.\nScope: block scoped: When users declare a const variable, they need to initialize it, otherwise, it returns an error. The user cannot update the const variable once it is declared. \nExample 1: We are changing the value of the const variable so that it returns an error. The output is shown in the console.\nJavascript\n\nOutput:\na=9\nTypeError:Assignment to constant variable.\nExample 2: Users cannot change the properties of the const object, but they can change the value of properties of the const object.\nJavascript\n\nOutput:\nUncaught SyntaxError:Unexpected identifier\nDifferences between var, let, and const\nNote: Sometimes, users face the problem while working with the var variable as they change the value of it in the particular block. So, users should use the let and const keyword to declare a variable in JavaScript. \ngabaa406\njavascript-basics\nJavaScript-Questions\nPicked\nDifference Between\nJavaScript\nWeb Technologies\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nDifference Between Method Overloading and Method Overriding in Java\nDifference between Process and Thread\nDifference between Clustered and Non-clustered index\nDifferences between IPv4 and IPv6\nDifferences between Procedural and Object Oriented Programming\nDifferences between Functional Components and Class Components in React\nRemove elements from a JavaScript Array\nHide or show elements in HTML using display property\nRoadmap to Learn JavaScript For Beginners\nDifference Between PUT and PATCH Request"},"parsed":{"kind":"list like","value":[{"code":null,"e":52,"s":24,"text":"\n15 Dec, 2021"},{"code":null,"e":304,"s":52,"text":"In JavaScript, users can declare a variable using 3 keywords that are var, let, and const. In this article, we will see the differences between the var, let, and const keywords. We will discuss the scope and other required concepts about each keyword."},{"code":null,"e":399,"s":304,"text":"var keyword in JavaScript: The var is the oldest keyword to declare a variable in JavaScript. "},{"code":null,"e":665,"s":399,"text":"Scope: Global scoped or function scoped. The scope of the var keyword is the global or function scope. It means variables defined outside the function can be accessed globally, and variables defined inside a particular function can be accessed within the function. "},{"code":null,"e":844,"s":665,"text":"Example 1: Variable ‘a’ is declared globally. So, the scope of the variable ‘a’ is global, and it can be accessible everywhere in the program. The output shown is in the console."},{"code":null,"e":855,"s":844,"text":"Javascript"},{"code":"","e":970,"s":855,"text":null},{"code":null,"e":979,"s":970,"text":"Output: "},{"code":null,"e":985,"s":979,"text":"10\n10"},{"code":null,"e":1296,"s":985,"text":"Example 2: The variable ‘a’ is declared inside the function. If the user tries to access it outside the function, it will display the error. Users can declare the 2 variables with the same name using the var keyword. Also, the user can reassign the value into the var variable. The output shown in the console."},{"code":null,"e":1307,"s":1296,"text":"Javascript"},{"code":"","e":1545,"s":1307,"text":null},{"code":null,"e":1553,"s":1545,"text":"Output:"},{"code":null,"e":1589,"s":1553,"text":"10\nReferenceError: a is not defined"},{"code":null,"e":1709,"s":1589,"text":"Example 3: User can re-declare variable using var and user can update var variable. The output is shown in the console."},{"code":null,"e":1720,"s":1709,"text":"Javascript"},{"code":"","e":1865,"s":1720,"text":null},{"code":null,"e":1873,"s":1865,"text":"Output:"},{"code":null,"e":1875,"s":1873,"text":"7"},{"code":null,"e":2017,"s":1875,"text":"Example 4: If users use the var variable before the declaration, it initializes with the undefined value. The output is shown in the console."},{"code":null,"e":2028,"s":2017,"text":"Javascript"},{"code":"","e":2532,"s":2405,"text":null},{"code":null,"e":2540,"s":2532,"text":"Output:"},{"code":null,"e":2545,"s":2540,"text":"9\n10"},{"code":null,"e":2688,"s":2545,"text":"Example 2: The code returns an error because we are accessing the let variable outside the function block. The output is shown in the console."},{"code":null,"e":2699,"s":2688,"text":"Javascript"},{"code":"","e":2988,"s":2699,"text":null},{"code":null,"e":2996,"s":2988,"text":"Output:"},{"code":null,"e":3031,"s":2996,"text":"9\nReferenceError: b is not defined"},{"code":null,"e":3127,"s":3031,"text":"Example 3: Users cannot re-declare the variable defined with the let keyword but can update it."},{"code":null,"e":3138,"s":3127,"text":"Javascript"},{"code":"","e":3241,"s":3138,"text":null},{"code":null,"e":3249,"s":3241,"text":"Output:"},{"code":null,"e":3312,"s":3249,"text":"Uncaught SyntaxError: Identifier 'a' has already been declared"},{"code":null,"e":3416,"s":3312,"text":"Example 4: Users can declare the variable with the same name in different blocks using the let keyword."},{"code":null,"e":3427,"s":3416,"text":"Javascript"},{"code":"","e":3549,"s":3427,"text":null},{"code":null,"e":3557,"s":3549,"text":"Output:"},{"code":null,"e":3563,"s":3557,"text":"9 \n10"},{"code":null,"e":3712,"s":3563,"text":"Example 5: If users use the let variable before the declaration, it does not initialize with undefined just like a var variable and return an error."},{"code":null,"e":3723,"s":3712,"text":"Javascript"},{"code":"","e":3775,"s":3723,"text":null},{"code":null,"e":3783,"s":3775,"text":"Output:"},{"code":null,"e":3848,"s":3783,"text":"Uncaught ReferenceError: Cannot access 'a' before initialization"},{"code":null,"e":3990,"s":3848,"text":"const keyword in JavaScript: The const keyword has all the properties that are the same as the let keyword, except the user cannot update it."},{"code":null,"e":4172,"s":3990,"text":"Scope: block scoped: When users declare a const variable, they need to initialize it, otherwise, it returns an error. The user cannot update the const variable once it is declared. "},{"code":null,"e":4296,"s":4172,"text":"Example 1: We are changing the value of the const variable so that it returns an error. The output is shown in the console."},{"code":null,"e":4307,"s":4296,"text":"Javascript"},{"code":"","e":4408,"s":4307,"text":null},{"code":null,"e":4416,"s":4408,"text":"Output:"},{"code":null,"e":4463,"s":4416,"text":"a=9\nTypeError:Assignment to constant variable."},{"code":null,"e":4595,"s":4463,"text":"Example 2: Users cannot change the properties of the const object, but they can change the value of properties of the const object."},{"code":null,"e":4606,"s":4595,"text":"Javascript"},{"code":"","e":4787,"s":4606,"text":null},{"code":null,"e":4795,"s":4787,"text":"Output:"},{"code":null,"e":4838,"s":4795,"text":"Uncaught SyntaxError:Unexpected identifier"},{"code":null,"e":4878,"s":4838,"text":"Differences between var, let, and const"},{"code":null,"e":5095,"s":4878,"text":"Note: Sometimes, users face the problem while working with the var variable as they change the value of it in the particular block. So, users should use the let and const keyword to declare a variable in JavaScript. "},{"code":null,"e":5104,"s":5095,"text":"gabaa406"},{"code":null,"e":5122,"s":5104,"text":"javascript-basics"},{"code":null,"e":5143,"s":5122,"text":"JavaScript-Questions"},{"code":null,"e":5150,"s":5143,"text":"Picked"},{"code":null,"e":5169,"s":5150,"text":"Difference Between"},{"code":null,"e":5180,"s":5169,"text":"JavaScript"},{"code":null,"e":5197,"s":5180,"text":"Web Technologies"},{"code":null,"e":5295,"s":5197,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":5363,"s":5295,"text":"Difference Between Method Overloading and Method Overriding in Java"},{"code":null,"e":5401,"s":5363,"text":"Difference between Process and Thread"},{"code":null,"e":5454,"s":5401,"text":"Difference between Clustered and Non-clustered index"},{"code":null,"e":5488,"s":5454,"text":"Differences between IPv4 and IPv6"},{"code":null,"e":5551,"s":5488,"text":"Differences between Procedural and Object Oriented Programming"},{"code":null,"e":5623,"s":5551,"text":"Differences between Functional Components and Class Components in React"},{"code":null,"e":5663,"s":5623,"text":"Remove elements from a JavaScript Array"},{"code":null,"e":5716,"s":5663,"text":"Hide or show elements in HTML using display property"},{"code":null,"e":5758,"s":5716,"text":"Roadmap to Learn JavaScript For Beginners"}],"string":"[\n {\n \"code\": null,\n \"e\": 52,\n \"s\": 24,\n \"text\": \"\\n15 Dec, 2021\"\n },\n {\n \"code\": null,\n \"e\": 304,\n \"s\": 52,\n \"text\": \"In JavaScript, users can declare a variable using 3 keywords that are var, let, and const. In this article, we will see the differences between the var, let, and const keywords. We will discuss the scope and other required concepts about each keyword.\"\n },\n {\n \"code\": null,\n \"e\": 399,\n \"s\": 304,\n \"text\": \"var keyword in JavaScript: The var is the oldest keyword to declare a variable in JavaScript. \"\n },\n {\n \"code\": null,\n \"e\": 665,\n \"s\": 399,\n \"text\": \"Scope: Global scoped or function scoped. The scope of the var keyword is the global or function scope. It means variables defined outside the function can be accessed globally, and variables defined inside a particular function can be accessed within the function. \"\n },\n {\n \"code\": null,\n \"e\": 844,\n \"s\": 665,\n \"text\": \"Example 1: Variable ‘a’ is declared globally. So, the scope of the variable ‘a’ is global, and it can be accessible everywhere in the program. The output shown is in the console.\"\n },\n {\n \"code\": null,\n \"e\": 855,\n \"s\": 844,\n \"text\": \"Javascript\"\n },\n {\n \"code\": \"\",\n \"e\": 970,\n \"s\": 855,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 979,\n \"s\": 970,\n \"text\": \"Output: \"\n },\n {\n \"code\": null,\n \"e\": 985,\n \"s\": 979,\n \"text\": \"10\\n10\"\n },\n {\n \"code\": null,\n \"e\": 1296,\n \"s\": 985,\n \"text\": \"Example 2: The variable ‘a’ is declared inside the function. If the user tries to access it outside the function, it will display the error. Users can declare the 2 variables with the same name using the var keyword. Also, the user can reassign the value into the var variable. The output shown in the console.\"\n },\n {\n \"code\": null,\n \"e\": 1307,\n \"s\": 1296,\n \"text\": \"Javascript\"\n },\n {\n \"code\": \"\",\n \"e\": 1545,\n \"s\": 1307,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 1553,\n \"s\": 1545,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 1589,\n \"s\": 1553,\n \"text\": \"10\\nReferenceError: a is not defined\"\n },\n {\n \"code\": null,\n \"e\": 1709,\n \"s\": 1589,\n \"text\": \"Example 3: User can re-declare variable using var and user can update var variable. The output is shown in the console.\"\n },\n {\n \"code\": null,\n \"e\": 1720,\n \"s\": 1709,\n \"text\": \"Javascript\"\n },\n {\n \"code\": \"\",\n \"e\": 1865,\n \"s\": 1720,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 1873,\n \"s\": 1865,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 1875,\n \"s\": 1873,\n \"text\": \"7\"\n },\n {\n \"code\": null,\n \"e\": 2017,\n \"s\": 1875,\n \"text\": \"Example 4: If users use the var variable before the declaration, it initializes with the undefined value. The output is shown in the console.\"\n },\n {\n \"code\": null,\n \"e\": 2028,\n \"s\": 2017,\n \"text\": \"Javascript\"\n },\n {\n \"code\": \"\",\n \"e\": 2532,\n \"s\": 2405,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 2540,\n \"s\": 2532,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 2545,\n \"s\": 2540,\n \"text\": \"9\\n10\"\n },\n {\n \"code\": null,\n \"e\": 2688,\n \"s\": 2545,\n \"text\": \"Example 2: The code returns an error because we are accessing the let variable outside the function block. The output is shown in the console.\"\n },\n {\n \"code\": null,\n \"e\": 2699,\n \"s\": 2688,\n \"text\": \"Javascript\"\n },\n {\n \"code\": \"\",\n \"e\": 2988,\n \"s\": 2699,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 2996,\n \"s\": 2988,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 3031,\n \"s\": 2996,\n \"text\": \"9\\nReferenceError: b is not defined\"\n },\n {\n \"code\": null,\n \"e\": 3127,\n \"s\": 3031,\n \"text\": \"Example 3: Users cannot re-declare the variable defined with the let keyword but can update it.\"\n },\n {\n \"code\": null,\n \"e\": 3138,\n \"s\": 3127,\n \"text\": \"Javascript\"\n },\n {\n \"code\": \"\",\n \"e\": 3241,\n \"s\": 3138,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 3249,\n \"s\": 3241,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 3312,\n \"s\": 3249,\n \"text\": \"Uncaught SyntaxError: Identifier 'a' has already been declared\"\n },\n {\n \"code\": null,\n \"e\": 3416,\n \"s\": 3312,\n \"text\": \"Example 4: Users can declare the variable with the same name in different blocks using the let keyword.\"\n },\n {\n \"code\": null,\n \"e\": 3427,\n \"s\": 3416,\n \"text\": \"Javascript\"\n },\n {\n \"code\": \"\",\n \"e\": 3549,\n \"s\": 3427,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 3557,\n \"s\": 3549,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 3563,\n \"s\": 3557,\n \"text\": \"9 \\n10\"\n },\n {\n \"code\": null,\n \"e\": 3712,\n \"s\": 3563,\n \"text\": \"Example 5: If users use the let variable before the declaration, it does not initialize with undefined just like a var variable and return an error.\"\n },\n {\n \"code\": null,\n \"e\": 3723,\n \"s\": 3712,\n \"text\": \"Javascript\"\n },\n {\n \"code\": \"\",\n \"e\": 3775,\n \"s\": 3723,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 3783,\n \"s\": 3775,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 3848,\n \"s\": 3783,\n \"text\": \"Uncaught ReferenceError: Cannot access 'a' before initialization\"\n },\n {\n \"code\": null,\n \"e\": 3990,\n \"s\": 3848,\n \"text\": \"const keyword in JavaScript: The const keyword has all the properties that are the same as the let keyword, except the user cannot update it.\"\n },\n {\n \"code\": null,\n \"e\": 4172,\n \"s\": 3990,\n \"text\": \"Scope: block scoped: When users declare a const variable, they need to initialize it, otherwise, it returns an error. The user cannot update the const variable once it is declared. \"\n },\n {\n \"code\": null,\n \"e\": 4296,\n \"s\": 4172,\n \"text\": \"Example 1: We are changing the value of the const variable so that it returns an error. The output is shown in the console.\"\n },\n {\n \"code\": null,\n \"e\": 4307,\n \"s\": 4296,\n \"text\": \"Javascript\"\n },\n {\n \"code\": \"\",\n \"e\": 4408,\n \"s\": 4307,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 4416,\n \"s\": 4408,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 4463,\n \"s\": 4416,\n \"text\": \"a=9\\nTypeError:Assignment to constant variable.\"\n },\n {\n \"code\": null,\n \"e\": 4595,\n \"s\": 4463,\n \"text\": \"Example 2: Users cannot change the properties of the const object, but they can change the value of properties of the const object.\"\n },\n {\n \"code\": null,\n \"e\": 4606,\n \"s\": 4595,\n \"text\": \"Javascript\"\n },\n {\n \"code\": \"\",\n \"e\": 4787,\n \"s\": 4606,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 4795,\n \"s\": 4787,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 4838,\n \"s\": 4795,\n \"text\": \"Uncaught SyntaxError:Unexpected identifier\"\n },\n {\n \"code\": null,\n \"e\": 4878,\n \"s\": 4838,\n \"text\": \"Differences between var, let, and const\"\n },\n {\n \"code\": null,\n \"e\": 5095,\n \"s\": 4878,\n \"text\": \"Note: Sometimes, users face the problem while working with the var variable as they change the value of it in the particular block. So, users should use the let and const keyword to declare a variable in JavaScript. \"\n },\n {\n \"code\": null,\n \"e\": 5104,\n \"s\": 5095,\n \"text\": \"gabaa406\"\n },\n {\n \"code\": null,\n \"e\": 5122,\n \"s\": 5104,\n \"text\": \"javascript-basics\"\n },\n {\n \"code\": null,\n \"e\": 5143,\n \"s\": 5122,\n \"text\": \"JavaScript-Questions\"\n },\n {\n \"code\": null,\n \"e\": 5150,\n \"s\": 5143,\n \"text\": \"Picked\"\n },\n {\n \"code\": null,\n \"e\": 5169,\n \"s\": 5150,\n \"text\": \"Difference Between\"\n },\n {\n \"code\": null,\n \"e\": 5180,\n \"s\": 5169,\n \"text\": \"JavaScript\"\n },\n {\n \"code\": null,\n \"e\": 5197,\n \"s\": 5180,\n \"text\": \"Web Technologies\"\n },\n {\n \"code\": null,\n \"e\": 5295,\n \"s\": 5197,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 5363,\n \"s\": 5295,\n \"text\": \"Difference Between Method Overloading and Method Overriding in Java\"\n },\n {\n \"code\": null,\n \"e\": 5401,\n \"s\": 5363,\n \"text\": \"Difference between Process and Thread\"\n },\n {\n \"code\": null,\n \"e\": 5454,\n \"s\": 5401,\n \"text\": \"Difference between Clustered and Non-clustered index\"\n },\n {\n \"code\": null,\n \"e\": 5488,\n \"s\": 5454,\n \"text\": \"Differences between IPv4 and IPv6\"\n },\n {\n \"code\": null,\n \"e\": 5551,\n \"s\": 5488,\n \"text\": \"Differences between Procedural and Object Oriented Programming\"\n },\n {\n \"code\": null,\n \"e\": 5623,\n \"s\": 5551,\n \"text\": \"Differences between Functional Components and Class Components in React\"\n },\n {\n \"code\": null,\n \"e\": 5663,\n \"s\": 5623,\n \"text\": \"Remove elements from a JavaScript Array\"\n },\n {\n \"code\": null,\n \"e\": 5716,\n \"s\": 5663,\n \"text\": \"Hide or show elements in HTML using display property\"\n },\n {\n \"code\": null,\n \"e\": 5758,\n \"s\": 5716,\n \"text\": \"Roadmap to Learn JavaScript For Beginners\"\n }\n]"}}},{"rowIdx":142,"cells":{"title":{"kind":"string","value":"p5.js | height variable"},"text":{"kind":"string","value":"16 Apr, 2019\nThe height variable in p5.js is a system variable which stores the height of the drawing canvas. It sets the second parameter of createCanvas() function.\nSyntax:\nheight\nBelow programs illustrate the height variable in p5.js:\nExample 1: This example uses height variable to display the height of canvas.\nfunction setup() { // Create Canvas of size 380*80 createCanvas(380, 80);} function draw() { // Set the background color background(220); // Set the text size textSize(16); // Set the text alignment textAlign(CENTER); // Set the text color fill(color('Green')); // Display result text(\"Height of Canvas is : \" + height, 180, 50);} \nOutput:\nExample 2: This example uses height variable to display the height of window.\nfunction setup() { // set height to window height height = windowHeight; //create Canvas of size 380*80 createCanvas(380, height);} function draw() { background(220); textSize(16); textAlign(CENTER); fill(color('Green')); text(\"Height of Canvas is : \"+height, 180, height/2); //use of height variable}\nOutput:\nReference: https://p5js.org/reference/#/p5/height\nJavaScript-p5.js\nJavaScript\nWeb Technologies\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nDifference between var, let and const keywords in JavaScript\nDifferences between Functional Components and Class Components in React\nRemove elements from a JavaScript Array\nHide or show elements in HTML using display property\nDifference Between PUT and PATCH Request\nInstallation of Node.js on Linux\nTop 10 Projects For Beginners To Practice HTML and CSS Skills\nDifference between var, let and const keywords in JavaScript\nHow to insert spaces/tabs in text using HTML/CSS?\nHow to fetch data from an API in ReactJS ?"},"parsed":{"kind":"list like","value":[{"code":null,"e":28,"s":0,"text":"\n16 Apr, 2019"},{"code":null,"e":182,"s":28,"text":"The height variable in p5.js is a system variable which stores the height of the drawing canvas. It sets the second parameter of createCanvas() function."},{"code":null,"e":190,"s":182,"text":"Syntax:"},{"code":null,"e":197,"s":190,"text":"height"},{"code":null,"e":253,"s":197,"text":"Below programs illustrate the height variable in p5.js:"},{"code":null,"e":331,"s":253,"text":"Example 1: This example uses height variable to display the height of canvas."},{"code":"function setup() { // Create Canvas of size 380*80 createCanvas(380, 80);} function draw() { // Set the background color background(220); // Set the text size textSize(16); // Set the text alignment textAlign(CENTER); // Set the text color fill(color('Green')); // Display result text(\"Height of Canvas is : \" + height, 180, 50);} ","e":746,"s":331,"text":null},{"code":null,"e":754,"s":746,"text":"Output:"},{"code":null,"e":832,"s":754,"text":"Example 2: This example uses height variable to display the height of window."},{"code":"function setup() { // set height to window height height = windowHeight; //create Canvas of size 380*80 createCanvas(380, height);} function draw() { background(220); textSize(16); textAlign(CENTER); fill(color('Green')); text(\"Height of Canvas is : \"+height, 180, height/2); //use of height variable}","e":1144,"s":832,"text":null},{"code":null,"e":1152,"s":1144,"text":"Output:"},{"code":null,"e":1202,"s":1152,"text":"Reference: https://p5js.org/reference/#/p5/height"},{"code":null,"e":1219,"s":1202,"text":"JavaScript-p5.js"},{"code":null,"e":1230,"s":1219,"text":"JavaScript"},{"code":null,"e":1247,"s":1230,"text":"Web Technologies"},{"code":null,"e":1345,"s":1247,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":1406,"s":1345,"text":"Difference between var, let and const keywords in JavaScript"},{"code":null,"e":1478,"s":1406,"text":"Differences between Functional Components and Class Components in React"},{"code":null,"e":1518,"s":1478,"text":"Remove elements from a JavaScript Array"},{"code":null,"e":1571,"s":1518,"text":"Hide or show elements in HTML using display property"},{"code":null,"e":1612,"s":1571,"text":"Difference Between PUT and PATCH Request"},{"code":null,"e":1645,"s":1612,"text":"Installation of Node.js on Linux"},{"code":null,"e":1707,"s":1645,"text":"Top 10 Projects For Beginners To Practice HTML and CSS Skills"},{"code":null,"e":1768,"s":1707,"text":"Difference between var, let and const keywords in JavaScript"},{"code":null,"e":1818,"s":1768,"text":"How to insert spaces/tabs in text using HTML/CSS?"}],"string":"[\n {\n \"code\": null,\n \"e\": 28,\n \"s\": 0,\n \"text\": \"\\n16 Apr, 2019\"\n },\n {\n \"code\": null,\n \"e\": 182,\n \"s\": 28,\n \"text\": \"The height variable in p5.js is a system variable which stores the height of the drawing canvas. It sets the second parameter of createCanvas() function.\"\n },\n {\n \"code\": null,\n \"e\": 190,\n \"s\": 182,\n \"text\": \"Syntax:\"\n },\n {\n \"code\": null,\n \"e\": 197,\n \"s\": 190,\n \"text\": \"height\"\n },\n {\n \"code\": null,\n \"e\": 253,\n \"s\": 197,\n \"text\": \"Below programs illustrate the height variable in p5.js:\"\n },\n {\n \"code\": null,\n \"e\": 331,\n \"s\": 253,\n \"text\": \"Example 1: This example uses height variable to display the height of canvas.\"\n },\n {\n \"code\": \"function setup() { // Create Canvas of size 380*80 createCanvas(380, 80);} function draw() { // Set the background color background(220); // Set the text size textSize(16); // Set the text alignment textAlign(CENTER); // Set the text color fill(color('Green')); // Display result text(\\\"Height of Canvas is : \\\" + height, 180, 50);} \",\n \"e\": 746,\n \"s\": 331,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 754,\n \"s\": 746,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 832,\n \"s\": 754,\n \"text\": \"Example 2: This example uses height variable to display the height of window.\"\n },\n {\n \"code\": \"function setup() { // set height to window height height = windowHeight; //create Canvas of size 380*80 createCanvas(380, height);} function draw() { background(220); textSize(16); textAlign(CENTER); fill(color('Green')); text(\\\"Height of Canvas is : \\\"+height, 180, height/2); //use of height variable}\",\n \"e\": 1144,\n \"s\": 832,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 1152,\n \"s\": 1144,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 1202,\n \"s\": 1152,\n \"text\": \"Reference: https://p5js.org/reference/#/p5/height\"\n },\n {\n \"code\": null,\n \"e\": 1219,\n \"s\": 1202,\n \"text\": \"JavaScript-p5.js\"\n },\n {\n \"code\": null,\n \"e\": 1230,\n \"s\": 1219,\n \"text\": \"JavaScript\"\n },\n {\n \"code\": null,\n \"e\": 1247,\n \"s\": 1230,\n \"text\": \"Web Technologies\"\n },\n {\n \"code\": null,\n \"e\": 1345,\n \"s\": 1247,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 1406,\n \"s\": 1345,\n \"text\": \"Difference between var, let and const keywords in JavaScript\"\n },\n {\n \"code\": null,\n \"e\": 1478,\n \"s\": 1406,\n \"text\": \"Differences between Functional Components and Class Components in React\"\n },\n {\n \"code\": null,\n \"e\": 1518,\n \"s\": 1478,\n \"text\": \"Remove elements from a JavaScript Array\"\n },\n {\n \"code\": null,\n \"e\": 1571,\n \"s\": 1518,\n \"text\": \"Hide or show elements in HTML using display property\"\n },\n {\n \"code\": null,\n \"e\": 1612,\n \"s\": 1571,\n \"text\": \"Difference Between PUT and PATCH Request\"\n },\n {\n \"code\": null,\n \"e\": 1645,\n \"s\": 1612,\n \"text\": \"Installation of Node.js on Linux\"\n },\n {\n \"code\": null,\n \"e\": 1707,\n \"s\": 1645,\n \"text\": \"Top 10 Projects For Beginners To Practice HTML and CSS Skills\"\n },\n {\n \"code\": null,\n \"e\": 1768,\n \"s\": 1707,\n \"text\": \"Difference between var, let and const keywords in JavaScript\"\n },\n {\n \"code\": null,\n \"e\": 1818,\n \"s\": 1768,\n \"text\": \"How to insert spaces/tabs in text using HTML/CSS?\"\n }\n]"}}},{"rowIdx":143,"cells":{"title":{"kind":"string","value":"Tilt of Binary Tree"},"text":{"kind":"string","value":"30 Jun, 2021\nGiven a binary tree, return the tilt of the whole tree. The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null nodes are assigned tilt to be zero. Therefore, tilt of the whole tree is defined as the sum of all nodes’ tilt.Examples: \nInput :\n 1\n / \\\n 2 3\nOutput : 1\nExplanation: \nTilt of node 2 : 0\nTilt of node 3 : 0\nTilt of node 1 : |2-3| = 1\nTilt of binary tree : 0 + 0 + 1 = 1\n\nInput :\n 4\n / \\\n 2 9\n / \\ \\\n3 5 7\nOutput : 15\nExplanation: \nTilt of node 3 : 0\nTilt of node 5 : 0\nTilt of node 7 : 0\nTilt of node 2 : |3-5| = 2\nTilt of node 9 : |0-7| = 7\nTilt of node 4 : |(3+5+2)-(9+7)| = 6\nTilt of binary tree : 0 + 0 + 0 + 2 + 7 + 6 = 15\n \nThe idea is to recursively traverse tree. While traversing, we keep track of two things, sum of subtree rooted under current node, tilt of current node. Sum is needed to compute tilt of parent. \nC++\nJava\nPython3\nC#\nJavascript\n// CPP Program to find Tilt of Binary Tree#include using namespace std; /* A binary tree node has data, pointer toleft child and a pointer to right child */struct Node { int val; struct Node *left, *right;}; /* Recursive function to calculate Tilt of whole tree */int traverse(Node* root, int* tilt){ if (!root) return 0; // Compute tilts of left and right subtrees // and find sums of left and right subtrees int left = traverse(root->left, tilt); int right = traverse(root->right, tilt); // Add current tilt to overall *tilt += abs(left - right); // Returns sum of nodes under current tree return left + right + root->val;} /* Driver function to print Tilt of whole tree */int Tilt(Node* root){ int tilt = 0; traverse(root, &tilt); return tilt;} /* Helper function that allocates anew node with the given data andNULL left and right pointers. */Node* newNode(int data){ Node* temp = new Node; temp->val = data; temp->left = temp->right = NULL; return temp;} // Driver codeint main(){ /* Let us construct a Binary Tree 4 / \\ 2 9 / \\ \\ 3 5 7 */ Node* root = NULL; root = newNode(4); root->left = newNode(2); root->right = newNode(9); root->left->left = newNode(3); root->left->right = newNode(8); root->right->right = newNode(7); cout << \"The Tilt of whole tree is \" << Tilt(root); return 0;}\n// Java Program to find Tilt of Binary Treeimport java.util.*;class GfG { /* A binary tree node has data, pointer toleft child and a pointer to right child */static class Node { int val; Node left, right;} /* Recursive function to calculate Tilt ofwhole tree */static class T{ int tilt = 0;}static int traverse(Node root, T t ){ if (root == null) return 0; // Compute tilts of left and right subtrees // and find sums of left and right subtrees int left = traverse(root.left, t); int right = traverse(root.right, t); // Add current tilt to overall t.tilt += Math.abs(left - right); // Returns sum of nodes under current tree return left + right + root.val;} /* Driver function to print Tilt of whole tree */static int Tilt(Node root){ T t = new T(); traverse(root, t); return t.tilt;} /* Helper function that allocates anew node with the given data andNULL left and right pointers. */static Node newNode(int data){ Node temp = new Node(); temp.val = data; temp.left = null; temp.right = null; return temp;} // Driver codepublic static void main(String[] args){ /* Let us construct a Binary Tree 4 / \\ 2 9 / \\ \\ 3 5 7 */ Node root = null; root = newNode(4); root.left = newNode(2); root.right = newNode(9); root.left.left = newNode(3); root.left.right = newNode(8); root.right.right = newNode(7); System.out.println(\"The Tilt of whole tree is \" + Tilt(root));}}\n# Python3 Program to find Tilt of# Binary Tree # class that allocates a new node# with the given data and# None left and right pointers.class newNode: def __init__(self, data): self.val = data self.left = self.right = None # Recursive function to calculate# Tilt of whole treedef traverse(root, tilt): if (not root): return 0 # Compute tilts of left and right subtrees # and find sums of left and right subtrees left = traverse(root.left, tilt) right = traverse(root.right, tilt) # Add current tilt to overall tilt[0] += abs(left - right) # Returns sum of nodes under # current tree return left + right + root.val # Driver function to print Tilt# of whole treedef Tilt(root): tilt = [0] traverse(root, tilt) return tilt[0] # Driver codeif __name__ == '__main__': # Let us construct a Binary Tree # 4 # / \\ # 2 9 # / \\ \\ # 3 5 7 root = None root = newNode(4) root.left = newNode(2) root.right = newNode(9) root.left.left = newNode(3) root.left.right = newNode(8) root.right.right = newNode(7) print(\"The Tilt of whole tree is\", Tilt(root)) # This code is contributed by PranchalK\n// C# Program to find Tilt of Binary Treeusing System; class GfG{ /* A binary tree node has data, pointer toleft child and a pointer to right child */public class Node{ public int val; public Node left, right;} /* Recursive function to calculate Tilt ofwhole tree */public class T{ public int tilt = 0;}static int traverse(Node root, T t ){ if (root == null) return 0; // Compute tilts of left and right subtrees // and find sums of left and right subtrees int left = traverse(root.left, t); int right = traverse(root.right, t); // Add current tilt to overall t.tilt += Math.Abs(left - right); // Returns sum of nodes under current tree return left + right + root.val;} /* Driver function to print Tilt of whole tree */static int Tilt(Node root){ T t = new T(); traverse(root, t); return t.tilt;} /* Helper function that allocates anew node with the given data andNULL left and right pointers. */static Node newNode(int data){ Node temp = new Node(); temp.val = data; temp.left = null; temp.right = null; return temp;} // Driver codepublic static void Main(String[] args){ /* Let us construct a Binary Tree 4 / \\ 2 9 / \\ \\ 3 5 7 */ Node root = null; root = newNode(4); root.left = newNode(2); root.right = newNode(9); root.left.left = newNode(3); root.left.right = newNode(8); root.right.right = newNode(7); Console.WriteLine(\"The Tilt of whole tree is \" + Tilt(root));}} // This code contributed by Rajput-Ji\n\nOutput: \nChapters\ndescriptions off, selected\ncaptions settings, opens captions settings dialog\ncaptions off, selected\nEnglish\nThis is a modal window.\nBeginning of dialog window. Escape will cancel and close the window.\nEnd of dialog window.\nThe Tilt of whole tree is 15\nComplexity Analysis: \nTime complexity: O(n), where n is the number of nodes in binary tree.\nAuxiliary Space: O(n) as in worst case, depth of binary tree will be n.\n \nPython Programming Tutorial | Count number of vowels using sets in given string | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPython Programming Tutorial | Count number of vowels using sets in given string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:07•Live•

An error occurred.

Try watching this video on www.youtube.com, or enable JavaScript if it is disabled in your browser.
\n \nprerna saini\nPranchalKatiyar\nRajput-Ji\nmukesh07\nTree\nTree\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nIntroduction to Data Structures\nIntroduction to Tree Data Structure\nWhat is Data Structure: Types, Classifications and Applications\nDiagonal Traversal of Binary Tree\nTop 50 Tree Coding Problems for Interviews\nOverview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)\nIterative Preorder Traversal\nLowest Common Ancestor in a Binary Search Tree.\nBoundary Traversal of binary tree\nHandshaking Lemma and Interesting Tree Properties"},"parsed":{"kind":"list like","value":[{"code":null,"e":54,"s":26,"text":"\n30 Jun, 2021"},{"code":null,"e":394,"s":54,"text":"Given a binary tree, return the tilt of the whole tree. The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null nodes are assigned tilt to be zero. Therefore, tilt of the whole tree is defined as the sum of all nodes’ tilt.Examples: "},{"code":null,"e":821,"s":394,"text":"Input :\n 1\n / \\\n 2 3\nOutput : 1\nExplanation: \nTilt of node 2 : 0\nTilt of node 3 : 0\nTilt of node 1 : |2-3| = 1\nTilt of binary tree : 0 + 0 + 1 = 1\n\nInput :\n 4\n / \\\n 2 9\n / \\ \\\n3 5 7\nOutput : 15\nExplanation: \nTilt of node 3 : 0\nTilt of node 5 : 0\nTilt of node 7 : 0\nTilt of node 2 : |3-5| = 2\nTilt of node 9 : |0-7| = 7\nTilt of node 4 : |(3+5+2)-(9+7)| = 6\nTilt of binary tree : 0 + 0 + 0 + 2 + 7 + 6 = 15"},{"code":null,"e":1019,"s":823,"text":"The idea is to recursively traverse tree. While traversing, we keep track of two things, sum of subtree rooted under current node, tilt of current node. Sum is needed to compute tilt of parent. "},{"code":null,"e":1023,"s":1019,"text":"C++"},{"code":null,"e":1028,"s":1023,"text":"Java"},{"code":null,"e":1036,"s":1028,"text":"Python3"},{"code":null,"e":1039,"s":1036,"text":"C#"},{"code":null,"e":1050,"s":1039,"text":"Javascript"},{"code":"// CPP Program to find Tilt of Binary Tree#include using namespace std; /* A binary tree node has data, pointer toleft child and a pointer to right child */struct Node { int val; struct Node *left, *right;}; /* Recursive function to calculate Tilt of whole tree */int traverse(Node* root, int* tilt){ if (!root) return 0; // Compute tilts of left and right subtrees // and find sums of left and right subtrees int left = traverse(root->left, tilt); int right = traverse(root->right, tilt); // Add current tilt to overall *tilt += abs(left - right); // Returns sum of nodes under current tree return left + right + root->val;} /* Driver function to print Tilt of whole tree */int Tilt(Node* root){ int tilt = 0; traverse(root, &tilt); return tilt;} /* Helper function that allocates anew node with the given data andNULL left and right pointers. */Node* newNode(int data){ Node* temp = new Node; temp->val = data; temp->left = temp->right = NULL; return temp;} // Driver codeint main(){ /* Let us construct a Binary Tree 4 / \\ 2 9 / \\ \\ 3 5 7 */ Node* root = NULL; root = newNode(4); root->left = newNode(2); root->right = newNode(9); root->left->left = newNode(3); root->left->right = newNode(8); root->right->right = newNode(7); cout << \"The Tilt of whole tree is \" << Tilt(root); return 0;}","e":2487,"s":1050,"text":null},{"code":"// Java Program to find Tilt of Binary Treeimport java.util.*;class GfG { /* A binary tree node has data, pointer toleft child and a pointer to right child */static class Node { int val; Node left, right;} /* Recursive function to calculate Tilt ofwhole tree */static class T{ int tilt = 0;}static int traverse(Node root, T t ){ if (root == null) return 0; // Compute tilts of left and right subtrees // and find sums of left and right subtrees int left = traverse(root.left, t); int right = traverse(root.right, t); // Add current tilt to overall t.tilt += Math.abs(left - right); // Returns sum of nodes under current tree return left + right + root.val;} /* Driver function to print Tilt of whole tree */static int Tilt(Node root){ T t = new T(); traverse(root, t); return t.tilt;} /* Helper function that allocates anew node with the given data andNULL left and right pointers. */static Node newNode(int data){ Node temp = new Node(); temp.val = data; temp.left = null; temp.right = null; return temp;} // Driver codepublic static void main(String[] args){ /* Let us construct a Binary Tree 4 / \\ 2 9 / \\ \\ 3 5 7 */ Node root = null; root = newNode(4); root.left = newNode(2); root.right = newNode(9); root.left.left = newNode(3); root.left.right = newNode(8); root.right.right = newNode(7); System.out.println(\"The Tilt of whole tree is \" + Tilt(root));}}","e":3965,"s":2487,"text":null},{"code":"# Python3 Program to find Tilt of# Binary Tree # class that allocates a new node# with the given data and# None left and right pointers.class newNode: def __init__(self, data): self.val = data self.left = self.right = None # Recursive function to calculate# Tilt of whole treedef traverse(root, tilt): if (not root): return 0 # Compute tilts of left and right subtrees # and find sums of left and right subtrees left = traverse(root.left, tilt) right = traverse(root.right, tilt) # Add current tilt to overall tilt[0] += abs(left - right) # Returns sum of nodes under # current tree return left + right + root.val # Driver function to print Tilt# of whole treedef Tilt(root): tilt = [0] traverse(root, tilt) return tilt[0] # Driver codeif __name__ == '__main__': # Let us construct a Binary Tree # 4 # / \\ # 2 9 # / \\ \\ # 3 5 7 root = None root = newNode(4) root.left = newNode(2) root.right = newNode(9) root.left.left = newNode(3) root.left.right = newNode(8) root.right.right = newNode(7) print(\"The Tilt of whole tree is\", Tilt(root)) # This code is contributed by PranchalK","e":5187,"s":3965,"text":null},{"code":"// C# Program to find Tilt of Binary Treeusing System; class GfG{ /* A binary tree node has data, pointer toleft child and a pointer to right child */public class Node{ public int val; public Node left, right;} /* Recursive function to calculate Tilt ofwhole tree */public class T{ public int tilt = 0;}static int traverse(Node root, T t ){ if (root == null) return 0; // Compute tilts of left and right subtrees // and find sums of left and right subtrees int left = traverse(root.left, t); int right = traverse(root.right, t); // Add current tilt to overall t.tilt += Math.Abs(left - right); // Returns sum of nodes under current tree return left + right + root.val;} /* Driver function to print Tilt of whole tree */static int Tilt(Node root){ T t = new T(); traverse(root, t); return t.tilt;} /* Helper function that allocates anew node with the given data andNULL left and right pointers. */static Node newNode(int data){ Node temp = new Node(); temp.val = data; temp.left = null; temp.right = null; return temp;} // Driver codepublic static void Main(String[] args){ /* Let us construct a Binary Tree 4 / \\ 2 9 / \\ \\ 3 5 7 */ Node root = null; root = newNode(4); root.left = newNode(2); root.right = newNode(9); root.left.left = newNode(3); root.left.right = newNode(8); root.right.right = newNode(7); Console.WriteLine(\"The Tilt of whole tree is \" + Tilt(root));}} // This code contributed by Rajput-Ji","e":6714,"s":5187,"text":null},{"code":"","e":8243,"s":6714,"text":null},{"code":null,"e":8253,"s":8243,"text":"Output: "},{"code":null,"e":8262,"s":8253,"text":"Chapters"},{"code":null,"e":8289,"s":8262,"text":"descriptions off, selected"},{"code":null,"e":8339,"s":8289,"text":"captions settings, opens captions settings dialog"},{"code":null,"e":8362,"s":8339,"text":"captions off, selected"},{"code":null,"e":8370,"s":8362,"text":"English"},{"code":null,"e":8394,"s":8370,"text":"This is a modal window."},{"code":null,"e":8463,"s":8394,"text":"Beginning of dialog window. Escape will cancel and close the window."},{"code":null,"e":8485,"s":8463,"text":"End of dialog window."},{"code":null,"e":8514,"s":8485,"text":"The Tilt of whole tree is 15"},{"code":null,"e":8537,"s":8514,"text":"Complexity Analysis: "},{"code":null,"e":8607,"s":8537,"text":"Time complexity: O(n), where n is the number of nodes in binary tree."},{"code":null,"e":8679,"s":8607,"text":"Auxiliary Space: O(n) as in worst case, depth of binary tree will be n."},{"code":null,"e":9657,"s":8681,"text":"Python Programming Tutorial | Count number of vowels using sets in given string | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPython Programming Tutorial | Count number of vowels using sets in given string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:07•Live•

An error occurred.

Try watching this video on www.youtube.com, or enable JavaScript if it is disabled in your browser.
"},{"code":null,"e":9672,"s":9659,"text":"prerna saini"},{"code":null,"e":9688,"s":9672,"text":"PranchalKatiyar"},{"code":null,"e":9698,"s":9688,"text":"Rajput-Ji"},{"code":null,"e":9707,"s":9698,"text":"mukesh07"},{"code":null,"e":9712,"s":9707,"text":"Tree"},{"code":null,"e":9717,"s":9712,"text":"Tree"},{"code":null,"e":9815,"s":9717,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":9847,"s":9815,"text":"Introduction to Data Structures"},{"code":null,"e":9883,"s":9847,"text":"Introduction to Tree Data Structure"},{"code":null,"e":9947,"s":9883,"text":"What is Data Structure: Types, Classifications and Applications"},{"code":null,"e":9981,"s":9947,"text":"Diagonal Traversal of Binary Tree"},{"code":null,"e":10024,"s":9981,"text":"Top 50 Tree Coding Problems for Interviews"},{"code":null,"e":10094,"s":10024,"text":"Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)"},{"code":null,"e":10123,"s":10094,"text":"Iterative Preorder Traversal"},{"code":null,"e":10171,"s":10123,"text":"Lowest Common Ancestor in a Binary Search Tree."},{"code":null,"e":10205,"s":10171,"text":"Boundary Traversal of binary tree"}],"string":"[\n {\n \"code\": null,\n \"e\": 54,\n \"s\": 26,\n \"text\": \"\\n30 Jun, 2021\"\n },\n {\n \"code\": null,\n \"e\": 394,\n \"s\": 54,\n \"text\": \"Given a binary tree, return the tilt of the whole tree. The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null nodes are assigned tilt to be zero. Therefore, tilt of the whole tree is defined as the sum of all nodes’ tilt.Examples: \"\n },\n {\n \"code\": null,\n \"e\": 821,\n \"s\": 394,\n \"text\": \"Input :\\n 1\\n / \\\\\\n 2 3\\nOutput : 1\\nExplanation: \\nTilt of node 2 : 0\\nTilt of node 3 : 0\\nTilt of node 1 : |2-3| = 1\\nTilt of binary tree : 0 + 0 + 1 = 1\\n\\nInput :\\n 4\\n / \\\\\\n 2 9\\n / \\\\ \\\\\\n3 5 7\\nOutput : 15\\nExplanation: \\nTilt of node 3 : 0\\nTilt of node 5 : 0\\nTilt of node 7 : 0\\nTilt of node 2 : |3-5| = 2\\nTilt of node 9 : |0-7| = 7\\nTilt of node 4 : |(3+5+2)-(9+7)| = 6\\nTilt of binary tree : 0 + 0 + 0 + 2 + 7 + 6 = 15\"\n },\n {\n \"code\": null,\n \"e\": 1019,\n \"s\": 823,\n \"text\": \"The idea is to recursively traverse tree. While traversing, we keep track of two things, sum of subtree rooted under current node, tilt of current node. Sum is needed to compute tilt of parent. \"\n },\n {\n \"code\": null,\n \"e\": 1023,\n \"s\": 1019,\n \"text\": \"C++\"\n },\n {\n \"code\": null,\n \"e\": 1028,\n \"s\": 1023,\n \"text\": \"Java\"\n },\n {\n \"code\": null,\n \"e\": 1036,\n \"s\": 1028,\n \"text\": \"Python3\"\n },\n {\n \"code\": null,\n \"e\": 1039,\n \"s\": 1036,\n \"text\": \"C#\"\n },\n {\n \"code\": null,\n \"e\": 1050,\n \"s\": 1039,\n \"text\": \"Javascript\"\n },\n {\n \"code\": \"// CPP Program to find Tilt of Binary Tree#include using namespace std; /* A binary tree node has data, pointer toleft child and a pointer to right child */struct Node { int val; struct Node *left, *right;}; /* Recursive function to calculate Tilt of whole tree */int traverse(Node* root, int* tilt){ if (!root) return 0; // Compute tilts of left and right subtrees // and find sums of left and right subtrees int left = traverse(root->left, tilt); int right = traverse(root->right, tilt); // Add current tilt to overall *tilt += abs(left - right); // Returns sum of nodes under current tree return left + right + root->val;} /* Driver function to print Tilt of whole tree */int Tilt(Node* root){ int tilt = 0; traverse(root, &tilt); return tilt;} /* Helper function that allocates anew node with the given data andNULL left and right pointers. */Node* newNode(int data){ Node* temp = new Node; temp->val = data; temp->left = temp->right = NULL; return temp;} // Driver codeint main(){ /* Let us construct a Binary Tree 4 / \\\\ 2 9 / \\\\ \\\\ 3 5 7 */ Node* root = NULL; root = newNode(4); root->left = newNode(2); root->right = newNode(9); root->left->left = newNode(3); root->left->right = newNode(8); root->right->right = newNode(7); cout << \\\"The Tilt of whole tree is \\\" << Tilt(root); return 0;}\",\n \"e\": 2487,\n \"s\": 1050,\n \"text\": null\n },\n {\n \"code\": \"// Java Program to find Tilt of Binary Treeimport java.util.*;class GfG { /* A binary tree node has data, pointer toleft child and a pointer to right child */static class Node { int val; Node left, right;} /* Recursive function to calculate Tilt ofwhole tree */static class T{ int tilt = 0;}static int traverse(Node root, T t ){ if (root == null) return 0; // Compute tilts of left and right subtrees // and find sums of left and right subtrees int left = traverse(root.left, t); int right = traverse(root.right, t); // Add current tilt to overall t.tilt += Math.abs(left - right); // Returns sum of nodes under current tree return left + right + root.val;} /* Driver function to print Tilt of whole tree */static int Tilt(Node root){ T t = new T(); traverse(root, t); return t.tilt;} /* Helper function that allocates anew node with the given data andNULL left and right pointers. */static Node newNode(int data){ Node temp = new Node(); temp.val = data; temp.left = null; temp.right = null; return temp;} // Driver codepublic static void main(String[] args){ /* Let us construct a Binary Tree 4 / \\\\ 2 9 / \\\\ \\\\ 3 5 7 */ Node root = null; root = newNode(4); root.left = newNode(2); root.right = newNode(9); root.left.left = newNode(3); root.left.right = newNode(8); root.right.right = newNode(7); System.out.println(\\\"The Tilt of whole tree is \\\" + Tilt(root));}}\",\n \"e\": 3965,\n \"s\": 2487,\n \"text\": null\n },\n {\n \"code\": \"# Python3 Program to find Tilt of# Binary Tree # class that allocates a new node# with the given data and# None left and right pointers.class newNode: def __init__(self, data): self.val = data self.left = self.right = None # Recursive function to calculate# Tilt of whole treedef traverse(root, tilt): if (not root): return 0 # Compute tilts of left and right subtrees # and find sums of left and right subtrees left = traverse(root.left, tilt) right = traverse(root.right, tilt) # Add current tilt to overall tilt[0] += abs(left - right) # Returns sum of nodes under # current tree return left + right + root.val # Driver function to print Tilt# of whole treedef Tilt(root): tilt = [0] traverse(root, tilt) return tilt[0] # Driver codeif __name__ == '__main__': # Let us construct a Binary Tree # 4 # / \\\\ # 2 9 # / \\\\ \\\\ # 3 5 7 root = None root = newNode(4) root.left = newNode(2) root.right = newNode(9) root.left.left = newNode(3) root.left.right = newNode(8) root.right.right = newNode(7) print(\\\"The Tilt of whole tree is\\\", Tilt(root)) # This code is contributed by PranchalK\",\n \"e\": 5187,\n \"s\": 3965,\n \"text\": null\n },\n {\n \"code\": \"// C# Program to find Tilt of Binary Treeusing System; class GfG{ /* A binary tree node has data, pointer toleft child and a pointer to right child */public class Node{ public int val; public Node left, right;} /* Recursive function to calculate Tilt ofwhole tree */public class T{ public int tilt = 0;}static int traverse(Node root, T t ){ if (root == null) return 0; // Compute tilts of left and right subtrees // and find sums of left and right subtrees int left = traverse(root.left, t); int right = traverse(root.right, t); // Add current tilt to overall t.tilt += Math.Abs(left - right); // Returns sum of nodes under current tree return left + right + root.val;} /* Driver function to print Tilt of whole tree */static int Tilt(Node root){ T t = new T(); traverse(root, t); return t.tilt;} /* Helper function that allocates anew node with the given data andNULL left and right pointers. */static Node newNode(int data){ Node temp = new Node(); temp.val = data; temp.left = null; temp.right = null; return temp;} // Driver codepublic static void Main(String[] args){ /* Let us construct a Binary Tree 4 / \\\\ 2 9 / \\\\ \\\\ 3 5 7 */ Node root = null; root = newNode(4); root.left = newNode(2); root.right = newNode(9); root.left.left = newNode(3); root.left.right = newNode(8); root.right.right = newNode(7); Console.WriteLine(\\\"The Tilt of whole tree is \\\" + Tilt(root));}} // This code contributed by Rajput-Ji\",\n \"e\": 6714,\n \"s\": 5187,\n \"text\": null\n },\n {\n \"code\": \"\",\n \"e\": 8243,\n \"s\": 6714,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 8253,\n \"s\": 8243,\n \"text\": \"Output: \"\n },\n {\n \"code\": null,\n \"e\": 8262,\n \"s\": 8253,\n \"text\": \"Chapters\"\n },\n {\n \"code\": null,\n \"e\": 8289,\n \"s\": 8262,\n \"text\": \"descriptions off, selected\"\n },\n {\n \"code\": null,\n \"e\": 8339,\n \"s\": 8289,\n \"text\": \"captions settings, opens captions settings dialog\"\n },\n {\n \"code\": null,\n \"e\": 8362,\n \"s\": 8339,\n \"text\": \"captions off, selected\"\n },\n {\n \"code\": null,\n \"e\": 8370,\n \"s\": 8362,\n \"text\": \"English\"\n },\n {\n \"code\": null,\n \"e\": 8394,\n \"s\": 8370,\n \"text\": \"This is a modal window.\"\n },\n {\n \"code\": null,\n \"e\": 8463,\n \"s\": 8394,\n \"text\": \"Beginning of dialog window. Escape will cancel and close the window.\"\n },\n {\n \"code\": null,\n \"e\": 8485,\n \"s\": 8463,\n \"text\": \"End of dialog window.\"\n },\n {\n \"code\": null,\n \"e\": 8514,\n \"s\": 8485,\n \"text\": \"The Tilt of whole tree is 15\"\n },\n {\n \"code\": null,\n \"e\": 8537,\n \"s\": 8514,\n \"text\": \"Complexity Analysis: \"\n },\n {\n \"code\": null,\n \"e\": 8607,\n \"s\": 8537,\n \"text\": \"Time complexity: O(n), where n is the number of nodes in binary tree.\"\n },\n {\n \"code\": null,\n \"e\": 8679,\n \"s\": 8607,\n \"text\": \"Auxiliary Space: O(n) as in worst case, depth of binary tree will be n.\"\n },\n {\n \"code\": null,\n \"e\": 9657,\n \"s\": 8681,\n \"text\": \"Python Programming Tutorial | Count number of vowels using sets in given string | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPython Programming Tutorial | Count number of vowels using sets in given string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:07•Live•

An error occurred.

Try watching this video on www.youtube.com, or enable JavaScript if it is disabled in your browser.
\"\n },\n {\n \"code\": null,\n \"e\": 9672,\n \"s\": 9659,\n \"text\": \"prerna saini\"\n },\n {\n \"code\": null,\n \"e\": 9688,\n \"s\": 9672,\n \"text\": \"PranchalKatiyar\"\n },\n {\n \"code\": null,\n \"e\": 9698,\n \"s\": 9688,\n \"text\": \"Rajput-Ji\"\n },\n {\n \"code\": null,\n \"e\": 9707,\n \"s\": 9698,\n \"text\": \"mukesh07\"\n },\n {\n \"code\": null,\n \"e\": 9712,\n \"s\": 9707,\n \"text\": \"Tree\"\n },\n {\n \"code\": null,\n \"e\": 9717,\n \"s\": 9712,\n \"text\": \"Tree\"\n },\n {\n \"code\": null,\n \"e\": 9815,\n \"s\": 9717,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 9847,\n \"s\": 9815,\n \"text\": \"Introduction to Data Structures\"\n },\n {\n \"code\": null,\n \"e\": 9883,\n \"s\": 9847,\n \"text\": \"Introduction to Tree Data Structure\"\n },\n {\n \"code\": null,\n \"e\": 9947,\n \"s\": 9883,\n \"text\": \"What is Data Structure: Types, Classifications and Applications\"\n },\n {\n \"code\": null,\n \"e\": 9981,\n \"s\": 9947,\n \"text\": \"Diagonal Traversal of Binary Tree\"\n },\n {\n \"code\": null,\n \"e\": 10024,\n \"s\": 9981,\n \"text\": \"Top 50 Tree Coding Problems for Interviews\"\n },\n {\n \"code\": null,\n \"e\": 10094,\n \"s\": 10024,\n \"text\": \"Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)\"\n },\n {\n \"code\": null,\n \"e\": 10123,\n \"s\": 10094,\n \"text\": \"Iterative Preorder Traversal\"\n },\n {\n \"code\": null,\n \"e\": 10171,\n \"s\": 10123,\n \"text\": \"Lowest Common Ancestor in a Binary Search Tree.\"\n },\n {\n \"code\": null,\n \"e\": 10205,\n \"s\": 10171,\n \"text\": \"Boundary Traversal of binary tree\"\n }\n]"}}},{"rowIdx":144,"cells":{"title":{"kind":"string","value":"Python | Spinner widget in kivy"},"text":{"kind":"string","value":"06 Feb, 2020\nKivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.\n Kivy Tutorial – Learn Kivy with Examples.\nTo work with spinner you must have to import:\nfrom kivy.uix.spinner import Spinner\nSpinner is a widget that provides a quick way to select one value from a set. In the default state, a spinner shows its currently selected value. Touching the spinner displays a dropdown menu with all the other available values from which the user can select a new one.Like a combo box, a spinner object can have multiple values and one of the values can be selected.A callback can be attached to the spinner object to receive notifications on selection of a value from the spinner object.\nBasic Approach :\n\n1) import kivy\n2) import kivyApp\n3) import Label\n4) import Spinner\n5) import Floatlayout\n6) Set minimum version(optional)\n7) create App class:\n 1) Create the spinner\n 2) Attach the labels to spinners\n 3) Attach a callback also \n8) return Layout/widget/Class(according to requirement)\n9) Run an instance of the class\nImplementation of a simple spinner:\n# Sample spinner app in kivy to change the# kivy default settings we use this module configfrom kivy.config import Config # 0 being off 1 being on as in true / false# you can use 0 or 1 && True or FalseConfig.set('graphics', 'resizable', True) # Program to Show how to create a switch# import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # The Label widget is for rendering text. from kivy.uix.label import Label # Spinner is a widget that provides a# quick way to select one value from a set.# like a dropdown listfrom kivy.uix.spinner import Spinner # module consist the floatlayout # to work with FloatLayout first # you have to import it from kivy.uix.floatlayout import FloatLayout # Make an App by deriving from the App classclass SpinnerExample(App): # define build def build(self): # creating floatlayout layout = FloatLayout() # creating the spinner # configure spinner object and add to layout self.spinnerObject = Spinner(text =\"Python\", values =(\"Python\", \"Java\", \"C++\", \"C\", \"C#\", \"PHP\"), background_color =(0.784, 0.443, 0.216, 1)) self.spinnerObject.size_hint = (0.3, 0.2) self.spinnerObject.pos_hint ={'x': .35, 'y':.75} layout.add_widget(self.spinnerObject) # return the layout return layout; # Run the appif __name__ == '__main__': SpinnerExample().run() \nOutput:\nImage 1:\nImage 2:\nNow if we have to tell user every time which element in a list is selected, we will display a label just beside the spinner which tells about the selected label. Also, we will print the value, and text of spinner.\nBelow is the Implementation:\n# Sample spinner app in kivy to change the# kivy default settings we use this module configfrom kivy.config import Config # 0 being off 1 being on as in true / false# you can use 0 or 1 && True or FalseConfig.set('graphics', 'resizable', True) # Program to Show how to create a switch# import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # The Label widget is for rendering text. from kivy.uix.label import Label # Spinner is a widget that provides a# quick way to select one value from a set.# like a dropdown listfrom kivy.uix.spinner import Spinner # module consist the floatlayout # to work with FloatLayout first # you have to import it from kivy.uix.floatlayout import FloatLayout # Make an App by deriving from the App classclass SpinnerExample(App): # define build def build(self): # creating floatlayout layout = FloatLayout() # creating the spinner # configure spinner object and add to layout self.spinnerObject = Spinner(text =\"Python\", values =(\"Python\", \"Java\", \"C++\", \"C\", \"C#\", \"PHP\"), background_color =(0.784, 0.443, 0.216, 1)) self.spinnerObject.size_hint = (0.3, 0.2) self.spinnerObject.pos_hint ={'x': .35, 'y':.75} layout.add_widget(self.spinnerObject) self.spinnerObject.bind(text = self.on_spinner_select) # It changes the label info as well # add a label displaying the selection from the spinner self.spinnerSelection = Label(text =\"Selected value in spinner is: %s\" %self.spinnerObject.text) layout.add_widget(self.spinnerSelection) self.spinnerSelection.pos_hint ={'x': .1, 'y':.3} return layout; # call back for the selection in spinner object def on_spinner_select(self, spinner, text): self.spinnerSelection.text = \"Selected value in spinner is: %s\" %self.spinnerObject.text) print('The spinner', spinner, 'have text', text) # Run the appif __name__ == '__main__': SpinnerExample().run() \nOutput:\nImage 1:\nImage 2:\nBelow is the output in video to get better understanding:\nMedia error: Format(s) not supported or source(s) not found\nPython-gui\nPython-kivy\nPython\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nRead JSON file using Python\nAdding new column to existing DataFrame in Pandas\nPython map() function\nHow to get column names in Pandas dataframe\nDifferent ways to create Pandas Dataframe\nEnumerate() in Python\nRead a file line by line in Python\nPython String | replace()\nHow to Install PIP on Windows ?\nIterate over a list in Python"},"parsed":{"kind":"list like","value":[{"code":null,"e":28,"s":0,"text":"\n06 Feb, 2020"},{"code":null,"e":264,"s":28,"text":"Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications."},{"code":null,"e":307,"s":264,"text":" Kivy Tutorial – Learn Kivy with Examples."},{"code":null,"e":353,"s":307,"text":"To work with spinner you must have to import:"},{"code":null,"e":390,"s":353,"text":"from kivy.uix.spinner import Spinner"},{"code":null,"e":880,"s":390,"text":"Spinner is a widget that provides a quick way to select one value from a set. In the default state, a spinner shows its currently selected value. Touching the spinner displays a dropdown menu with all the other available values from which the user can select a new one.Like a combo box, a spinner object can have multiple values and one of the values can be selected.A callback can be attached to the spinner object to receive notifications on selection of a value from the spinner object."},{"code":null,"e":1235,"s":880,"text":"Basic Approach :\n\n1) import kivy\n2) import kivyApp\n3) import Label\n4) import Spinner\n5) import Floatlayout\n6) Set minimum version(optional)\n7) create App class:\n 1) Create the spinner\n 2) Attach the labels to spinners\n 3) Attach a callback also \n8) return Layout/widget/Class(according to requirement)\n9) Run an instance of the class"},{"code":null,"e":1271,"s":1235,"text":"Implementation of a simple spinner:"},{"code":"# Sample spinner app in kivy to change the# kivy default settings we use this module configfrom kivy.config import Config # 0 being off 1 being on as in true / false# you can use 0 or 1 && True or FalseConfig.set('graphics', 'resizable', True) # Program to Show how to create a switch# import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # The Label widget is for rendering text. from kivy.uix.label import Label # Spinner is a widget that provides a# quick way to select one value from a set.# like a dropdown listfrom kivy.uix.spinner import Spinner # module consist the floatlayout # to work with FloatLayout first # you have to import it from kivy.uix.floatlayout import FloatLayout # Make an App by deriving from the App classclass SpinnerExample(App): # define build def build(self): # creating floatlayout layout = FloatLayout() # creating the spinner # configure spinner object and add to layout self.spinnerObject = Spinner(text =\"Python\", values =(\"Python\", \"Java\", \"C++\", \"C\", \"C#\", \"PHP\"), background_color =(0.784, 0.443, 0.216, 1)) self.spinnerObject.size_hint = (0.3, 0.2) self.spinnerObject.pos_hint ={'x': .35, 'y':.75} layout.add_widget(self.spinnerObject) # return the layout return layout; # Run the appif __name__ == '__main__': SpinnerExample().run() ","e":2928,"s":1271,"text":null},{"code":null,"e":2936,"s":2928,"text":"Output:"},{"code":null,"e":2945,"s":2936,"text":"Image 1:"},{"code":null,"e":2954,"s":2945,"text":"Image 2:"},{"code":null,"e":3168,"s":2954,"text":"Now if we have to tell user every time which element in a list is selected, we will display a label just beside the spinner which tells about the selected label. Also, we will print the value, and text of spinner."},{"code":null,"e":3197,"s":3168,"text":"Below is the Implementation:"},{"code":"# Sample spinner app in kivy to change the# kivy default settings we use this module configfrom kivy.config import Config # 0 being off 1 being on as in true / false# you can use 0 or 1 && True or FalseConfig.set('graphics', 'resizable', True) # Program to Show how to create a switch# import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # The Label widget is for rendering text. from kivy.uix.label import Label # Spinner is a widget that provides a# quick way to select one value from a set.# like a dropdown listfrom kivy.uix.spinner import Spinner # module consist the floatlayout # to work with FloatLayout first # you have to import it from kivy.uix.floatlayout import FloatLayout # Make an App by deriving from the App classclass SpinnerExample(App): # define build def build(self): # creating floatlayout layout = FloatLayout() # creating the spinner # configure spinner object and add to layout self.spinnerObject = Spinner(text =\"Python\", values =(\"Python\", \"Java\", \"C++\", \"C\", \"C#\", \"PHP\"), background_color =(0.784, 0.443, 0.216, 1)) self.spinnerObject.size_hint = (0.3, 0.2) self.spinnerObject.pos_hint ={'x': .35, 'y':.75} layout.add_widget(self.spinnerObject) self.spinnerObject.bind(text = self.on_spinner_select) # It changes the label info as well # add a label displaying the selection from the spinner self.spinnerSelection = Label(text =\"Selected value in spinner is: %s\" %self.spinnerObject.text) layout.add_widget(self.spinnerSelection) self.spinnerSelection.pos_hint ={'x': .1, 'y':.3} return layout; # call back for the selection in spinner object def on_spinner_select(self, spinner, text): self.spinnerSelection.text = \"Selected value in spinner is: %s\" %self.spinnerObject.text) print('The spinner', spinner, 'have text', text) # Run the appif __name__ == '__main__': SpinnerExample().run() ","e":5575,"s":3197,"text":null},{"code":null,"e":5583,"s":5575,"text":"Output:"},{"code":null,"e":5592,"s":5583,"text":"Image 1:"},{"code":null,"e":5601,"s":5592,"text":"Image 2:"},{"code":null,"e":5659,"s":5601,"text":"Below is the output in video to get better understanding:"},{"code":null,"e":5719,"s":5659,"text":"Media error: Format(s) not supported or source(s) not found"},{"code":null,"e":5730,"s":5719,"text":"Python-gui"},{"code":null,"e":5742,"s":5730,"text":"Python-kivy"},{"code":null,"e":5749,"s":5742,"text":"Python"},{"code":null,"e":5847,"s":5749,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":5875,"s":5847,"text":"Read JSON file using Python"},{"code":null,"e":5925,"s":5875,"text":"Adding new column to existing DataFrame in Pandas"},{"code":null,"e":5947,"s":5925,"text":"Python map() function"},{"code":null,"e":5991,"s":5947,"text":"How to get column names in Pandas dataframe"},{"code":null,"e":6033,"s":5991,"text":"Different ways to create Pandas Dataframe"},{"code":null,"e":6055,"s":6033,"text":"Enumerate() in Python"},{"code":null,"e":6090,"s":6055,"text":"Read a file line by line in Python"},{"code":null,"e":6116,"s":6090,"text":"Python String | replace()"},{"code":null,"e":6148,"s":6116,"text":"How to Install PIP on Windows ?"}],"string":"[\n {\n \"code\": null,\n \"e\": 28,\n \"s\": 0,\n \"text\": \"\\n06 Feb, 2020\"\n },\n {\n \"code\": null,\n \"e\": 264,\n \"s\": 28,\n \"text\": \"Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.\"\n },\n {\n \"code\": null,\n \"e\": 307,\n \"s\": 264,\n \"text\": \" Kivy Tutorial – Learn Kivy with Examples.\"\n },\n {\n \"code\": null,\n \"e\": 353,\n \"s\": 307,\n \"text\": \"To work with spinner you must have to import:\"\n },\n {\n \"code\": null,\n \"e\": 390,\n \"s\": 353,\n \"text\": \"from kivy.uix.spinner import Spinner\"\n },\n {\n \"code\": null,\n \"e\": 880,\n \"s\": 390,\n \"text\": \"Spinner is a widget that provides a quick way to select one value from a set. In the default state, a spinner shows its currently selected value. Touching the spinner displays a dropdown menu with all the other available values from which the user can select a new one.Like a combo box, a spinner object can have multiple values and one of the values can be selected.A callback can be attached to the spinner object to receive notifications on selection of a value from the spinner object.\"\n },\n {\n \"code\": null,\n \"e\": 1235,\n \"s\": 880,\n \"text\": \"Basic Approach :\\n\\n1) import kivy\\n2) import kivyApp\\n3) import Label\\n4) import Spinner\\n5) import Floatlayout\\n6) Set minimum version(optional)\\n7) create App class:\\n 1) Create the spinner\\n 2) Attach the labels to spinners\\n 3) Attach a callback also \\n8) return Layout/widget/Class(according to requirement)\\n9) Run an instance of the class\"\n },\n {\n \"code\": null,\n \"e\": 1271,\n \"s\": 1235,\n \"text\": \"Implementation of a simple spinner:\"\n },\n {\n \"code\": \"# Sample spinner app in kivy to change the# kivy default settings we use this module configfrom kivy.config import Config # 0 being off 1 being on as in true / false# you can use 0 or 1 && True or FalseConfig.set('graphics', 'resizable', True) # Program to Show how to create a switch# import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # The Label widget is for rendering text. from kivy.uix.label import Label # Spinner is a widget that provides a# quick way to select one value from a set.# like a dropdown listfrom kivy.uix.spinner import Spinner # module consist the floatlayout # to work with FloatLayout first # you have to import it from kivy.uix.floatlayout import FloatLayout # Make an App by deriving from the App classclass SpinnerExample(App): # define build def build(self): # creating floatlayout layout = FloatLayout() # creating the spinner # configure spinner object and add to layout self.spinnerObject = Spinner(text =\\\"Python\\\", values =(\\\"Python\\\", \\\"Java\\\", \\\"C++\\\", \\\"C\\\", \\\"C#\\\", \\\"PHP\\\"), background_color =(0.784, 0.443, 0.216, 1)) self.spinnerObject.size_hint = (0.3, 0.2) self.spinnerObject.pos_hint ={'x': .35, 'y':.75} layout.add_widget(self.spinnerObject) # return the layout return layout; # Run the appif __name__ == '__main__': SpinnerExample().run() \",\n \"e\": 2928,\n \"s\": 1271,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 2936,\n \"s\": 2928,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 2945,\n \"s\": 2936,\n \"text\": \"Image 1:\"\n },\n {\n \"code\": null,\n \"e\": 2954,\n \"s\": 2945,\n \"text\": \"Image 2:\"\n },\n {\n \"code\": null,\n \"e\": 3168,\n \"s\": 2954,\n \"text\": \"Now if we have to tell user every time which element in a list is selected, we will display a label just beside the spinner which tells about the selected label. Also, we will print the value, and text of spinner.\"\n },\n {\n \"code\": null,\n \"e\": 3197,\n \"s\": 3168,\n \"text\": \"Below is the Implementation:\"\n },\n {\n \"code\": \"# Sample spinner app in kivy to change the# kivy default settings we use this module configfrom kivy.config import Config # 0 being off 1 being on as in true / false# you can use 0 or 1 && True or FalseConfig.set('graphics', 'resizable', True) # Program to Show how to create a switch# import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # The Label widget is for rendering text. from kivy.uix.label import Label # Spinner is a widget that provides a# quick way to select one value from a set.# like a dropdown listfrom kivy.uix.spinner import Spinner # module consist the floatlayout # to work with FloatLayout first # you have to import it from kivy.uix.floatlayout import FloatLayout # Make an App by deriving from the App classclass SpinnerExample(App): # define build def build(self): # creating floatlayout layout = FloatLayout() # creating the spinner # configure spinner object and add to layout self.spinnerObject = Spinner(text =\\\"Python\\\", values =(\\\"Python\\\", \\\"Java\\\", \\\"C++\\\", \\\"C\\\", \\\"C#\\\", \\\"PHP\\\"), background_color =(0.784, 0.443, 0.216, 1)) self.spinnerObject.size_hint = (0.3, 0.2) self.spinnerObject.pos_hint ={'x': .35, 'y':.75} layout.add_widget(self.spinnerObject) self.spinnerObject.bind(text = self.on_spinner_select) # It changes the label info as well # add a label displaying the selection from the spinner self.spinnerSelection = Label(text =\\\"Selected value in spinner is: %s\\\" %self.spinnerObject.text) layout.add_widget(self.spinnerSelection) self.spinnerSelection.pos_hint ={'x': .1, 'y':.3} return layout; # call back for the selection in spinner object def on_spinner_select(self, spinner, text): self.spinnerSelection.text = \\\"Selected value in spinner is: %s\\\" %self.spinnerObject.text) print('The spinner', spinner, 'have text', text) # Run the appif __name__ == '__main__': SpinnerExample().run() \",\n \"e\": 5575,\n \"s\": 3197,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 5583,\n \"s\": 5575,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 5592,\n \"s\": 5583,\n \"text\": \"Image 1:\"\n },\n {\n \"code\": null,\n \"e\": 5601,\n \"s\": 5592,\n \"text\": \"Image 2:\"\n },\n {\n \"code\": null,\n \"e\": 5659,\n \"s\": 5601,\n \"text\": \"Below is the output in video to get better understanding:\"\n },\n {\n \"code\": null,\n \"e\": 5719,\n \"s\": 5659,\n \"text\": \"Media error: Format(s) not supported or source(s) not found\"\n },\n {\n \"code\": null,\n \"e\": 5730,\n \"s\": 5719,\n \"text\": \"Python-gui\"\n },\n {\n \"code\": null,\n \"e\": 5742,\n \"s\": 5730,\n \"text\": \"Python-kivy\"\n },\n {\n \"code\": null,\n \"e\": 5749,\n \"s\": 5742,\n \"text\": \"Python\"\n },\n {\n \"code\": null,\n \"e\": 5847,\n \"s\": 5749,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 5875,\n \"s\": 5847,\n \"text\": \"Read JSON file using Python\"\n },\n {\n \"code\": null,\n \"e\": 5925,\n \"s\": 5875,\n \"text\": \"Adding new column to existing DataFrame in Pandas\"\n },\n {\n \"code\": null,\n \"e\": 5947,\n \"s\": 5925,\n \"text\": \"Python map() function\"\n },\n {\n \"code\": null,\n \"e\": 5991,\n \"s\": 5947,\n \"text\": \"How to get column names in Pandas dataframe\"\n },\n {\n \"code\": null,\n \"e\": 6033,\n \"s\": 5991,\n \"text\": \"Different ways to create Pandas Dataframe\"\n },\n {\n \"code\": null,\n \"e\": 6055,\n \"s\": 6033,\n \"text\": \"Enumerate() in Python\"\n },\n {\n \"code\": null,\n \"e\": 6090,\n \"s\": 6055,\n \"text\": \"Read a file line by line in Python\"\n },\n {\n \"code\": null,\n \"e\": 6116,\n \"s\": 6090,\n \"text\": \"Python String | replace()\"\n },\n {\n \"code\": null,\n \"e\": 6148,\n \"s\": 6116,\n \"text\": \"How to Install PIP on Windows ?\"\n }\n]"}}},{"rowIdx":145,"cells":{"title":{"kind":"string","value":"Secrets | Python module to Generate secure random numbers"},"text":{"kind":"string","value":"30 May, 2018\nThe secrets module is used for generating random numbers for managing important data such as passwords, account authentication, security tokens, and related secrets, that are cryptographically strong. This module is responsible for providing access to the most secure source of randomness. This module is present in Python 3.6 and above.\nRandom Numbers: class secrets.SystemRandom\nThis class uses the os.urandom() function for the generation of random numbers from sources provided by the operating system.\nsecrets.choice(sequence): This function returns a randomly-chosen element from a non-empty sequence to manage a basic level of security.Example 1 : Generate a ten-character alphanumeric password.import secretsimport string alphabet = string.ascii_letters + string.digitspassword = ''.join(secrets.choice(alphabet) for i in range(10)) print(password)Output :'tmX47l1uo4'\nExample 2 : Generate a ten-character alphanumeric password with at least one lowercase character, at least one uppercase character, and at least three digits.import secretsimport string alphabet = string.ascii_letters + string.digitswhile True: password = ''.join(secrets.choice(alphabet) for i in range(10)) if (any(c.islower() for c in password) and any(c.isupper() for c in password) and sum(c.isdigit() for c in password) >= 3): print(password) breakOutput :Tx8LppU05Q\nsecrets.randbelow(n): This function returns a random integer in the range [0, n).import secrets passwd = secrets.randbelow(20)print(passwd)Output :2\nsecrets.randbits(k): This function returns an int with k random bits.import secrets passwd = secrets.randbits(7)print(passwd)Output :61\n\nsecrets.choice(sequence): This function returns a randomly-chosen element from a non-empty sequence to manage a basic level of security.Example 1 : Generate a ten-character alphanumeric password.import secretsimport string alphabet = string.ascii_letters + string.digitspassword = ''.join(secrets.choice(alphabet) for i in range(10)) print(password)Output :'tmX47l1uo4'\nExample 2 : Generate a ten-character alphanumeric password with at least one lowercase character, at least one uppercase character, and at least three digits.import secretsimport string alphabet = string.ascii_letters + string.digitswhile True: password = ''.join(secrets.choice(alphabet) for i in range(10)) if (any(c.islower() for c in password) and any(c.isupper() for c in password) and sum(c.isdigit() for c in password) >= 3): print(password) breakOutput :Tx8LppU05Q\n\nimport secretsimport string alphabet = string.ascii_letters + string.digitspassword = ''.join(secrets.choice(alphabet) for i in range(10)) print(password)\nOutput :\n'tmX47l1uo4'\n\nExample 2 : Generate a ten-character alphanumeric password with at least one lowercase character, at least one uppercase character, and at least three digits.\nimport secretsimport string alphabet = string.ascii_letters + string.digitswhile True: password = ''.join(secrets.choice(alphabet) for i in range(10)) if (any(c.islower() for c in password) and any(c.isupper() for c in password) and sum(c.isdigit() for c in password) >= 3): print(password) break\nOutput :\nTx8LppU05Q\n\nsecrets.randbelow(n): This function returns a random integer in the range [0, n).import secrets passwd = secrets.randbelow(20)print(passwd)Output :2\n\nimport secrets passwd = secrets.randbelow(20)print(passwd)\nOutput :\n2\n\nsecrets.randbits(k): This function returns an int with k random bits.import secrets passwd = secrets.randbits(7)print(passwd)Output :61\n\nimport secrets passwd = secrets.randbits(7)print(passwd)\nOutput :\n61\n\nGenerating tokens\nThis module provides several functions for generating secure tokens for applications such as password resets, hard-to-guess URLs etc.\nsecrets.token_bytes([nbytes=None]) : This function is responsible for generating a random byte string containing nbytes number of bytes. If no value is provided, a reasonable default is used.import secrets token1 = secrets.token_bytes()token2 = secrets.token_bytes(10) print(token1)print(token2)Output :b\"\\x86?\\x85\\xcf\\x8ek8ud\\x8a\\x92\\x8b>R\\xc7\\x89_\\xc4x\\xce'u]\\x95\\x0c\\x05*?HG8\\xfb\"\nb'Dx\\xe8\\x7f\\xc05\\xdf\\xe0\\xf6\\xe1'\nsecrets.token_hex([nbytes=None]) : This function is responsible for generating a random text string in hexadecimal containing nbytes random bytes. If no value is provided, a reasonable default is used.import secrets token1 = secrets.token_hex(16)token2 = secrets.token_hex(9) print(token1)print(token2)Output :5d894a501c88fbe735c6ff496a6d3e51\n78baed9057e597dce4\nsecrets.token_urlsafe([nbytes=None]) : This function is responsible for generating a random URL-safe text string containing nbytes random bytes. This is suitable for password recovery applications.Example : Generate a hard-to-guess temporary URL containing a security token.import secrets url = 'https://mydomain.com/reset=' + secrets.token_urlsafe()print(url)Output :https://mydomain.com/reset=GbOiFIvhMoqWsfaTQKbj8ydbo8G1lsMx1ECa6SXjb1s\nHow many bytes should tokens use?At least 32 bytes for tokens should be used to be secure against a brute-force attack.\nsecrets.token_bytes([nbytes=None]) : This function is responsible for generating a random byte string containing nbytes number of bytes. If no value is provided, a reasonable default is used.import secrets token1 = secrets.token_bytes()token2 = secrets.token_bytes(10) print(token1)print(token2)Output :b\"\\x86?\\x85\\xcf\\x8ek8ud\\x8a\\x92\\x8b>R\\xc7\\x89_\\xc4x\\xce'u]\\x95\\x0c\\x05*?HG8\\xfb\"\nb'Dx\\xe8\\x7f\\xc05\\xdf\\xe0\\xf6\\xe1'\n\nimport secrets token1 = secrets.token_bytes()token2 = secrets.token_bytes(10) print(token1)print(token2)\nOutput :\nb\"\\x86?\\x85\\xcf\\x8ek8ud\\x8a\\x92\\x8b>R\\xc7\\x89_\\xc4x\\xce'u]\\x95\\x0c\\x05*?HG8\\xfb\"\nb'Dx\\xe8\\x7f\\xc05\\xdf\\xe0\\xf6\\xe1'\n\nsecrets.token_hex([nbytes=None]) : This function is responsible for generating a random text string in hexadecimal containing nbytes random bytes. If no value is provided, a reasonable default is used.import secrets token1 = secrets.token_hex(16)token2 = secrets.token_hex(9) print(token1)print(token2)Output :5d894a501c88fbe735c6ff496a6d3e51\n78baed9057e597dce4\n\nimport secrets token1 = secrets.token_hex(16)token2 = secrets.token_hex(9) print(token1)print(token2)\nOutput :\n5d894a501c88fbe735c6ff496a6d3e51\n78baed9057e597dce4\n\nsecrets.token_urlsafe([nbytes=None]) : This function is responsible for generating a random URL-safe text string containing nbytes random bytes. This is suitable for password recovery applications.Example : Generate a hard-to-guess temporary URL containing a security token.import secrets url = 'https://mydomain.com/reset=' + secrets.token_urlsafe()print(url)Output :https://mydomain.com/reset=GbOiFIvhMoqWsfaTQKbj8ydbo8G1lsMx1ECa6SXjb1s\n\nimport secrets url = 'https://mydomain.com/reset=' + secrets.token_urlsafe()print(url)\nOutput :\nhttps://mydomain.com/reset=GbOiFIvhMoqWsfaTQKbj8ydbo8G1lsMx1ECa6SXjb1s\n\nHow many bytes should tokens use?At least 32 bytes for tokens should be used to be secure against a brute-force attack.\nReference: Official Python DocumentationThis article is contributed by Aditi Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.\nPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above.\nPython-Library\nPython\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nHow to Install PIP on Windows ?\nPython Classes and Objects\nPython OOPs Concepts\nPython | os.path.join() method\nHow to drop one or multiple columns in Pandas Dataframe\nIntroduction To PYTHON\nHow To Convert Python Dictionary To JSON?\nCheck if element exists in list in Python\nPython | datetime.timedelta() function\nPython | Get unique values from a list"},"parsed":{"kind":"list like","value":[{"code":null,"e":54,"s":26,"text":"\n30 May, 2018"},{"code":null,"e":392,"s":54,"text":"The secrets module is used for generating random numbers for managing important data such as passwords, account authentication, security tokens, and related secrets, that are cryptographically strong. This module is responsible for providing access to the most secure source of randomness. This module is present in Python 3.6 and above."},{"code":null,"e":435,"s":392,"text":"Random Numbers: class secrets.SystemRandom"},{"code":null,"e":561,"s":435,"text":"This class uses the os.urandom() function for the generation of random numbers from sources provided by the operating system."},{"code":null,"e":1719,"s":561,"text":"secrets.choice(sequence): This function returns a randomly-chosen element from a non-empty sequence to manage a basic level of security.Example 1 : Generate a ten-character alphanumeric password.import secretsimport string alphabet = string.ascii_letters + string.digitspassword = ''.join(secrets.choice(alphabet) for i in range(10)) print(password)Output :'tmX47l1uo4'\nExample 2 : Generate a ten-character alphanumeric password with at least one lowercase character, at least one uppercase character, and at least three digits.import secretsimport string alphabet = string.ascii_letters + string.digitswhile True: password = ''.join(secrets.choice(alphabet) for i in range(10)) if (any(c.islower() for c in password) and any(c.isupper() for c in password) and sum(c.isdigit() for c in password) >= 3): print(password) breakOutput :Tx8LppU05Q\nsecrets.randbelow(n): This function returns a random integer in the range [0, n).import secrets passwd = secrets.randbelow(20)print(passwd)Output :2\nsecrets.randbits(k): This function returns an int with k random bits.import secrets passwd = secrets.randbits(7)print(passwd)Output :61\n"},{"code":null,"e":2590,"s":1719,"text":"secrets.choice(sequence): This function returns a randomly-chosen element from a non-empty sequence to manage a basic level of security.Example 1 : Generate a ten-character alphanumeric password.import secretsimport string alphabet = string.ascii_letters + string.digitspassword = ''.join(secrets.choice(alphabet) for i in range(10)) print(password)Output :'tmX47l1uo4'\nExample 2 : Generate a ten-character alphanumeric password with at least one lowercase character, at least one uppercase character, and at least three digits.import secretsimport string alphabet = string.ascii_letters + string.digitswhile True: password = ''.join(secrets.choice(alphabet) for i in range(10)) if (any(c.islower() for c in password) and any(c.isupper() for c in password) and sum(c.isdigit() for c in password) >= 3): print(password) breakOutput :Tx8LppU05Q\n"},{"code":"import secretsimport string alphabet = string.ascii_letters + string.digitspassword = ''.join(secrets.choice(alphabet) for i in range(10)) print(password)","e":2747,"s":2590,"text":null},{"code":null,"e":2756,"s":2747,"text":"Output :"},{"code":null,"e":2770,"s":2756,"text":"'tmX47l1uo4'\n"},{"code":null,"e":2929,"s":2770,"text":"Example 2 : Generate a ten-character alphanumeric password with at least one lowercase character, at least one uppercase character, and at least three digits."},{"code":"import secretsimport string alphabet = string.ascii_letters + string.digitswhile True: password = ''.join(secrets.choice(alphabet) for i in range(10)) if (any(c.islower() for c in password) and any(c.isupper() for c in password) and sum(c.isdigit() for c in password) >= 3): print(password) break","e":3251,"s":2929,"text":null},{"code":null,"e":3260,"s":3251,"text":"Output :"},{"code":null,"e":3272,"s":3260,"text":"Tx8LppU05Q\n"},{"code":null,"e":3423,"s":3272,"text":"secrets.randbelow(n): This function returns a random integer in the range [0, n).import secrets passwd = secrets.randbelow(20)print(passwd)Output :2\n"},{"code":"import secrets passwd = secrets.randbelow(20)print(passwd)","e":3483,"s":3423,"text":null},{"code":null,"e":3492,"s":3483,"text":"Output :"},{"code":null,"e":3495,"s":3492,"text":"2\n"},{"code":null,"e":3633,"s":3495,"text":"secrets.randbits(k): This function returns an int with k random bits.import secrets passwd = secrets.randbits(7)print(passwd)Output :61\n"},{"code":"import secrets passwd = secrets.randbits(7)print(passwd)","e":3691,"s":3633,"text":null},{"code":null,"e":3700,"s":3691,"text":"Output :"},{"code":null,"e":3704,"s":3700,"text":"61\n"},{"code":null,"e":3722,"s":3704,"text":"Generating tokens"},{"code":null,"e":3856,"s":3722,"text":"This module provides several functions for generating secure tokens for applications such as password resets, hard-to-guess URLs etc."},{"code":null,"e":5201,"s":3856,"text":"secrets.token_bytes([nbytes=None]) : This function is responsible for generating a random byte string containing nbytes number of bytes. If no value is provided, a reasonable default is used.import secrets token1 = secrets.token_bytes()token2 = secrets.token_bytes(10) print(token1)print(token2)Output :b\"\\x86?\\x85\\xcf\\x8ek8ud\\x8a\\x92\\x8b>R\\xc7\\x89_\\xc4x\\xce'u]\\x95\\x0c\\x05*?HG8\\xfb\"\nb'Dx\\xe8\\x7f\\xc05\\xdf\\xe0\\xf6\\xe1'\nsecrets.token_hex([nbytes=None]) : This function is responsible for generating a random text string in hexadecimal containing nbytes random bytes. If no value is provided, a reasonable default is used.import secrets token1 = secrets.token_hex(16)token2 = secrets.token_hex(9) print(token1)print(token2)Output :5d894a501c88fbe735c6ff496a6d3e51\n78baed9057e597dce4\nsecrets.token_urlsafe([nbytes=None]) : This function is responsible for generating a random URL-safe text string containing nbytes random bytes. This is suitable for password recovery applications.Example : Generate a hard-to-guess temporary URL containing a security token.import secrets url = 'https://mydomain.com/reset=' + secrets.token_urlsafe()print(url)Output :https://mydomain.com/reset=GbOiFIvhMoqWsfaTQKbj8ydbo8G1lsMx1ECa6SXjb1s\nHow many bytes should tokens use?At least 32 bytes for tokens should be used to be secure against a brute-force attack."},{"code":null,"e":5623,"s":5201,"text":"secrets.token_bytes([nbytes=None]) : This function is responsible for generating a random byte string containing nbytes number of bytes. If no value is provided, a reasonable default is used.import secrets token1 = secrets.token_bytes()token2 = secrets.token_bytes(10) print(token1)print(token2)Output :b\"\\x86?\\x85\\xcf\\x8ek8ud\\x8a\\x92\\x8b>R\\xc7\\x89_\\xc4x\\xce'u]\\x95\\x0c\\x05*?HG8\\xfb\"\nb'Dx\\xe8\\x7f\\xc05\\xdf\\xe0\\xf6\\xe1'\n"},{"code":"import secrets token1 = secrets.token_bytes()token2 = secrets.token_bytes(10) print(token1)print(token2)","e":5730,"s":5623,"text":null},{"code":null,"e":5739,"s":5730,"text":"Output :"},{"code":null,"e":5856,"s":5739,"text":"b\"\\x86?\\x85\\xcf\\x8ek8ud\\x8a\\x92\\x8b>R\\xc7\\x89_\\xc4x\\xce'u]\\x95\\x0c\\x05*?HG8\\xfb\"\nb'Dx\\xe8\\x7f\\xc05\\xdf\\xe0\\xf6\\xe1'\n"},{"code":null,"e":6221,"s":5856,"text":"secrets.token_hex([nbytes=None]) : This function is responsible for generating a random text string in hexadecimal containing nbytes random bytes. If no value is provided, a reasonable default is used.import secrets token1 = secrets.token_hex(16)token2 = secrets.token_hex(9) print(token1)print(token2)Output :5d894a501c88fbe735c6ff496a6d3e51\n78baed9057e597dce4\n"},{"code":"import secrets token1 = secrets.token_hex(16)token2 = secrets.token_hex(9) print(token1)print(token2)","e":6325,"s":6221,"text":null},{"code":null,"e":6334,"s":6325,"text":"Output :"},{"code":null,"e":6387,"s":6334,"text":"5d894a501c88fbe735c6ff496a6d3e51\n78baed9057e597dce4\n"},{"code":null,"e":6828,"s":6387,"text":"secrets.token_urlsafe([nbytes=None]) : This function is responsible for generating a random URL-safe text string containing nbytes random bytes. This is suitable for password recovery applications.Example : Generate a hard-to-guess temporary URL containing a security token.import secrets url = 'https://mydomain.com/reset=' + secrets.token_urlsafe()print(url)Output :https://mydomain.com/reset=GbOiFIvhMoqWsfaTQKbj8ydbo8G1lsMx1ECa6SXjb1s\n"},{"code":"import secrets url = 'https://mydomain.com/reset=' + secrets.token_urlsafe()print(url)","e":6916,"s":6828,"text":null},{"code":null,"e":6925,"s":6916,"text":"Output :"},{"code":null,"e":6997,"s":6925,"text":"https://mydomain.com/reset=GbOiFIvhMoqWsfaTQKbj8ydbo8G1lsMx1ECa6SXjb1s\n"},{"code":null,"e":7117,"s":6997,"text":"How many bytes should tokens use?At least 32 bytes for tokens should be used to be secure against a brute-force attack."},{"code":null,"e":7456,"s":7117,"text":"Reference: Official Python DocumentationThis article is contributed by Aditi Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."},{"code":null,"e":7581,"s":7456,"text":"Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."},{"code":null,"e":7596,"s":7581,"text":"Python-Library"},{"code":null,"e":7603,"s":7596,"text":"Python"},{"code":null,"e":7701,"s":7603,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":7733,"s":7701,"text":"How to Install PIP on Windows ?"},{"code":null,"e":7760,"s":7733,"text":"Python Classes and Objects"},{"code":null,"e":7781,"s":7760,"text":"Python OOPs Concepts"},{"code":null,"e":7812,"s":7781,"text":"Python | os.path.join() method"},{"code":null,"e":7868,"s":7812,"text":"How to drop one or multiple columns in Pandas Dataframe"},{"code":null,"e":7891,"s":7868,"text":"Introduction To PYTHON"},{"code":null,"e":7933,"s":7891,"text":"How To Convert Python Dictionary To JSON?"},{"code":null,"e":7975,"s":7933,"text":"Check if element exists in list in Python"},{"code":null,"e":8014,"s":7975,"text":"Python | datetime.timedelta() function"}],"string":"[\n {\n \"code\": null,\n \"e\": 54,\n \"s\": 26,\n \"text\": \"\\n30 May, 2018\"\n },\n {\n \"code\": null,\n \"e\": 392,\n \"s\": 54,\n \"text\": \"The secrets module is used for generating random numbers for managing important data such as passwords, account authentication, security tokens, and related secrets, that are cryptographically strong. This module is responsible for providing access to the most secure source of randomness. This module is present in Python 3.6 and above.\"\n },\n {\n \"code\": null,\n \"e\": 435,\n \"s\": 392,\n \"text\": \"Random Numbers: class secrets.SystemRandom\"\n },\n {\n \"code\": null,\n \"e\": 561,\n \"s\": 435,\n \"text\": \"This class uses the os.urandom() function for the generation of random numbers from sources provided by the operating system.\"\n },\n {\n \"code\": null,\n \"e\": 1719,\n \"s\": 561,\n \"text\": \"secrets.choice(sequence): This function returns a randomly-chosen element from a non-empty sequence to manage a basic level of security.Example 1 : Generate a ten-character alphanumeric password.import secretsimport string alphabet = string.ascii_letters + string.digitspassword = ''.join(secrets.choice(alphabet) for i in range(10)) print(password)Output :'tmX47l1uo4'\\nExample 2 : Generate a ten-character alphanumeric password with at least one lowercase character, at least one uppercase character, and at least three digits.import secretsimport string alphabet = string.ascii_letters + string.digitswhile True: password = ''.join(secrets.choice(alphabet) for i in range(10)) if (any(c.islower() for c in password) and any(c.isupper() for c in password) and sum(c.isdigit() for c in password) >= 3): print(password) breakOutput :Tx8LppU05Q\\nsecrets.randbelow(n): This function returns a random integer in the range [0, n).import secrets passwd = secrets.randbelow(20)print(passwd)Output :2\\nsecrets.randbits(k): This function returns an int with k random bits.import secrets passwd = secrets.randbits(7)print(passwd)Output :61\\n\"\n },\n {\n \"code\": null,\n \"e\": 2590,\n \"s\": 1719,\n \"text\": \"secrets.choice(sequence): This function returns a randomly-chosen element from a non-empty sequence to manage a basic level of security.Example 1 : Generate a ten-character alphanumeric password.import secretsimport string alphabet = string.ascii_letters + string.digitspassword = ''.join(secrets.choice(alphabet) for i in range(10)) print(password)Output :'tmX47l1uo4'\\nExample 2 : Generate a ten-character alphanumeric password with at least one lowercase character, at least one uppercase character, and at least three digits.import secretsimport string alphabet = string.ascii_letters + string.digitswhile True: password = ''.join(secrets.choice(alphabet) for i in range(10)) if (any(c.islower() for c in password) and any(c.isupper() for c in password) and sum(c.isdigit() for c in password) >= 3): print(password) breakOutput :Tx8LppU05Q\\n\"\n },\n {\n \"code\": \"import secretsimport string alphabet = string.ascii_letters + string.digitspassword = ''.join(secrets.choice(alphabet) for i in range(10)) print(password)\",\n \"e\": 2747,\n \"s\": 2590,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 2756,\n \"s\": 2747,\n \"text\": \"Output :\"\n },\n {\n \"code\": null,\n \"e\": 2770,\n \"s\": 2756,\n \"text\": \"'tmX47l1uo4'\\n\"\n },\n {\n \"code\": null,\n \"e\": 2929,\n \"s\": 2770,\n \"text\": \"Example 2 : Generate a ten-character alphanumeric password with at least one lowercase character, at least one uppercase character, and at least three digits.\"\n },\n {\n \"code\": \"import secretsimport string alphabet = string.ascii_letters + string.digitswhile True: password = ''.join(secrets.choice(alphabet) for i in range(10)) if (any(c.islower() for c in password) and any(c.isupper() for c in password) and sum(c.isdigit() for c in password) >= 3): print(password) break\",\n \"e\": 3251,\n \"s\": 2929,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 3260,\n \"s\": 3251,\n \"text\": \"Output :\"\n },\n {\n \"code\": null,\n \"e\": 3272,\n \"s\": 3260,\n \"text\": \"Tx8LppU05Q\\n\"\n },\n {\n \"code\": null,\n \"e\": 3423,\n \"s\": 3272,\n \"text\": \"secrets.randbelow(n): This function returns a random integer in the range [0, n).import secrets passwd = secrets.randbelow(20)print(passwd)Output :2\\n\"\n },\n {\n \"code\": \"import secrets passwd = secrets.randbelow(20)print(passwd)\",\n \"e\": 3483,\n \"s\": 3423,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 3492,\n \"s\": 3483,\n \"text\": \"Output :\"\n },\n {\n \"code\": null,\n \"e\": 3495,\n \"s\": 3492,\n \"text\": \"2\\n\"\n },\n {\n \"code\": null,\n \"e\": 3633,\n \"s\": 3495,\n \"text\": \"secrets.randbits(k): This function returns an int with k random bits.import secrets passwd = secrets.randbits(7)print(passwd)Output :61\\n\"\n },\n {\n \"code\": \"import secrets passwd = secrets.randbits(7)print(passwd)\",\n \"e\": 3691,\n \"s\": 3633,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 3700,\n \"s\": 3691,\n \"text\": \"Output :\"\n },\n {\n \"code\": null,\n \"e\": 3704,\n \"s\": 3700,\n \"text\": \"61\\n\"\n },\n {\n \"code\": null,\n \"e\": 3722,\n \"s\": 3704,\n \"text\": \"Generating tokens\"\n },\n {\n \"code\": null,\n \"e\": 3856,\n \"s\": 3722,\n \"text\": \"This module provides several functions for generating secure tokens for applications such as password resets, hard-to-guess URLs etc.\"\n },\n {\n \"code\": null,\n \"e\": 5201,\n \"s\": 3856,\n \"text\": \"secrets.token_bytes([nbytes=None]) : This function is responsible for generating a random byte string containing nbytes number of bytes. If no value is provided, a reasonable default is used.import secrets token1 = secrets.token_bytes()token2 = secrets.token_bytes(10) print(token1)print(token2)Output :b\\\"\\\\x86?\\\\x85\\\\xcf\\\\x8ek8ud\\\\x8a\\\\x92\\\\x8b>R\\\\xc7\\\\x89_\\\\xc4x\\\\xce'u]\\\\x95\\\\x0c\\\\x05*?HG8\\\\xfb\\\"\\nb'Dx\\\\xe8\\\\x7f\\\\xc05\\\\xdf\\\\xe0\\\\xf6\\\\xe1'\\nsecrets.token_hex([nbytes=None]) : This function is responsible for generating a random text string in hexadecimal containing nbytes random bytes. If no value is provided, a reasonable default is used.import secrets token1 = secrets.token_hex(16)token2 = secrets.token_hex(9) print(token1)print(token2)Output :5d894a501c88fbe735c6ff496a6d3e51\\n78baed9057e597dce4\\nsecrets.token_urlsafe([nbytes=None]) : This function is responsible for generating a random URL-safe text string containing nbytes random bytes. This is suitable for password recovery applications.Example : Generate a hard-to-guess temporary URL containing a security token.import secrets url = 'https://mydomain.com/reset=' + secrets.token_urlsafe()print(url)Output :https://mydomain.com/reset=GbOiFIvhMoqWsfaTQKbj8ydbo8G1lsMx1ECa6SXjb1s\\nHow many bytes should tokens use?At least 32 bytes for tokens should be used to be secure against a brute-force attack.\"\n },\n {\n \"code\": null,\n \"e\": 5623,\n \"s\": 5201,\n \"text\": \"secrets.token_bytes([nbytes=None]) : This function is responsible for generating a random byte string containing nbytes number of bytes. If no value is provided, a reasonable default is used.import secrets token1 = secrets.token_bytes()token2 = secrets.token_bytes(10) print(token1)print(token2)Output :b\\\"\\\\x86?\\\\x85\\\\xcf\\\\x8ek8ud\\\\x8a\\\\x92\\\\x8b>R\\\\xc7\\\\x89_\\\\xc4x\\\\xce'u]\\\\x95\\\\x0c\\\\x05*?HG8\\\\xfb\\\"\\nb'Dx\\\\xe8\\\\x7f\\\\xc05\\\\xdf\\\\xe0\\\\xf6\\\\xe1'\\n\"\n },\n {\n \"code\": \"import secrets token1 = secrets.token_bytes()token2 = secrets.token_bytes(10) print(token1)print(token2)\",\n \"e\": 5730,\n \"s\": 5623,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 5739,\n \"s\": 5730,\n \"text\": \"Output :\"\n },\n {\n \"code\": null,\n \"e\": 5856,\n \"s\": 5739,\n \"text\": \"b\\\"\\\\x86?\\\\x85\\\\xcf\\\\x8ek8ud\\\\x8a\\\\x92\\\\x8b>R\\\\xc7\\\\x89_\\\\xc4x\\\\xce'u]\\\\x95\\\\x0c\\\\x05*?HG8\\\\xfb\\\"\\nb'Dx\\\\xe8\\\\x7f\\\\xc05\\\\xdf\\\\xe0\\\\xf6\\\\xe1'\\n\"\n },\n {\n \"code\": null,\n \"e\": 6221,\n \"s\": 5856,\n \"text\": \"secrets.token_hex([nbytes=None]) : This function is responsible for generating a random text string in hexadecimal containing nbytes random bytes. If no value is provided, a reasonable default is used.import secrets token1 = secrets.token_hex(16)token2 = secrets.token_hex(9) print(token1)print(token2)Output :5d894a501c88fbe735c6ff496a6d3e51\\n78baed9057e597dce4\\n\"\n },\n {\n \"code\": \"import secrets token1 = secrets.token_hex(16)token2 = secrets.token_hex(9) print(token1)print(token2)\",\n \"e\": 6325,\n \"s\": 6221,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 6334,\n \"s\": 6325,\n \"text\": \"Output :\"\n },\n {\n \"code\": null,\n \"e\": 6387,\n \"s\": 6334,\n \"text\": \"5d894a501c88fbe735c6ff496a6d3e51\\n78baed9057e597dce4\\n\"\n },\n {\n \"code\": null,\n \"e\": 6828,\n \"s\": 6387,\n \"text\": \"secrets.token_urlsafe([nbytes=None]) : This function is responsible for generating a random URL-safe text string containing nbytes random bytes. This is suitable for password recovery applications.Example : Generate a hard-to-guess temporary URL containing a security token.import secrets url = 'https://mydomain.com/reset=' + secrets.token_urlsafe()print(url)Output :https://mydomain.com/reset=GbOiFIvhMoqWsfaTQKbj8ydbo8G1lsMx1ECa6SXjb1s\\n\"\n },\n {\n \"code\": \"import secrets url = 'https://mydomain.com/reset=' + secrets.token_urlsafe()print(url)\",\n \"e\": 6916,\n \"s\": 6828,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 6925,\n \"s\": 6916,\n \"text\": \"Output :\"\n },\n {\n \"code\": null,\n \"e\": 6997,\n \"s\": 6925,\n \"text\": \"https://mydomain.com/reset=GbOiFIvhMoqWsfaTQKbj8ydbo8G1lsMx1ECa6SXjb1s\\n\"\n },\n {\n \"code\": null,\n \"e\": 7117,\n \"s\": 6997,\n \"text\": \"How many bytes should tokens use?At least 32 bytes for tokens should be used to be secure against a brute-force attack.\"\n },\n {\n \"code\": null,\n \"e\": 7456,\n \"s\": 7117,\n \"text\": \"Reference: Official Python DocumentationThis article is contributed by Aditi Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.\"\n },\n {\n \"code\": null,\n \"e\": 7581,\n \"s\": 7456,\n \"text\": \"Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.\"\n },\n {\n \"code\": null,\n \"e\": 7596,\n \"s\": 7581,\n \"text\": \"Python-Library\"\n },\n {\n \"code\": null,\n \"e\": 7603,\n \"s\": 7596,\n \"text\": \"Python\"\n },\n {\n \"code\": null,\n \"e\": 7701,\n \"s\": 7603,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 7733,\n \"s\": 7701,\n \"text\": \"How to Install PIP on Windows ?\"\n },\n {\n \"code\": null,\n \"e\": 7760,\n \"s\": 7733,\n \"text\": \"Python Classes and Objects\"\n },\n {\n \"code\": null,\n \"e\": 7781,\n \"s\": 7760,\n \"text\": \"Python OOPs Concepts\"\n },\n {\n \"code\": null,\n \"e\": 7812,\n \"s\": 7781,\n \"text\": \"Python | os.path.join() method\"\n },\n {\n \"code\": null,\n \"e\": 7868,\n \"s\": 7812,\n \"text\": \"How to drop one or multiple columns in Pandas Dataframe\"\n },\n {\n \"code\": null,\n \"e\": 7891,\n \"s\": 7868,\n \"text\": \"Introduction To PYTHON\"\n },\n {\n \"code\": null,\n \"e\": 7933,\n \"s\": 7891,\n \"text\": \"How To Convert Python Dictionary To JSON?\"\n },\n {\n \"code\": null,\n \"e\": 7975,\n \"s\": 7933,\n \"text\": \"Check if element exists in list in Python\"\n },\n {\n \"code\": null,\n \"e\": 8014,\n \"s\": 7975,\n \"text\": \"Python | datetime.timedelta() function\"\n }\n]"}}},{"rowIdx":146,"cells":{"title":{"kind":"string","value":"Kth largest element in a stream | Practice | GeeksforGeeks"},"text":{"kind":"string","value":"Given an input stream arr[] of n integers. Find the Kth largest element for each element in the stream and if the Kth element doesn't exist, return -1.\nExample 1:\nInput:\nk = 4, n = 6\narr[] = {1, 2, 3, 4, 5, 6}\nOutput:\n-1 -1 -1 1 2 3\nExplanation:\nk = 4\nFor 1, the 4th largest element doesn't\nexist so we print -1.\nFor 2, the 4th largest element doesn't\nexist so we print -1.\nFor 3, the 4th largest element doesn't\nexist so we print -1.\nFor 4, the 4th largest element is 1.\nFor 5, the 4th largest element is 2.\nfor 6, the 4th largest element is 3.\nExample 2:\nInput:\nk = 1, n = 2\narr[] = {3, 4}\nOutput:\n3 4 \nExplanation: \nFor the 1st and 2nd element the 1st largest \nelement is itself.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function kthLargest() which takes 2 Integers k, and n and also an array arr[] of size n as input and returns the kth largest element in the stream.\n \nExpected Time Complexity: O(nlogk)\nExpected Auxiliary Space: O(n)\n \nConstraints:\n1 ≤ k ≤ n ≤ 105\n1 ≤ arr[i] ≤ 105\n0\nrayalravi20016 days ago\nc++ solution\n \n vector res; int old=0; priority_queue,greater> pq; for(int i=0; itop)?res.push_back(old):res.push_back(top); if(old v(n,-1); priority_queue,greater> q; for(int i=0;i=k) { if(q.top()>prev) { v[i]=q.top(); prev=q.top(); q.pop(); } else { v[i]=prev; q.pop(); } } } return v;\n+1\nbadgujarsachin832 months ago\nvector kthLargest(int k, int arr[], int n) {\n // code here\n priority_queue,greater> q;\n vector v;\n for(int i=0;iq.top()){\n q.pop();\n q.push(arr[i]);\n }\n }\n v.push_back(q.top());\n return v;\n }\n-1\nsaurabhsathe12343 months ago\nSimple C++ Solution Using MinHeap : 0.7sec\nvector kthLargest(int k, int arr[], int n) {\n \n // code here\n priority_queue,greater> pq;\n vector v;\n for(int i=0;i pq.top())\n {\n pq.pop();\n pq.push(arr[i]);\n \n }\n }\n v.push_back(pq.top());\n return v;\n }\n+1\nabhixhek053 months ago\n vector kthLargest(int k, int arr[], int n) {\n // code here\n priority_queue, greater>q;\n vectorans;\n for(int i=0;ik){\n q.pop();\n }\n ans.push_back(q.top()); \n }\n return ans;\n }\n-2\nkumaarsahab4323 months ago\n//Using Priority Queue\nvector kthLargest(int k, int arr[], int n) {\n vector ans ;\n priority_queue, greater> pq ;\n for(int i=0 ; ik) pq.pop() ;\n if(pq.size()==k)\n ans.push_back(pq.top()) ;\n else ans.push_back(-1) ;\n }\n \n return ans ;\n }\n-1\nareeshaanjum7483 months ago\nclass Solution { static int[] kthLargest(int k, int[] arr, int n) { int[] ans = new int[n]; int i = 0; //i will point to ans array //We will add (-1) k-1 times bcoz upto that //kth element would not exist while(i < k-1){ ans[i] = -1; i++; } //Let us take the stream as 2, 1, 4, 3 //4th largest elem will be '1' PriorityQueue minHeap = new PriorityQueue<>(k); int index = 0; while(index < k){ minHeap.add(arr[index]); index++; } ans[i] = minHeap.peek(); i++; //Now, the stream becomes 2, 1, 4, 3, 0 //this '0' will not change 4th largest elem //So we can say any elem less than the 4th largest elem //will not change the 4th largest elem //Atlast, our stream becomes 2, 1, 4, 3, 0, 5 //this '5' will definitely change the 4th largest elem //now our 4th largest elem will be '2' while(index minHeap.peek()){ minHeap.poll(); minHeap.add(arr[index]); } ans[i] = minHeap.peek(); index++; i++; } return ans; }};\n-3\nharshchittora20013 months ago\n vector kthLargest(int k, int arr[], int n) { // code here vectorx; priority_queue,greater>min_heap; for(int i=0;ik) { min_heap.pop(); } if(min_heap.size()>=k) { x.push_back(min_heap.top()); } else if(min_heap.size()<=k) { x.push_back(-1); } } return x; }\n-1\nnitind3563 months ago\nSimple C++ Code:-\n\nvector kthLargest(int k, int arr[], int n) {\n vectorx;\n priority_queue,greater>min;\n for(int i=0;ik)\n {\n min.pop();\n }\n if(min.size()>=k)\n {\n x.push_back(min.top());\n }\n else if(min.size()ans; priority_queue,greater> minheap;\n \n for(int i=0;i res; int old=0; priority_queue,greater> pq; for(int i=0; itop)?res.push_back(old):res.push_back(top); if(old v(n,-1); priority_queue,greater> q; for(int i=0;i=k) { if(q.top()>prev) { v[i]=q.top(); prev=q.top(); q.pop(); } else { v[i]=prev; q.pop(); } } } return v;"},{"code":null,"e":2377,"s":2374,"text":"+1"},{"code":null,"e":2406,"s":2377,"text":"badgujarsachin832 months ago"},{"code":null,"e":2926,"s":2406,"text":"vector kthLargest(int k, int arr[], int n) {\n // code here\n priority_queue,greater> q;\n vector v;\n for(int i=0;iq.top()){\n q.pop();\n q.push(arr[i]);\n }\n }\n v.push_back(q.top());\n return v;\n }"},{"code":null,"e":2929,"s":2926,"text":"-1"},{"code":null,"e":2958,"s":2929,"text":"saurabhsathe12343 months ago"},{"code":null,"e":3001,"s":2958,"text":"Simple C++ Solution Using MinHeap : 0.7sec"},{"code":null,"e":3576,"s":3001,"text":"vector kthLargest(int k, int arr[], int n) {\n \n // code here\n priority_queue,greater> pq;\n vector v;\n for(int i=0;i pq.top())\n {\n pq.pop();\n pq.push(arr[i]);\n \n }\n }\n v.push_back(pq.top());\n return v;\n }"},{"code":null,"e":3579,"s":3576,"text":"+1"},{"code":null,"e":3602,"s":3579,"text":"abhixhek053 months ago"},{"code":null,"e":4094,"s":3602,"text":" vector kthLargest(int k, int arr[], int n) {\n // code here\n priority_queue, greater>q;\n vectorans;\n for(int i=0;ik){\n q.pop();\n }\n ans.push_back(q.top()); \n }\n return ans;\n }"},{"code":null,"e":4097,"s":4094,"text":"-2"},{"code":null,"e":4124,"s":4097,"text":"kumaarsahab4323 months ago"},{"code":null,"e":4549,"s":4124,"text":"//Using Priority Queue\nvector kthLargest(int k, int arr[], int n) {\n vector ans ;\n priority_queue, greater> pq ;\n for(int i=0 ; ik) pq.pop() ;\n if(pq.size()==k)\n ans.push_back(pq.top()) ;\n else ans.push_back(-1) ;\n }\n \n return ans ;\n }"},{"code":null,"e":4552,"s":4549,"text":"-1"},{"code":null,"e":4580,"s":4552,"text":"areeshaanjum7483 months ago"},{"code":null,"e":5855,"s":4580,"text":"class Solution { static int[] kthLargest(int k, int[] arr, int n) { int[] ans = new int[n]; int i = 0; //i will point to ans array //We will add (-1) k-1 times bcoz upto that //kth element would not exist while(i < k-1){ ans[i] = -1; i++; } //Let us take the stream as 2, 1, 4, 3 //4th largest elem will be '1' PriorityQueue minHeap = new PriorityQueue<>(k); int index = 0; while(index < k){ minHeap.add(arr[index]); index++; } ans[i] = minHeap.peek(); i++; //Now, the stream becomes 2, 1, 4, 3, 0 //this '0' will not change 4th largest elem //So we can say any elem less than the 4th largest elem //will not change the 4th largest elem //Atlast, our stream becomes 2, 1, 4, 3, 0, 5 //this '5' will definitely change the 4th largest elem //now our 4th largest elem will be '2' while(index minHeap.peek()){ minHeap.poll(); minHeap.add(arr[index]); } ans[i] = minHeap.peek(); index++; i++; } return ans; }};"},{"code":null,"e":5858,"s":5855,"text":"-3"},{"code":null,"e":5888,"s":5858,"text":"harshchittora20013 months ago"},{"code":null,"e":6361,"s":5888,"text":" vector kthLargest(int k, int arr[], int n) { // code here vectorx; priority_queue,greater>min_heap; for(int i=0;ik) { min_heap.pop(); } if(min_heap.size()>=k) { x.push_back(min_heap.top()); } else if(min_heap.size()<=k) { x.push_back(-1); } } return x; }"},{"code":null,"e":6364,"s":6361,"text":"-1"},{"code":null,"e":6386,"s":6364,"text":"nitind3563 months ago"},{"code":null,"e":6850,"s":6386,"text":"Simple C++ Code:-\n\nvector kthLargest(int k, int arr[], int n) {\n vectorx;\n priority_queue,greater>min;\n for(int i=0;ik)\n {\n min.pop();\n }\n if(min.size()>=k)\n {\n x.push_back(min.top());\n }\n else if(min.size()ans; priority_queue,greater> minheap;\n \n for(int i=0;i res; int old=0; priority_queue,greater> pq; for(int i=0; itop)?res.push_back(old):res.push_back(top); if(old v(n,-1); priority_queue,greater> q; for(int i=0;i=k) { if(q.top()>prev) { v[i]=q.top(); prev=q.top(); q.pop(); } else { v[i]=prev; q.pop(); } } } return v;\"\n },\n {\n \"code\": null,\n \"e\": 2377,\n \"s\": 2374,\n \"text\": \"+1\"\n },\n {\n \"code\": null,\n \"e\": 2406,\n \"s\": 2377,\n \"text\": \"badgujarsachin832 months ago\"\n },\n {\n \"code\": null,\n \"e\": 2926,\n \"s\": 2406,\n \"text\": \"vector kthLargest(int k, int arr[], int n) {\\n // code here\\n priority_queue,greater> q;\\n vector v;\\n for(int i=0;iq.top()){\\n q.pop();\\n q.push(arr[i]);\\n }\\n }\\n v.push_back(q.top());\\n return v;\\n }\"\n },\n {\n \"code\": null,\n \"e\": 2929,\n \"s\": 2926,\n \"text\": \"-1\"\n },\n {\n \"code\": null,\n \"e\": 2958,\n \"s\": 2929,\n \"text\": \"saurabhsathe12343 months ago\"\n },\n {\n \"code\": null,\n \"e\": 3001,\n \"s\": 2958,\n \"text\": \"Simple C++ Solution Using MinHeap : 0.7sec\"\n },\n {\n \"code\": null,\n \"e\": 3576,\n \"s\": 3001,\n \"text\": \"vector kthLargest(int k, int arr[], int n) {\\n \\n // code here\\n priority_queue,greater> pq;\\n vector v;\\n for(int i=0;i pq.top())\\n {\\n pq.pop();\\n pq.push(arr[i]);\\n \\n }\\n }\\n v.push_back(pq.top());\\n return v;\\n }\"\n },\n {\n \"code\": null,\n \"e\": 3579,\n \"s\": 3576,\n \"text\": \"+1\"\n },\n {\n \"code\": null,\n \"e\": 3602,\n \"s\": 3579,\n \"text\": \"abhixhek053 months ago\"\n },\n {\n \"code\": null,\n \"e\": 4094,\n \"s\": 3602,\n \"text\": \" vector kthLargest(int k, int arr[], int n) {\\n // code here\\n priority_queue, greater>q;\\n vectorans;\\n for(int i=0;ik){\\n q.pop();\\n }\\n ans.push_back(q.top()); \\n }\\n return ans;\\n }\"\n },\n {\n \"code\": null,\n \"e\": 4097,\n \"s\": 4094,\n \"text\": \"-2\"\n },\n {\n \"code\": null,\n \"e\": 4124,\n \"s\": 4097,\n \"text\": \"kumaarsahab4323 months ago\"\n },\n {\n \"code\": null,\n \"e\": 4549,\n \"s\": 4124,\n \"text\": \"//Using Priority Queue\\nvector kthLargest(int k, int arr[], int n) {\\n vector ans ;\\n priority_queue, greater> pq ;\\n for(int i=0 ; ik) pq.pop() ;\\n if(pq.size()==k)\\n ans.push_back(pq.top()) ;\\n else ans.push_back(-1) ;\\n }\\n \\n return ans ;\\n }\"\n },\n {\n \"code\": null,\n \"e\": 4552,\n \"s\": 4549,\n \"text\": \"-1\"\n },\n {\n \"code\": null,\n \"e\": 4580,\n \"s\": 4552,\n \"text\": \"areeshaanjum7483 months ago\"\n },\n {\n \"code\": null,\n \"e\": 5855,\n \"s\": 4580,\n \"text\": \"class Solution { static int[] kthLargest(int k, int[] arr, int n) { int[] ans = new int[n]; int i = 0; //i will point to ans array //We will add (-1) k-1 times bcoz upto that //kth element would not exist while(i < k-1){ ans[i] = -1; i++; } //Let us take the stream as 2, 1, 4, 3 //4th largest elem will be '1' PriorityQueue minHeap = new PriorityQueue<>(k); int index = 0; while(index < k){ minHeap.add(arr[index]); index++; } ans[i] = minHeap.peek(); i++; //Now, the stream becomes 2, 1, 4, 3, 0 //this '0' will not change 4th largest elem //So we can say any elem less than the 4th largest elem //will not change the 4th largest elem //Atlast, our stream becomes 2, 1, 4, 3, 0, 5 //this '5' will definitely change the 4th largest elem //now our 4th largest elem will be '2' while(index minHeap.peek()){ minHeap.poll(); minHeap.add(arr[index]); } ans[i] = minHeap.peek(); index++; i++; } return ans; }};\"\n },\n {\n \"code\": null,\n \"e\": 5858,\n \"s\": 5855,\n \"text\": \"-3\"\n },\n {\n \"code\": null,\n \"e\": 5888,\n \"s\": 5858,\n \"text\": \"harshchittora20013 months ago\"\n },\n {\n \"code\": null,\n \"e\": 6361,\n \"s\": 5888,\n \"text\": \" vector kthLargest(int k, int arr[], int n) { // code here vectorx; priority_queue,greater>min_heap; for(int i=0;ik) { min_heap.pop(); } if(min_heap.size()>=k) { x.push_back(min_heap.top()); } else if(min_heap.size()<=k) { x.push_back(-1); } } return x; }\"\n },\n {\n \"code\": null,\n \"e\": 6364,\n \"s\": 6361,\n \"text\": \"-1\"\n },\n {\n \"code\": null,\n \"e\": 6386,\n \"s\": 6364,\n \"text\": \"nitind3563 months ago\"\n },\n {\n \"code\": null,\n \"e\": 6850,\n \"s\": 6386,\n \"text\": \"Simple C++ Code:-\\n\\nvector kthLargest(int k, int arr[], int n) {\\n vectorx;\\n priority_queue,greater>min;\\n for(int i=0;ik)\\n {\\n min.pop();\\n }\\n if(min.size()>=k)\\n {\\n x.push_back(min.top());\\n }\\n else if(min.size()ans; priority_queue,greater> minheap;\\n \\n for(int i=0;idb.countNumberOfElementsDemo.insertOne({\"UserMessage\":[\"Hi\",\"Hello\",\"Bye\",\"Awesome\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cef8ec2ef71edecf6a1f6a1\")\n}\nDisplay all documents from a collection with the help of find() method −\n> db.countNumberOfElementsDemo.find().pretty();\nThis will produce the following output −\n{\n \"_id\" : ObjectId(\"5cef8ec2ef71edecf6a1f6a1\"),\n \"UserMessage\" : [\n \"Hi\",\n \"Hello\",\n \"Bye\",\n \"Awesome\"\n ]\n}\nFollowing is the query to count number of elements in an array −\n> db.countNumberOfElementsDemo.aggregate({$project: { NumberOfElements: { $size:\"$UserMessage\" }}})\nThis will produce the following output −\n{ \"_id\" : ObjectId(\"5cef8ec2ef71edecf6a1f6a1\"), \"NumberOfElements\" : 4 }"},"parsed":{"kind":"list like","value":[{"code":null,"e":1182,"s":1062,"text":"To count number of elements in an array, use the aggregate framework. Let us first create a collection with documents −"},{"code":null,"e":1356,"s":1182,"text":">db.countNumberOfElementsDemo.insertOne({\"UserMessage\":[\"Hi\",\"Hello\",\"Bye\",\"Awesome\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cef8ec2ef71edecf6a1f6a1\")\n}"},{"code":null,"e":1429,"s":1356,"text":"Display all documents from a collection with the help of find() method −"},{"code":null,"e":1477,"s":1429,"text":"> db.countNumberOfElementsDemo.find().pretty();"},{"code":null,"e":1518,"s":1477,"text":"This will produce the following output −"},{"code":null,"e":1653,"s":1518,"text":"{\n \"_id\" : ObjectId(\"5cef8ec2ef71edecf6a1f6a1\"),\n \"UserMessage\" : [\n \"Hi\",\n \"Hello\",\n \"Bye\",\n \"Awesome\"\n ]\n}"},{"code":null,"e":1718,"s":1653,"text":"Following is the query to count number of elements in an array −"},{"code":null,"e":1818,"s":1718,"text":"> db.countNumberOfElementsDemo.aggregate({$project: { NumberOfElements: { $size:\"$UserMessage\" }}})"},{"code":null,"e":1859,"s":1818,"text":"This will produce the following output −"},{"code":null,"e":1932,"s":1859,"text":"{ \"_id\" : ObjectId(\"5cef8ec2ef71edecf6a1f6a1\"), \"NumberOfElements\" : 4 }"}],"string":"[\n {\n \"code\": null,\n \"e\": 1182,\n \"s\": 1062,\n \"text\": \"To count number of elements in an array, use the aggregate framework. Let us first create a collection with documents −\"\n },\n {\n \"code\": null,\n \"e\": 1356,\n \"s\": 1182,\n \"text\": \">db.countNumberOfElementsDemo.insertOne({\\\"UserMessage\\\":[\\\"Hi\\\",\\\"Hello\\\",\\\"Bye\\\",\\\"Awesome\\\"]});\\n{\\n \\\"acknowledged\\\" : true,\\n \\\"insertedId\\\" : ObjectId(\\\"5cef8ec2ef71edecf6a1f6a1\\\")\\n}\"\n },\n {\n \"code\": null,\n \"e\": 1429,\n \"s\": 1356,\n \"text\": \"Display all documents from a collection with the help of find() method −\"\n },\n {\n \"code\": null,\n \"e\": 1477,\n \"s\": 1429,\n \"text\": \"> db.countNumberOfElementsDemo.find().pretty();\"\n },\n {\n \"code\": null,\n \"e\": 1518,\n \"s\": 1477,\n \"text\": \"This will produce the following output −\"\n },\n {\n \"code\": null,\n \"e\": 1653,\n \"s\": 1518,\n \"text\": \"{\\n \\\"_id\\\" : ObjectId(\\\"5cef8ec2ef71edecf6a1f6a1\\\"),\\n \\\"UserMessage\\\" : [\\n \\\"Hi\\\",\\n \\\"Hello\\\",\\n \\\"Bye\\\",\\n \\\"Awesome\\\"\\n ]\\n}\"\n },\n {\n \"code\": null,\n \"e\": 1718,\n \"s\": 1653,\n \"text\": \"Following is the query to count number of elements in an array −\"\n },\n {\n \"code\": null,\n \"e\": 1818,\n \"s\": 1718,\n \"text\": \"> db.countNumberOfElementsDemo.aggregate({$project: { NumberOfElements: { $size:\\\"$UserMessage\\\" }}})\"\n },\n {\n \"code\": null,\n \"e\": 1859,\n \"s\": 1818,\n \"text\": \"This will produce the following output −\"\n },\n {\n \"code\": null,\n \"e\": 1932,\n \"s\": 1859,\n \"text\": \"{ \\\"_id\\\" : ObjectId(\\\"5cef8ec2ef71edecf6a1f6a1\\\"), \\\"NumberOfElements\\\" : 4 }\"\n }\n]"}}},{"rowIdx":148,"cells":{"title":{"kind":"string","value":"ExoPlayer in Android with Example - GeeksforGeeks"},"text":{"kind":"string","value":"15 Dec, 2021\nExoPlayerView is one of the most used UI components in many apps such as YouTube, Netflix, and many video streaming platforms. ExoPlayerView is used for audio as well as video streaming in Android apps. Many Google apps use ExoPlayerView for streaming audios and videos. ExoPlayer is a media player library that provides a way to play audio and video with lots of customization in it. It is an alternative that is used to play videos and audios in Android along with MediaPlayer. ExoPlayer is a library that is the best alternative source for playing audio and videos on Android. This library will also help you to customize your media player according to our requirements. \nExoPlayer provides the support for the playlist and with this, you can clip or merge your media.\nWith the help of ExoPlayer, you can directly fetch media files such as audios and videos directly from the internet and play them inside the ExoPlayer.\nIt provides smooth encryption and streaming of video and audio files.\nExoPlayer provides you the ability to customize your media player according to your requirements.\nExoPlayer\nMediaPlayer\nWe will be creating a simple video player app in which we will be fetching a video from a URL and play that video inside our ExoPlayer. Note that we are using JAVA for implementing ExoPlayer in Android. \nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Add dependency to the build.gradle(Module:app)\nNavigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. \n// dependency for exoplayer\nimplementation ‘com.google.android.exoplayer:exoplayer:r2.4.0’\n// for core support in exoplayer.\nimplementation ‘com.google.android.exoplayer:exoplayer-core:r2.4.0’\n// for adding dash support in our exoplayer.\nimplementation ‘com.google.android.exoplayer:exoplayer-dash:r2.4.0’\n// for adding hls support in exoplayer.\nimplementation ‘com.google.android.exoplayer:exoplayer-hls:r2.4.0’\n// for smooth streaming of video in our exoplayer.\nimplementation ‘com.google.android.exoplayer:exoplayer-smoothstreaming:r2.4.0’\n// for generating default ui of exoplayer\nimplementation ‘com.google.android.exoplayer:exoplayer-ui:r2.4.0’\nAfter adding this dependency sync the project.\nStep 3: Add internet permission in your Manifest file\nNavigate to the app > manifest folder and write down the following permissions to it. \n\n\n\nStep 4: Working with the activity_main.xml\nNow we will start implementing our ExoPlayerView in our XML file. Navigate to the app > res > layout > activity_main.xml. Inside that file add the below code.\nXML\n \nStep 5: Working with the MainActivity.java file\nNavigate to the app > java > your apps package name > MainActivity.java file. Inside that file add the below code. Comments are added inside the code to understand the code in more detail.\nJava\nimport android.net.Uri;import android.os.Bundle;import android.util.Log; import androidx.appcompat.app.AppCompatActivity; import com.google.android.exoplayer2.ExoPlayerFactory;import com.google.android.exoplayer2.SimpleExoPlayer;import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;import com.google.android.exoplayer2.extractor.ExtractorsFactory;import com.google.android.exoplayer2.source.ExtractorMediaSource;import com.google.android.exoplayer2.source.MediaSource;import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;import com.google.android.exoplayer2.trackselection.TrackSelector;import com.google.android.exoplayer2.ui.SimpleExoPlayerView;import com.google.android.exoplayer2.upstream.BandwidthMeter;import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory; public class MainActivity extends AppCompatActivity { // creating a variable for exoplayerview. SimpleExoPlayerView exoPlayerView; // creating a variable for exoplayer SimpleExoPlayer exoPlayer; // url of video which we are loading. String videoURL = \"https://media.geeksforgeeks.org/wp-content/uploads/20201217163353/Screenrecorder-2020-12-17-16-32-03-350.mp4\"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); exoPlayerView = findViewById(R.id.idExoPlayerVIew); try { // bandwisthmeter is used for // getting default bandwidth BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter(); // track selector is used to navigate between // video using a default seekbar. TrackSelector trackSelector = new DefaultTrackSelector(new AdaptiveTrackSelection.Factory(bandwidthMeter)); // we are adding our track selector to exoplayer. exoPlayer = ExoPlayerFactory.newSimpleInstance(this, trackSelector); // we are parsing a video url // and parsing its video uri. Uri videouri = Uri.parse(videoURL); // we are creating a variable for datasource factory // and setting its user agent as 'exoplayer_view' DefaultHttpDataSourceFactory dataSourceFactory = new DefaultHttpDataSourceFactory(\"exoplayer_video\"); // we are creating a variable for extractor factory // and setting it to default extractor factory. ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory(); // we are creating a media source with above variables // and passing our event handler as null, MediaSource mediaSource = new ExtractorMediaSource(videouri, dataSourceFactory, extractorsFactory, null, null); // inside our exoplayer view // we are setting our player exoPlayerView.setPlayer(exoPlayer); // we are preparing our exoplayer // with media source. exoPlayer.prepare(mediaSource); // we are setting our exoplayer // when it is ready. exoPlayer.setPlayWhenReady(true); } catch (Exception e) { // below line is used for // handling our errors. Log.e(\"TAG\", \"Error : \" + e.toString()); } }}\nNote: We have used this video in this project.\nCheck out the project: https://github.com/ChaitanyaMunje/QRCodeGenerator/tree/ExoPlayer\nkalrap615\nandroid\nAndroid-View\nTechnical Scripter 2020\nAndroid\nJava\nTechnical Scripter\nJava\nAndroid\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nHow to Create and Add Data to SQLite Database in Android?\nBroadcast Receiver in Android With Example\nResource Raw Folder in Android Studio\nAndroid RecyclerView in Kotlin\nCardView in Android With Example\nArrays in Java\nSplit() String method in Java with examples\nFor-each loop in Java\nObject Oriented Programming (OOPs) Concept in Java\nStream In Java"},"parsed":{"kind":"list like","value":[{"code":null,"e":26315,"s":26287,"text":"\n15 Dec, 2021"},{"code":null,"e":26990,"s":26315,"text":"ExoPlayerView is one of the most used UI components in many apps such as YouTube, Netflix, and many video streaming platforms. ExoPlayerView is used for audio as well as video streaming in Android apps. Many Google apps use ExoPlayerView for streaming audios and videos. ExoPlayer is a media player library that provides a way to play audio and video with lots of customization in it. It is an alternative that is used to play videos and audios in Android along with MediaPlayer. ExoPlayer is a library that is the best alternative source for playing audio and videos on Android. This library will also help you to customize your media player according to our requirements. "},{"code":null,"e":27087,"s":26990,"text":"ExoPlayer provides the support for the playlist and with this, you can clip or merge your media."},{"code":null,"e":27239,"s":27087,"text":"With the help of ExoPlayer, you can directly fetch media files such as audios and videos directly from the internet and play them inside the ExoPlayer."},{"code":null,"e":27309,"s":27239,"text":"It provides smooth encryption and streaming of video and audio files."},{"code":null,"e":27407,"s":27309,"text":"ExoPlayer provides you the ability to customize your media player according to your requirements."},{"code":null,"e":27417,"s":27407,"text":"ExoPlayer"},{"code":null,"e":27429,"s":27417,"text":"MediaPlayer"},{"code":null,"e":27633,"s":27429,"text":"We will be creating a simple video player app in which we will be fetching a video from a URL and play that video inside our ExoPlayer. Note that we are using JAVA for implementing ExoPlayer in Android. "},{"code":null,"e":27662,"s":27633,"text":"Step 1: Create a New Project"},{"code":null,"e":27824,"s":27662,"text":"To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."},{"code":null,"e":27879,"s":27824,"text":"Step 2: Add dependency to the build.gradle(Module:app)"},{"code":null,"e":27996,"s":27879,"text":"Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. "},{"code":null,"e":28024,"s":27996,"text":"// dependency for exoplayer"},{"code":null,"e":28087,"s":28024,"text":"implementation ‘com.google.android.exoplayer:exoplayer:r2.4.0’"},{"code":null,"e":28121,"s":28087,"text":"// for core support in exoplayer."},{"code":null,"e":28189,"s":28121,"text":"implementation ‘com.google.android.exoplayer:exoplayer-core:r2.4.0’"},{"code":null,"e":28234,"s":28189,"text":"// for adding dash support in our exoplayer."},{"code":null,"e":28302,"s":28234,"text":"implementation ‘com.google.android.exoplayer:exoplayer-dash:r2.4.0’"},{"code":null,"e":28342,"s":28302,"text":"// for adding hls support in exoplayer."},{"code":null,"e":28409,"s":28342,"text":"implementation ‘com.google.android.exoplayer:exoplayer-hls:r2.4.0’"},{"code":null,"e":28460,"s":28409,"text":"// for smooth streaming of video in our exoplayer."},{"code":null,"e":28539,"s":28460,"text":"implementation ‘com.google.android.exoplayer:exoplayer-smoothstreaming:r2.4.0’"},{"code":null,"e":28581,"s":28539,"text":"// for generating default ui of exoplayer"},{"code":null,"e":28647,"s":28581,"text":"implementation ‘com.google.android.exoplayer:exoplayer-ui:r2.4.0’"},{"code":null,"e":28694,"s":28647,"text":"After adding this dependency sync the project."},{"code":null,"e":28748,"s":28694,"text":"Step 3: Add internet permission in your Manifest file"},{"code":null,"e":28835,"s":28748,"text":"Navigate to the app > manifest folder and write down the following permissions to it. "},{"code":null,"e":28890,"s":28835,"text":""},{"code":null,"e":28952,"s":28890,"text":""},{"code":null,"e":29026,"s":28952,"text":""},{"code":null,"e":29069,"s":29026,"text":"Step 4: Working with the activity_main.xml"},{"code":null,"e":29228,"s":29069,"text":"Now we will start implementing our ExoPlayerView in our XML file. Navigate to the app > res > layout > activity_main.xml. Inside that file add the below code."},{"code":null,"e":29232,"s":29228,"text":"XML"},{"code":" ","e":29754,"s":29232,"text":null},{"code":null,"e":29802,"s":29754,"text":"Step 5: Working with the MainActivity.java file"},{"code":null,"e":29991,"s":29802,"text":"Navigate to the app > java > your apps package name > MainActivity.java file. Inside that file add the below code. Comments are added inside the code to understand the code in more detail."},{"code":null,"e":29996,"s":29991,"text":"Java"},{"code":"import android.net.Uri;import android.os.Bundle;import android.util.Log; import androidx.appcompat.app.AppCompatActivity; import com.google.android.exoplayer2.ExoPlayerFactory;import com.google.android.exoplayer2.SimpleExoPlayer;import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;import com.google.android.exoplayer2.extractor.ExtractorsFactory;import com.google.android.exoplayer2.source.ExtractorMediaSource;import com.google.android.exoplayer2.source.MediaSource;import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;import com.google.android.exoplayer2.trackselection.TrackSelector;import com.google.android.exoplayer2.ui.SimpleExoPlayerView;import com.google.android.exoplayer2.upstream.BandwidthMeter;import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory; public class MainActivity extends AppCompatActivity { // creating a variable for exoplayerview. SimpleExoPlayerView exoPlayerView; // creating a variable for exoplayer SimpleExoPlayer exoPlayer; // url of video which we are loading. String videoURL = \"https://media.geeksforgeeks.org/wp-content/uploads/20201217163353/Screenrecorder-2020-12-17-16-32-03-350.mp4\"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); exoPlayerView = findViewById(R.id.idExoPlayerVIew); try { // bandwisthmeter is used for // getting default bandwidth BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter(); // track selector is used to navigate between // video using a default seekbar. TrackSelector trackSelector = new DefaultTrackSelector(new AdaptiveTrackSelection.Factory(bandwidthMeter)); // we are adding our track selector to exoplayer. exoPlayer = ExoPlayerFactory.newSimpleInstance(this, trackSelector); // we are parsing a video url // and parsing its video uri. Uri videouri = Uri.parse(videoURL); // we are creating a variable for datasource factory // and setting its user agent as 'exoplayer_view' DefaultHttpDataSourceFactory dataSourceFactory = new DefaultHttpDataSourceFactory(\"exoplayer_video\"); // we are creating a variable for extractor factory // and setting it to default extractor factory. ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory(); // we are creating a media source with above variables // and passing our event handler as null, MediaSource mediaSource = new ExtractorMediaSource(videouri, dataSourceFactory, extractorsFactory, null, null); // inside our exoplayer view // we are setting our player exoPlayerView.setPlayer(exoPlayer); // we are preparing our exoplayer // with media source. exoPlayer.prepare(mediaSource); // we are setting our exoplayer // when it is ready. exoPlayer.setPlayWhenReady(true); } catch (Exception e) { // below line is used for // handling our errors. Log.e(\"TAG\", \"Error : \" + e.toString()); } }}","e":33615,"s":29996,"text":null},{"code":null,"e":33662,"s":33615,"text":"Note: We have used this video in this project."},{"code":null,"e":33750,"s":33662,"text":"Check out the project: https://github.com/ChaitanyaMunje/QRCodeGenerator/tree/ExoPlayer"},{"code":null,"e":33760,"s":33750,"text":"kalrap615"},{"code":null,"e":33768,"s":33760,"text":"android"},{"code":null,"e":33781,"s":33768,"text":"Android-View"},{"code":null,"e":33805,"s":33781,"text":"Technical Scripter 2020"},{"code":null,"e":33813,"s":33805,"text":"Android"},{"code":null,"e":33818,"s":33813,"text":"Java"},{"code":null,"e":33837,"s":33818,"text":"Technical Scripter"},{"code":null,"e":33842,"s":33837,"text":"Java"},{"code":null,"e":33850,"s":33842,"text":"Android"},{"code":null,"e":33948,"s":33850,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":34006,"s":33948,"text":"How to Create and Add Data to SQLite Database in Android?"},{"code":null,"e":34049,"s":34006,"text":"Broadcast Receiver in Android With Example"},{"code":null,"e":34087,"s":34049,"text":"Resource Raw Folder in Android Studio"},{"code":null,"e":34118,"s":34087,"text":"Android RecyclerView in Kotlin"},{"code":null,"e":34151,"s":34118,"text":"CardView in Android With Example"},{"code":null,"e":34166,"s":34151,"text":"Arrays in Java"},{"code":null,"e":34210,"s":34166,"text":"Split() String method in Java with examples"},{"code":null,"e":34232,"s":34210,"text":"For-each loop in Java"},{"code":null,"e":34283,"s":34232,"text":"Object Oriented Programming (OOPs) Concept in Java"}],"string":"[\n {\n \"code\": null,\n \"e\": 26315,\n \"s\": 26287,\n \"text\": \"\\n15 Dec, 2021\"\n },\n {\n \"code\": null,\n \"e\": 26990,\n \"s\": 26315,\n \"text\": \"ExoPlayerView is one of the most used UI components in many apps such as YouTube, Netflix, and many video streaming platforms. ExoPlayerView is used for audio as well as video streaming in Android apps. Many Google apps use ExoPlayerView for streaming audios and videos. ExoPlayer is a media player library that provides a way to play audio and video with lots of customization in it. It is an alternative that is used to play videos and audios in Android along with MediaPlayer. ExoPlayer is a library that is the best alternative source for playing audio and videos on Android. This library will also help you to customize your media player according to our requirements. \"\n },\n {\n \"code\": null,\n \"e\": 27087,\n \"s\": 26990,\n \"text\": \"ExoPlayer provides the support for the playlist and with this, you can clip or merge your media.\"\n },\n {\n \"code\": null,\n \"e\": 27239,\n \"s\": 27087,\n \"text\": \"With the help of ExoPlayer, you can directly fetch media files such as audios and videos directly from the internet and play them inside the ExoPlayer.\"\n },\n {\n \"code\": null,\n \"e\": 27309,\n \"s\": 27239,\n \"text\": \"It provides smooth encryption and streaming of video and audio files.\"\n },\n {\n \"code\": null,\n \"e\": 27407,\n \"s\": 27309,\n \"text\": \"ExoPlayer provides you the ability to customize your media player according to your requirements.\"\n },\n {\n \"code\": null,\n \"e\": 27417,\n \"s\": 27407,\n \"text\": \"ExoPlayer\"\n },\n {\n \"code\": null,\n \"e\": 27429,\n \"s\": 27417,\n \"text\": \"MediaPlayer\"\n },\n {\n \"code\": null,\n \"e\": 27633,\n \"s\": 27429,\n \"text\": \"We will be creating a simple video player app in which we will be fetching a video from a URL and play that video inside our ExoPlayer. Note that we are using JAVA for implementing ExoPlayer in Android. \"\n },\n {\n \"code\": null,\n \"e\": 27662,\n \"s\": 27633,\n \"text\": \"Step 1: Create a New Project\"\n },\n {\n \"code\": null,\n \"e\": 27824,\n \"s\": 27662,\n \"text\": \"To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\"\n },\n {\n \"code\": null,\n \"e\": 27879,\n \"s\": 27824,\n \"text\": \"Step 2: Add dependency to the build.gradle(Module:app)\"\n },\n {\n \"code\": null,\n \"e\": 27996,\n \"s\": 27879,\n \"text\": \"Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. \"\n },\n {\n \"code\": null,\n \"e\": 28024,\n \"s\": 27996,\n \"text\": \"// dependency for exoplayer\"\n },\n {\n \"code\": null,\n \"e\": 28087,\n \"s\": 28024,\n \"text\": \"implementation ‘com.google.android.exoplayer:exoplayer:r2.4.0’\"\n },\n {\n \"code\": null,\n \"e\": 28121,\n \"s\": 28087,\n \"text\": \"// for core support in exoplayer.\"\n },\n {\n \"code\": null,\n \"e\": 28189,\n \"s\": 28121,\n \"text\": \"implementation ‘com.google.android.exoplayer:exoplayer-core:r2.4.0’\"\n },\n {\n \"code\": null,\n \"e\": 28234,\n \"s\": 28189,\n \"text\": \"// for adding dash support in our exoplayer.\"\n },\n {\n \"code\": null,\n \"e\": 28302,\n \"s\": 28234,\n \"text\": \"implementation ‘com.google.android.exoplayer:exoplayer-dash:r2.4.0’\"\n },\n {\n \"code\": null,\n \"e\": 28342,\n \"s\": 28302,\n \"text\": \"// for adding hls support in exoplayer.\"\n },\n {\n \"code\": null,\n \"e\": 28409,\n \"s\": 28342,\n \"text\": \"implementation ‘com.google.android.exoplayer:exoplayer-hls:r2.4.0’\"\n },\n {\n \"code\": null,\n \"e\": 28460,\n \"s\": 28409,\n \"text\": \"// for smooth streaming of video in our exoplayer.\"\n },\n {\n \"code\": null,\n \"e\": 28539,\n \"s\": 28460,\n \"text\": \"implementation ‘com.google.android.exoplayer:exoplayer-smoothstreaming:r2.4.0’\"\n },\n {\n \"code\": null,\n \"e\": 28581,\n \"s\": 28539,\n \"text\": \"// for generating default ui of exoplayer\"\n },\n {\n \"code\": null,\n \"e\": 28647,\n \"s\": 28581,\n \"text\": \"implementation ‘com.google.android.exoplayer:exoplayer-ui:r2.4.0’\"\n },\n {\n \"code\": null,\n \"e\": 28694,\n \"s\": 28647,\n \"text\": \"After adding this dependency sync the project.\"\n },\n {\n \"code\": null,\n \"e\": 28748,\n \"s\": 28694,\n \"text\": \"Step 3: Add internet permission in your Manifest file\"\n },\n {\n \"code\": null,\n \"e\": 28835,\n \"s\": 28748,\n \"text\": \"Navigate to the app > manifest folder and write down the following permissions to it. \"\n },\n {\n \"code\": null,\n \"e\": 28890,\n \"s\": 28835,\n \"text\": \"\"\n },\n {\n \"code\": null,\n \"e\": 28952,\n \"s\": 28890,\n \"text\": \"\"\n },\n {\n \"code\": null,\n \"e\": 29026,\n \"s\": 28952,\n \"text\": \"\"\n },\n {\n \"code\": null,\n \"e\": 29069,\n \"s\": 29026,\n \"text\": \"Step 4: Working with the activity_main.xml\"\n },\n {\n \"code\": null,\n \"e\": 29228,\n \"s\": 29069,\n \"text\": \"Now we will start implementing our ExoPlayerView in our XML file. Navigate to the app > res > layout > activity_main.xml. Inside that file add the below code.\"\n },\n {\n \"code\": null,\n \"e\": 29232,\n \"s\": 29228,\n \"text\": \"XML\"\n },\n {\n \"code\": \" \",\n \"e\": 29754,\n \"s\": 29232,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 29802,\n \"s\": 29754,\n \"text\": \"Step 5: Working with the MainActivity.java file\"\n },\n {\n \"code\": null,\n \"e\": 29991,\n \"s\": 29802,\n \"text\": \"Navigate to the app > java > your apps package name > MainActivity.java file. Inside that file add the below code. Comments are added inside the code to understand the code in more detail.\"\n },\n {\n \"code\": null,\n \"e\": 29996,\n \"s\": 29991,\n \"text\": \"Java\"\n },\n {\n \"code\": \"import android.net.Uri;import android.os.Bundle;import android.util.Log; import androidx.appcompat.app.AppCompatActivity; import com.google.android.exoplayer2.ExoPlayerFactory;import com.google.android.exoplayer2.SimpleExoPlayer;import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;import com.google.android.exoplayer2.extractor.ExtractorsFactory;import com.google.android.exoplayer2.source.ExtractorMediaSource;import com.google.android.exoplayer2.source.MediaSource;import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;import com.google.android.exoplayer2.trackselection.TrackSelector;import com.google.android.exoplayer2.ui.SimpleExoPlayerView;import com.google.android.exoplayer2.upstream.BandwidthMeter;import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory; public class MainActivity extends AppCompatActivity { // creating a variable for exoplayerview. SimpleExoPlayerView exoPlayerView; // creating a variable for exoplayer SimpleExoPlayer exoPlayer; // url of video which we are loading. String videoURL = \\\"https://media.geeksforgeeks.org/wp-content/uploads/20201217163353/Screenrecorder-2020-12-17-16-32-03-350.mp4\\\"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); exoPlayerView = findViewById(R.id.idExoPlayerVIew); try { // bandwisthmeter is used for // getting default bandwidth BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter(); // track selector is used to navigate between // video using a default seekbar. TrackSelector trackSelector = new DefaultTrackSelector(new AdaptiveTrackSelection.Factory(bandwidthMeter)); // we are adding our track selector to exoplayer. exoPlayer = ExoPlayerFactory.newSimpleInstance(this, trackSelector); // we are parsing a video url // and parsing its video uri. Uri videouri = Uri.parse(videoURL); // we are creating a variable for datasource factory // and setting its user agent as 'exoplayer_view' DefaultHttpDataSourceFactory dataSourceFactory = new DefaultHttpDataSourceFactory(\\\"exoplayer_video\\\"); // we are creating a variable for extractor factory // and setting it to default extractor factory. ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory(); // we are creating a media source with above variables // and passing our event handler as null, MediaSource mediaSource = new ExtractorMediaSource(videouri, dataSourceFactory, extractorsFactory, null, null); // inside our exoplayer view // we are setting our player exoPlayerView.setPlayer(exoPlayer); // we are preparing our exoplayer // with media source. exoPlayer.prepare(mediaSource); // we are setting our exoplayer // when it is ready. exoPlayer.setPlayWhenReady(true); } catch (Exception e) { // below line is used for // handling our errors. Log.e(\\\"TAG\\\", \\\"Error : \\\" + e.toString()); } }}\",\n \"e\": 33615,\n \"s\": 29996,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 33662,\n \"s\": 33615,\n \"text\": \"Note: We have used this video in this project.\"\n },\n {\n \"code\": null,\n \"e\": 33750,\n \"s\": 33662,\n \"text\": \"Check out the project: https://github.com/ChaitanyaMunje/QRCodeGenerator/tree/ExoPlayer\"\n },\n {\n \"code\": null,\n \"e\": 33760,\n \"s\": 33750,\n \"text\": \"kalrap615\"\n },\n {\n \"code\": null,\n \"e\": 33768,\n \"s\": 33760,\n \"text\": \"android\"\n },\n {\n \"code\": null,\n \"e\": 33781,\n \"s\": 33768,\n \"text\": \"Android-View\"\n },\n {\n \"code\": null,\n \"e\": 33805,\n \"s\": 33781,\n \"text\": \"Technical Scripter 2020\"\n },\n {\n \"code\": null,\n \"e\": 33813,\n \"s\": 33805,\n \"text\": \"Android\"\n },\n {\n \"code\": null,\n \"e\": 33818,\n \"s\": 33813,\n \"text\": \"Java\"\n },\n {\n \"code\": null,\n \"e\": 33837,\n \"s\": 33818,\n \"text\": \"Technical Scripter\"\n },\n {\n \"code\": null,\n \"e\": 33842,\n \"s\": 33837,\n \"text\": \"Java\"\n },\n {\n \"code\": null,\n \"e\": 33850,\n \"s\": 33842,\n \"text\": \"Android\"\n },\n {\n \"code\": null,\n \"e\": 33948,\n \"s\": 33850,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 34006,\n \"s\": 33948,\n \"text\": \"How to Create and Add Data to SQLite Database in Android?\"\n },\n {\n \"code\": null,\n \"e\": 34049,\n \"s\": 34006,\n \"text\": \"Broadcast Receiver in Android With Example\"\n },\n {\n \"code\": null,\n \"e\": 34087,\n \"s\": 34049,\n \"text\": \"Resource Raw Folder in Android Studio\"\n },\n {\n \"code\": null,\n \"e\": 34118,\n \"s\": 34087,\n \"text\": \"Android RecyclerView in Kotlin\"\n },\n {\n \"code\": null,\n \"e\": 34151,\n \"s\": 34118,\n \"text\": \"CardView in Android With Example\"\n },\n {\n \"code\": null,\n \"e\": 34166,\n \"s\": 34151,\n \"text\": \"Arrays in Java\"\n },\n {\n \"code\": null,\n \"e\": 34210,\n \"s\": 34166,\n \"text\": \"Split() String method in Java with examples\"\n },\n {\n \"code\": null,\n \"e\": 34232,\n \"s\": 34210,\n \"text\": \"For-each loop in Java\"\n },\n {\n \"code\": null,\n \"e\": 34283,\n \"s\": 34232,\n \"text\": \"Object Oriented Programming (OOPs) Concept in Java\"\n }\n]"}}},{"rowIdx":149,"cells":{"title":{"kind":"string","value":"Best Time to Buy and Sell Stock with Cooldown in C++"},"text":{"kind":"string","value":"Suppose we have an array for which the ith element is the price of a given stock on the day i. We have to design an algorithm to find the maximum profit. We may complete as many transactions as we want (So, buy one and sell one share of the stock multiple times). But we have to follow these rules −\nWe may not engage in multiple transactions at the same time (So, we must sell the stock before you buy again).\nAfter we sell our stock, we cannot buy stock on next day. (So cool down 1 day)\nIf the input is like [1,2,3,0,2], then the output will be 3, the sequence is like [buy, sell, cooldown, buy, sell]\nTo solve this, we will follow these steps −\nendWithSell := 0, endWithBuy := -ve infinity, prevBuy := 0 and prevSell := 0\nfor i := 0 to size of the given arrayprevBuy := endWithBuyendWithBuy := max of endWithBuy and prevSell – Arr[i]prevSell := endWithSellendWithSell := max of endWithSell and prevBuy + Arr[i]\nprevBuy := endWithBuy\nendWithBuy := max of endWithBuy and prevSell – Arr[i]\nprevSell := endWithSell\nendWithSell := max of endWithSell and prevBuy + Arr[i]\nreturn endWithSell\nLet us see the following implementation to get better understanding −\n Live Demo\n#include \nusing namespace std;\nclass Solution {\n public:\n int maxProfit(vector& p) {\n int endWithSell = 0;\n int endWithBuy = INT_MIN;\n int prevBuy =0, prevSell = 0;\n for(int i =0;i v = {1,2,3,0,2};\n cout << (ob.maxProfit(v));\n}\n[1,2,3,0,2]\n3"},"parsed":{"kind":"list like","value":[{"code":null,"e":1362,"s":1062,"text":"Suppose we have an array for which the ith element is the price of a given stock on the day i. We have to design an algorithm to find the maximum profit. We may complete as many transactions as we want (So, buy one and sell one share of the stock multiple times). But we have to follow these rules −"},{"code":null,"e":1473,"s":1362,"text":"We may not engage in multiple transactions at the same time (So, we must sell the stock before you buy again)."},{"code":null,"e":1552,"s":1473,"text":"After we sell our stock, we cannot buy stock on next day. (So cool down 1 day)"},{"code":null,"e":1667,"s":1552,"text":"If the input is like [1,2,3,0,2], then the output will be 3, the sequence is like [buy, sell, cooldown, buy, sell]"},{"code":null,"e":1711,"s":1667,"text":"To solve this, we will follow these steps −"},{"code":null,"e":1788,"s":1711,"text":"endWithSell := 0, endWithBuy := -ve infinity, prevBuy := 0 and prevSell := 0"},{"code":null,"e":1977,"s":1788,"text":"for i := 0 to size of the given arrayprevBuy := endWithBuyendWithBuy := max of endWithBuy and prevSell – Arr[i]prevSell := endWithSellendWithSell := max of endWithSell and prevBuy + Arr[i]"},{"code":null,"e":1999,"s":1977,"text":"prevBuy := endWithBuy"},{"code":null,"e":2053,"s":1999,"text":"endWithBuy := max of endWithBuy and prevSell – Arr[i]"},{"code":null,"e":2077,"s":2053,"text":"prevSell := endWithSell"},{"code":null,"e":2132,"s":2077,"text":"endWithSell := max of endWithSell and prevBuy + Arr[i]"},{"code":null,"e":2151,"s":2132,"text":"return endWithSell"},{"code":null,"e":2221,"s":2151,"text":"Let us see the following implementation to get better understanding −"},{"code":null,"e":2232,"s":2221,"text":" Live Demo"},{"code":null,"e":2778,"s":2232,"text":"#include \nusing namespace std;\nclass Solution {\n public:\n int maxProfit(vector& p) {\n int endWithSell = 0;\n int endWithBuy = INT_MIN;\n int prevBuy =0, prevSell = 0;\n for(int i =0;i v = {1,2,3,0,2};\n cout << (ob.maxProfit(v));\n}"},{"code":null,"e":2790,"s":2778,"text":"[1,2,3,0,2]"},{"code":null,"e":2792,"s":2790,"text":"3"}],"string":"[\n {\n \"code\": null,\n \"e\": 1362,\n \"s\": 1062,\n \"text\": \"Suppose we have an array for which the ith element is the price of a given stock on the day i. We have to design an algorithm to find the maximum profit. We may complete as many transactions as we want (So, buy one and sell one share of the stock multiple times). But we have to follow these rules −\"\n },\n {\n \"code\": null,\n \"e\": 1473,\n \"s\": 1362,\n \"text\": \"We may not engage in multiple transactions at the same time (So, we must sell the stock before you buy again).\"\n },\n {\n \"code\": null,\n \"e\": 1552,\n \"s\": 1473,\n \"text\": \"After we sell our stock, we cannot buy stock on next day. (So cool down 1 day)\"\n },\n {\n \"code\": null,\n \"e\": 1667,\n \"s\": 1552,\n \"text\": \"If the input is like [1,2,3,0,2], then the output will be 3, the sequence is like [buy, sell, cooldown, buy, sell]\"\n },\n {\n \"code\": null,\n \"e\": 1711,\n \"s\": 1667,\n \"text\": \"To solve this, we will follow these steps −\"\n },\n {\n \"code\": null,\n \"e\": 1788,\n \"s\": 1711,\n \"text\": \"endWithSell := 0, endWithBuy := -ve infinity, prevBuy := 0 and prevSell := 0\"\n },\n {\n \"code\": null,\n \"e\": 1977,\n \"s\": 1788,\n \"text\": \"for i := 0 to size of the given arrayprevBuy := endWithBuyendWithBuy := max of endWithBuy and prevSell – Arr[i]prevSell := endWithSellendWithSell := max of endWithSell and prevBuy + Arr[i]\"\n },\n {\n \"code\": null,\n \"e\": 1999,\n \"s\": 1977,\n \"text\": \"prevBuy := endWithBuy\"\n },\n {\n \"code\": null,\n \"e\": 2053,\n \"s\": 1999,\n \"text\": \"endWithBuy := max of endWithBuy and prevSell – Arr[i]\"\n },\n {\n \"code\": null,\n \"e\": 2077,\n \"s\": 2053,\n \"text\": \"prevSell := endWithSell\"\n },\n {\n \"code\": null,\n \"e\": 2132,\n \"s\": 2077,\n \"text\": \"endWithSell := max of endWithSell and prevBuy + Arr[i]\"\n },\n {\n \"code\": null,\n \"e\": 2151,\n \"s\": 2132,\n \"text\": \"return endWithSell\"\n },\n {\n \"code\": null,\n \"e\": 2221,\n \"s\": 2151,\n \"text\": \"Let us see the following implementation to get better understanding −\"\n },\n {\n \"code\": null,\n \"e\": 2232,\n \"s\": 2221,\n \"text\": \" Live Demo\"\n },\n {\n \"code\": null,\n \"e\": 2778,\n \"s\": 2232,\n \"text\": \"#include \\nusing namespace std;\\nclass Solution {\\n public:\\n int maxProfit(vector& p) {\\n int endWithSell = 0;\\n int endWithBuy = INT_MIN;\\n int prevBuy =0, prevSell = 0;\\n for(int i =0;i v = {1,2,3,0,2};\\n cout << (ob.maxProfit(v));\\n}\"\n },\n {\n \"code\": null,\n \"e\": 2790,\n \"s\": 2778,\n \"text\": \"[1,2,3,0,2]\"\n },\n {\n \"code\": null,\n \"e\": 2792,\n \"s\": 2790,\n \"text\": \"3\"\n }\n]"}}},{"rowIdx":150,"cells":{"title":{"kind":"string","value":"Convert a Singly Linked List to an array"},"text":{"kind":"string","value":"24 Mar, 2022\nGiven a singly linked list and the task is to convert it into an array.Examples: \nInput: List = 1 -> 2 -> 3 -> 4 -> 5 -> NULL Output: 1 2 3 4 5Input: List = 10 -> 20 -> 30 -> 40 -> 50 -> NULL Output: 10 20 30 40 50 \n \nApproach: An approach to creating a linked list from the given array has been discussed in this article. Here, an approach to convert the given linked list to an array will be discussed. \nFind the length of the given linked list say len.\nCreate an array of size len.\nTraverse the given linked list and store the elements in the array one at a time.\nBelow is the implementation of the above approach: \nC++\nJava\nPython3\nC#\nJavascript\n// C++ implementation of the approach#include using namespace std; // Singly Linked List structurestruct node { int data; node* next;}; // Function to add a new node// to the Linked Listnode* add(int data){ node* newnode = new node; newnode->data = data; newnode->next = NULL; return newnode;} // Function to print the array contentsvoid printArr(int a[], int n){ for (int i = 0; i < n; i++) cout << a[i] << \" \";} // Function to return the length// of the Linked Listint findlength(node* head){ node* curr = head; int cnt = 0; while (curr != NULL) { cnt++; curr = curr->next; } return cnt;} // Function to convert the// Linked List to an arrayvoid convertArr(node* head){ // Find the length of the // given linked list int len = findlength(head); // Create an array of the // required length int arr[len]; int index = 0; node* curr = head; // Traverse the Linked List and add the // elements to the array one by one while (curr != NULL) { arr[index++] = curr->data; curr = curr->next; } // Print the created array printArr(arr, len);} // Driver codeint main(){ node* head = NULL; head = add(1); head->next = add(2); head->next->next = add(3); head->next->next->next = add(4); head->next->next->next->next = add(5); convertArr(head); return 0;}\n// Java implementation of the approachclass GFG{ // Singly Linked List structurestatic class node{ int data; node next;} // Function to add a new node// to the Linked Liststatic node add(int data){ node newnode = new node(); newnode.data = data; newnode.next = null; return newnode;} // Function to print the array contentsstatic void printArr(int a[], int n){ for (int i = 0; i < n; i++) System.out.print(a[i]+\" \");} // Function to return the length// of the Linked Liststatic int findlength(node head){ node curr = head; int cnt = 0; while (curr != null) { cnt++; curr = curr.next; } return cnt;} // Function to convert the// Linked List to an arraystatic void convertArr(node head){ // Find the length of the // given linked list int len = findlength(head); // Create an array of the // required length int []arr = new int[len]; int index = 0; node curr = head; // Traverse the Linked List and add the // elements to the array one by one while (curr != null) { arr[index++] = curr.data; curr = curr.next; } // Print the created array printArr(arr, len);} // Driver codepublic static void main(String []args){ node head = new node(); head = add(1); head.next = add(2); head.next.next = add(3); head.next.next.next = add(4); head.next.next.next.next = add(5); convertArr(head);}} // This code is contributed by Rajput-Ji\n# Python3 implementation of the approach # Structure of a Nodeclass node: def __init__(self, data): self.data = data self.next = None # Function to add a new node# to the Linked Listdef add(data): newnode = node(0) newnode.data = data newnode.next = None return newnode # Function to print the array contentsdef printArr(a, n): i = 0 while(i < n): print (a[i], end = \" \") i = i + 1 # Function to return the length# of the Linked Listdef findlength( head): curr = head cnt = 0 while (curr != None): cnt = cnt + 1 curr = curr.next return cnt # Function to convert the# Linked List to an arraydef convertArr(head): # Find the length of the # given linked list len1 = findlength(head) # Create an array of the # required length arr = [] index = 0 curr = head # Traverse the Linked List and add the # elements to the array one by one while (curr != None): arr.append( curr.data) curr = curr.next # Print the created array printArr(arr, len1) # Driver codehead = node(0)head = add(1)head.next = add(2)head.next.next = add(3)head.next.next.next = add(4)head.next.next.next.next = add(5)convertArr(head) # This code is contributed by Arnab kundu\n// C# implementation of the approachusing System; class GFG{ // Singly Linked List structurepublic class node{ public int data; public node next;} // Function to add a new node// to the Linked Liststatic node add(int data){ node newnode = new node(); newnode.data = data; newnode.next = null; return newnode;} // Function to print the array contentsstatic void printArr(int []a, int n){ for (int i = 0; i < n; i++) Console.Write(a[i] + \" \");} // Function to return the length// of the Linked Liststatic int findlength(node head){ node curr = head; int cnt = 0; while (curr != null) { cnt++; curr = curr.next; } return cnt;} // Function to convert the// Linked List to an arraystatic void convertArr(node head){ // Find the length of the // given linked list int len = findlength(head); // Create an array of the // required length int []arr = new int[len]; int index = 0; node curr = head; // Traverse the Linked List and add the // elements to the array one by one while (curr != null) { arr[index++] = curr.data; curr = curr.next; } // Print the created array printArr(arr, len);} // Driver codepublic static void Main(String []args){ node head = new node(); head = add(1); head.next = add(2); head.next.next = add(3); head.next.next.next = add(4); head.next.next.next.next = add(5); convertArr(head);}} // This code is contributed by 29AjayKumar\n\n1 2 3 4 5\n \nTime Complexity: O(N)Auxiliary Space: O(N)\nRajput-Ji\n29AjayKumar\nandrew1234\njana_sayantan\npankajsharmagfg\nsurinderdawra388\nAlgorithms\nArrays\nLinked List\nTechnical Scripter\nLinked List\nArrays\nAlgorithms\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nWhat is Hashing | A Complete Tutorial\nFind if there is a path between two vertices in an undirected graph\nHow to Start Learning DSA?\nComplete Roadmap To Learn DSA From Scratch\nTypes of Complexity Classes | P, NP, CoNP, NP hard and NP complete\nArrays in Java\nWrite a program to reverse an array or string\nMaximum and minimum of an array using minimum number of comparisons\nLargest Sum Contiguous Subarray\nArrays in C/C++"},"parsed":{"kind":"list like","value":[{"code":null,"e":52,"s":24,"text":"\n24 Mar, 2022"},{"code":null,"e":135,"s":52,"text":"Given a singly linked list and the task is to convert it into an array.Examples: "},{"code":null,"e":270,"s":135,"text":"Input: List = 1 -> 2 -> 3 -> 4 -> 5 -> NULL Output: 1 2 3 4 5Input: List = 10 -> 20 -> 30 -> 40 -> 50 -> NULL Output: 10 20 30 40 50 "},{"code":null,"e":461,"s":272,"text":"Approach: An approach to creating a linked list from the given array has been discussed in this article. Here, an approach to convert the given linked list to an array will be discussed. "},{"code":null,"e":511,"s":461,"text":"Find the length of the given linked list say len."},{"code":null,"e":540,"s":511,"text":"Create an array of size len."},{"code":null,"e":622,"s":540,"text":"Traverse the given linked list and store the elements in the array one at a time."},{"code":null,"e":675,"s":622,"text":"Below is the implementation of the above approach: "},{"code":null,"e":679,"s":675,"text":"C++"},{"code":null,"e":684,"s":679,"text":"Java"},{"code":null,"e":692,"s":684,"text":"Python3"},{"code":null,"e":695,"s":692,"text":"C#"},{"code":null,"e":706,"s":695,"text":"Javascript"},{"code":"// C++ implementation of the approach#include using namespace std; // Singly Linked List structurestruct node { int data; node* next;}; // Function to add a new node// to the Linked Listnode* add(int data){ node* newnode = new node; newnode->data = data; newnode->next = NULL; return newnode;} // Function to print the array contentsvoid printArr(int a[], int n){ for (int i = 0; i < n; i++) cout << a[i] << \" \";} // Function to return the length// of the Linked Listint findlength(node* head){ node* curr = head; int cnt = 0; while (curr != NULL) { cnt++; curr = curr->next; } return cnt;} // Function to convert the// Linked List to an arrayvoid convertArr(node* head){ // Find the length of the // given linked list int len = findlength(head); // Create an array of the // required length int arr[len]; int index = 0; node* curr = head; // Traverse the Linked List and add the // elements to the array one by one while (curr != NULL) { arr[index++] = curr->data; curr = curr->next; } // Print the created array printArr(arr, len);} // Driver codeint main(){ node* head = NULL; head = add(1); head->next = add(2); head->next->next = add(3); head->next->next->next = add(4); head->next->next->next->next = add(5); convertArr(head); return 0;}","e":2104,"s":706,"text":null},{"code":"// Java implementation of the approachclass GFG{ // Singly Linked List structurestatic class node{ int data; node next;} // Function to add a new node// to the Linked Liststatic node add(int data){ node newnode = new node(); newnode.data = data; newnode.next = null; return newnode;} // Function to print the array contentsstatic void printArr(int a[], int n){ for (int i = 0; i < n; i++) System.out.print(a[i]+\" \");} // Function to return the length// of the Linked Liststatic int findlength(node head){ node curr = head; int cnt = 0; while (curr != null) { cnt++; curr = curr.next; } return cnt;} // Function to convert the// Linked List to an arraystatic void convertArr(node head){ // Find the length of the // given linked list int len = findlength(head); // Create an array of the // required length int []arr = new int[len]; int index = 0; node curr = head; // Traverse the Linked List and add the // elements to the array one by one while (curr != null) { arr[index++] = curr.data; curr = curr.next; } // Print the created array printArr(arr, len);} // Driver codepublic static void main(String []args){ node head = new node(); head = add(1); head.next = add(2); head.next.next = add(3); head.next.next.next = add(4); head.next.next.next.next = add(5); convertArr(head);}} // This code is contributed by Rajput-Ji","e":3572,"s":2104,"text":null},{"code":"# Python3 implementation of the approach # Structure of a Nodeclass node: def __init__(self, data): self.data = data self.next = None # Function to add a new node# to the Linked Listdef add(data): newnode = node(0) newnode.data = data newnode.next = None return newnode # Function to print the array contentsdef printArr(a, n): i = 0 while(i < n): print (a[i], end = \" \") i = i + 1 # Function to return the length# of the Linked Listdef findlength( head): curr = head cnt = 0 while (curr != None): cnt = cnt + 1 curr = curr.next return cnt # Function to convert the# Linked List to an arraydef convertArr(head): # Find the length of the # given linked list len1 = findlength(head) # Create an array of the # required length arr = [] index = 0 curr = head # Traverse the Linked List and add the # elements to the array one by one while (curr != None): arr.append( curr.data) curr = curr.next # Print the created array printArr(arr, len1) # Driver codehead = node(0)head = add(1)head.next = add(2)head.next.next = add(3)head.next.next.next = add(4)head.next.next.next.next = add(5)convertArr(head) # This code is contributed by Arnab kundu","e":4860,"s":3572,"text":null},{"code":"// C# implementation of the approachusing System; class GFG{ // Singly Linked List structurepublic class node{ public int data; public node next;} // Function to add a new node// to the Linked Liststatic node add(int data){ node newnode = new node(); newnode.data = data; newnode.next = null; return newnode;} // Function to print the array contentsstatic void printArr(int []a, int n){ for (int i = 0; i < n; i++) Console.Write(a[i] + \" \");} // Function to return the length// of the Linked Liststatic int findlength(node head){ node curr = head; int cnt = 0; while (curr != null) { cnt++; curr = curr.next; } return cnt;} // Function to convert the// Linked List to an arraystatic void convertArr(node head){ // Find the length of the // given linked list int len = findlength(head); // Create an array of the // required length int []arr = new int[len]; int index = 0; node curr = head; // Traverse the Linked List and add the // elements to the array one by one while (curr != null) { arr[index++] = curr.data; curr = curr.next; } // Print the created array printArr(arr, len);} // Driver codepublic static void Main(String []args){ node head = new node(); head = add(1); head.next = add(2); head.next.next = add(3); head.next.next.next = add(4); head.next.next.next.next = add(5); convertArr(head);}} // This code is contributed by 29AjayKumar","e":6375,"s":4860,"text":null},{"code":"","e":7804,"s":6375,"text":null},{"code":null,"e":7814,"s":7804,"text":"1 2 3 4 5"},{"code":null,"e":7859,"s":7816,"text":"Time Complexity: O(N)Auxiliary Space: O(N)"},{"code":null,"e":7869,"s":7859,"text":"Rajput-Ji"},{"code":null,"e":7881,"s":7869,"text":"29AjayKumar"},{"code":null,"e":7892,"s":7881,"text":"andrew1234"},{"code":null,"e":7906,"s":7892,"text":"jana_sayantan"},{"code":null,"e":7922,"s":7906,"text":"pankajsharmagfg"},{"code":null,"e":7939,"s":7922,"text":"surinderdawra388"},{"code":null,"e":7950,"s":7939,"text":"Algorithms"},{"code":null,"e":7957,"s":7950,"text":"Arrays"},{"code":null,"e":7969,"s":7957,"text":"Linked List"},{"code":null,"e":7988,"s":7969,"text":"Technical Scripter"},{"code":null,"e":8000,"s":7988,"text":"Linked List"},{"code":null,"e":8007,"s":8000,"text":"Arrays"},{"code":null,"e":8018,"s":8007,"text":"Algorithms"},{"code":null,"e":8116,"s":8018,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":8154,"s":8116,"text":"What is Hashing | A Complete Tutorial"},{"code":null,"e":8222,"s":8154,"text":"Find if there is a path between two vertices in an undirected graph"},{"code":null,"e":8249,"s":8222,"text":"How to Start Learning DSA?"},{"code":null,"e":8292,"s":8249,"text":"Complete Roadmap To Learn DSA From Scratch"},{"code":null,"e":8359,"s":8292,"text":"Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"},{"code":null,"e":8374,"s":8359,"text":"Arrays in Java"},{"code":null,"e":8420,"s":8374,"text":"Write a program to reverse an array or string"},{"code":null,"e":8488,"s":8420,"text":"Maximum and minimum of an array using minimum number of comparisons"},{"code":null,"e":8520,"s":8488,"text":"Largest Sum Contiguous Subarray"}],"string":"[\n {\n \"code\": null,\n \"e\": 52,\n \"s\": 24,\n \"text\": \"\\n24 Mar, 2022\"\n },\n {\n \"code\": null,\n \"e\": 135,\n \"s\": 52,\n \"text\": \"Given a singly linked list and the task is to convert it into an array.Examples: \"\n },\n {\n \"code\": null,\n \"e\": 270,\n \"s\": 135,\n \"text\": \"Input: List = 1 -> 2 -> 3 -> 4 -> 5 -> NULL Output: 1 2 3 4 5Input: List = 10 -> 20 -> 30 -> 40 -> 50 -> NULL Output: 10 20 30 40 50 \"\n },\n {\n \"code\": null,\n \"e\": 461,\n \"s\": 272,\n \"text\": \"Approach: An approach to creating a linked list from the given array has been discussed in this article. Here, an approach to convert the given linked list to an array will be discussed. \"\n },\n {\n \"code\": null,\n \"e\": 511,\n \"s\": 461,\n \"text\": \"Find the length of the given linked list say len.\"\n },\n {\n \"code\": null,\n \"e\": 540,\n \"s\": 511,\n \"text\": \"Create an array of size len.\"\n },\n {\n \"code\": null,\n \"e\": 622,\n \"s\": 540,\n \"text\": \"Traverse the given linked list and store the elements in the array one at a time.\"\n },\n {\n \"code\": null,\n \"e\": 675,\n \"s\": 622,\n \"text\": \"Below is the implementation of the above approach: \"\n },\n {\n \"code\": null,\n \"e\": 679,\n \"s\": 675,\n \"text\": \"C++\"\n },\n {\n \"code\": null,\n \"e\": 684,\n \"s\": 679,\n \"text\": \"Java\"\n },\n {\n \"code\": null,\n \"e\": 692,\n \"s\": 684,\n \"text\": \"Python3\"\n },\n {\n \"code\": null,\n \"e\": 695,\n \"s\": 692,\n \"text\": \"C#\"\n },\n {\n \"code\": null,\n \"e\": 706,\n \"s\": 695,\n \"text\": \"Javascript\"\n },\n {\n \"code\": \"// C++ implementation of the approach#include using namespace std; // Singly Linked List structurestruct node { int data; node* next;}; // Function to add a new node// to the Linked Listnode* add(int data){ node* newnode = new node; newnode->data = data; newnode->next = NULL; return newnode;} // Function to print the array contentsvoid printArr(int a[], int n){ for (int i = 0; i < n; i++) cout << a[i] << \\\" \\\";} // Function to return the length// of the Linked Listint findlength(node* head){ node* curr = head; int cnt = 0; while (curr != NULL) { cnt++; curr = curr->next; } return cnt;} // Function to convert the// Linked List to an arrayvoid convertArr(node* head){ // Find the length of the // given linked list int len = findlength(head); // Create an array of the // required length int arr[len]; int index = 0; node* curr = head; // Traverse the Linked List and add the // elements to the array one by one while (curr != NULL) { arr[index++] = curr->data; curr = curr->next; } // Print the created array printArr(arr, len);} // Driver codeint main(){ node* head = NULL; head = add(1); head->next = add(2); head->next->next = add(3); head->next->next->next = add(4); head->next->next->next->next = add(5); convertArr(head); return 0;}\",\n \"e\": 2104,\n \"s\": 706,\n \"text\": null\n },\n {\n \"code\": \"// Java implementation of the approachclass GFG{ // Singly Linked List structurestatic class node{ int data; node next;} // Function to add a new node// to the Linked Liststatic node add(int data){ node newnode = new node(); newnode.data = data; newnode.next = null; return newnode;} // Function to print the array contentsstatic void printArr(int a[], int n){ for (int i = 0; i < n; i++) System.out.print(a[i]+\\\" \\\");} // Function to return the length// of the Linked Liststatic int findlength(node head){ node curr = head; int cnt = 0; while (curr != null) { cnt++; curr = curr.next; } return cnt;} // Function to convert the// Linked List to an arraystatic void convertArr(node head){ // Find the length of the // given linked list int len = findlength(head); // Create an array of the // required length int []arr = new int[len]; int index = 0; node curr = head; // Traverse the Linked List and add the // elements to the array one by one while (curr != null) { arr[index++] = curr.data; curr = curr.next; } // Print the created array printArr(arr, len);} // Driver codepublic static void main(String []args){ node head = new node(); head = add(1); head.next = add(2); head.next.next = add(3); head.next.next.next = add(4); head.next.next.next.next = add(5); convertArr(head);}} // This code is contributed by Rajput-Ji\",\n \"e\": 3572,\n \"s\": 2104,\n \"text\": null\n },\n {\n \"code\": \"# Python3 implementation of the approach # Structure of a Nodeclass node: def __init__(self, data): self.data = data self.next = None # Function to add a new node# to the Linked Listdef add(data): newnode = node(0) newnode.data = data newnode.next = None return newnode # Function to print the array contentsdef printArr(a, n): i = 0 while(i < n): print (a[i], end = \\\" \\\") i = i + 1 # Function to return the length# of the Linked Listdef findlength( head): curr = head cnt = 0 while (curr != None): cnt = cnt + 1 curr = curr.next return cnt # Function to convert the# Linked List to an arraydef convertArr(head): # Find the length of the # given linked list len1 = findlength(head) # Create an array of the # required length arr = [] index = 0 curr = head # Traverse the Linked List and add the # elements to the array one by one while (curr != None): arr.append( curr.data) curr = curr.next # Print the created array printArr(arr, len1) # Driver codehead = node(0)head = add(1)head.next = add(2)head.next.next = add(3)head.next.next.next = add(4)head.next.next.next.next = add(5)convertArr(head) # This code is contributed by Arnab kundu\",\n \"e\": 4860,\n \"s\": 3572,\n \"text\": null\n },\n {\n \"code\": \"// C# implementation of the approachusing System; class GFG{ // Singly Linked List structurepublic class node{ public int data; public node next;} // Function to add a new node// to the Linked Liststatic node add(int data){ node newnode = new node(); newnode.data = data; newnode.next = null; return newnode;} // Function to print the array contentsstatic void printArr(int []a, int n){ for (int i = 0; i < n; i++) Console.Write(a[i] + \\\" \\\");} // Function to return the length// of the Linked Liststatic int findlength(node head){ node curr = head; int cnt = 0; while (curr != null) { cnt++; curr = curr.next; } return cnt;} // Function to convert the// Linked List to an arraystatic void convertArr(node head){ // Find the length of the // given linked list int len = findlength(head); // Create an array of the // required length int []arr = new int[len]; int index = 0; node curr = head; // Traverse the Linked List and add the // elements to the array one by one while (curr != null) { arr[index++] = curr.data; curr = curr.next; } // Print the created array printArr(arr, len);} // Driver codepublic static void Main(String []args){ node head = new node(); head = add(1); head.next = add(2); head.next.next = add(3); head.next.next.next = add(4); head.next.next.next.next = add(5); convertArr(head);}} // This code is contributed by 29AjayKumar\",\n \"e\": 6375,\n \"s\": 4860,\n \"text\": null\n },\n {\n \"code\": \"\",\n \"e\": 7804,\n \"s\": 6375,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 7814,\n \"s\": 7804,\n \"text\": \"1 2 3 4 5\"\n },\n {\n \"code\": null,\n \"e\": 7859,\n \"s\": 7816,\n \"text\": \"Time Complexity: O(N)Auxiliary Space: O(N)\"\n },\n {\n \"code\": null,\n \"e\": 7869,\n \"s\": 7859,\n \"text\": \"Rajput-Ji\"\n },\n {\n \"code\": null,\n \"e\": 7881,\n \"s\": 7869,\n \"text\": \"29AjayKumar\"\n },\n {\n \"code\": null,\n \"e\": 7892,\n \"s\": 7881,\n \"text\": \"andrew1234\"\n },\n {\n \"code\": null,\n \"e\": 7906,\n \"s\": 7892,\n \"text\": \"jana_sayantan\"\n },\n {\n \"code\": null,\n \"e\": 7922,\n \"s\": 7906,\n \"text\": \"pankajsharmagfg\"\n },\n {\n \"code\": null,\n \"e\": 7939,\n \"s\": 7922,\n \"text\": \"surinderdawra388\"\n },\n {\n \"code\": null,\n \"e\": 7950,\n \"s\": 7939,\n \"text\": \"Algorithms\"\n },\n {\n \"code\": null,\n \"e\": 7957,\n \"s\": 7950,\n \"text\": \"Arrays\"\n },\n {\n \"code\": null,\n \"e\": 7969,\n \"s\": 7957,\n \"text\": \"Linked List\"\n },\n {\n \"code\": null,\n \"e\": 7988,\n \"s\": 7969,\n \"text\": \"Technical Scripter\"\n },\n {\n \"code\": null,\n \"e\": 8000,\n \"s\": 7988,\n \"text\": \"Linked List\"\n },\n {\n \"code\": null,\n \"e\": 8007,\n \"s\": 8000,\n \"text\": \"Arrays\"\n },\n {\n \"code\": null,\n \"e\": 8018,\n \"s\": 8007,\n \"text\": \"Algorithms\"\n },\n {\n \"code\": null,\n \"e\": 8116,\n \"s\": 8018,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 8154,\n \"s\": 8116,\n \"text\": \"What is Hashing | A Complete Tutorial\"\n },\n {\n \"code\": null,\n \"e\": 8222,\n \"s\": 8154,\n \"text\": \"Find if there is a path between two vertices in an undirected graph\"\n },\n {\n \"code\": null,\n \"e\": 8249,\n \"s\": 8222,\n \"text\": \"How to Start Learning DSA?\"\n },\n {\n \"code\": null,\n \"e\": 8292,\n \"s\": 8249,\n \"text\": \"Complete Roadmap To Learn DSA From Scratch\"\n },\n {\n \"code\": null,\n \"e\": 8359,\n \"s\": 8292,\n \"text\": \"Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete\"\n },\n {\n \"code\": null,\n \"e\": 8374,\n \"s\": 8359,\n \"text\": \"Arrays in Java\"\n },\n {\n \"code\": null,\n \"e\": 8420,\n \"s\": 8374,\n \"text\": \"Write a program to reverse an array or string\"\n },\n {\n \"code\": null,\n \"e\": 8488,\n \"s\": 8420,\n \"text\": \"Maximum and minimum of an array using minimum number of comparisons\"\n },\n {\n \"code\": null,\n \"e\": 8520,\n \"s\": 8488,\n \"text\": \"Largest Sum Contiguous Subarray\"\n }\n]"}}},{"rowIdx":151,"cells":{"title":{"kind":"string","value":"Python | Vkeyboard (virtual keyboard) in kivy"},"text":{"kind":"string","value":"05 Sep, 2019\nKivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.\nVKeyboard is an onscreen keyboard for Kivy. Its operation is intended to be transparent to the user. Using the widget directly is NOT recommended. Read the section Request keyboard first.\nModes in Vkeyboard:\nThis virtual keyboard has a docked and free mode:\nDocked mode: (VKeyboard.docked = True) Generally used when only one person is using the computer, like a tablet or personal computer etc.\nFree mode: (VKeyboard.docked = False) Mostly for multitouch surfaces. This mode allows multiple virtual keyboards to be used on the screen.\nIf the docked mode changes, you need to manually call VKeyboard.setup_mode() otherwise, the change will have no impact.\nDuring that call, the VKeyboard, implemented on top of a Scatter, will change the behavior of the scatter and position the keyboard near the target (if target and docked mode are set).\nBasic Approach:\n1) import kivy\n2) import kivyApp\n3) import vkeyboard\n4) set kivy version (optional)\n5) Create the Vkeyboard class\n6) Create the App class\n7) return the vkeyboard class\n8) Run the App\n\n# Implementation of the Approach:\n# import kivy module import kivy # this restricts the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require(\"1.9.1\") # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # VKeyboard is an onscreen keyboard# for Kivy. Its operation is intended# to be transparent to the user. from kivy.uix.vkeyboard import VKeyboard # Create the vkeyboardclass Test(VKeyboard): player = VKeyboard() # Create the App classclass VkeyboardApp(App): def build(self): return Test() # run the Appif __name__ == '__main__': VkeyboardApp().run()\nOutput:\nPython-gui\nPython-kivy\nPython\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},"parsed":{"kind":"list like","value":[{"code":null,"e":52,"s":24,"text":"\n05 Sep, 2019"},{"code":null,"e":288,"s":52,"text":"Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications."},{"code":null,"e":476,"s":288,"text":"VKeyboard is an onscreen keyboard for Kivy. Its operation is intended to be transparent to the user. Using the widget directly is NOT recommended. Read the section Request keyboard first."},{"code":null,"e":496,"s":476,"text":"Modes in Vkeyboard:"},{"code":null,"e":546,"s":496,"text":"This virtual keyboard has a docked and free mode:"},{"code":null,"e":684,"s":546,"text":"Docked mode: (VKeyboard.docked = True) Generally used when only one person is using the computer, like a tablet or personal computer etc."},{"code":null,"e":824,"s":684,"text":"Free mode: (VKeyboard.docked = False) Mostly for multitouch surfaces. This mode allows multiple virtual keyboards to be used on the screen."},{"code":null,"e":944,"s":824,"text":"If the docked mode changes, you need to manually call VKeyboard.setup_mode() otherwise, the change will have no impact."},{"code":null,"e":1129,"s":944,"text":"During that call, the VKeyboard, implemented on top of a Scatter, will change the behavior of the scatter and position the keyboard near the target (if target and docked mode are set)."},{"code":null,"e":1329,"s":1129,"text":"Basic Approach:\n1) import kivy\n2) import kivyApp\n3) import vkeyboard\n4) set kivy version (optional)\n5) Create the Vkeyboard class\n6) Create the App class\n7) return the vkeyboard class\n8) Run the App\n"},{"code":null,"e":1363,"s":1329,"text":"# Implementation of the Approach:"},{"code":"# import kivy module import kivy # this restricts the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require(\"1.9.1\") # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # VKeyboard is an onscreen keyboard# for Kivy. Its operation is intended# to be transparent to the user. from kivy.uix.vkeyboard import VKeyboard # Create the vkeyboardclass Test(VKeyboard): player = VKeyboard() # Create the App classclass VkeyboardApp(App): def build(self): return Test() # run the Appif __name__ == '__main__': VkeyboardApp().run()","e":2045,"s":1363,"text":null},{"code":null,"e":2053,"s":2045,"text":"Output:"},{"code":null,"e":2064,"s":2053,"text":"Python-gui"},{"code":null,"e":2076,"s":2064,"text":"Python-kivy"},{"code":null,"e":2083,"s":2076,"text":"Python"}],"string":"[\n {\n \"code\": null,\n \"e\": 52,\n \"s\": 24,\n \"text\": \"\\n05 Sep, 2019\"\n },\n {\n \"code\": null,\n \"e\": 288,\n \"s\": 52,\n \"text\": \"Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.\"\n },\n {\n \"code\": null,\n \"e\": 476,\n \"s\": 288,\n \"text\": \"VKeyboard is an onscreen keyboard for Kivy. Its operation is intended to be transparent to the user. Using the widget directly is NOT recommended. Read the section Request keyboard first.\"\n },\n {\n \"code\": null,\n \"e\": 496,\n \"s\": 476,\n \"text\": \"Modes in Vkeyboard:\"\n },\n {\n \"code\": null,\n \"e\": 546,\n \"s\": 496,\n \"text\": \"This virtual keyboard has a docked and free mode:\"\n },\n {\n \"code\": null,\n \"e\": 684,\n \"s\": 546,\n \"text\": \"Docked mode: (VKeyboard.docked = True) Generally used when only one person is using the computer, like a tablet or personal computer etc.\"\n },\n {\n \"code\": null,\n \"e\": 824,\n \"s\": 684,\n \"text\": \"Free mode: (VKeyboard.docked = False) Mostly for multitouch surfaces. This mode allows multiple virtual keyboards to be used on the screen.\"\n },\n {\n \"code\": null,\n \"e\": 944,\n \"s\": 824,\n \"text\": \"If the docked mode changes, you need to manually call VKeyboard.setup_mode() otherwise, the change will have no impact.\"\n },\n {\n \"code\": null,\n \"e\": 1129,\n \"s\": 944,\n \"text\": \"During that call, the VKeyboard, implemented on top of a Scatter, will change the behavior of the scatter and position the keyboard near the target (if target and docked mode are set).\"\n },\n {\n \"code\": null,\n \"e\": 1329,\n \"s\": 1129,\n \"text\": \"Basic Approach:\\n1) import kivy\\n2) import kivyApp\\n3) import vkeyboard\\n4) set kivy version (optional)\\n5) Create the Vkeyboard class\\n6) Create the App class\\n7) return the vkeyboard class\\n8) Run the App\\n\"\n },\n {\n \"code\": null,\n \"e\": 1363,\n \"s\": 1329,\n \"text\": \"# Implementation of the Approach:\"\n },\n {\n \"code\": \"# import kivy module import kivy # this restricts the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require(\\\"1.9.1\\\") # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # VKeyboard is an onscreen keyboard# for Kivy. Its operation is intended# to be transparent to the user. from kivy.uix.vkeyboard import VKeyboard # Create the vkeyboardclass Test(VKeyboard): player = VKeyboard() # Create the App classclass VkeyboardApp(App): def build(self): return Test() # run the Appif __name__ == '__main__': VkeyboardApp().run()\",\n \"e\": 2045,\n \"s\": 1363,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 2053,\n \"s\": 2045,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 2064,\n \"s\": 2053,\n \"text\": \"Python-gui\"\n },\n {\n \"code\": null,\n \"e\": 2076,\n \"s\": 2064,\n \"text\": \"Python-kivy\"\n },\n {\n \"code\": null,\n \"e\": 2083,\n \"s\": 2076,\n \"text\": \"Python\"\n }\n]"}}},{"rowIdx":152,"cells":{"title":{"kind":"string","value":"Python | Split the Even and Odd elements into two different lists"},"text":{"kind":"string","value":"19 Apr, 2020\nIn this program, a list is accepted with the mixture of odd and even elements and based on whether the element is even or odd, it is split into two different lists.\nExamples:\nInput : [8, 12, 15, 9, 3, 11, 26, 23]\nOutput : Even lists: [8, 12, 26]\n Odd lists: [15, 9, 3, 11, 23]\n\n\nInput : [2, 5, 13, 17, 51, 62, 73, 84, 95]\nOutput : Even lists: [2, 62, 84]\n Odd lists: [5, 13, 17, 51, 73, 95]\n\n# Python code to split into even and odd lists# Function to splitdef Split(mix): ev_li = [] od_li = [] for i in mix: if (i % 2 == 0): ev_li.append(i) else: od_li.append(i) print(\"Even lists:\", ev_li) print(\"Odd lists:\", od_li) # Driver Codemix = [2, 5, 13, 17, 51, 62, 73, 84, 95]Split(mix)\nOutput:\nEven lists: [2, 62, 84]\nOdd lists: [5, 13, 17, 51, 73, 95]\n\nAlternate Shorter Solution :\ndef Split(mix): ev_li = [ele for ele in li_in if ele%2 ==0] od_li = [ele for ele in li_in if ele%2 !=0] print(\"Even lists:\", ev_li) print(\"Odd lists:\", od_li) # Driver Codemix = [2, 5, 13, 17, 51, 62, 73, 84, 95]Split(mix)\nOutput:\nEven lists: [2, 62, 84]\nOdd lists: [5, 13, 17, 51, 73, 95]\n\nshubham_singh\nzwwingfan\nPython list-programs\npython-list\nPython\npython-list\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},"parsed":{"kind":"list like","value":[{"code":null,"e":28,"s":0,"text":"\n19 Apr, 2020"},{"code":null,"e":193,"s":28,"text":"In this program, a list is accepted with the mixture of odd and even elements and based on whether the element is even or odd, it is split into two different lists."},{"code":null,"e":203,"s":193,"text":"Examples:"},{"code":null,"e":436,"s":203,"text":"Input : [8, 12, 15, 9, 3, 11, 26, 23]\nOutput : Even lists: [8, 12, 26]\n Odd lists: [15, 9, 3, 11, 23]\n\n\nInput : [2, 5, 13, 17, 51, 62, 73, 84, 95]\nOutput : Even lists: [2, 62, 84]\n Odd lists: [5, 13, 17, 51, 73, 95]\n"},{"code":"# Python code to split into even and odd lists# Function to splitdef Split(mix): ev_li = [] od_li = [] for i in mix: if (i % 2 == 0): ev_li.append(i) else: od_li.append(i) print(\"Even lists:\", ev_li) print(\"Odd lists:\", od_li) # Driver Codemix = [2, 5, 13, 17, 51, 62, 73, 84, 95]Split(mix)","e":779,"s":436,"text":null},{"code":null,"e":787,"s":779,"text":"Output:"},{"code":null,"e":847,"s":787,"text":"Even lists: [2, 62, 84]\nOdd lists: [5, 13, 17, 51, 73, 95]\n"},{"code":null,"e":876,"s":847,"text":"Alternate Shorter Solution :"},{"code":"def Split(mix): ev_li = [ele for ele in li_in if ele%2 ==0] od_li = [ele for ele in li_in if ele%2 !=0] print(\"Even lists:\", ev_li) print(\"Odd lists:\", od_li) # Driver Codemix = [2, 5, 13, 17, 51, 62, 73, 84, 95]Split(mix)","e":1112,"s":876,"text":null},{"code":null,"e":1120,"s":1112,"text":"Output:"},{"code":null,"e":1180,"s":1120,"text":"Even lists: [2, 62, 84]\nOdd lists: [5, 13, 17, 51, 73, 95]\n"},{"code":null,"e":1194,"s":1180,"text":"shubham_singh"},{"code":null,"e":1204,"s":1194,"text":"zwwingfan"},{"code":null,"e":1225,"s":1204,"text":"Python list-programs"},{"code":null,"e":1237,"s":1225,"text":"python-list"},{"code":null,"e":1244,"s":1237,"text":"Python"},{"code":null,"e":1256,"s":1244,"text":"python-list"}],"string":"[\n {\n \"code\": null,\n \"e\": 28,\n \"s\": 0,\n \"text\": \"\\n19 Apr, 2020\"\n },\n {\n \"code\": null,\n \"e\": 193,\n \"s\": 28,\n \"text\": \"In this program, a list is accepted with the mixture of odd and even elements and based on whether the element is even or odd, it is split into two different lists.\"\n },\n {\n \"code\": null,\n \"e\": 203,\n \"s\": 193,\n \"text\": \"Examples:\"\n },\n {\n \"code\": null,\n \"e\": 436,\n \"s\": 203,\n \"text\": \"Input : [8, 12, 15, 9, 3, 11, 26, 23]\\nOutput : Even lists: [8, 12, 26]\\n Odd lists: [15, 9, 3, 11, 23]\\n\\n\\nInput : [2, 5, 13, 17, 51, 62, 73, 84, 95]\\nOutput : Even lists: [2, 62, 84]\\n Odd lists: [5, 13, 17, 51, 73, 95]\\n\"\n },\n {\n \"code\": \"# Python code to split into even and odd lists# Function to splitdef Split(mix): ev_li = [] od_li = [] for i in mix: if (i % 2 == 0): ev_li.append(i) else: od_li.append(i) print(\\\"Even lists:\\\", ev_li) print(\\\"Odd lists:\\\", od_li) # Driver Codemix = [2, 5, 13, 17, 51, 62, 73, 84, 95]Split(mix)\",\n \"e\": 779,\n \"s\": 436,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 787,\n \"s\": 779,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 847,\n \"s\": 787,\n \"text\": \"Even lists: [2, 62, 84]\\nOdd lists: [5, 13, 17, 51, 73, 95]\\n\"\n },\n {\n \"code\": null,\n \"e\": 876,\n \"s\": 847,\n \"text\": \"Alternate Shorter Solution :\"\n },\n {\n \"code\": \"def Split(mix): ev_li = [ele for ele in li_in if ele%2 ==0] od_li = [ele for ele in li_in if ele%2 !=0] print(\\\"Even lists:\\\", ev_li) print(\\\"Odd lists:\\\", od_li) # Driver Codemix = [2, 5, 13, 17, 51, 62, 73, 84, 95]Split(mix)\",\n \"e\": 1112,\n \"s\": 876,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 1120,\n \"s\": 1112,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 1180,\n \"s\": 1120,\n \"text\": \"Even lists: [2, 62, 84]\\nOdd lists: [5, 13, 17, 51, 73, 95]\\n\"\n },\n {\n \"code\": null,\n \"e\": 1194,\n \"s\": 1180,\n \"text\": \"shubham_singh\"\n },\n {\n \"code\": null,\n \"e\": 1204,\n \"s\": 1194,\n \"text\": \"zwwingfan\"\n },\n {\n \"code\": null,\n \"e\": 1225,\n \"s\": 1204,\n \"text\": \"Python list-programs\"\n },\n {\n \"code\": null,\n \"e\": 1237,\n \"s\": 1225,\n \"text\": \"python-list\"\n },\n {\n \"code\": null,\n \"e\": 1244,\n \"s\": 1237,\n \"text\": \"Python\"\n },\n {\n \"code\": null,\n \"e\": 1256,\n \"s\": 1244,\n \"text\": \"python-list\"\n }\n]"}}},{"rowIdx":153,"cells":{"title":{"kind":"string","value":"Setting up Google Cloud SQL with Flask"},"text":{"kind":"string","value":"16 Jan, 2022\nSetting up a database can be very tricky, yet some pretty simple and scalable solutions are available and one such solution is Google Cloud SQL. Cloud SQL is a fully-managed database service that makes it easy to set up, maintain, and administer your relational PostgreSQL and MySQL databases in the cloud. Setting it up can be both tricky and simple, confused? I am here to clear the confusion.\nFirst of all, you need a Google Cloud Platform (GCP) account. If you don’t want one, then create an account by going to this link here. You will also get $300 free credits for one year when you signup. You also need to set up your billing account to be able to use some of the GCP services which include Cloud SQL. Don’t worry you won’t get charged for this tutorial if you have free credits.\nNow, you need to enable Cloud SQL Admin API from the marketplace. You can do that by click on this link here.Now, let’s jump into our GCP dashboard and then search for Cloud SQL. Your CLoud SQL page should look something like this.\nNow, click on CREATE INSTANCE and then for this tutorial we would be selecting the MySQL option. Now, you should be greeted with the following page.\nNow, fill up the details. It is always advised to generate the password because it creates a random string and note the password because you can not retrieve it if you forget it and also change the region to your nearest one geographically and then click on create. That’s all. Now, the next page should look something like this.\nNow, you first need to create a database. To do that simply, click on the Databases option on the navigation bar at the left and then click on Create database and then provide the name of your database. For this tutorial, our database name will be testing. After you have done that, you should see your database listed there. That all for the setup part. Now let’s actually see how can connect to this database from your flask app.\nObviously, you will be needing Python. In this tutorial, we are currently on the latest python version that is 3.8You also need to install flask, flask-sqlalchemy and mysqlclient. To install those, simply run the following command in your terminal.\npip3 install Flask Flask-SQLAlchemy mysqlclient\nNote: If you are on a Linux machine, then your need to have libmysqlclient-dev installed before you install mysqlclient. To install it simply run sudo apt-get install libmysqlclient-dev in your terminal.\nWith all your pre-requisites done, let’s actually jump right into the code. For simplicity purposes, I will be writing all the code in a single file but as you know, if you are planning on building a mid-size application even, then you need to have separate files for routes, models, etc.Here, the entire code will be written inside a single file called app.py. I have added explanations for every line in my code in the form of inline comments.\nPython3\n# importsfrom flask import Flask, request, make_responsefrom flask_sqlalchemy import SQLAlchemy # initializing Flask appapp = Flask(__name__) # Google Cloud SQL (change this accordingly)PASSWORD =\"your database password\"PUBLIC_IP_ADDRESS =\"public ip of database\"DBNAME =\"database name\"PROJECT_ID =\"gcp project id\"INSTANCE_NAME =\"instance name\" # configurationapp.config[\"SECRET_KEY\"] = \"yoursecretkey\"app.config[\"SQLALCHEMY_DATABASE_URI\"]= f\"mysql + mysqldb://root:{PASSWORD}@{PUBLIC_IP_ADDRESS}/{DBNAME}?unix_socket =/cloudsql/{PROJECT_ID}:{INSTANCE_NAME}\"app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"]= True db = SQLAlchemy(app) # User ORM for SQLAlchemyclass Users(db.Model): id = db.Column(db.Integer, primary_key = True, nullable = False) name = db.Column(db.String(50), nullable = False) email = db.Column(db.String(50), nullable = False, unique = True) @app.route('/add', methods =['POST'])def add(): # getting name and email name = request.form.get('name') email = request.form.get('email') # checking if user already exists user = Users.query.filter_by(email = email).first() if not user: try: # creating Users object user = Users( name = name, email = email ) # adding the fields to users table db.session.add(user) db.session.commit() # response responseObject = { 'status' : 'success', 'message': 'Successfully registered.' } return make_response(responseObject, 200) except: responseObject = { 'status' : 'fail', 'message': 'Some error occured !!' } return make_response(responseObject, 400) else: # if user already exists then send status as fail responseObject = { 'status' : 'fail', 'message': 'User already exists !!' } return make_response(responseObject, 403) @app.route('/view')def view(): # fetches all the users users = Users.query.all() # response list consisting user details response = list() for user in users: response.append({ \"name\" : user.name, \"email\": user.email }) return make_response({ 'status' : 'success', 'message': response }, 200) if __name__ == \"__main__\": # serving the app directly app.run()\nYou need to change the following placeholders in the code \nPASSWORD: the password you set for your database while creating the instance\nPUBLIC_IP_ADDRESS: your GCP instances public IP (can be found in the overview page)\nDBNAME: name of the database that you created later on (for this tutorial it was ‘testing’)\nPROJECT_ID: your GCP project ID\nINSTANCE_NAME: you Cloud SQL instance name\nYour code is ready but it still can’t access your database. This is where most people get it wrong. They keep on checking the documentations and their codebase but they find no mistake and they get completely frustrated and give up, but I hope you are not the one to give up, right? So, let us see what is left to be done.\nThe reason why your database isn’t accessible by your code is that GCP by default blocks all incoming connections from unknown sources (for security purposes). So, what you need to do right now, is to add your systems public IP address to the Authorised Network. To do that, first, go to your Cloud SQL instance page and click on the edit button. You should see a page like this\nHere, click on the Add network button under public IP. There, you need to enter your Public IP address. If you don’t know your Public IP then go to this link. After you have entered your Public IP, you are good to go.Now, your app should be able to connect to your database from your system. Now, open up your terminal inside your project directory and type python inside it. This should open up the python interpreter. Now, simply type the following lines in it to create your table from the ORM.\nPython3\nfrom app import dbdb.create_all()\nThat’s all. Now you are ready to test out your app. Go ahead and using any API request tool to check if it works or not. You can use the famous Postman to test it out.The ability to host your database on an external service is very crucial for student developers, otherwise, it is impossible to showcase your projects. \nruhelaa48\nakshaysingh98088\nsweetyty\nsaurabh1990aror\nmysql\nPython Flask\nPython\nSQL\nWeb Technologies\nSQL\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nPython Dictionary\nDifferent ways to create Pandas Dataframe\nEnumerate() in Python\nPython String | replace()\nHow to Install PIP on Windows ?\nSQL | DDL, DQL, DML, DCL and TCL Commands\nSQL | Join (Inner, Left, Right and Full Joins)\nSQL | WITH clause\nHow to find Nth highest salary from a table\nCTE in SQL"},"parsed":{"kind":"list like","value":[{"code":null,"e":28,"s":0,"text":"\n16 Jan, 2022"},{"code":null,"e":424,"s":28,"text":"Setting up a database can be very tricky, yet some pretty simple and scalable solutions are available and one such solution is Google Cloud SQL. Cloud SQL is a fully-managed database service that makes it easy to set up, maintain, and administer your relational PostgreSQL and MySQL databases in the cloud. Setting it up can be both tricky and simple, confused? I am here to clear the confusion."},{"code":null,"e":817,"s":424,"text":"First of all, you need a Google Cloud Platform (GCP) account. If you don’t want one, then create an account by going to this link here. You will also get $300 free credits for one year when you signup. You also need to set up your billing account to be able to use some of the GCP services which include Cloud SQL. Don’t worry you won’t get charged for this tutorial if you have free credits."},{"code":null,"e":1049,"s":817,"text":"Now, you need to enable Cloud SQL Admin API from the marketplace. You can do that by click on this link here.Now, let’s jump into our GCP dashboard and then search for Cloud SQL. Your CLoud SQL page should look something like this."},{"code":null,"e":1198,"s":1049,"text":"Now, click on CREATE INSTANCE and then for this tutorial we would be selecting the MySQL option. Now, you should be greeted with the following page."},{"code":null,"e":1528,"s":1198,"text":"Now, fill up the details. It is always advised to generate the password because it creates a random string and note the password because you can not retrieve it if you forget it and also change the region to your nearest one geographically and then click on create. That’s all. Now, the next page should look something like this."},{"code":null,"e":1960,"s":1528,"text":"Now, you first need to create a database. To do that simply, click on the Databases option on the navigation bar at the left and then click on Create database and then provide the name of your database. For this tutorial, our database name will be testing. After you have done that, you should see your database listed there. That all for the setup part. Now let’s actually see how can connect to this database from your flask app."},{"code":null,"e":2209,"s":1960,"text":"Obviously, you will be needing Python. In this tutorial, we are currently on the latest python version that is 3.8You also need to install flask, flask-sqlalchemy and mysqlclient. To install those, simply run the following command in your terminal."},{"code":null,"e":2257,"s":2209,"text":"pip3 install Flask Flask-SQLAlchemy mysqlclient"},{"code":null,"e":2461,"s":2257,"text":"Note: If you are on a Linux machine, then your need to have libmysqlclient-dev installed before you install mysqlclient. To install it simply run sudo apt-get install libmysqlclient-dev in your terminal."},{"code":null,"e":2907,"s":2461,"text":"With all your pre-requisites done, let’s actually jump right into the code. For simplicity purposes, I will be writing all the code in a single file but as you know, if you are planning on building a mid-size application even, then you need to have separate files for routes, models, etc.Here, the entire code will be written inside a single file called app.py. I have added explanations for every line in my code in the form of inline comments."},{"code":null,"e":2915,"s":2907,"text":"Python3"},{"code":"# importsfrom flask import Flask, request, make_responsefrom flask_sqlalchemy import SQLAlchemy # initializing Flask appapp = Flask(__name__) # Google Cloud SQL (change this accordingly)PASSWORD =\"your database password\"PUBLIC_IP_ADDRESS =\"public ip of database\"DBNAME =\"database name\"PROJECT_ID =\"gcp project id\"INSTANCE_NAME =\"instance name\" # configurationapp.config[\"SECRET_KEY\"] = \"yoursecretkey\"app.config[\"SQLALCHEMY_DATABASE_URI\"]= f\"mysql + mysqldb://root:{PASSWORD}@{PUBLIC_IP_ADDRESS}/{DBNAME}?unix_socket =/cloudsql/{PROJECT_ID}:{INSTANCE_NAME}\"app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"]= True db = SQLAlchemy(app) # User ORM for SQLAlchemyclass Users(db.Model): id = db.Column(db.Integer, primary_key = True, nullable = False) name = db.Column(db.String(50), nullable = False) email = db.Column(db.String(50), nullable = False, unique = True) @app.route('/add', methods =['POST'])def add(): # getting name and email name = request.form.get('name') email = request.form.get('email') # checking if user already exists user = Users.query.filter_by(email = email).first() if not user: try: # creating Users object user = Users( name = name, email = email ) # adding the fields to users table db.session.add(user) db.session.commit() # response responseObject = { 'status' : 'success', 'message': 'Successfully registered.' } return make_response(responseObject, 200) except: responseObject = { 'status' : 'fail', 'message': 'Some error occured !!' } return make_response(responseObject, 400) else: # if user already exists then send status as fail responseObject = { 'status' : 'fail', 'message': 'User already exists !!' } return make_response(responseObject, 403) @app.route('/view')def view(): # fetches all the users users = Users.query.all() # response list consisting user details response = list() for user in users: response.append({ \"name\" : user.name, \"email\": user.email }) return make_response({ 'status' : 'success', 'message': response }, 200) if __name__ == \"__main__\": # serving the app directly app.run()","e":5369,"s":2915,"text":null},{"code":null,"e":5428,"s":5369,"text":"You need to change the following placeholders in the code "},{"code":null,"e":5505,"s":5428,"text":"PASSWORD: the password you set for your database while creating the instance"},{"code":null,"e":5589,"s":5505,"text":"PUBLIC_IP_ADDRESS: your GCP instances public IP (can be found in the overview page)"},{"code":null,"e":5681,"s":5589,"text":"DBNAME: name of the database that you created later on (for this tutorial it was ‘testing’)"},{"code":null,"e":5713,"s":5681,"text":"PROJECT_ID: your GCP project ID"},{"code":null,"e":5756,"s":5713,"text":"INSTANCE_NAME: you Cloud SQL instance name"},{"code":null,"e":6079,"s":5756,"text":"Your code is ready but it still can’t access your database. This is where most people get it wrong. They keep on checking the documentations and their codebase but they find no mistake and they get completely frustrated and give up, but I hope you are not the one to give up, right? So, let us see what is left to be done."},{"code":null,"e":6458,"s":6079,"text":"The reason why your database isn’t accessible by your code is that GCP by default blocks all incoming connections from unknown sources (for security purposes). So, what you need to do right now, is to add your systems public IP address to the Authorised Network. To do that, first, go to your Cloud SQL instance page and click on the edit button. You should see a page like this"},{"code":null,"e":6956,"s":6458,"text":"Here, click on the Add network button under public IP. There, you need to enter your Public IP address. If you don’t know your Public IP then go to this link. After you have entered your Public IP, you are good to go.Now, your app should be able to connect to your database from your system. Now, open up your terminal inside your project directory and type python inside it. This should open up the python interpreter. Now, simply type the following lines in it to create your table from the ORM."},{"code":null,"e":6964,"s":6956,"text":"Python3"},{"code":"from app import dbdb.create_all()","e":6998,"s":6964,"text":null},{"code":null,"e":7318,"s":6998,"text":"That’s all. Now you are ready to test out your app. Go ahead and using any API request tool to check if it works or not. You can use the famous Postman to test it out.The ability to host your database on an external service is very crucial for student developers, otherwise, it is impossible to showcase your projects. "},{"code":null,"e":7328,"s":7318,"text":"ruhelaa48"},{"code":null,"e":7345,"s":7328,"text":"akshaysingh98088"},{"code":null,"e":7354,"s":7345,"text":"sweetyty"},{"code":null,"e":7370,"s":7354,"text":"saurabh1990aror"},{"code":null,"e":7376,"s":7370,"text":"mysql"},{"code":null,"e":7389,"s":7376,"text":"Python Flask"},{"code":null,"e":7396,"s":7389,"text":"Python"},{"code":null,"e":7400,"s":7396,"text":"SQL"},{"code":null,"e":7417,"s":7400,"text":"Web Technologies"},{"code":null,"e":7421,"s":7417,"text":"SQL"},{"code":null,"e":7519,"s":7421,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":7537,"s":7519,"text":"Python Dictionary"},{"code":null,"e":7579,"s":7537,"text":"Different ways to create Pandas Dataframe"},{"code":null,"e":7601,"s":7579,"text":"Enumerate() in Python"},{"code":null,"e":7627,"s":7601,"text":"Python String | replace()"},{"code":null,"e":7659,"s":7627,"text":"How to Install PIP on Windows ?"},{"code":null,"e":7701,"s":7659,"text":"SQL | DDL, DQL, DML, DCL and TCL Commands"},{"code":null,"e":7748,"s":7701,"text":"SQL | Join (Inner, Left, Right and Full Joins)"},{"code":null,"e":7766,"s":7748,"text":"SQL | WITH clause"},{"code":null,"e":7810,"s":7766,"text":"How to find Nth highest salary from a table"}],"string":"[\n {\n \"code\": null,\n \"e\": 28,\n \"s\": 0,\n \"text\": \"\\n16 Jan, 2022\"\n },\n {\n \"code\": null,\n \"e\": 424,\n \"s\": 28,\n \"text\": \"Setting up a database can be very tricky, yet some pretty simple and scalable solutions are available and one such solution is Google Cloud SQL. Cloud SQL is a fully-managed database service that makes it easy to set up, maintain, and administer your relational PostgreSQL and MySQL databases in the cloud. Setting it up can be both tricky and simple, confused? I am here to clear the confusion.\"\n },\n {\n \"code\": null,\n \"e\": 817,\n \"s\": 424,\n \"text\": \"First of all, you need a Google Cloud Platform (GCP) account. If you don’t want one, then create an account by going to this link here. You will also get $300 free credits for one year when you signup. You also need to set up your billing account to be able to use some of the GCP services which include Cloud SQL. Don’t worry you won’t get charged for this tutorial if you have free credits.\"\n },\n {\n \"code\": null,\n \"e\": 1049,\n \"s\": 817,\n \"text\": \"Now, you need to enable Cloud SQL Admin API from the marketplace. You can do that by click on this link here.Now, let’s jump into our GCP dashboard and then search for Cloud SQL. Your CLoud SQL page should look something like this.\"\n },\n {\n \"code\": null,\n \"e\": 1198,\n \"s\": 1049,\n \"text\": \"Now, click on CREATE INSTANCE and then for this tutorial we would be selecting the MySQL option. Now, you should be greeted with the following page.\"\n },\n {\n \"code\": null,\n \"e\": 1528,\n \"s\": 1198,\n \"text\": \"Now, fill up the details. It is always advised to generate the password because it creates a random string and note the password because you can not retrieve it if you forget it and also change the region to your nearest one geographically and then click on create. That’s all. Now, the next page should look something like this.\"\n },\n {\n \"code\": null,\n \"e\": 1960,\n \"s\": 1528,\n \"text\": \"Now, you first need to create a database. To do that simply, click on the Databases option on the navigation bar at the left and then click on Create database and then provide the name of your database. For this tutorial, our database name will be testing. After you have done that, you should see your database listed there. That all for the setup part. Now let’s actually see how can connect to this database from your flask app.\"\n },\n {\n \"code\": null,\n \"e\": 2209,\n \"s\": 1960,\n \"text\": \"Obviously, you will be needing Python. In this tutorial, we are currently on the latest python version that is 3.8You also need to install flask, flask-sqlalchemy and mysqlclient. To install those, simply run the following command in your terminal.\"\n },\n {\n \"code\": null,\n \"e\": 2257,\n \"s\": 2209,\n \"text\": \"pip3 install Flask Flask-SQLAlchemy mysqlclient\"\n },\n {\n \"code\": null,\n \"e\": 2461,\n \"s\": 2257,\n \"text\": \"Note: If you are on a Linux machine, then your need to have libmysqlclient-dev installed before you install mysqlclient. To install it simply run sudo apt-get install libmysqlclient-dev in your terminal.\"\n },\n {\n \"code\": null,\n \"e\": 2907,\n \"s\": 2461,\n \"text\": \"With all your pre-requisites done, let’s actually jump right into the code. For simplicity purposes, I will be writing all the code in a single file but as you know, if you are planning on building a mid-size application even, then you need to have separate files for routes, models, etc.Here, the entire code will be written inside a single file called app.py. I have added explanations for every line in my code in the form of inline comments.\"\n },\n {\n \"code\": null,\n \"e\": 2915,\n \"s\": 2907,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"# importsfrom flask import Flask, request, make_responsefrom flask_sqlalchemy import SQLAlchemy # initializing Flask appapp = Flask(__name__) # Google Cloud SQL (change this accordingly)PASSWORD =\\\"your database password\\\"PUBLIC_IP_ADDRESS =\\\"public ip of database\\\"DBNAME =\\\"database name\\\"PROJECT_ID =\\\"gcp project id\\\"INSTANCE_NAME =\\\"instance name\\\" # configurationapp.config[\\\"SECRET_KEY\\\"] = \\\"yoursecretkey\\\"app.config[\\\"SQLALCHEMY_DATABASE_URI\\\"]= f\\\"mysql + mysqldb://root:{PASSWORD}@{PUBLIC_IP_ADDRESS}/{DBNAME}?unix_socket =/cloudsql/{PROJECT_ID}:{INSTANCE_NAME}\\\"app.config[\\\"SQLALCHEMY_TRACK_MODIFICATIONS\\\"]= True db = SQLAlchemy(app) # User ORM for SQLAlchemyclass Users(db.Model): id = db.Column(db.Integer, primary_key = True, nullable = False) name = db.Column(db.String(50), nullable = False) email = db.Column(db.String(50), nullable = False, unique = True) @app.route('/add', methods =['POST'])def add(): # getting name and email name = request.form.get('name') email = request.form.get('email') # checking if user already exists user = Users.query.filter_by(email = email).first() if not user: try: # creating Users object user = Users( name = name, email = email ) # adding the fields to users table db.session.add(user) db.session.commit() # response responseObject = { 'status' : 'success', 'message': 'Successfully registered.' } return make_response(responseObject, 200) except: responseObject = { 'status' : 'fail', 'message': 'Some error occured !!' } return make_response(responseObject, 400) else: # if user already exists then send status as fail responseObject = { 'status' : 'fail', 'message': 'User already exists !!' } return make_response(responseObject, 403) @app.route('/view')def view(): # fetches all the users users = Users.query.all() # response list consisting user details response = list() for user in users: response.append({ \\\"name\\\" : user.name, \\\"email\\\": user.email }) return make_response({ 'status' : 'success', 'message': response }, 200) if __name__ == \\\"__main__\\\": # serving the app directly app.run()\",\n \"e\": 5369,\n \"s\": 2915,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 5428,\n \"s\": 5369,\n \"text\": \"You need to change the following placeholders in the code \"\n },\n {\n \"code\": null,\n \"e\": 5505,\n \"s\": 5428,\n \"text\": \"PASSWORD: the password you set for your database while creating the instance\"\n },\n {\n \"code\": null,\n \"e\": 5589,\n \"s\": 5505,\n \"text\": \"PUBLIC_IP_ADDRESS: your GCP instances public IP (can be found in the overview page)\"\n },\n {\n \"code\": null,\n \"e\": 5681,\n \"s\": 5589,\n \"text\": \"DBNAME: name of the database that you created later on (for this tutorial it was ‘testing’)\"\n },\n {\n \"code\": null,\n \"e\": 5713,\n \"s\": 5681,\n \"text\": \"PROJECT_ID: your GCP project ID\"\n },\n {\n \"code\": null,\n \"e\": 5756,\n \"s\": 5713,\n \"text\": \"INSTANCE_NAME: you Cloud SQL instance name\"\n },\n {\n \"code\": null,\n \"e\": 6079,\n \"s\": 5756,\n \"text\": \"Your code is ready but it still can’t access your database. This is where most people get it wrong. They keep on checking the documentations and their codebase but they find no mistake and they get completely frustrated and give up, but I hope you are not the one to give up, right? So, let us see what is left to be done.\"\n },\n {\n \"code\": null,\n \"e\": 6458,\n \"s\": 6079,\n \"text\": \"The reason why your database isn’t accessible by your code is that GCP by default blocks all incoming connections from unknown sources (for security purposes). So, what you need to do right now, is to add your systems public IP address to the Authorised Network. To do that, first, go to your Cloud SQL instance page and click on the edit button. You should see a page like this\"\n },\n {\n \"code\": null,\n \"e\": 6956,\n \"s\": 6458,\n \"text\": \"Here, click on the Add network button under public IP. There, you need to enter your Public IP address. If you don’t know your Public IP then go to this link. After you have entered your Public IP, you are good to go.Now, your app should be able to connect to your database from your system. Now, open up your terminal inside your project directory and type python inside it. This should open up the python interpreter. Now, simply type the following lines in it to create your table from the ORM.\"\n },\n {\n \"code\": null,\n \"e\": 6964,\n \"s\": 6956,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"from app import dbdb.create_all()\",\n \"e\": 6998,\n \"s\": 6964,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 7318,\n \"s\": 6998,\n \"text\": \"That’s all. Now you are ready to test out your app. Go ahead and using any API request tool to check if it works or not. You can use the famous Postman to test it out.The ability to host your database on an external service is very crucial for student developers, otherwise, it is impossible to showcase your projects. \"\n },\n {\n \"code\": null,\n \"e\": 7328,\n \"s\": 7318,\n \"text\": \"ruhelaa48\"\n },\n {\n \"code\": null,\n \"e\": 7345,\n \"s\": 7328,\n \"text\": \"akshaysingh98088\"\n },\n {\n \"code\": null,\n \"e\": 7354,\n \"s\": 7345,\n \"text\": \"sweetyty\"\n },\n {\n \"code\": null,\n \"e\": 7370,\n \"s\": 7354,\n \"text\": \"saurabh1990aror\"\n },\n {\n \"code\": null,\n \"e\": 7376,\n \"s\": 7370,\n \"text\": \"mysql\"\n },\n {\n \"code\": null,\n \"e\": 7389,\n \"s\": 7376,\n \"text\": \"Python Flask\"\n },\n {\n \"code\": null,\n \"e\": 7396,\n \"s\": 7389,\n \"text\": \"Python\"\n },\n {\n \"code\": null,\n \"e\": 7400,\n \"s\": 7396,\n \"text\": \"SQL\"\n },\n {\n \"code\": null,\n \"e\": 7417,\n \"s\": 7400,\n \"text\": \"Web Technologies\"\n },\n {\n \"code\": null,\n \"e\": 7421,\n \"s\": 7417,\n \"text\": \"SQL\"\n },\n {\n \"code\": null,\n \"e\": 7519,\n \"s\": 7421,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 7537,\n \"s\": 7519,\n \"text\": \"Python Dictionary\"\n },\n {\n \"code\": null,\n \"e\": 7579,\n \"s\": 7537,\n \"text\": \"Different ways to create Pandas Dataframe\"\n },\n {\n \"code\": null,\n \"e\": 7601,\n \"s\": 7579,\n \"text\": \"Enumerate() in Python\"\n },\n {\n \"code\": null,\n \"e\": 7627,\n \"s\": 7601,\n \"text\": \"Python String | replace()\"\n },\n {\n \"code\": null,\n \"e\": 7659,\n \"s\": 7627,\n \"text\": \"How to Install PIP on Windows ?\"\n },\n {\n \"code\": null,\n \"e\": 7701,\n \"s\": 7659,\n \"text\": \"SQL | DDL, DQL, DML, DCL and TCL Commands\"\n },\n {\n \"code\": null,\n \"e\": 7748,\n \"s\": 7701,\n \"text\": \"SQL | Join (Inner, Left, Right and Full Joins)\"\n },\n {\n \"code\": null,\n \"e\": 7766,\n \"s\": 7748,\n \"text\": \"SQL | WITH clause\"\n },\n {\n \"code\": null,\n \"e\": 7810,\n \"s\": 7766,\n \"text\": \"How to find Nth highest salary from a table\"\n }\n]"}}},{"rowIdx":154,"cells":{"title":{"kind":"string","value":"Drop rows from the dataframe based on certain condition applied on a column"},"text":{"kind":"string","value":"05 Feb, 2019\nPandas provides a rich collection of functions to perform data analysis in Python. While performing data analysis, quite often we require to filter the data to remove unnecessary rows or columns.\nWe have already discussed earlier how to drop rows or columns based on their labels. However, in this post we are going to discuss several approaches on how to drop rows from the dataframe based on certain condition applied on a column. Retain all those rows for which the applied condition on the given column evaluates to True.\nTo download the CSV used in code, click here.\nYou are given the “nba.csv” dataset. Drop all the players from the dataset whose age is below 25 years.\nSolution #1 : We will use vectorization to filter out such rows from the dataset which satisfy the applied condition.\n# importing pandas as pdimport pandas as pd # Read the csv file and construct the # dataframedf = pd.read_csv('nba.csv') # Visualize the dataframeprint(df.head(15) # Print the shape of the dataframeprint(df.shape)\nOutput :\nIn this dataframe, currently, we are having 458 rows and 9 columns. Let’s use vectorization operation to filter out all those rows which satisfy the given condition.\n# Filter all rows for which the player's# age is greater than or equal to 25df_filtered = df[df['Age'] >= 25] # Print the new dataframeprint(df_filtered.head(15) # Print the shape of the dataframeprint(df_filtered.shape)\nOutput :As we can see in the output, the returned dataframe only contains those players whose age is greater than or equal to 25 years. Solution #2 : We can use the DataFrame.drop() function to drop such rows which does not satisfy the given condition.\n# importing pandas as pdimport pandas as pd # Read the csv file and construct the # dataframedf = pd.read_csv('nba.csv') # First filter out those rows which# does not contain any datadf = df.dropna(how = 'all') # Filter all rows for which the player's# age is greater than or equal to 25df.drop(df[df['Age'] < 25].index, inplace = True) # Print the modified dataframeprint(df.head(15)) # Print the shape of the dataframeprint(df.shape)\nOutput :As we can see in the output, we have successfully dropped all those rows which do not satisfy the given condition applied to the ‘Age’ column.\npandas-dataframe-program\nPython pandas-dataFrame\nPython-pandas\nPython\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nPython Dictionary\nDifferent ways to create Pandas Dataframe\nEnumerate() in Python\nRead a file line by line in Python\nPython String | replace()\nHow to Install PIP on Windows ?\n*args and **kwargs in Python\nPython Classes and Objects\nIterate over a list in Python\nPython OOPs Concepts"},"parsed":{"kind":"list like","value":[{"code":null,"e":52,"s":24,"text":"\n05 Feb, 2019"},{"code":null,"e":248,"s":52,"text":"Pandas provides a rich collection of functions to perform data analysis in Python. While performing data analysis, quite often we require to filter the data to remove unnecessary rows or columns."},{"code":null,"e":578,"s":248,"text":"We have already discussed earlier how to drop rows or columns based on their labels. However, in this post we are going to discuss several approaches on how to drop rows from the dataframe based on certain condition applied on a column. Retain all those rows for which the applied condition on the given column evaluates to True."},{"code":null,"e":624,"s":578,"text":"To download the CSV used in code, click here."},{"code":null,"e":728,"s":624,"text":"You are given the “nba.csv” dataset. Drop all the players from the dataset whose age is below 25 years."},{"code":null,"e":846,"s":728,"text":"Solution #1 : We will use vectorization to filter out such rows from the dataset which satisfy the applied condition."},{"code":"# importing pandas as pdimport pandas as pd # Read the csv file and construct the # dataframedf = pd.read_csv('nba.csv') # Visualize the dataframeprint(df.head(15) # Print the shape of the dataframeprint(df.shape)","e":1063,"s":846,"text":null},{"code":null,"e":1072,"s":1063,"text":"Output :"},{"code":null,"e":1238,"s":1072,"text":"In this dataframe, currently, we are having 458 rows and 9 columns. Let’s use vectorization operation to filter out all those rows which satisfy the given condition."},{"code":"# Filter all rows for which the player's# age is greater than or equal to 25df_filtered = df[df['Age'] >= 25] # Print the new dataframeprint(df_filtered.head(15) # Print the shape of the dataframeprint(df_filtered.shape)","e":1461,"s":1238,"text":null},{"code":null,"e":1714,"s":1461,"text":"Output :As we can see in the output, the returned dataframe only contains those players whose age is greater than or equal to 25 years. Solution #2 : We can use the DataFrame.drop() function to drop such rows which does not satisfy the given condition."},{"code":"# importing pandas as pdimport pandas as pd # Read the csv file and construct the # dataframedf = pd.read_csv('nba.csv') # First filter out those rows which# does not contain any datadf = df.dropna(how = 'all') # Filter all rows for which the player's# age is greater than or equal to 25df.drop(df[df['Age'] < 25].index, inplace = True) # Print the modified dataframeprint(df.head(15)) # Print the shape of the dataframeprint(df.shape)","e":2155,"s":1714,"text":null},{"code":null,"e":2306,"s":2155,"text":"Output :As we can see in the output, we have successfully dropped all those rows which do not satisfy the given condition applied to the ‘Age’ column."},{"code":null,"e":2331,"s":2306,"text":"pandas-dataframe-program"},{"code":null,"e":2355,"s":2331,"text":"Python pandas-dataFrame"},{"code":null,"e":2369,"s":2355,"text":"Python-pandas"},{"code":null,"e":2376,"s":2369,"text":"Python"},{"code":null,"e":2474,"s":2376,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":2492,"s":2474,"text":"Python Dictionary"},{"code":null,"e":2534,"s":2492,"text":"Different ways to create Pandas Dataframe"},{"code":null,"e":2556,"s":2534,"text":"Enumerate() in Python"},{"code":null,"e":2591,"s":2556,"text":"Read a file line by line in Python"},{"code":null,"e":2617,"s":2591,"text":"Python String | replace()"},{"code":null,"e":2649,"s":2617,"text":"How to Install PIP on Windows ?"},{"code":null,"e":2678,"s":2649,"text":"*args and **kwargs in Python"},{"code":null,"e":2705,"s":2678,"text":"Python Classes and Objects"},{"code":null,"e":2735,"s":2705,"text":"Iterate over a list in Python"}],"string":"[\n {\n \"code\": null,\n \"e\": 52,\n \"s\": 24,\n \"text\": \"\\n05 Feb, 2019\"\n },\n {\n \"code\": null,\n \"e\": 248,\n \"s\": 52,\n \"text\": \"Pandas provides a rich collection of functions to perform data analysis in Python. While performing data analysis, quite often we require to filter the data to remove unnecessary rows or columns.\"\n },\n {\n \"code\": null,\n \"e\": 578,\n \"s\": 248,\n \"text\": \"We have already discussed earlier how to drop rows or columns based on their labels. However, in this post we are going to discuss several approaches on how to drop rows from the dataframe based on certain condition applied on a column. Retain all those rows for which the applied condition on the given column evaluates to True.\"\n },\n {\n \"code\": null,\n \"e\": 624,\n \"s\": 578,\n \"text\": \"To download the CSV used in code, click here.\"\n },\n {\n \"code\": null,\n \"e\": 728,\n \"s\": 624,\n \"text\": \"You are given the “nba.csv” dataset. Drop all the players from the dataset whose age is below 25 years.\"\n },\n {\n \"code\": null,\n \"e\": 846,\n \"s\": 728,\n \"text\": \"Solution #1 : We will use vectorization to filter out such rows from the dataset which satisfy the applied condition.\"\n },\n {\n \"code\": \"# importing pandas as pdimport pandas as pd # Read the csv file and construct the # dataframedf = pd.read_csv('nba.csv') # Visualize the dataframeprint(df.head(15) # Print the shape of the dataframeprint(df.shape)\",\n \"e\": 1063,\n \"s\": 846,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 1072,\n \"s\": 1063,\n \"text\": \"Output :\"\n },\n {\n \"code\": null,\n \"e\": 1238,\n \"s\": 1072,\n \"text\": \"In this dataframe, currently, we are having 458 rows and 9 columns. Let’s use vectorization operation to filter out all those rows which satisfy the given condition.\"\n },\n {\n \"code\": \"# Filter all rows for which the player's# age is greater than or equal to 25df_filtered = df[df['Age'] >= 25] # Print the new dataframeprint(df_filtered.head(15) # Print the shape of the dataframeprint(df_filtered.shape)\",\n \"e\": 1461,\n \"s\": 1238,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 1714,\n \"s\": 1461,\n \"text\": \"Output :As we can see in the output, the returned dataframe only contains those players whose age is greater than or equal to 25 years. Solution #2 : We can use the DataFrame.drop() function to drop such rows which does not satisfy the given condition.\"\n },\n {\n \"code\": \"# importing pandas as pdimport pandas as pd # Read the csv file and construct the # dataframedf = pd.read_csv('nba.csv') # First filter out those rows which# does not contain any datadf = df.dropna(how = 'all') # Filter all rows for which the player's# age is greater than or equal to 25df.drop(df[df['Age'] < 25].index, inplace = True) # Print the modified dataframeprint(df.head(15)) # Print the shape of the dataframeprint(df.shape)\",\n \"e\": 2155,\n \"s\": 1714,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 2306,\n \"s\": 2155,\n \"text\": \"Output :As we can see in the output, we have successfully dropped all those rows which do not satisfy the given condition applied to the ‘Age’ column.\"\n },\n {\n \"code\": null,\n \"e\": 2331,\n \"s\": 2306,\n \"text\": \"pandas-dataframe-program\"\n },\n {\n \"code\": null,\n \"e\": 2355,\n \"s\": 2331,\n \"text\": \"Python pandas-dataFrame\"\n },\n {\n \"code\": null,\n \"e\": 2369,\n \"s\": 2355,\n \"text\": \"Python-pandas\"\n },\n {\n \"code\": null,\n \"e\": 2376,\n \"s\": 2369,\n \"text\": \"Python\"\n },\n {\n \"code\": null,\n \"e\": 2474,\n \"s\": 2376,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 2492,\n \"s\": 2474,\n \"text\": \"Python Dictionary\"\n },\n {\n \"code\": null,\n \"e\": 2534,\n \"s\": 2492,\n \"text\": \"Different ways to create Pandas Dataframe\"\n },\n {\n \"code\": null,\n \"e\": 2556,\n \"s\": 2534,\n \"text\": \"Enumerate() in Python\"\n },\n {\n \"code\": null,\n \"e\": 2591,\n \"s\": 2556,\n \"text\": \"Read a file line by line in Python\"\n },\n {\n \"code\": null,\n \"e\": 2617,\n \"s\": 2591,\n \"text\": \"Python String | replace()\"\n },\n {\n \"code\": null,\n \"e\": 2649,\n \"s\": 2617,\n \"text\": \"How to Install PIP on Windows ?\"\n },\n {\n \"code\": null,\n \"e\": 2678,\n \"s\": 2649,\n \"text\": \"*args and **kwargs in Python\"\n },\n {\n \"code\": null,\n \"e\": 2705,\n \"s\": 2678,\n \"text\": \"Python Classes and Objects\"\n },\n {\n \"code\": null,\n \"e\": 2735,\n \"s\": 2705,\n \"text\": \"Iterate over a list in Python\"\n }\n]"}}},{"rowIdx":155,"cells":{"title":{"kind":"string","value":"Print Hello World Without using a Semicolon in Java"},"text":{"kind":"string","value":"23 Nov, 2021\nEvery statement in Java must end with a semicolon as per the basics. However, unlike other languages, almost all statements in Java can be treated as expressions. However, there are a few scenarios when we can write a running program without semicolons. If we place the statement inside an if/for statement with a blank pair of parentheses, we don’t have to end it with a semicolon. Also, calling a function that returns void will not work here as void functions are not expressions.\nMethods: \nUsing if-else statementsUsing append() method of StringBuilder classUsing equals method of String class \nUsing if-else statements\nUsing append() method of StringBuilder class\nUsing equals method of String class \nMethod 1: Using if statement\nJava\n// Java program to Print Hello World Without Semicolon// Using if statement // Main classclass GFG { // Main driver method public static void main(String args[]) { // Using if statement to // print hello world if (System.out.printf(\"Hello World\") == null) { } }}\nHello World\nMethod 2: Using append() method of StringBuilder class\nJava\n// Java Program to Print Hello World Without Semicolon// Using append() method of String class // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Using append() method to print statement if (System.out.append(\"Hello World\") == null) { } }}\nHello World\nMethod 3: Using equals method of String class\nJava\n// Java Program to Print Hello World Without Semicolon// Using equals() method of String class // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Using equals() method to print statement if (System.out.append(\"Hello World\").equals(null)) { } }}\nHello World\nsurindertarika1234\nreetbatra25\njava-basics\nJava\nJava\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},"parsed":{"kind":"list like","value":[{"code":null,"e":54,"s":26,"text":"\n23 Nov, 2021"},{"code":null,"e":538,"s":54,"text":"Every statement in Java must end with a semicolon as per the basics. However, unlike other languages, almost all statements in Java can be treated as expressions. However, there are a few scenarios when we can write a running program without semicolons. If we place the statement inside an if/for statement with a blank pair of parentheses, we don’t have to end it with a semicolon. Also, calling a function that returns void will not work here as void functions are not expressions."},{"code":null,"e":548,"s":538,"text":"Methods: "},{"code":null,"e":653,"s":548,"text":"Using if-else statementsUsing append() method of StringBuilder classUsing equals method of String class "},{"code":null,"e":678,"s":653,"text":"Using if-else statements"},{"code":null,"e":723,"s":678,"text":"Using append() method of StringBuilder class"},{"code":null,"e":760,"s":723,"text":"Using equals method of String class "},{"code":null,"e":789,"s":760,"text":"Method 1: Using if statement"},{"code":null,"e":794,"s":789,"text":"Java"},{"code":"// Java program to Print Hello World Without Semicolon// Using if statement // Main classclass GFG { // Main driver method public static void main(String args[]) { // Using if statement to // print hello world if (System.out.printf(\"Hello World\") == null) { } }}","e":1099,"s":794,"text":null},{"code":null,"e":1111,"s":1099,"text":"Hello World"},{"code":null,"e":1166,"s":1111,"text":"Method 2: Using append() method of StringBuilder class"},{"code":null,"e":1171,"s":1166,"text":"Java"},{"code":"// Java Program to Print Hello World Without Semicolon// Using append() method of String class // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Using append() method to print statement if (System.out.append(\"Hello World\") == null) { } }}","e":1535,"s":1171,"text":null},{"code":null,"e":1547,"s":1535,"text":"Hello World"},{"code":null,"e":1593,"s":1547,"text":"Method 3: Using equals method of String class"},{"code":null,"e":1598,"s":1593,"text":"Java"},{"code":"// Java Program to Print Hello World Without Semicolon// Using equals() method of String class // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Using equals() method to print statement if (System.out.append(\"Hello World\").equals(null)) { } }}","e":1966,"s":1598,"text":null},{"code":null,"e":1978,"s":1966,"text":"Hello World"},{"code":null,"e":1997,"s":1978,"text":"surindertarika1234"},{"code":null,"e":2009,"s":1997,"text":"reetbatra25"},{"code":null,"e":2021,"s":2009,"text":"java-basics"},{"code":null,"e":2026,"s":2021,"text":"Java"},{"code":null,"e":2031,"s":2026,"text":"Java"}],"string":"[\n {\n \"code\": null,\n \"e\": 54,\n \"s\": 26,\n \"text\": \"\\n23 Nov, 2021\"\n },\n {\n \"code\": null,\n \"e\": 538,\n \"s\": 54,\n \"text\": \"Every statement in Java must end with a semicolon as per the basics. However, unlike other languages, almost all statements in Java can be treated as expressions. However, there are a few scenarios when we can write a running program without semicolons. If we place the statement inside an if/for statement with a blank pair of parentheses, we don’t have to end it with a semicolon. Also, calling a function that returns void will not work here as void functions are not expressions.\"\n },\n {\n \"code\": null,\n \"e\": 548,\n \"s\": 538,\n \"text\": \"Methods: \"\n },\n {\n \"code\": null,\n \"e\": 653,\n \"s\": 548,\n \"text\": \"Using if-else statementsUsing append() method of StringBuilder classUsing equals method of String class \"\n },\n {\n \"code\": null,\n \"e\": 678,\n \"s\": 653,\n \"text\": \"Using if-else statements\"\n },\n {\n \"code\": null,\n \"e\": 723,\n \"s\": 678,\n \"text\": \"Using append() method of StringBuilder class\"\n },\n {\n \"code\": null,\n \"e\": 760,\n \"s\": 723,\n \"text\": \"Using equals method of String class \"\n },\n {\n \"code\": null,\n \"e\": 789,\n \"s\": 760,\n \"text\": \"Method 1: Using if statement\"\n },\n {\n \"code\": null,\n \"e\": 794,\n \"s\": 789,\n \"text\": \"Java\"\n },\n {\n \"code\": \"// Java program to Print Hello World Without Semicolon// Using if statement // Main classclass GFG { // Main driver method public static void main(String args[]) { // Using if statement to // print hello world if (System.out.printf(\\\"Hello World\\\") == null) { } }}\",\n \"e\": 1099,\n \"s\": 794,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 1111,\n \"s\": 1099,\n \"text\": \"Hello World\"\n },\n {\n \"code\": null,\n \"e\": 1166,\n \"s\": 1111,\n \"text\": \"Method 2: Using append() method of StringBuilder class\"\n },\n {\n \"code\": null,\n \"e\": 1171,\n \"s\": 1166,\n \"text\": \"Java\"\n },\n {\n \"code\": \"// Java Program to Print Hello World Without Semicolon// Using append() method of String class // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Using append() method to print statement if (System.out.append(\\\"Hello World\\\") == null) { } }}\",\n \"e\": 1535,\n \"s\": 1171,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 1547,\n \"s\": 1535,\n \"text\": \"Hello World\"\n },\n {\n \"code\": null,\n \"e\": 1593,\n \"s\": 1547,\n \"text\": \"Method 3: Using equals method of String class\"\n },\n {\n \"code\": null,\n \"e\": 1598,\n \"s\": 1593,\n \"text\": \"Java\"\n },\n {\n \"code\": \"// Java Program to Print Hello World Without Semicolon// Using equals() method of String class // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Using equals() method to print statement if (System.out.append(\\\"Hello World\\\").equals(null)) { } }}\",\n \"e\": 1966,\n \"s\": 1598,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 1978,\n \"s\": 1966,\n \"text\": \"Hello World\"\n },\n {\n \"code\": null,\n \"e\": 1997,\n \"s\": 1978,\n \"text\": \"surindertarika1234\"\n },\n {\n \"code\": null,\n \"e\": 2009,\n \"s\": 1997,\n \"text\": \"reetbatra25\"\n },\n {\n \"code\": null,\n \"e\": 2021,\n \"s\": 2009,\n \"text\": \"java-basics\"\n },\n {\n \"code\": null,\n \"e\": 2026,\n \"s\": 2021,\n \"text\": \"Java\"\n },\n {\n \"code\": null,\n \"e\": 2031,\n \"s\": 2026,\n \"text\": \"Java\"\n }\n]"}}},{"rowIdx":156,"cells":{"title":{"kind":"string","value":"How to Share Files On Local Network Using Apache File Server?"},"text":{"kind":"string","value":"30 Mar, 2021\nNormally we share files between our computers and mobiles using Gmail, Whatsapp, Bluetooth, etc. But here we are going to discuss sharing files using Apache Server from your computer. Your system has to be connected to a LAN for Accessing the files from one computer to another connected on a LAN.\nThe local server is the same as our web server. As our Web Server serves our needs anywhere and anytime. But Local server operates when multiple clients are connected to the same LAN(Local Area Network). And if we connect a router and connect our mobiles to the Wi-Fi of that router then we can access the files which were shared by the Computer on that server.\nApache HTTP Server is a very powerful HTTP server. It is the replacement for NCSA Server. It is Free of cost and open Source.\nComputerWi-Fi Router(For Mobile Users)Local Area Network Connection(Acts as Local Server)\nComputer\nWi-Fi Router(For Mobile Users)\nLocal Area Network Connection(Acts as Local Server)\nYou need to download Apache24 from Google and install it on your device. Download the file which is available in 32 bit and 64bit.Unzip the downloaded files where you would like to install the same.Now, open the command prompt and navigate to the location where you have unzipped the folder.Now Use the below command to open the specific folder for starting the server.\nYou need to download Apache24 from Google and install it on your device. Download the file which is available in 32 bit and 64bit.\nUnzip the downloaded files where you would like to install the same.\nNow, open the command prompt and navigate to the location where you have unzipped the folder.\nNow Use the below command to open the specific folder for starting the server.\ncd Apache24/bin/httpd\nNow After entering this command you will get a dialogue box for Allowing Access. You have to give access to all Public and Private Networks.\nNow You can access the files on the network. Just by typing the host’s IP Address.\nHere we have just placed an HTML File, so it is showing the text “It Works” in the browser. You can even place your HTML projects or Your Files in a Folder and Access them.\nExample:\nIf you type in the below statement in the command prompt:\n- 192.168.102.67/Geeks\nYou will get all the files stored in Geeks Folder which is Located in Apache24/htdocs folder.\nTo access the files on another machine connected to the same network just type the host computer IP Address forwarded by the folder name.\n192.168.102.67/Geeks.\nSo you can access the files.\nHow To\nTechTips\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nHow to Set Git Username and Password in GitBash?\nHow to Install Jupyter Notebook on MacOS?\nHow to Install and Use NVM on Windows?\nHow to Install Python Packages for AWS Lambda Layers?\nHow to Install Git in VS Code?\nDocker - COPY Instruction\nSetting up the environment in Java\nHow to Run a Python Script using Docker?\nRunning Python script on GPU.\nHow to setup cron jobs in Ubuntu"},"parsed":{"kind":"list like","value":[{"code":null,"e":54,"s":26,"text":"\n30 Mar, 2021"},{"code":null,"e":352,"s":54,"text":"Normally we share files between our computers and mobiles using Gmail, Whatsapp, Bluetooth, etc. But here we are going to discuss sharing files using Apache Server from your computer. Your system has to be connected to a LAN for Accessing the files from one computer to another connected on a LAN."},{"code":null,"e":714,"s":352,"text":"The local server is the same as our web server. As our Web Server serves our needs anywhere and anytime. But Local server operates when multiple clients are connected to the same LAN(Local Area Network). And if we connect a router and connect our mobiles to the Wi-Fi of that router then we can access the files which were shared by the Computer on that server."},{"code":null,"e":840,"s":714,"text":"Apache HTTP Server is a very powerful HTTP server. It is the replacement for NCSA Server. It is Free of cost and open Source."},{"code":null,"e":930,"s":840,"text":"ComputerWi-Fi Router(For Mobile Users)Local Area Network Connection(Acts as Local Server)"},{"code":null,"e":939,"s":930,"text":"Computer"},{"code":null,"e":970,"s":939,"text":"Wi-Fi Router(For Mobile Users)"},{"code":null,"e":1022,"s":970,"text":"Local Area Network Connection(Acts as Local Server)"},{"code":null,"e":1392,"s":1022,"text":"You need to download Apache24 from Google and install it on your device. Download the file which is available in 32 bit and 64bit.Unzip the downloaded files where you would like to install the same.Now, open the command prompt and navigate to the location where you have unzipped the folder.Now Use the below command to open the specific folder for starting the server."},{"code":null,"e":1523,"s":1392,"text":"You need to download Apache24 from Google and install it on your device. Download the file which is available in 32 bit and 64bit."},{"code":null,"e":1592,"s":1523,"text":"Unzip the downloaded files where you would like to install the same."},{"code":null,"e":1686,"s":1592,"text":"Now, open the command prompt and navigate to the location where you have unzipped the folder."},{"code":null,"e":1765,"s":1686,"text":"Now Use the below command to open the specific folder for starting the server."},{"code":null,"e":1787,"s":1765,"text":"cd Apache24/bin/httpd"},{"code":null,"e":1928,"s":1787,"text":"Now After entering this command you will get a dialogue box for Allowing Access. You have to give access to all Public and Private Networks."},{"code":null,"e":2011,"s":1928,"text":"Now You can access the files on the network. Just by typing the host’s IP Address."},{"code":null,"e":2184,"s":2011,"text":"Here we have just placed an HTML File, so it is showing the text “It Works” in the browser. You can even place your HTML projects or Your Files in a Folder and Access them."},{"code":null,"e":2193,"s":2184,"text":"Example:"},{"code":null,"e":2251,"s":2193,"text":"If you type in the below statement in the command prompt:"},{"code":null,"e":2274,"s":2251,"text":"- 192.168.102.67/Geeks"},{"code":null,"e":2368,"s":2274,"text":"You will get all the files stored in Geeks Folder which is Located in Apache24/htdocs folder."},{"code":null,"e":2506,"s":2368,"text":"To access the files on another machine connected to the same network just type the host computer IP Address forwarded by the folder name."},{"code":null,"e":2528,"s":2506,"text":"192.168.102.67/Geeks."},{"code":null,"e":2557,"s":2528,"text":"So you can access the files."},{"code":null,"e":2564,"s":2557,"text":"How To"},{"code":null,"e":2573,"s":2564,"text":"TechTips"},{"code":null,"e":2671,"s":2573,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":2720,"s":2671,"text":"How to Set Git Username and Password in GitBash?"},{"code":null,"e":2762,"s":2720,"text":"How to Install Jupyter Notebook on MacOS?"},{"code":null,"e":2801,"s":2762,"text":"How to Install and Use NVM on Windows?"},{"code":null,"e":2855,"s":2801,"text":"How to Install Python Packages for AWS Lambda Layers?"},{"code":null,"e":2886,"s":2855,"text":"How to Install Git in VS Code?"},{"code":null,"e":2912,"s":2886,"text":"Docker - COPY Instruction"},{"code":null,"e":2947,"s":2912,"text":"Setting up the environment in Java"},{"code":null,"e":2988,"s":2947,"text":"How to Run a Python Script using Docker?"},{"code":null,"e":3018,"s":2988,"text":"Running Python script on GPU."}],"string":"[\n {\n \"code\": null,\n \"e\": 54,\n \"s\": 26,\n \"text\": \"\\n30 Mar, 2021\"\n },\n {\n \"code\": null,\n \"e\": 352,\n \"s\": 54,\n \"text\": \"Normally we share files between our computers and mobiles using Gmail, Whatsapp, Bluetooth, etc. But here we are going to discuss sharing files using Apache Server from your computer. Your system has to be connected to a LAN for Accessing the files from one computer to another connected on a LAN.\"\n },\n {\n \"code\": null,\n \"e\": 714,\n \"s\": 352,\n \"text\": \"The local server is the same as our web server. As our Web Server serves our needs anywhere and anytime. But Local server operates when multiple clients are connected to the same LAN(Local Area Network). And if we connect a router and connect our mobiles to the Wi-Fi of that router then we can access the files which were shared by the Computer on that server.\"\n },\n {\n \"code\": null,\n \"e\": 840,\n \"s\": 714,\n \"text\": \"Apache HTTP Server is a very powerful HTTP server. It is the replacement for NCSA Server. It is Free of cost and open Source.\"\n },\n {\n \"code\": null,\n \"e\": 930,\n \"s\": 840,\n \"text\": \"ComputerWi-Fi Router(For Mobile Users)Local Area Network Connection(Acts as Local Server)\"\n },\n {\n \"code\": null,\n \"e\": 939,\n \"s\": 930,\n \"text\": \"Computer\"\n },\n {\n \"code\": null,\n \"e\": 970,\n \"s\": 939,\n \"text\": \"Wi-Fi Router(For Mobile Users)\"\n },\n {\n \"code\": null,\n \"e\": 1022,\n \"s\": 970,\n \"text\": \"Local Area Network Connection(Acts as Local Server)\"\n },\n {\n \"code\": null,\n \"e\": 1392,\n \"s\": 1022,\n \"text\": \"You need to download Apache24 from Google and install it on your device. Download the file which is available in 32 bit and 64bit.Unzip the downloaded files where you would like to install the same.Now, open the command prompt and navigate to the location where you have unzipped the folder.Now Use the below command to open the specific folder for starting the server.\"\n },\n {\n \"code\": null,\n \"e\": 1523,\n \"s\": 1392,\n \"text\": \"You need to download Apache24 from Google and install it on your device. Download the file which is available in 32 bit and 64bit.\"\n },\n {\n \"code\": null,\n \"e\": 1592,\n \"s\": 1523,\n \"text\": \"Unzip the downloaded files where you would like to install the same.\"\n },\n {\n \"code\": null,\n \"e\": 1686,\n \"s\": 1592,\n \"text\": \"Now, open the command prompt and navigate to the location where you have unzipped the folder.\"\n },\n {\n \"code\": null,\n \"e\": 1765,\n \"s\": 1686,\n \"text\": \"Now Use the below command to open the specific folder for starting the server.\"\n },\n {\n \"code\": null,\n \"e\": 1787,\n \"s\": 1765,\n \"text\": \"cd Apache24/bin/httpd\"\n },\n {\n \"code\": null,\n \"e\": 1928,\n \"s\": 1787,\n \"text\": \"Now After entering this command you will get a dialogue box for Allowing Access. You have to give access to all Public and Private Networks.\"\n },\n {\n \"code\": null,\n \"e\": 2011,\n \"s\": 1928,\n \"text\": \"Now You can access the files on the network. Just by typing the host’s IP Address.\"\n },\n {\n \"code\": null,\n \"e\": 2184,\n \"s\": 2011,\n \"text\": \"Here we have just placed an HTML File, so it is showing the text “It Works” in the browser. You can even place your HTML projects or Your Files in a Folder and Access them.\"\n },\n {\n \"code\": null,\n \"e\": 2193,\n \"s\": 2184,\n \"text\": \"Example:\"\n },\n {\n \"code\": null,\n \"e\": 2251,\n \"s\": 2193,\n \"text\": \"If you type in the below statement in the command prompt:\"\n },\n {\n \"code\": null,\n \"e\": 2274,\n \"s\": 2251,\n \"text\": \"- 192.168.102.67/Geeks\"\n },\n {\n \"code\": null,\n \"e\": 2368,\n \"s\": 2274,\n \"text\": \"You will get all the files stored in Geeks Folder which is Located in Apache24/htdocs folder.\"\n },\n {\n \"code\": null,\n \"e\": 2506,\n \"s\": 2368,\n \"text\": \"To access the files on another machine connected to the same network just type the host computer IP Address forwarded by the folder name.\"\n },\n {\n \"code\": null,\n \"e\": 2528,\n \"s\": 2506,\n \"text\": \"192.168.102.67/Geeks.\"\n },\n {\n \"code\": null,\n \"e\": 2557,\n \"s\": 2528,\n \"text\": \"So you can access the files.\"\n },\n {\n \"code\": null,\n \"e\": 2564,\n \"s\": 2557,\n \"text\": \"How To\"\n },\n {\n \"code\": null,\n \"e\": 2573,\n \"s\": 2564,\n \"text\": \"TechTips\"\n },\n {\n \"code\": null,\n \"e\": 2671,\n \"s\": 2573,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 2720,\n \"s\": 2671,\n \"text\": \"How to Set Git Username and Password in GitBash?\"\n },\n {\n \"code\": null,\n \"e\": 2762,\n \"s\": 2720,\n \"text\": \"How to Install Jupyter Notebook on MacOS?\"\n },\n {\n \"code\": null,\n \"e\": 2801,\n \"s\": 2762,\n \"text\": \"How to Install and Use NVM on Windows?\"\n },\n {\n \"code\": null,\n \"e\": 2855,\n \"s\": 2801,\n \"text\": \"How to Install Python Packages for AWS Lambda Layers?\"\n },\n {\n \"code\": null,\n \"e\": 2886,\n \"s\": 2855,\n \"text\": \"How to Install Git in VS Code?\"\n },\n {\n \"code\": null,\n \"e\": 2912,\n \"s\": 2886,\n \"text\": \"Docker - COPY Instruction\"\n },\n {\n \"code\": null,\n \"e\": 2947,\n \"s\": 2912,\n \"text\": \"Setting up the environment in Java\"\n },\n {\n \"code\": null,\n \"e\": 2988,\n \"s\": 2947,\n \"text\": \"How to Run a Python Script using Docker?\"\n },\n {\n \"code\": null,\n \"e\": 3018,\n \"s\": 2988,\n \"text\": \"Running Python script on GPU.\"\n }\n]"}}},{"rowIdx":157,"cells":{"title":{"kind":"string","value":"Java Program to Check If a Number is Neon Number or Not"},"text":{"kind":"string","value":"15 Oct, 2021\nA neon number is a number where the sum of digits of the square of the number is equal to the number. The task is to check and print neon numbers in a range.\nIllustration:\nCase 1:\n\nInput : 9\nOutput : Given number 9 is Neon number\n\nExplanation : square of 9=9*9=81;\n sum of digit of square : 8+1=9(which is equal to given number)\n\n\nCase 2:\n\nInput : 8\nOutput : Given number is not a Neon number\n \nExplanation : square of 8=8*8=64\n sum of digit of square : 6+4=10(which is not equal to given number)\nAlgorithm :\nFirst, find the square of the given number.Find the sum of the digit of the square by using a loop. The condition checksum is equal to the given numberReturn trueElse return false.\nFirst, find the square of the given number.\nFind the sum of the digit of the square by using a loop. \nThe condition checksum is equal to the given numberReturn trueElse return false.\nReturn trueElse return false.\nReturn true\nElse return false.\nPseudo code : Square =n*n;\n while(square>0)\n {\n int r=square%10;\n sum+=r;\n square=square/10;\n }\nExample:\nJava\n// Java Program to Check If a Number is Neon number or not // Importing java input/output libraryimport java.io.*; class GFG { // Method to check whether number is neon or not // Boolean type public static boolean checkNeon(int n) { // squaring the number to be checked int square = n * n; // Initializing current sum to 0 int sum = 0; // If product is positive while (square > 0) { // Step 1: Find remainder int r = square % 10; // Add remainder to the current sum sum += r; // Drop last digit of the product // and store the number square = square / 10; } // Condition check // Sum of digits of number obtained is // equal to original number if (sum == n) // number is neon return true; else // number is not neon return false; } // Main driver method public static void main(String[] args) { // Custom input int n = 9; // Calling above function to check custom number or // if user entered number via Scanner class if (checkNeon(n)) // Print number considered is neon System.out.println(\"Given number \" + n + \" is Neon number\"); else // Print number considered is not neon System.out.println(\"Given number \" + n + \" is not a Neon number\"); }}\nGiven number 9 is Neon number\nTime Complexity: O(l) where l is the number of the digit in the square of the given number\n \nclintra\nsurinderdawra388\nsimmytarika5\nPicked\nTechnical Scripter 2020\nJava\nJava Programs\nTechnical Scripter\nJava\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},"parsed":{"kind":"list like","value":[{"code":null,"e":52,"s":24,"text":"\n15 Oct, 2021"},{"code":null,"e":210,"s":52,"text":"A neon number is a number where the sum of digits of the square of the number is equal to the number. The task is to check and print neon numbers in a range."},{"code":null,"e":224,"s":210,"text":"Illustration:"},{"code":null,"e":577,"s":224,"text":"Case 1:\n\nInput : 9\nOutput : Given number 9 is Neon number\n\nExplanation : square of 9=9*9=81;\n sum of digit of square : 8+1=9(which is equal to given number)\n\n\nCase 2:\n\nInput : 8\nOutput : Given number is not a Neon number\n \nExplanation : square of 8=8*8=64\n sum of digit of square : 6+4=10(which is not equal to given number)"},{"code":null,"e":589,"s":577,"text":"Algorithm :"},{"code":null,"e":770,"s":589,"text":"First, find the square of the given number.Find the sum of the digit of the square by using a loop. The condition checksum is equal to the given numberReturn trueElse return false."},{"code":null,"e":814,"s":770,"text":"First, find the square of the given number."},{"code":null,"e":872,"s":814,"text":"Find the sum of the digit of the square by using a loop. "},{"code":null,"e":953,"s":872,"text":"The condition checksum is equal to the given numberReturn trueElse return false."},{"code":null,"e":983,"s":953,"text":"Return trueElse return false."},{"code":null,"e":995,"s":983,"text":"Return true"},{"code":null,"e":1014,"s":995,"text":"Else return false."},{"code":null,"e":1188,"s":1014,"text":"Pseudo code : Square =n*n;\n while(square>0)\n {\n int r=square%10;\n sum+=r;\n square=square/10;\n }"},{"code":null,"e":1197,"s":1188,"text":"Example:"},{"code":null,"e":1202,"s":1197,"text":"Java"},{"code":"// Java Program to Check If a Number is Neon number or not // Importing java input/output libraryimport java.io.*; class GFG { // Method to check whether number is neon or not // Boolean type public static boolean checkNeon(int n) { // squaring the number to be checked int square = n * n; // Initializing current sum to 0 int sum = 0; // If product is positive while (square > 0) { // Step 1: Find remainder int r = square % 10; // Add remainder to the current sum sum += r; // Drop last digit of the product // and store the number square = square / 10; } // Condition check // Sum of digits of number obtained is // equal to original number if (sum == n) // number is neon return true; else // number is not neon return false; } // Main driver method public static void main(String[] args) { // Custom input int n = 9; // Calling above function to check custom number or // if user entered number via Scanner class if (checkNeon(n)) // Print number considered is neon System.out.println(\"Given number \" + n + \" is Neon number\"); else // Print number considered is not neon System.out.println(\"Given number \" + n + \" is not a Neon number\"); }}","e":2739,"s":1202,"text":null},{"code":null,"e":2769,"s":2739,"text":"Given number 9 is Neon number"},{"code":null,"e":2860,"s":2769,"text":"Time Complexity: O(l) where l is the number of the digit in the square of the given number"},{"code":null,"e":2870,"s":2862,"text":"clintra"},{"code":null,"e":2887,"s":2870,"text":"surinderdawra388"},{"code":null,"e":2900,"s":2887,"text":"simmytarika5"},{"code":null,"e":2907,"s":2900,"text":"Picked"},{"code":null,"e":2931,"s":2907,"text":"Technical Scripter 2020"},{"code":null,"e":2936,"s":2931,"text":"Java"},{"code":null,"e":2950,"s":2936,"text":"Java Programs"},{"code":null,"e":2969,"s":2950,"text":"Technical Scripter"},{"code":null,"e":2974,"s":2969,"text":"Java"}],"string":"[\n {\n \"code\": null,\n \"e\": 52,\n \"s\": 24,\n \"text\": \"\\n15 Oct, 2021\"\n },\n {\n \"code\": null,\n \"e\": 210,\n \"s\": 52,\n \"text\": \"A neon number is a number where the sum of digits of the square of the number is equal to the number. The task is to check and print neon numbers in a range.\"\n },\n {\n \"code\": null,\n \"e\": 224,\n \"s\": 210,\n \"text\": \"Illustration:\"\n },\n {\n \"code\": null,\n \"e\": 577,\n \"s\": 224,\n \"text\": \"Case 1:\\n\\nInput : 9\\nOutput : Given number 9 is Neon number\\n\\nExplanation : square of 9=9*9=81;\\n sum of digit of square : 8+1=9(which is equal to given number)\\n\\n\\nCase 2:\\n\\nInput : 8\\nOutput : Given number is not a Neon number\\n \\nExplanation : square of 8=8*8=64\\n sum of digit of square : 6+4=10(which is not equal to given number)\"\n },\n {\n \"code\": null,\n \"e\": 589,\n \"s\": 577,\n \"text\": \"Algorithm :\"\n },\n {\n \"code\": null,\n \"e\": 770,\n \"s\": 589,\n \"text\": \"First, find the square of the given number.Find the sum of the digit of the square by using a loop. The condition checksum is equal to the given numberReturn trueElse return false.\"\n },\n {\n \"code\": null,\n \"e\": 814,\n \"s\": 770,\n \"text\": \"First, find the square of the given number.\"\n },\n {\n \"code\": null,\n \"e\": 872,\n \"s\": 814,\n \"text\": \"Find the sum of the digit of the square by using a loop. \"\n },\n {\n \"code\": null,\n \"e\": 953,\n \"s\": 872,\n \"text\": \"The condition checksum is equal to the given numberReturn trueElse return false.\"\n },\n {\n \"code\": null,\n \"e\": 983,\n \"s\": 953,\n \"text\": \"Return trueElse return false.\"\n },\n {\n \"code\": null,\n \"e\": 995,\n \"s\": 983,\n \"text\": \"Return true\"\n },\n {\n \"code\": null,\n \"e\": 1014,\n \"s\": 995,\n \"text\": \"Else return false.\"\n },\n {\n \"code\": null,\n \"e\": 1188,\n \"s\": 1014,\n \"text\": \"Pseudo code : Square =n*n;\\n while(square>0)\\n {\\n int r=square%10;\\n sum+=r;\\n square=square/10;\\n }\"\n },\n {\n \"code\": null,\n \"e\": 1197,\n \"s\": 1188,\n \"text\": \"Example:\"\n },\n {\n \"code\": null,\n \"e\": 1202,\n \"s\": 1197,\n \"text\": \"Java\"\n },\n {\n \"code\": \"// Java Program to Check If a Number is Neon number or not // Importing java input/output libraryimport java.io.*; class GFG { // Method to check whether number is neon or not // Boolean type public static boolean checkNeon(int n) { // squaring the number to be checked int square = n * n; // Initializing current sum to 0 int sum = 0; // If product is positive while (square > 0) { // Step 1: Find remainder int r = square % 10; // Add remainder to the current sum sum += r; // Drop last digit of the product // and store the number square = square / 10; } // Condition check // Sum of digits of number obtained is // equal to original number if (sum == n) // number is neon return true; else // number is not neon return false; } // Main driver method public static void main(String[] args) { // Custom input int n = 9; // Calling above function to check custom number or // if user entered number via Scanner class if (checkNeon(n)) // Print number considered is neon System.out.println(\\\"Given number \\\" + n + \\\" is Neon number\\\"); else // Print number considered is not neon System.out.println(\\\"Given number \\\" + n + \\\" is not a Neon number\\\"); }}\",\n \"e\": 2739,\n \"s\": 1202,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 2769,\n \"s\": 2739,\n \"text\": \"Given number 9 is Neon number\"\n },\n {\n \"code\": null,\n \"e\": 2860,\n \"s\": 2769,\n \"text\": \"Time Complexity: O(l) where l is the number of the digit in the square of the given number\"\n },\n {\n \"code\": null,\n \"e\": 2870,\n \"s\": 2862,\n \"text\": \"clintra\"\n },\n {\n \"code\": null,\n \"e\": 2887,\n \"s\": 2870,\n \"text\": \"surinderdawra388\"\n },\n {\n \"code\": null,\n \"e\": 2900,\n \"s\": 2887,\n \"text\": \"simmytarika5\"\n },\n {\n \"code\": null,\n \"e\": 2907,\n \"s\": 2900,\n \"text\": \"Picked\"\n },\n {\n \"code\": null,\n \"e\": 2931,\n \"s\": 2907,\n \"text\": \"Technical Scripter 2020\"\n },\n {\n \"code\": null,\n \"e\": 2936,\n \"s\": 2931,\n \"text\": \"Java\"\n },\n {\n \"code\": null,\n \"e\": 2950,\n \"s\": 2936,\n \"text\": \"Java Programs\"\n },\n {\n \"code\": null,\n \"e\": 2969,\n \"s\": 2950,\n \"text\": \"Technical Scripter\"\n },\n {\n \"code\": null,\n \"e\": 2974,\n \"s\": 2969,\n \"text\": \"Java\"\n }\n]"}}},{"rowIdx":158,"cells":{"title":{"kind":"string","value":"Convert string to title case in JavaScript"},"text":{"kind":"string","value":"23 Apr, 2019\nWe convert a string to title case in such a way that every new word begins with a capital(uppercase) letter.This can be achieved by following ways-1) By using replace() function\n\nOUTPUT\nGeeks For Geeks\n2) By using For loop to titlecase a string\n\nOUTPUT\nGeeks For Geeks\n3) By using map() method\n\nOUTPUT\nConverting String To Titlecase\njavascript-string\nPicked\nJavaScript\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nDifference between var, let and const keywords in JavaScript\nRemove elements from a JavaScript Array\nRoadmap to Learn JavaScript For Beginners\nDifference Between PUT and PATCH Request\nJavaScript | Promises\nHow to filter object array based on attributes?\nLodash _.debounce() Method\nJavaScript String includes() Method\nJavaScript | fetch() Method\nHow to map, reduce and filter a Set element using JavaScript ?"},"parsed":{"kind":"list like","value":[{"code":null,"e":28,"s":0,"text":"\n23 Apr, 2019"},{"code":null,"e":206,"s":28,"text":"We convert a string to title case in such a way that every new word begins with a capital(uppercase) letter.This can be achieved by following ways-1) By using replace() function"},{"code":"","e":507,"s":206,"text":null},{"code":null,"e":514,"s":507,"text":"OUTPUT"},{"code":null,"e":530,"s":514,"text":"Geeks For Geeks"},{"code":null,"e":573,"s":530,"text":"2) By using For loop to titlecase a string"},{"code":"","e":828,"s":573,"text":null},{"code":null,"e":835,"s":828,"text":"OUTPUT"},{"code":null,"e":851,"s":835,"text":"Geeks For Geeks"},{"code":null,"e":876,"s":851,"text":"3) By using map() method"},{"code":"","e":1111,"s":876,"text":null},{"code":null,"e":1118,"s":1111,"text":"OUTPUT"},{"code":null,"e":1149,"s":1118,"text":"Converting String To Titlecase"},{"code":null,"e":1167,"s":1149,"text":"javascript-string"},{"code":null,"e":1174,"s":1167,"text":"Picked"},{"code":null,"e":1185,"s":1174,"text":"JavaScript"},{"code":null,"e":1283,"s":1185,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":1344,"s":1283,"text":"Difference between var, let and const keywords in JavaScript"},{"code":null,"e":1384,"s":1344,"text":"Remove elements from a JavaScript Array"},{"code":null,"e":1426,"s":1384,"text":"Roadmap to Learn JavaScript For Beginners"},{"code":null,"e":1467,"s":1426,"text":"Difference Between PUT and PATCH Request"},{"code":null,"e":1489,"s":1467,"text":"JavaScript | Promises"},{"code":null,"e":1537,"s":1489,"text":"How to filter object array based on attributes?"},{"code":null,"e":1564,"s":1537,"text":"Lodash _.debounce() Method"},{"code":null,"e":1600,"s":1564,"text":"JavaScript String includes() Method"},{"code":null,"e":1628,"s":1600,"text":"JavaScript | fetch() Method"}],"string":"[\n {\n \"code\": null,\n \"e\": 28,\n \"s\": 0,\n \"text\": \"\\n23 Apr, 2019\"\n },\n {\n \"code\": null,\n \"e\": 206,\n \"s\": 28,\n \"text\": \"We convert a string to title case in such a way that every new word begins with a capital(uppercase) letter.This can be achieved by following ways-1) By using replace() function\"\n },\n {\n \"code\": \"\",\n \"e\": 507,\n \"s\": 206,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 514,\n \"s\": 507,\n \"text\": \"OUTPUT\"\n },\n {\n \"code\": null,\n \"e\": 530,\n \"s\": 514,\n \"text\": \"Geeks For Geeks\"\n },\n {\n \"code\": null,\n \"e\": 573,\n \"s\": 530,\n \"text\": \"2) By using For loop to titlecase a string\"\n },\n {\n \"code\": \"\",\n \"e\": 828,\n \"s\": 573,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 835,\n \"s\": 828,\n \"text\": \"OUTPUT\"\n },\n {\n \"code\": null,\n \"e\": 851,\n \"s\": 835,\n \"text\": \"Geeks For Geeks\"\n },\n {\n \"code\": null,\n \"e\": 876,\n \"s\": 851,\n \"text\": \"3) By using map() method\"\n },\n {\n \"code\": \"\",\n \"e\": 1111,\n \"s\": 876,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 1118,\n \"s\": 1111,\n \"text\": \"OUTPUT\"\n },\n {\n \"code\": null,\n \"e\": 1149,\n \"s\": 1118,\n \"text\": \"Converting String To Titlecase\"\n },\n {\n \"code\": null,\n \"e\": 1167,\n \"s\": 1149,\n \"text\": \"javascript-string\"\n },\n {\n \"code\": null,\n \"e\": 1174,\n \"s\": 1167,\n \"text\": \"Picked\"\n },\n {\n \"code\": null,\n \"e\": 1185,\n \"s\": 1174,\n \"text\": \"JavaScript\"\n },\n {\n \"code\": null,\n \"e\": 1283,\n \"s\": 1185,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 1344,\n \"s\": 1283,\n \"text\": \"Difference between var, let and const keywords in JavaScript\"\n },\n {\n \"code\": null,\n \"e\": 1384,\n \"s\": 1344,\n \"text\": \"Remove elements from a JavaScript Array\"\n },\n {\n \"code\": null,\n \"e\": 1426,\n \"s\": 1384,\n \"text\": \"Roadmap to Learn JavaScript For Beginners\"\n },\n {\n \"code\": null,\n \"e\": 1467,\n \"s\": 1426,\n \"text\": \"Difference Between PUT and PATCH Request\"\n },\n {\n \"code\": null,\n \"e\": 1489,\n \"s\": 1467,\n \"text\": \"JavaScript | Promises\"\n },\n {\n \"code\": null,\n \"e\": 1537,\n \"s\": 1489,\n \"text\": \"How to filter object array based on attributes?\"\n },\n {\n \"code\": null,\n \"e\": 1564,\n \"s\": 1537,\n \"text\": \"Lodash _.debounce() Method\"\n },\n {\n \"code\": null,\n \"e\": 1600,\n \"s\": 1564,\n \"text\": \"JavaScript String includes() Method\"\n },\n {\n \"code\": null,\n \"e\": 1628,\n \"s\": 1600,\n \"text\": \"JavaScript | fetch() Method\"\n }\n]"}}},{"rowIdx":159,"cells":{"title":{"kind":"string","value":"wxPython - Event Handling"},"text":{"kind":"string","value":"Unlike a console mode application, which is executed in a sequential manner, a GUI based application is event driven. Functions or methods are executed in response to user’s actions like clicking a button, selecting an item from collection or mouse click, etc., called events.\nData pertaining to an event which takes place during the application’s runtime is stored as object of a subclass derived from wx.Event. A display control (such as Button) is the source of event of a particular type and produces an object of Event class associated to it. For instance, click of a button emits a wx.CommandEvent. This event data is dispatched to event handler method in the program. wxPython has many predefined event binders. An Event binder encapsulates relationship between a specific widget (control), its associated event type and the event handler method.\nFor example, to call OnClick() method of the program on a button’s click event, the following statement is required −\nself.b1.Bind(EVT_BUTTON, OnClick)\n\nBind() method is inherited by all display objects from wx.EvtHandler class. EVT_.BUTTON here is the binder, which associates button click event to OnClick() method.\nIn the following example, the MoveEvent, caused by dragging the top level window – a wx.Frame object in this case – is connected to OnMove() method using wx.EVT_MOVE binder. The code displays a window. If it is moved using mouse, its instantaneous coordinates are displayed on the console.\nimport wx\n \nclass Example(wx.Frame): \n \n def __init__(self, *args, **kw): \n super(Example, self).__init__(*args, **kw) \n self.InitUI() \n \n def InitUI(self): \n self.Bind(wx.EVT_MOVE, self.OnMove) \n self.SetSize((250, 180)) \n self.SetTitle('Move event') \n self.Centre() \n self.Show(True)\n\t\t \n def OnMove(self, e): \n x, y = e.GetPosition() \n print \"current window position x = \",x,\" y= \",y \n \nex = wx.App() \nExample(None) \nex.MainLoop() \nThe above code produces the following output −\ncurrent window position x = 562 y = 309\ncurrent window position x = 562 y = 309\ncurrent window position x = 326 y = 304\ncurrent window position x = 384 y = 240\ncurrent window position x = 173 y = 408\ncurrent window position x = 226 y = 30\ncurrent window position x = 481 y = 80\nSome of the subclasses inherited from wx.Event are listed in the following table −\nwxKeyEvent\nOccurs when a key is presses or released\nwxPaintEvent\nIs generated whenever contents of the window needs to be redrawn\nwxMouseEvent\nContains data about any event due to mouse activity like mouse button pressed or dragged\nwxScrollEvent\nAssociated with scrollable controls like wxScrollbar and wxSlider\nwxCommandEvent\nContains event data originating from many widgets such as button, dialogs, clipboard, etc.\nwxMenuEvent\nDifferent menu-related events excluding menu command button click\nwxColourPickerEvent\nwxColourPickerCtrl generated events\nwxDirFilePickerEvent\nEvents generated by FileDialog and DirDialog\nEvents in wxPython are of two types. Basic events and Command events. A basic event stays local to the window in which it originates. Most of the wxWidgets generate command events. A command event can be propagated to window or windows, which are above the source window in class hierarchy.\nFollowing is a simple example of event propagation. The complete code is −\nimport wx\n \nclass MyPanel(wx.Panel): \n \n def __init__(self, parent): \n super(MyPanel, self).__init__(parent)\n\t\t\n b = wx.Button(self, label = 'Btn', pos = (100,100)) \n b.Bind(wx.EVT_BUTTON, self.btnclk) \n self.Bind(wx.EVT_BUTTON, self.OnButtonClicked) \n\t\t\n def OnButtonClicked(self, e): \n \n print 'Panel received click event. propagated to Frame class' \n e.Skip() \n\t\t\n def btnclk(self,e): \n print \"Button received click event. propagated to Panel class\" \n e.Skip()\n\t\t\nclass Example(wx.Frame):\n\n def __init__(self,parent): \n super(Example, self).__init__(parent) \n \n self.InitUI() \n\n def InitUI(self):\n\t\n mpnl = MyPanel(self) \n self.Bind(wx.EVT_BUTTON, self.OnButtonClicked)\n\t\t\n self.SetTitle('Event propagation demo') \n self.Centre() \n self.Show(True)\n\t\t\n def OnButtonClicked(self, e): \n \n print 'click event received by frame class' \n e.Skip()\n\t\t\nex = wx.App() \nExample(None) \nex.MainLoop()\nIn the above code, there are two classes. MyPanel, a wx.Panel subclass and Example, a wx.Frame subclass which is the top level window for the program. A button is placed in the panel.\nThis Button object is bound to an event handler btnclk() which propagates it to parent class (MyPanel in this case). Button click generates a CommandEvent which can be propagated to its parent by Skip() method.\nMyPanel class object also binds the received event to another handler OnButtonClicked(). This function in turn transmits to its parent, the Example class. The above code produces the following output −\nButton received click event. Propagated to Panel class. \nPanel received click event. Propagated to Frame class. \nClick event received by frame class."},"parsed":{"kind":"list like","value":[{"code":null,"e":2293,"s":2016,"text":"Unlike a console mode application, which is executed in a sequential manner, a GUI based application is event driven. Functions or methods are executed in response to user’s actions like clicking a button, selecting an item from collection or mouse click, etc., called events."},{"code":null,"e":2870,"s":2293,"text":"Data pertaining to an event which takes place during the application’s runtime is stored as object of a subclass derived from wx.Event. A display control (such as Button) is the source of event of a particular type and produces an object of Event class associated to it. For instance, click of a button emits a wx.CommandEvent. This event data is dispatched to event handler method in the program. wxPython has many predefined event binders. An Event binder encapsulates relationship between a specific widget (control), its associated event type and the event handler method."},{"code":null,"e":2988,"s":2870,"text":"For example, to call OnClick() method of the program on a button’s click event, the following statement is required −"},{"code":null,"e":3023,"s":2988,"text":"self.b1.Bind(EVT_BUTTON, OnClick)\n"},{"code":null,"e":3188,"s":3023,"text":"Bind() method is inherited by all display objects from wx.EvtHandler class. EVT_.BUTTON here is the binder, which associates button click event to OnClick() method."},{"code":null,"e":3478,"s":3188,"text":"In the following example, the MoveEvent, caused by dragging the top level window – a wx.Frame object in this case – is connected to OnMove() method using wx.EVT_MOVE binder. The code displays a window. If it is moved using mouse, its instantaneous coordinates are displayed on the console."},{"code":null,"e":3999,"s":3478,"text":"import wx\n \nclass Example(wx.Frame): \n \n def __init__(self, *args, **kw): \n super(Example, self).__init__(*args, **kw) \n self.InitUI() \n \n def InitUI(self): \n self.Bind(wx.EVT_MOVE, self.OnMove) \n self.SetSize((250, 180)) \n self.SetTitle('Move event') \n self.Centre() \n self.Show(True)\n\t\t \n def OnMove(self, e): \n x, y = e.GetPosition() \n print \"current window position x = \",x,\" y= \",y \n \nex = wx.App() \nExample(None) \nex.MainLoop() "},{"code":null,"e":4046,"s":3999,"text":"The above code produces the following output −"},{"code":null,"e":4087,"s":4046,"text":"current window position x = 562 y = 309"},{"code":null,"e":4128,"s":4087,"text":"current window position x = 562 y = 309"},{"code":null,"e":4169,"s":4128,"text":"current window position x = 326 y = 304"},{"code":null,"e":4210,"s":4169,"text":"current window position x = 384 y = 240"},{"code":null,"e":4251,"s":4210,"text":"current window position x = 173 y = 408"},{"code":null,"e":4291,"s":4251,"text":"current window position x = 226 y = 30"},{"code":null,"e":4331,"s":4291,"text":"current window position x = 481 y = 80"},{"code":null,"e":4414,"s":4331,"text":"Some of the subclasses inherited from wx.Event are listed in the following table −"},{"code":null,"e":4425,"s":4414,"text":"wxKeyEvent"},{"code":null,"e":4466,"s":4425,"text":"Occurs when a key is presses or released"},{"code":null,"e":4479,"s":4466,"text":"wxPaintEvent"},{"code":null,"e":4544,"s":4479,"text":"Is generated whenever contents of the window needs to be redrawn"},{"code":null,"e":4557,"s":4544,"text":"wxMouseEvent"},{"code":null,"e":4646,"s":4557,"text":"Contains data about any event due to mouse activity like mouse button pressed or dragged"},{"code":null,"e":4660,"s":4646,"text":"wxScrollEvent"},{"code":null,"e":4726,"s":4660,"text":"Associated with scrollable controls like wxScrollbar and wxSlider"},{"code":null,"e":4741,"s":4726,"text":"wxCommandEvent"},{"code":null,"e":4832,"s":4741,"text":"Contains event data originating from many widgets such as button, dialogs, clipboard, etc."},{"code":null,"e":4844,"s":4832,"text":"wxMenuEvent"},{"code":null,"e":4910,"s":4844,"text":"Different menu-related events excluding menu command button click"},{"code":null,"e":4930,"s":4910,"text":"wxColourPickerEvent"},{"code":null,"e":4966,"s":4930,"text":"wxColourPickerCtrl generated events"},{"code":null,"e":4987,"s":4966,"text":"wxDirFilePickerEvent"},{"code":null,"e":5032,"s":4987,"text":"Events generated by FileDialog and DirDialog"},{"code":null,"e":5323,"s":5032,"text":"Events in wxPython are of two types. Basic events and Command events. A basic event stays local to the window in which it originates. Most of the wxWidgets generate command events. A command event can be propagated to window or windows, which are above the source window in class hierarchy."},{"code":null,"e":5398,"s":5323,"text":"Following is a simple example of event propagation. The complete code is −"},{"code":null,"e":6417,"s":5398,"text":"import wx\n \nclass MyPanel(wx.Panel): \n \n def __init__(self, parent): \n super(MyPanel, self).__init__(parent)\n\t\t\n b = wx.Button(self, label = 'Btn', pos = (100,100)) \n b.Bind(wx.EVT_BUTTON, self.btnclk) \n self.Bind(wx.EVT_BUTTON, self.OnButtonClicked) \n\t\t\n def OnButtonClicked(self, e): \n \n print 'Panel received click event. propagated to Frame class' \n e.Skip() \n\t\t\n def btnclk(self,e): \n print \"Button received click event. propagated to Panel class\" \n e.Skip()\n\t\t\nclass Example(wx.Frame):\n\n def __init__(self,parent): \n super(Example, self).__init__(parent) \n \n self.InitUI() \n\n def InitUI(self):\n\t\n mpnl = MyPanel(self) \n self.Bind(wx.EVT_BUTTON, self.OnButtonClicked)\n\t\t\n self.SetTitle('Event propagation demo') \n self.Centre() \n self.Show(True)\n\t\t\n def OnButtonClicked(self, e): \n \n print 'click event received by frame class' \n e.Skip()\n\t\t\nex = wx.App() \nExample(None) \nex.MainLoop()"},{"code":null,"e":6601,"s":6417,"text":"In the above code, there are two classes. MyPanel, a wx.Panel subclass and Example, a wx.Frame subclass which is the top level window for the program. A button is placed in the panel."},{"code":null,"e":6812,"s":6601,"text":"This Button object is bound to an event handler btnclk() which propagates it to parent class (MyPanel in this case). Button click generates a CommandEvent which can be propagated to its parent by Skip() method."},{"code":null,"e":7014,"s":6812,"text":"MyPanel class object also binds the received event to another handler OnButtonClicked(). This function in turn transmits to its parent, the Example class. The above code produces the following output −"}],"string":"[\n {\n \"code\": null,\n \"e\": 2293,\n \"s\": 2016,\n \"text\": \"Unlike a console mode application, which is executed in a sequential manner, a GUI based application is event driven. Functions or methods are executed in response to user’s actions like clicking a button, selecting an item from collection or mouse click, etc., called events.\"\n },\n {\n \"code\": null,\n \"e\": 2870,\n \"s\": 2293,\n \"text\": \"Data pertaining to an event which takes place during the application’s runtime is stored as object of a subclass derived from wx.Event. A display control (such as Button) is the source of event of a particular type and produces an object of Event class associated to it. For instance, click of a button emits a wx.CommandEvent. This event data is dispatched to event handler method in the program. wxPython has many predefined event binders. An Event binder encapsulates relationship between a specific widget (control), its associated event type and the event handler method.\"\n },\n {\n \"code\": null,\n \"e\": 2988,\n \"s\": 2870,\n \"text\": \"For example, to call OnClick() method of the program on a button’s click event, the following statement is required −\"\n },\n {\n \"code\": null,\n \"e\": 3023,\n \"s\": 2988,\n \"text\": \"self.b1.Bind(EVT_BUTTON, OnClick)\\n\"\n },\n {\n \"code\": null,\n \"e\": 3188,\n \"s\": 3023,\n \"text\": \"Bind() method is inherited by all display objects from wx.EvtHandler class. EVT_.BUTTON here is the binder, which associates button click event to OnClick() method.\"\n },\n {\n \"code\": null,\n \"e\": 3478,\n \"s\": 3188,\n \"text\": \"In the following example, the MoveEvent, caused by dragging the top level window – a wx.Frame object in this case – is connected to OnMove() method using wx.EVT_MOVE binder. The code displays a window. If it is moved using mouse, its instantaneous coordinates are displayed on the console.\"\n },\n {\n \"code\": null,\n \"e\": 3999,\n \"s\": 3478,\n \"text\": \"import wx\\n \\nclass Example(wx.Frame): \\n \\n def __init__(self, *args, **kw): \\n super(Example, self).__init__(*args, **kw) \\n self.InitUI() \\n \\n def InitUI(self): \\n self.Bind(wx.EVT_MOVE, self.OnMove) \\n self.SetSize((250, 180)) \\n self.SetTitle('Move event') \\n self.Centre() \\n self.Show(True)\\n\\t\\t \\n def OnMove(self, e): \\n x, y = e.GetPosition() \\n print \\\"current window position x = \\\",x,\\\" y= \\\",y \\n \\nex = wx.App() \\nExample(None) \\nex.MainLoop() \"\n },\n {\n \"code\": null,\n \"e\": 4046,\n \"s\": 3999,\n \"text\": \"The above code produces the following output −\"\n },\n {\n \"code\": null,\n \"e\": 4087,\n \"s\": 4046,\n \"text\": \"current window position x = 562 y = 309\"\n },\n {\n \"code\": null,\n \"e\": 4128,\n \"s\": 4087,\n \"text\": \"current window position x = 562 y = 309\"\n },\n {\n \"code\": null,\n \"e\": 4169,\n \"s\": 4128,\n \"text\": \"current window position x = 326 y = 304\"\n },\n {\n \"code\": null,\n \"e\": 4210,\n \"s\": 4169,\n \"text\": \"current window position x = 384 y = 240\"\n },\n {\n \"code\": null,\n \"e\": 4251,\n \"s\": 4210,\n \"text\": \"current window position x = 173 y = 408\"\n },\n {\n \"code\": null,\n \"e\": 4291,\n \"s\": 4251,\n \"text\": \"current window position x = 226 y = 30\"\n },\n {\n \"code\": null,\n \"e\": 4331,\n \"s\": 4291,\n \"text\": \"current window position x = 481 y = 80\"\n },\n {\n \"code\": null,\n \"e\": 4414,\n \"s\": 4331,\n \"text\": \"Some of the subclasses inherited from wx.Event are listed in the following table −\"\n },\n {\n \"code\": null,\n \"e\": 4425,\n \"s\": 4414,\n \"text\": \"wxKeyEvent\"\n },\n {\n \"code\": null,\n \"e\": 4466,\n \"s\": 4425,\n \"text\": \"Occurs when a key is presses or released\"\n },\n {\n \"code\": null,\n \"e\": 4479,\n \"s\": 4466,\n \"text\": \"wxPaintEvent\"\n },\n {\n \"code\": null,\n \"e\": 4544,\n \"s\": 4479,\n \"text\": \"Is generated whenever contents of the window needs to be redrawn\"\n },\n {\n \"code\": null,\n \"e\": 4557,\n \"s\": 4544,\n \"text\": \"wxMouseEvent\"\n },\n {\n \"code\": null,\n \"e\": 4646,\n \"s\": 4557,\n \"text\": \"Contains data about any event due to mouse activity like mouse button pressed or dragged\"\n },\n {\n \"code\": null,\n \"e\": 4660,\n \"s\": 4646,\n \"text\": \"wxScrollEvent\"\n },\n {\n \"code\": null,\n \"e\": 4726,\n \"s\": 4660,\n \"text\": \"Associated with scrollable controls like wxScrollbar and wxSlider\"\n },\n {\n \"code\": null,\n \"e\": 4741,\n \"s\": 4726,\n \"text\": \"wxCommandEvent\"\n },\n {\n \"code\": null,\n \"e\": 4832,\n \"s\": 4741,\n \"text\": \"Contains event data originating from many widgets such as button, dialogs, clipboard, etc.\"\n },\n {\n \"code\": null,\n \"e\": 4844,\n \"s\": 4832,\n \"text\": \"wxMenuEvent\"\n },\n {\n \"code\": null,\n \"e\": 4910,\n \"s\": 4844,\n \"text\": \"Different menu-related events excluding menu command button click\"\n },\n {\n \"code\": null,\n \"e\": 4930,\n \"s\": 4910,\n \"text\": \"wxColourPickerEvent\"\n },\n {\n \"code\": null,\n \"e\": 4966,\n \"s\": 4930,\n \"text\": \"wxColourPickerCtrl generated events\"\n },\n {\n \"code\": null,\n \"e\": 4987,\n \"s\": 4966,\n \"text\": \"wxDirFilePickerEvent\"\n },\n {\n \"code\": null,\n \"e\": 5032,\n \"s\": 4987,\n \"text\": \"Events generated by FileDialog and DirDialog\"\n },\n {\n \"code\": null,\n \"e\": 5323,\n \"s\": 5032,\n \"text\": \"Events in wxPython are of two types. Basic events and Command events. A basic event stays local to the window in which it originates. Most of the wxWidgets generate command events. A command event can be propagated to window or windows, which are above the source window in class hierarchy.\"\n },\n {\n \"code\": null,\n \"e\": 5398,\n \"s\": 5323,\n \"text\": \"Following is a simple example of event propagation. The complete code is −\"\n },\n {\n \"code\": null,\n \"e\": 6417,\n \"s\": 5398,\n \"text\": \"import wx\\n \\nclass MyPanel(wx.Panel): \\n \\n def __init__(self, parent): \\n super(MyPanel, self).__init__(parent)\\n\\t\\t\\n b = wx.Button(self, label = 'Btn', pos = (100,100)) \\n b.Bind(wx.EVT_BUTTON, self.btnclk) \\n self.Bind(wx.EVT_BUTTON, self.OnButtonClicked) \\n\\t\\t\\n def OnButtonClicked(self, e): \\n \\n print 'Panel received click event. propagated to Frame class' \\n e.Skip() \\n\\t\\t\\n def btnclk(self,e): \\n print \\\"Button received click event. propagated to Panel class\\\" \\n e.Skip()\\n\\t\\t\\nclass Example(wx.Frame):\\n\\n def __init__(self,parent): \\n super(Example, self).__init__(parent) \\n \\n self.InitUI() \\n\\n def InitUI(self):\\n\\t\\n mpnl = MyPanel(self) \\n self.Bind(wx.EVT_BUTTON, self.OnButtonClicked)\\n\\t\\t\\n self.SetTitle('Event propagation demo') \\n self.Centre() \\n self.Show(True)\\n\\t\\t\\n def OnButtonClicked(self, e): \\n \\n print 'click event received by frame class' \\n e.Skip()\\n\\t\\t\\nex = wx.App() \\nExample(None) \\nex.MainLoop()\"\n },\n {\n \"code\": null,\n \"e\": 6601,\n \"s\": 6417,\n \"text\": \"In the above code, there are two classes. MyPanel, a wx.Panel subclass and Example, a wx.Frame subclass which is the top level window for the program. A button is placed in the panel.\"\n },\n {\n \"code\": null,\n \"e\": 6812,\n \"s\": 6601,\n \"text\": \"This Button object is bound to an event handler btnclk() which propagates it to parent class (MyPanel in this case). Button click generates a CommandEvent which can be propagated to its parent by Skip() method.\"\n },\n {\n \"code\": null,\n \"e\": 7014,\n \"s\": 6812,\n \"text\": \"MyPanel class object also binds the received event to another handler OnButtonClicked(). This function in turn transmits to its parent, the Example class. The above code produces the following output −\"\n }\n]"}}},{"rowIdx":160,"cells":{"title":{"kind":"string","value":"Difference between long int and long long int in C/C++"},"text":{"kind":"string","value":"13 Jun, 2022\nAll variables use data type during declarations to restrict the type of data to be stored. Therefore, we can say that data types are used to tell the variables the type of data it can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared. Different data types require a different amount of memory.\nInteger: The keyword used for integer data types is int. Integers typically require 4 bytes of memory space and range from -2147483648 to 2147483647.\nDatatype Modifiers: As the name implies, datatype modifiers are used with the built-in data types to modify the length of data that a particular data type can hold. \nBelow is a list of ranges along with the memory requirements and format specifiers on the 32-bit GCC compiler.\nS. No. \nData Type\nMemory\n(bytes)\nRange\n Long long takes the double memory as compared to long. But it can also be different on various systems. Its range depends on the type of application. The guaranteed minimum usable bit sizes for different data types:\nchar: 8\nshort:16\nint: 16\nlong: 32\nlong long: 64\nThe decreasing order is: long long >=long>=int>=short>=char\nProgram 1:\nIn various competitive coding platforms, the constraints are between 107 to 1018. Below is the program to understand the concept:\nC++\n// C++ program to implement// the above approach#include using namespace std; // Driver codeint main(){ // Value of p 10^5 int p = 100000; // Value of q 10^5 int q = 100000; int result = p * q; cout << result << endl; return 0;}\n1410065408\nAs above, the output is not correct as int can’t store a 1010 value(out of its range). In this case, long long should be used.\nProgram 2:\nBelow is the C++ program to demonstrate how converting int to long long affects the output:\nC++\n// C++ program to implement// the above approach#include using namespace std; // Driver codeint main(){ // Value of p 10^5 int p = 100000; // Value of q 10^5 int q = 100000; long long int result = p * q; cout << result << endl; return 0;}\n1410065408\nExplanation: The above program gives the same output even after converting int to long long int because at first, the result is declared as long long. But before assigning the value of multiplication of p and q, it is already overflowed. Now, to prevent the overflow condition, it is required to convert the int result to the long long int before assigning the result value so that the overflow condition does not occur.\nProgram 3:\nBelow is the C++ program to implement the above approach:\nC++\n// C++ program to implement// the above approach#include using namespace std; // Driver codeint main(){ // Value of p 10^5 int p = 100000; // Value of q 10^5 int q = 100000; long long int result = (long long int)p * q; cout << result << endl; return 0;}\n10000000000\nExplanation: After this, it gives the correct output, which is 1010, which can be easily stored into a long long data type as the range is up to 1018.\nnobleniraj\nData Types\nArticles\nC++\nC++ Programs\nCPP\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nDocker - COPY Instruction\nTime complexities of different data structures\nDifference Between Object And Class\nSQL | DROP, TRUNCATE\nImplementation of LinkedList in Javascript\nVector in C++ STL\nMap in C++ Standard Template Library (STL)\nInitialize a vector in C++ (7 different ways)\nstd::sort() in C++ STL\nBitwise Operators in C/C++"},"parsed":{"kind":"list like","value":[{"code":null,"e":52,"s":24,"text":"\n13 Jun, 2022"},{"code":null,"e":444,"s":52,"text":"All variables use data type during declarations to restrict the type of data to be stored. Therefore, we can say that data types are used to tell the variables the type of data it can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared. Different data types require a different amount of memory."},{"code":null,"e":594,"s":444,"text":"Integer: The keyword used for integer data types is int. Integers typically require 4 bytes of memory space and range from -2147483648 to 2147483647."},{"code":null,"e":760,"s":594,"text":"Datatype Modifiers: As the name implies, datatype modifiers are used with the built-in data types to modify the length of data that a particular data type can hold. "},{"code":null,"e":871,"s":760,"text":"Below is a list of ranges along with the memory requirements and format specifiers on the 32-bit GCC compiler."},{"code":null,"e":879,"s":871,"text":"S. No. "},{"code":null,"e":889,"s":879,"text":"Data Type"},{"code":null,"e":896,"s":889,"text":"Memory"},{"code":null,"e":904,"s":896,"text":"(bytes)"},{"code":null,"e":910,"s":904,"text":"Range"},{"code":null,"e":1127,"s":910,"text":" Long long takes the double memory as compared to long. But it can also be different on various systems. Its range depends on the type of application. The guaranteed minimum usable bit sizes for different data types:"},{"code":null,"e":1135,"s":1127,"text":"char: 8"},{"code":null,"e":1144,"s":1135,"text":"short:16"},{"code":null,"e":1152,"s":1144,"text":"int: 16"},{"code":null,"e":1161,"s":1152,"text":"long: 32"},{"code":null,"e":1175,"s":1161,"text":"long long: 64"},{"code":null,"e":1235,"s":1175,"text":"The decreasing order is: long long >=long>=int>=short>=char"},{"code":null,"e":1246,"s":1235,"text":"Program 1:"},{"code":null,"e":1376,"s":1246,"text":"In various competitive coding platforms, the constraints are between 107 to 1018. Below is the program to understand the concept:"},{"code":null,"e":1380,"s":1376,"text":"C++"},{"code":"// C++ program to implement// the above approach#include using namespace std; // Driver codeint main(){ // Value of p 10^5 int p = 100000; // Value of q 10^5 int q = 100000; int result = p * q; cout << result << endl; return 0;}","e":1642,"s":1380,"text":null},{"code":null,"e":1653,"s":1642,"text":"1410065408"},{"code":null,"e":1780,"s":1653,"text":"As above, the output is not correct as int can’t store a 1010 value(out of its range). In this case, long long should be used."},{"code":null,"e":1791,"s":1780,"text":"Program 2:"},{"code":null,"e":1883,"s":1791,"text":"Below is the C++ program to demonstrate how converting int to long long affects the output:"},{"code":null,"e":1887,"s":1883,"text":"C++"},{"code":"// C++ program to implement// the above approach#include using namespace std; // Driver codeint main(){ // Value of p 10^5 int p = 100000; // Value of q 10^5 int q = 100000; long long int result = p * q; cout << result << endl; return 0;}","e":2159,"s":1887,"text":null},{"code":null,"e":2170,"s":2159,"text":"1410065408"},{"code":null,"e":2591,"s":2170,"text":"Explanation: The above program gives the same output even after converting int to long long int because at first, the result is declared as long long. But before assigning the value of multiplication of p and q, it is already overflowed. Now, to prevent the overflow condition, it is required to convert the int result to the long long int before assigning the result value so that the overflow condition does not occur."},{"code":null,"e":2602,"s":2591,"text":"Program 3:"},{"code":null,"e":2660,"s":2602,"text":"Below is the C++ program to implement the above approach:"},{"code":null,"e":2664,"s":2660,"text":"C++"},{"code":"// C++ program to implement// the above approach#include using namespace std; // Driver codeint main(){ // Value of p 10^5 int p = 100000; // Value of q 10^5 int q = 100000; long long int result = (long long int)p * q; cout << result << endl; return 0;}","e":2951,"s":2664,"text":null},{"code":null,"e":2963,"s":2951,"text":"10000000000"},{"code":null,"e":3114,"s":2963,"text":"Explanation: After this, it gives the correct output, which is 1010, which can be easily stored into a long long data type as the range is up to 1018."},{"code":null,"e":3125,"s":3114,"text":"nobleniraj"},{"code":null,"e":3136,"s":3125,"text":"Data Types"},{"code":null,"e":3145,"s":3136,"text":"Articles"},{"code":null,"e":3149,"s":3145,"text":"C++"},{"code":null,"e":3162,"s":3149,"text":"C++ Programs"},{"code":null,"e":3166,"s":3162,"text":"CPP"},{"code":null,"e":3264,"s":3166,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":3290,"s":3264,"text":"Docker - COPY Instruction"},{"code":null,"e":3337,"s":3290,"text":"Time complexities of different data structures"},{"code":null,"e":3373,"s":3337,"text":"Difference Between Object And Class"},{"code":null,"e":3394,"s":3373,"text":"SQL | DROP, TRUNCATE"},{"code":null,"e":3437,"s":3394,"text":"Implementation of LinkedList in Javascript"},{"code":null,"e":3455,"s":3437,"text":"Vector in C++ STL"},{"code":null,"e":3498,"s":3455,"text":"Map in C++ Standard Template Library (STL)"},{"code":null,"e":3544,"s":3498,"text":"Initialize a vector in C++ (7 different ways)"},{"code":null,"e":3567,"s":3544,"text":"std::sort() in C++ STL"}],"string":"[\n {\n \"code\": null,\n \"e\": 52,\n \"s\": 24,\n \"text\": \"\\n13 Jun, 2022\"\n },\n {\n \"code\": null,\n \"e\": 444,\n \"s\": 52,\n \"text\": \"All variables use data type during declarations to restrict the type of data to be stored. Therefore, we can say that data types are used to tell the variables the type of data it can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared. Different data types require a different amount of memory.\"\n },\n {\n \"code\": null,\n \"e\": 594,\n \"s\": 444,\n \"text\": \"Integer: The keyword used for integer data types is int. Integers typically require 4 bytes of memory space and range from -2147483648 to 2147483647.\"\n },\n {\n \"code\": null,\n \"e\": 760,\n \"s\": 594,\n \"text\": \"Datatype Modifiers: As the name implies, datatype modifiers are used with the built-in data types to modify the length of data that a particular data type can hold. \"\n },\n {\n \"code\": null,\n \"e\": 871,\n \"s\": 760,\n \"text\": \"Below is a list of ranges along with the memory requirements and format specifiers on the 32-bit GCC compiler.\"\n },\n {\n \"code\": null,\n \"e\": 879,\n \"s\": 871,\n \"text\": \"S. No. \"\n },\n {\n \"code\": null,\n \"e\": 889,\n \"s\": 879,\n \"text\": \"Data Type\"\n },\n {\n \"code\": null,\n \"e\": 896,\n \"s\": 889,\n \"text\": \"Memory\"\n },\n {\n \"code\": null,\n \"e\": 904,\n \"s\": 896,\n \"text\": \"(bytes)\"\n },\n {\n \"code\": null,\n \"e\": 910,\n \"s\": 904,\n \"text\": \"Range\"\n },\n {\n \"code\": null,\n \"e\": 1127,\n \"s\": 910,\n \"text\": \" Long long takes the double memory as compared to long. But it can also be different on various systems. Its range depends on the type of application. The guaranteed minimum usable bit sizes for different data types:\"\n },\n {\n \"code\": null,\n \"e\": 1135,\n \"s\": 1127,\n \"text\": \"char: 8\"\n },\n {\n \"code\": null,\n \"e\": 1144,\n \"s\": 1135,\n \"text\": \"short:16\"\n },\n {\n \"code\": null,\n \"e\": 1152,\n \"s\": 1144,\n \"text\": \"int: 16\"\n },\n {\n \"code\": null,\n \"e\": 1161,\n \"s\": 1152,\n \"text\": \"long: 32\"\n },\n {\n \"code\": null,\n \"e\": 1175,\n \"s\": 1161,\n \"text\": \"long long: 64\"\n },\n {\n \"code\": null,\n \"e\": 1235,\n \"s\": 1175,\n \"text\": \"The decreasing order is: long long >=long>=int>=short>=char\"\n },\n {\n \"code\": null,\n \"e\": 1246,\n \"s\": 1235,\n \"text\": \"Program 1:\"\n },\n {\n \"code\": null,\n \"e\": 1376,\n \"s\": 1246,\n \"text\": \"In various competitive coding platforms, the constraints are between 107 to 1018. Below is the program to understand the concept:\"\n },\n {\n \"code\": null,\n \"e\": 1380,\n \"s\": 1376,\n \"text\": \"C++\"\n },\n {\n \"code\": \"// C++ program to implement// the above approach#include using namespace std; // Driver codeint main(){ // Value of p 10^5 int p = 100000; // Value of q 10^5 int q = 100000; int result = p * q; cout << result << endl; return 0;}\",\n \"e\": 1642,\n \"s\": 1380,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 1653,\n \"s\": 1642,\n \"text\": \"1410065408\"\n },\n {\n \"code\": null,\n \"e\": 1780,\n \"s\": 1653,\n \"text\": \"As above, the output is not correct as int can’t store a 1010 value(out of its range). In this case, long long should be used.\"\n },\n {\n \"code\": null,\n \"e\": 1791,\n \"s\": 1780,\n \"text\": \"Program 2:\"\n },\n {\n \"code\": null,\n \"e\": 1883,\n \"s\": 1791,\n \"text\": \"Below is the C++ program to demonstrate how converting int to long long affects the output:\"\n },\n {\n \"code\": null,\n \"e\": 1887,\n \"s\": 1883,\n \"text\": \"C++\"\n },\n {\n \"code\": \"// C++ program to implement// the above approach#include using namespace std; // Driver codeint main(){ // Value of p 10^5 int p = 100000; // Value of q 10^5 int q = 100000; long long int result = p * q; cout << result << endl; return 0;}\",\n \"e\": 2159,\n \"s\": 1887,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 2170,\n \"s\": 2159,\n \"text\": \"1410065408\"\n },\n {\n \"code\": null,\n \"e\": 2591,\n \"s\": 2170,\n \"text\": \"Explanation: The above program gives the same output even after converting int to long long int because at first, the result is declared as long long. But before assigning the value of multiplication of p and q, it is already overflowed. Now, to prevent the overflow condition, it is required to convert the int result to the long long int before assigning the result value so that the overflow condition does not occur.\"\n },\n {\n \"code\": null,\n \"e\": 2602,\n \"s\": 2591,\n \"text\": \"Program 3:\"\n },\n {\n \"code\": null,\n \"e\": 2660,\n \"s\": 2602,\n \"text\": \"Below is the C++ program to implement the above approach:\"\n },\n {\n \"code\": null,\n \"e\": 2664,\n \"s\": 2660,\n \"text\": \"C++\"\n },\n {\n \"code\": \"// C++ program to implement// the above approach#include using namespace std; // Driver codeint main(){ // Value of p 10^5 int p = 100000; // Value of q 10^5 int q = 100000; long long int result = (long long int)p * q; cout << result << endl; return 0;}\",\n \"e\": 2951,\n \"s\": 2664,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 2963,\n \"s\": 2951,\n \"text\": \"10000000000\"\n },\n {\n \"code\": null,\n \"e\": 3114,\n \"s\": 2963,\n \"text\": \"Explanation: After this, it gives the correct output, which is 1010, which can be easily stored into a long long data type as the range is up to 1018.\"\n },\n {\n \"code\": null,\n \"e\": 3125,\n \"s\": 3114,\n \"text\": \"nobleniraj\"\n },\n {\n \"code\": null,\n \"e\": 3136,\n \"s\": 3125,\n \"text\": \"Data Types\"\n },\n {\n \"code\": null,\n \"e\": 3145,\n \"s\": 3136,\n \"text\": \"Articles\"\n },\n {\n \"code\": null,\n \"e\": 3149,\n \"s\": 3145,\n \"text\": \"C++\"\n },\n {\n \"code\": null,\n \"e\": 3162,\n \"s\": 3149,\n \"text\": \"C++ Programs\"\n },\n {\n \"code\": null,\n \"e\": 3166,\n \"s\": 3162,\n \"text\": \"CPP\"\n },\n {\n \"code\": null,\n \"e\": 3264,\n \"s\": 3166,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 3290,\n \"s\": 3264,\n \"text\": \"Docker - COPY Instruction\"\n },\n {\n \"code\": null,\n \"e\": 3337,\n \"s\": 3290,\n \"text\": \"Time complexities of different data structures\"\n },\n {\n \"code\": null,\n \"e\": 3373,\n \"s\": 3337,\n \"text\": \"Difference Between Object And Class\"\n },\n {\n \"code\": null,\n \"e\": 3394,\n \"s\": 3373,\n \"text\": \"SQL | DROP, TRUNCATE\"\n },\n {\n \"code\": null,\n \"e\": 3437,\n \"s\": 3394,\n \"text\": \"Implementation of LinkedList in Javascript\"\n },\n {\n \"code\": null,\n \"e\": 3455,\n \"s\": 3437,\n \"text\": \"Vector in C++ STL\"\n },\n {\n \"code\": null,\n \"e\": 3498,\n \"s\": 3455,\n \"text\": \"Map in C++ Standard Template Library (STL)\"\n },\n {\n \"code\": null,\n \"e\": 3544,\n \"s\": 3498,\n \"text\": \"Initialize a vector in C++ (7 different ways)\"\n },\n {\n \"code\": null,\n \"e\": 3567,\n \"s\": 3544,\n \"text\": \"std::sort() in C++ STL\"\n }\n]"}}},{"rowIdx":161,"cells":{"title":{"kind":"string","value":"Maximum Difference | Practice | GeeksforGeeks"},"text":{"kind":"string","value":"Given array A[] of integers, the task is to complete the function findMaxDiff which finds the maximum absolute difference between nearest left and right smaller element of every element in array.If the element is the leftmost element, nearest smaller element on left side is considered as 0. Similarly if the element is the rightmost elements, smaller element on right side is considered as 0.\nExamples:\nInput : arr[] = {2, 1, 8}\nOutput : 1\nLeft smaller LS[] {0, 0, 1}\nRight smaller RS[] {1, 0, 0}\nMaximum Diff of abs(LS[i] - RS[i]) = 1 \n\nInput : arr[] = {2, 4, 8, 7, 7, 9, 3}\nOutput : 4\nLeft smaller LS[] = {0, 2, 4, 4, 4, 7, 2}\nRight smaller RS[] = {0, 3, 7, 3, 3, 3, 0}\nMaximum Diff of abs(LS[i] - RS[i]) = 7 - 3 = 4 \n\nInput : arr[] = {5, 1, 9, 2, 5, 1, 7}\nOutput : 1\nInput:\nThe first line of input contains an integer T denoting the no of test cases. Then T test cases follow .Each test case contains an integer N denoting the size of the array A. In the next line are N space separated values of the array A.\n\nOutput:\nFor each test case output will be in a new line denoting the the maximum absolute difference between nearest left and right smaller element of every element in array.\n\nConstraints:\n1<=T<=100\n1<=N<=100\n1<=A[ ]<=100\n\nExample(To be used only for expected output) :\nInput:\n2\n3\n2 1 8\n7\n2 4 8 7 7 9 3\nOutput\n1\n4\n+1\nsauravmehta8185 days ago\nO(n) Solution\n \nclass Solution\n{\n int findMaxDiff(int arr[], int n)\n {\n int[] output1=leftsmall(arr);\n int[] output2=rightsmall(arr);\n int num=Integer.MIN_VALUE;\n for(int i=0;inum)\n num=Math.abs(output1[i]-output2[i]);\n }\n return num;\n }\n public int[] leftsmall(int[] arr)\n {\n Stack stk=new Stack<>();\n int[] output=new int[arr.length];\n stk.push(arr[0]);\n output[0]=0;\n for(int i=1;i=arr[i])\n stk.pop();\n output[i]=stk.empty()? 0:stk.peek();\n stk.push(arr[i]);\n }\n return output;\n }\n \n \n public int[] rightsmall(int[] arr)\n {\n Stack stk=new Stack<>();\n int[] output=new int[arr.length];\n stk.push(arr[arr.length-1]);\n output[arr.length-1]=0;\n for(int i=arr.length-2;i>=0;i--)\n {\n while(!stk.empty() && stk.peek()>=arr[i])\n stk.pop();\n output[i]=stk.empty()? 0:stk.peek();\n stk.push(arr[i]);\n }\n return output;\n }\n}\n0\nbhavinbansal78652 weeks ago\nint findMaxDiff(int a[], int n) { //Your code here int left[n]; left[0]=0; int k; bool flag; for(int i=1;i=0) { if(a[i]>a[k]) { left[i]=a[k]; flag=true; break; } k--; } if(flag==false) left[i]=0; } int right[n]; right[n-1]=0; for(int i=n-2;i>=0;i--) { k=i+1; flag=false; while(k<=(n-1)) { if(a[i]>a[k]) { right[i]=a[k]; flag=true; break; } k++; } if(flag==false) right[i]=0; } int res=0; for(int i=0;i s;\n int ls[n]={0},ans=0;\n for(int i=0;ia[i]){\n ans=max(ans,abs(ls[s.top()]-a[i]));\n s.pop();\n }\n if(!s.empty())\n ls[i]=a[s.top()]==a[i] ? ls[s.top()] : a[s.top()];\n s.push(i);\n }\n while(!s.empty()){\n ans=max(ans,ls[s.top()]);\n s.pop();\n }\n return ans;\n }\n+1\nankitmaurya31 month ago\ndef nearestleftsmaller(a,n):\n ans = []\n stack = []\n for i in range(n):\n while(len(stack)!=0 and a[i]<=stack[-1]):\n stack.pop()\n if len(stack)==0:\n ans.append(0)\n else:\n ans.append(stack[-1])\n# ans.append(0 if len(stack)==0 else stack[-1])\n stack.append(a[i])\n return ans\n \ndef nearestrightsmaller(a,n):\n ans = [0 for i in range(n)]\n stack = []\n for i in range(n-1,-1,-1):\n while(len(stack)!=0 and a[i]<=stack[-1]):\n stack.pop()\n if len(stack)==0:\n ans[i] = 0\n else:\n ans[i] = stack[-1]\n# ans.append(0 if len(stack)==0 else stack[-1])\n stack.append(a[i])\n return ans\n \n \nclass Solution:\n # Your task is to complete this function\n # Function should return an integer denoting the required answer\n def findMaxDiff(self, a, n):\n nrs = nearestrightsmaller(a,n)\n nls = nearestleftsmaller(a,n)\n res = 0\n for i in range(n):\n res = max(res,abs(nls[i]-nrs[i]))\n return res\n0\nanupamojha31131 month ago\n //Your code here // Time Taken 0.01/1.29 int ans=0; for(int i=0;iarr[j]){ r=arr[j]; break; } } for(int j=i;j>=0;j--){ if(arr[i]>arr[j]){ l=arr[j]; break; } } ans=max(ans,abs(l-r)); } return ans;\n0\n21mx1261 month ago\n//c++ program\n \nvector ls(n,0); vector stk; stk.push_back(0); for(int i=0;istk[stk.size()-1]){ ls[i]=stk[stk.size()-1]; stk.push_back(A[i]); }else{ while(A[i]<=stk[stk.size()-1]){ stk.erase(stk.begin()+stk.size()-1); } ls[i]=stk[stk.size()-1]; stk.push_back(A[i]); } } stk.clear(); stk.push_back(0); int res=INT_MIN; for(int i=n-1;i>=0;i--){ if(A[i]>stk[stk.size()-1]){ //cout << stk[stk.size()-1] << \" \"; res = (res > abs(ls[i]-stk[stk.size()-1]) ? res : abs(ls[i]-stk[stk.size()-1])); stk.push_back(A[i]); }else{ while(A[i]<=stk[stk.size()-1]){ stk.erase(stk.begin()+stk.size()-1); } //cout << stk[stk.size()-1] << \" \"; res = (res > abs(ls[i]-stk[stk.size()-1]) ? res : abs(ls[i]-stk[stk.size()-1])); stk.push_back(A[i]); } } return res;\n0\n21mx126\nThis comment was deleted.\n0\nonlybkm20021 month ago\nint findMaxDiff(int A[], int n)\n {\n stack st1;\n stack st2;\n vector ls(n,0);\n vector rs(n,0);\n for(int i=n-1; i>=0; i--)\n {\n while(!st1.empty() && st1.top()>=A[i])\n {\n st1.pop();\n }\n if(i=A[i])\n {\n st2.pop();\n }\n if(i diff(n);\n for(int i=0; ist=new Stack<>(); findls(ls,arr,st,n); st=new Stack<>(); findrs(rs,arr,st,n); // System.out.println(Arrays.toString(ls)); int max=Integer.MIN_VALUE; for(int i=0;imax)max=t; } return max; } public static void findls(Integer[]ans,int[]arr,Stackst,int n) { ans[0]=0; st.push(arr[0]); for(int i=1;i0 && st.peek()0 && st.peek()>=arr[i]) { st.pop(); } if(st.size()==0) { ans[i]=0; st.push(arr[i]); } else{ ans[i]=st.peek(); st.push(arr[i]); } } } } } public static void findrs(Integer[]ans,int[]arr,Stackst,int n){ ans[n-1]=0; st.push(arr[n-1]); for(int i=n-2;i>=0;i--) { if(st.peek()0 && st.peek()>=arr[i]) { st.pop(); } if(st.size()==0) { ans[i]=0; st.push(arr[i]); }else{ ans[i]=st.peek(); st.push(arr[i]); } } } }}\n0\nshubhankardey29sep2 months ago\nclass Solution\n{\n int findMaxDiff(int a[], int n)\n {\n\t// Your code here\t\n\tint []r1 = nsl(a,n);\n\tint []r2 = nsr(a,n);\n\tint max = 0;\n\t\n\tfor(int i=0;i st = new Stack<>();\n int []res = new int[n];\n res[0] = 0;\n st.push(a[0]);\n int idx = 1;\n for(int i=1;i=a[i])\n st.pop();\n \n if(st.size()==0)\n res[idx++] = 0;\n \n else\n res[idx++] = st.peek();\n \n st.push(a[i]);\n }\n return res;\n }\n int[] nsr(int []a,int n)\n {\n Stack st = new Stack<>();\n int []res = new int[n];\n res[n-1] = 0;\n st.push(a[n-1]);\n int idx = n-2;\n for(int i=n-2;i>=0;i--)\n {\n while(!st.isEmpty() && st.peek()>=a[i])\n st.pop();\n \n if(st.size()==0)\n res[idx--] = 0;\n \n else\n res[idx--] = st.peek();\n \n st.push(a[i]);\n }\n return res;\n }\n}\nWe strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?\n Login to access your submissions. \n\nProblem\n\n\nContest\n\nReset the IDE using the second button on the top right corner.\nAvoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values.\nPassing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints.\nYou can access the hints to get an idea about what is expected of you as well as\n the final solution code.\nYou can view the solutions submitted by other users from the submission tab.\nMake sure you are not using ad-blockers.\nDisable browser extensions.\nWe recommend using latest version of your browser for best experience.\nAvoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values.\nPassing the Sample/Custom Test cases in coding problems does not guarantee the \n correctness of code. On submission, your code is tested against multiple test cases\n consisting of all possible corner cases and stress constraints."},"parsed":{"kind":"list like","value":[{"code":null,"e":632,"s":238,"text":"Given array A[] of integers, the task is to complete the function findMaxDiff which finds the maximum absolute difference between nearest left and right smaller element of every element in array.If the element is the leftmost element, nearest smaller element on left side is considered as 0. Similarly if the element is the rightmost elements, smaller element on right side is considered as 0."},{"code":null,"e":642,"s":632,"text":"Examples:"},{"code":null,"e":1014,"s":642,"text":"Input : arr[] = {2, 1, 8}\nOutput : 1\nLeft smaller LS[] {0, 0, 1}\nRight smaller RS[] {1, 0, 0}\nMaximum Diff of abs(LS[i] - RS[i]) = 1 \n\nInput : arr[] = {2, 4, 8, 7, 7, 9, 3}\nOutput : 4\nLeft smaller LS[] = {0, 2, 4, 4, 4, 7, 2}\nRight smaller RS[] = {0, 3, 7, 3, 3, 3, 0}\nMaximum Diff of abs(LS[i] - RS[i]) = 7 - 3 = 4 \n\nInput : arr[] = {5, 1, 9, 2, 5, 1, 7}\nOutput : 1"},{"code":null,"e":1572,"s":1014,"text":"Input:\nThe first line of input contains an integer T denoting the no of test cases. Then T test cases follow .Each test case contains an integer N denoting the size of the array A. In the next line are N space separated values of the array A.\n\nOutput:\nFor each test case output will be in a new line denoting the the maximum absolute difference between nearest left and right smaller element of every element in array.\n\nConstraints:\n1<=T<=100\n1<=N<=100\n1<=A[ ]<=100\n\nExample(To be used only for expected output) :\nInput:\n2\n3\n2 1 8\n7\n2 4 8 7 7 9 3\nOutput\n1\n4"},{"code":null,"e":1575,"s":1572,"text":"+1"},{"code":null,"e":1600,"s":1575,"text":"sauravmehta8185 days ago"},{"code":null,"e":1614,"s":1600,"text":"O(n) Solution"},{"code":null,"e":2815,"s":1616,"text":"class Solution\n{\n int findMaxDiff(int arr[], int n)\n {\n int[] output1=leftsmall(arr);\n int[] output2=rightsmall(arr);\n int num=Integer.MIN_VALUE;\n for(int i=0;inum)\n num=Math.abs(output1[i]-output2[i]);\n }\n return num;\n }\n public int[] leftsmall(int[] arr)\n {\n Stack stk=new Stack<>();\n int[] output=new int[arr.length];\n stk.push(arr[0]);\n output[0]=0;\n for(int i=1;i=arr[i])\n stk.pop();\n output[i]=stk.empty()? 0:stk.peek();\n stk.push(arr[i]);\n }\n return output;\n }\n \n \n public int[] rightsmall(int[] arr)\n {\n Stack stk=new Stack<>();\n int[] output=new int[arr.length];\n stk.push(arr[arr.length-1]);\n output[arr.length-1]=0;\n for(int i=arr.length-2;i>=0;i--)\n {\n while(!stk.empty() && stk.peek()>=arr[i])\n stk.pop();\n output[i]=stk.empty()? 0:stk.peek();\n stk.push(arr[i]);\n }\n return output;\n }\n}"},{"code":null,"e":2817,"s":2815,"text":"0"},{"code":null,"e":2845,"s":2817,"text":"bhavinbansal78652 weeks ago"},{"code":null,"e":3768,"s":2845,"text":"int findMaxDiff(int a[], int n) { //Your code here int left[n]; left[0]=0; int k; bool flag; for(int i=1;i=0) { if(a[i]>a[k]) { left[i]=a[k]; flag=true; break; } k--; } if(flag==false) left[i]=0; } int right[n]; right[n-1]=0; for(int i=n-2;i>=0;i--) { k=i+1; flag=false; while(k<=(n-1)) { if(a[i]>a[k]) { right[i]=a[k]; flag=true; break; } k++; } if(flag==false) right[i]=0; } int res=0; for(int i=0;i s;\n int ls[n]={0},ans=0;\n for(int i=0;ia[i]){\n ans=max(ans,abs(ls[s.top()]-a[i]));\n s.pop();\n }\n if(!s.empty())\n ls[i]=a[s.top()]==a[i] ? ls[s.top()] : a[s.top()];\n s.push(i);\n }\n while(!s.empty()){\n ans=max(ans,ls[s.top()]);\n s.pop();\n }\n return ans;\n }"},{"code":null,"e":4301,"s":4298,"text":"+1"},{"code":null,"e":4325,"s":4301,"text":"ankitmaurya31 month ago"},{"code":null,"e":5415,"s":4325,"text":"def nearestleftsmaller(a,n):\n ans = []\n stack = []\n for i in range(n):\n while(len(stack)!=0 and a[i]<=stack[-1]):\n stack.pop()\n if len(stack)==0:\n ans.append(0)\n else:\n ans.append(stack[-1])\n# ans.append(0 if len(stack)==0 else stack[-1])\n stack.append(a[i])\n return ans\n \ndef nearestrightsmaller(a,n):\n ans = [0 for i in range(n)]\n stack = []\n for i in range(n-1,-1,-1):\n while(len(stack)!=0 and a[i]<=stack[-1]):\n stack.pop()\n if len(stack)==0:\n ans[i] = 0\n else:\n ans[i] = stack[-1]\n# ans.append(0 if len(stack)==0 else stack[-1])\n stack.append(a[i])\n return ans\n \n \nclass Solution:\n # Your task is to complete this function\n # Function should return an integer denoting the required answer\n def findMaxDiff(self, a, n):\n nrs = nearestrightsmaller(a,n)\n nls = nearestleftsmaller(a,n)\n res = 0\n for i in range(n):\n res = max(res,abs(nls[i]-nrs[i]))\n return res"},{"code":null,"e":5417,"s":5415,"text":"0"},{"code":null,"e":5443,"s":5417,"text":"anupamojha31131 month ago"},{"code":null,"e":5815,"s":5443,"text":" //Your code here // Time Taken 0.01/1.29 int ans=0; for(int i=0;iarr[j]){ r=arr[j]; break; } } for(int j=i;j>=0;j--){ if(arr[i]>arr[j]){ l=arr[j]; break; } } ans=max(ans,abs(l-r)); } return ans;"},{"code":null,"e":5817,"s":5815,"text":"0"},{"code":null,"e":5836,"s":5817,"text":"21mx1261 month ago"},{"code":null,"e":5850,"s":5836,"text":"//c++ program"},{"code":null,"e":6954,"s":5852,"text":"vector ls(n,0); vector stk; stk.push_back(0); for(int i=0;istk[stk.size()-1]){ ls[i]=stk[stk.size()-1]; stk.push_back(A[i]); }else{ while(A[i]<=stk[stk.size()-1]){ stk.erase(stk.begin()+stk.size()-1); } ls[i]=stk[stk.size()-1]; stk.push_back(A[i]); } } stk.clear(); stk.push_back(0); int res=INT_MIN; for(int i=n-1;i>=0;i--){ if(A[i]>stk[stk.size()-1]){ //cout << stk[stk.size()-1] << \" \"; res = (res > abs(ls[i]-stk[stk.size()-1]) ? res : abs(ls[i]-stk[stk.size()-1])); stk.push_back(A[i]); }else{ while(A[i]<=stk[stk.size()-1]){ stk.erase(stk.begin()+stk.size()-1); } //cout << stk[stk.size()-1] << \" \"; res = (res > abs(ls[i]-stk[stk.size()-1]) ? res : abs(ls[i]-stk[stk.size()-1])); stk.push_back(A[i]); } } return res;"},{"code":null,"e":6956,"s":6954,"text":"0"},{"code":null,"e":6964,"s":6956,"text":"21mx126"},{"code":null,"e":6990,"s":6964,"text":"This comment was deleted."},{"code":null,"e":6992,"s":6990,"text":"0"},{"code":null,"e":7015,"s":6992,"text":"onlybkm20021 month ago"},{"code":null,"e":8030,"s":7015,"text":"int findMaxDiff(int A[], int n)\n {\n stack st1;\n stack st2;\n vector ls(n,0);\n vector rs(n,0);\n for(int i=n-1; i>=0; i--)\n {\n while(!st1.empty() && st1.top()>=A[i])\n {\n st1.pop();\n }\n if(i=A[i])\n {\n st2.pop();\n }\n if(i diff(n);\n for(int i=0; ist=new Stack<>(); findls(ls,arr,st,n); st=new Stack<>(); findrs(rs,arr,st,n); // System.out.println(Arrays.toString(ls)); int max=Integer.MIN_VALUE; for(int i=0;imax)max=t; } return max; } public static void findls(Integer[]ans,int[]arr,Stackst,int n) { ans[0]=0; st.push(arr[0]); for(int i=1;i0 && st.peek()0 && st.peek()>=arr[i]) { st.pop(); } if(st.size()==0) { ans[i]=0; st.push(arr[i]); } else{ ans[i]=st.peek(); st.push(arr[i]); } } } } } public static void findrs(Integer[]ans,int[]arr,Stackst,int n){ ans[n-1]=0; st.push(arr[n-1]); for(int i=n-2;i>=0;i--) { if(st.peek()0 && st.peek()>=arr[i]) { st.pop(); } if(st.size()==0) { ans[i]=0; st.push(arr[i]); }else{ ans[i]=st.peek(); st.push(arr[i]); } } } }}"},{"code":null,"e":10069,"s":10067,"text":"0"},{"code":null,"e":10100,"s":10069,"text":"shubhankardey29sep2 months ago"},{"code":null,"e":11365,"s":10100,"text":"class Solution\n{\n int findMaxDiff(int a[], int n)\n {\n\t// Your code here\t\n\tint []r1 = nsl(a,n);\n\tint []r2 = nsr(a,n);\n\tint max = 0;\n\t\n\tfor(int i=0;i st = new Stack<>();\n int []res = new int[n];\n res[0] = 0;\n st.push(a[0]);\n int idx = 1;\n for(int i=1;i=a[i])\n st.pop();\n \n if(st.size()==0)\n res[idx++] = 0;\n \n else\n res[idx++] = st.peek();\n \n st.push(a[i]);\n }\n return res;\n }\n int[] nsr(int []a,int n)\n {\n Stack st = new Stack<>();\n int []res = new int[n];\n res[n-1] = 0;\n st.push(a[n-1]);\n int idx = n-2;\n for(int i=n-2;i>=0;i--)\n {\n while(!st.isEmpty() && st.peek()>=a[i])\n st.pop();\n \n if(st.size()==0)\n res[idx--] = 0;\n \n else\n res[idx--] = st.peek();\n \n st.push(a[i]);\n }\n return res;\n }\n}"},{"code":null,"e":11511,"s":11365,"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":11547,"s":11511,"text":" Login to access your submissions. "},{"code":null,"e":11557,"s":11547,"text":"\nProblem\n"},{"code":null,"e":11567,"s":11557,"text":"\nContest\n"},{"code":null,"e":11630,"s":11567,"text":"Reset the IDE using the second button on the top right corner."},{"code":null,"e":11815,"s":11630,"text":"Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."},{"code":null,"e":12099,"s":11815,"text":"Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."},{"code":null,"e":12245,"s":12099,"text":"You can access the hints to get an idea about what is expected of you as well as\n the final solution code."},{"code":null,"e":12322,"s":12245,"text":"You can view the solutions submitted by other users from the submission tab."},{"code":null,"e":12363,"s":12322,"text":"Make sure you are not using ad-blockers."},{"code":null,"e":12391,"s":12363,"text":"Disable browser extensions."},{"code":null,"e":12462,"s":12391,"text":"We recommend using latest version of your browser for best experience."},{"code":null,"e":12649,"s":12462,"text":"Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."}],"string":"[\n {\n \"code\": null,\n \"e\": 632,\n \"s\": 238,\n \"text\": \"Given array A[] of integers, the task is to complete the function findMaxDiff which finds the maximum absolute difference between nearest left and right smaller element of every element in array.If the element is the leftmost element, nearest smaller element on left side is considered as 0. Similarly if the element is the rightmost elements, smaller element on right side is considered as 0.\"\n },\n {\n \"code\": null,\n \"e\": 642,\n \"s\": 632,\n \"text\": \"Examples:\"\n },\n {\n \"code\": null,\n \"e\": 1014,\n \"s\": 642,\n \"text\": \"Input : arr[] = {2, 1, 8}\\nOutput : 1\\nLeft smaller LS[] {0, 0, 1}\\nRight smaller RS[] {1, 0, 0}\\nMaximum Diff of abs(LS[i] - RS[i]) = 1 \\n\\nInput : arr[] = {2, 4, 8, 7, 7, 9, 3}\\nOutput : 4\\nLeft smaller LS[] = {0, 2, 4, 4, 4, 7, 2}\\nRight smaller RS[] = {0, 3, 7, 3, 3, 3, 0}\\nMaximum Diff of abs(LS[i] - RS[i]) = 7 - 3 = 4 \\n\\nInput : arr[] = {5, 1, 9, 2, 5, 1, 7}\\nOutput : 1\"\n },\n {\n \"code\": null,\n \"e\": 1572,\n \"s\": 1014,\n \"text\": \"Input:\\nThe first line of input contains an integer T denoting the no of test cases. Then T test cases follow .Each test case contains an integer N denoting the size of the array A. In the next line are N space separated values of the array A.\\n\\nOutput:\\nFor each test case output will be in a new line denoting the the maximum absolute difference between nearest left and right smaller element of every element in array.\\n\\nConstraints:\\n1<=T<=100\\n1<=N<=100\\n1<=A[ ]<=100\\n\\nExample(To be used only for expected output) :\\nInput:\\n2\\n3\\n2 1 8\\n7\\n2 4 8 7 7 9 3\\nOutput\\n1\\n4\"\n },\n {\n \"code\": null,\n \"e\": 1575,\n \"s\": 1572,\n \"text\": \"+1\"\n },\n {\n \"code\": null,\n \"e\": 1600,\n \"s\": 1575,\n \"text\": \"sauravmehta8185 days ago\"\n },\n {\n \"code\": null,\n \"e\": 1614,\n \"s\": 1600,\n \"text\": \"O(n) Solution\"\n },\n {\n \"code\": null,\n \"e\": 2815,\n \"s\": 1616,\n \"text\": \"class Solution\\n{\\n int findMaxDiff(int arr[], int n)\\n {\\n int[] output1=leftsmall(arr);\\n int[] output2=rightsmall(arr);\\n int num=Integer.MIN_VALUE;\\n for(int i=0;inum)\\n num=Math.abs(output1[i]-output2[i]);\\n }\\n return num;\\n }\\n public int[] leftsmall(int[] arr)\\n {\\n Stack stk=new Stack<>();\\n int[] output=new int[arr.length];\\n stk.push(arr[0]);\\n output[0]=0;\\n for(int i=1;i=arr[i])\\n stk.pop();\\n output[i]=stk.empty()? 0:stk.peek();\\n stk.push(arr[i]);\\n }\\n return output;\\n }\\n \\n \\n public int[] rightsmall(int[] arr)\\n {\\n Stack stk=new Stack<>();\\n int[] output=new int[arr.length];\\n stk.push(arr[arr.length-1]);\\n output[arr.length-1]=0;\\n for(int i=arr.length-2;i>=0;i--)\\n {\\n while(!stk.empty() && stk.peek()>=arr[i])\\n stk.pop();\\n output[i]=stk.empty()? 0:stk.peek();\\n stk.push(arr[i]);\\n }\\n return output;\\n }\\n}\"\n },\n {\n \"code\": null,\n \"e\": 2817,\n \"s\": 2815,\n \"text\": \"0\"\n },\n {\n \"code\": null,\n \"e\": 2845,\n \"s\": 2817,\n \"text\": \"bhavinbansal78652 weeks ago\"\n },\n {\n \"code\": null,\n \"e\": 3768,\n \"s\": 2845,\n \"text\": \"int findMaxDiff(int a[], int n) { //Your code here int left[n]; left[0]=0; int k; bool flag; for(int i=1;i=0) { if(a[i]>a[k]) { left[i]=a[k]; flag=true; break; } k--; } if(flag==false) left[i]=0; } int right[n]; right[n-1]=0; for(int i=n-2;i>=0;i--) { k=i+1; flag=false; while(k<=(n-1)) { if(a[i]>a[k]) { right[i]=a[k]; flag=true; break; } k++; } if(flag==false) right[i]=0; } int res=0; for(int i=0;i s;\\n int ls[n]={0},ans=0;\\n for(int i=0;ia[i]){\\n ans=max(ans,abs(ls[s.top()]-a[i]));\\n s.pop();\\n }\\n if(!s.empty())\\n ls[i]=a[s.top()]==a[i] ? ls[s.top()] : a[s.top()];\\n s.push(i);\\n }\\n while(!s.empty()){\\n ans=max(ans,ls[s.top()]);\\n s.pop();\\n }\\n return ans;\\n }\"\n },\n {\n \"code\": null,\n \"e\": 4301,\n \"s\": 4298,\n \"text\": \"+1\"\n },\n {\n \"code\": null,\n \"e\": 4325,\n \"s\": 4301,\n \"text\": \"ankitmaurya31 month ago\"\n },\n {\n \"code\": null,\n \"e\": 5415,\n \"s\": 4325,\n \"text\": \"def nearestleftsmaller(a,n):\\n ans = []\\n stack = []\\n for i in range(n):\\n while(len(stack)!=0 and a[i]<=stack[-1]):\\n stack.pop()\\n if len(stack)==0:\\n ans.append(0)\\n else:\\n ans.append(stack[-1])\\n# ans.append(0 if len(stack)==0 else stack[-1])\\n stack.append(a[i])\\n return ans\\n \\ndef nearestrightsmaller(a,n):\\n ans = [0 for i in range(n)]\\n stack = []\\n for i in range(n-1,-1,-1):\\n while(len(stack)!=0 and a[i]<=stack[-1]):\\n stack.pop()\\n if len(stack)==0:\\n ans[i] = 0\\n else:\\n ans[i] = stack[-1]\\n# ans.append(0 if len(stack)==0 else stack[-1])\\n stack.append(a[i])\\n return ans\\n \\n \\nclass Solution:\\n # Your task is to complete this function\\n # Function should return an integer denoting the required answer\\n def findMaxDiff(self, a, n):\\n nrs = nearestrightsmaller(a,n)\\n nls = nearestleftsmaller(a,n)\\n res = 0\\n for i in range(n):\\n res = max(res,abs(nls[i]-nrs[i]))\\n return res\"\n },\n {\n \"code\": null,\n \"e\": 5417,\n \"s\": 5415,\n \"text\": \"0\"\n },\n {\n \"code\": null,\n \"e\": 5443,\n \"s\": 5417,\n \"text\": \"anupamojha31131 month ago\"\n },\n {\n \"code\": null,\n \"e\": 5815,\n \"s\": 5443,\n \"text\": \" //Your code here // Time Taken 0.01/1.29 int ans=0; for(int i=0;iarr[j]){ r=arr[j]; break; } } for(int j=i;j>=0;j--){ if(arr[i]>arr[j]){ l=arr[j]; break; } } ans=max(ans,abs(l-r)); } return ans;\"\n },\n {\n \"code\": null,\n \"e\": 5817,\n \"s\": 5815,\n \"text\": \"0\"\n },\n {\n \"code\": null,\n \"e\": 5836,\n \"s\": 5817,\n \"text\": \"21mx1261 month ago\"\n },\n {\n \"code\": null,\n \"e\": 5850,\n \"s\": 5836,\n \"text\": \"//c++ program\"\n },\n {\n \"code\": null,\n \"e\": 6954,\n \"s\": 5852,\n \"text\": \"vector ls(n,0); vector stk; stk.push_back(0); for(int i=0;istk[stk.size()-1]){ ls[i]=stk[stk.size()-1]; stk.push_back(A[i]); }else{ while(A[i]<=stk[stk.size()-1]){ stk.erase(stk.begin()+stk.size()-1); } ls[i]=stk[stk.size()-1]; stk.push_back(A[i]); } } stk.clear(); stk.push_back(0); int res=INT_MIN; for(int i=n-1;i>=0;i--){ if(A[i]>stk[stk.size()-1]){ //cout << stk[stk.size()-1] << \\\" \\\"; res = (res > abs(ls[i]-stk[stk.size()-1]) ? res : abs(ls[i]-stk[stk.size()-1])); stk.push_back(A[i]); }else{ while(A[i]<=stk[stk.size()-1]){ stk.erase(stk.begin()+stk.size()-1); } //cout << stk[stk.size()-1] << \\\" \\\"; res = (res > abs(ls[i]-stk[stk.size()-1]) ? res : abs(ls[i]-stk[stk.size()-1])); stk.push_back(A[i]); } } return res;\"\n },\n {\n \"code\": null,\n \"e\": 6956,\n \"s\": 6954,\n \"text\": \"0\"\n },\n {\n \"code\": null,\n \"e\": 6964,\n \"s\": 6956,\n \"text\": \"21mx126\"\n },\n {\n \"code\": null,\n \"e\": 6990,\n \"s\": 6964,\n \"text\": \"This comment was deleted.\"\n },\n {\n \"code\": null,\n \"e\": 6992,\n \"s\": 6990,\n \"text\": \"0\"\n },\n {\n \"code\": null,\n \"e\": 7015,\n \"s\": 6992,\n \"text\": \"onlybkm20021 month ago\"\n },\n {\n \"code\": null,\n \"e\": 8030,\n \"s\": 7015,\n \"text\": \"int findMaxDiff(int A[], int n)\\n {\\n stack st1;\\n stack st2;\\n vector ls(n,0);\\n vector rs(n,0);\\n for(int i=n-1; i>=0; i--)\\n {\\n while(!st1.empty() && st1.top()>=A[i])\\n {\\n st1.pop();\\n }\\n if(i=A[i])\\n {\\n st2.pop();\\n }\\n if(i diff(n);\\n for(int i=0; ist=new Stack<>(); findls(ls,arr,st,n); st=new Stack<>(); findrs(rs,arr,st,n); // System.out.println(Arrays.toString(ls)); int max=Integer.MIN_VALUE; for(int i=0;imax)max=t; } return max; } public static void findls(Integer[]ans,int[]arr,Stackst,int n) { ans[0]=0; st.push(arr[0]); for(int i=1;i0 && st.peek()0 && st.peek()>=arr[i]) { st.pop(); } if(st.size()==0) { ans[i]=0; st.push(arr[i]); } else{ ans[i]=st.peek(); st.push(arr[i]); } } } } } public static void findrs(Integer[]ans,int[]arr,Stackst,int n){ ans[n-1]=0; st.push(arr[n-1]); for(int i=n-2;i>=0;i--) { if(st.peek()0 && st.peek()>=arr[i]) { st.pop(); } if(st.size()==0) { ans[i]=0; st.push(arr[i]); }else{ ans[i]=st.peek(); st.push(arr[i]); } } } }}\"\n },\n {\n \"code\": null,\n \"e\": 10069,\n \"s\": 10067,\n \"text\": \"0\"\n },\n {\n \"code\": null,\n \"e\": 10100,\n \"s\": 10069,\n \"text\": \"shubhankardey29sep2 months ago\"\n },\n {\n \"code\": null,\n \"e\": 11365,\n \"s\": 10100,\n \"text\": \"class Solution\\n{\\n int findMaxDiff(int a[], int n)\\n {\\n\\t// Your code here\\t\\n\\tint []r1 = nsl(a,n);\\n\\tint []r2 = nsr(a,n);\\n\\tint max = 0;\\n\\t\\n\\tfor(int i=0;i st = new Stack<>();\\n int []res = new int[n];\\n res[0] = 0;\\n st.push(a[0]);\\n int idx = 1;\\n for(int i=1;i=a[i])\\n st.pop();\\n \\n if(st.size()==0)\\n res[idx++] = 0;\\n \\n else\\n res[idx++] = st.peek();\\n \\n st.push(a[i]);\\n }\\n return res;\\n }\\n int[] nsr(int []a,int n)\\n {\\n Stack st = new Stack<>();\\n int []res = new int[n];\\n res[n-1] = 0;\\n st.push(a[n-1]);\\n int idx = n-2;\\n for(int i=n-2;i>=0;i--)\\n {\\n while(!st.isEmpty() && st.peek()>=a[i])\\n st.pop();\\n \\n if(st.size()==0)\\n res[idx--] = 0;\\n \\n else\\n res[idx--] = st.peek();\\n \\n st.push(a[i]);\\n }\\n return res;\\n }\\n}\"\n },\n {\n \"code\": null,\n \"e\": 11511,\n \"s\": 11365,\n \"text\": \"We strongly recommend solving this problem on your own before viewing its editorial. Do you still\\n want to view the editorial?\"\n },\n {\n \"code\": null,\n \"e\": 11547,\n \"s\": 11511,\n \"text\": \" Login to access your submissions. \"\n },\n {\n \"code\": null,\n \"e\": 11557,\n \"s\": 11547,\n \"text\": \"\\nProblem\\n\"\n },\n {\n \"code\": null,\n \"e\": 11567,\n \"s\": 11557,\n \"text\": \"\\nContest\\n\"\n },\n {\n \"code\": null,\n \"e\": 11630,\n \"s\": 11567,\n \"text\": \"Reset the IDE using the second button on the top right corner.\"\n },\n {\n \"code\": null,\n \"e\": 11815,\n \"s\": 11630,\n \"text\": \"Avoid using static/global variables in your code as your code is tested \\n against multiple test cases and these tend to retain their previous values.\"\n },\n {\n \"code\": null,\n \"e\": 12099,\n \"s\": 11815,\n \"text\": \"Passing the Sample/Custom Test cases does not guarantee the correctness of code.\\n On submission, your code is tested against multiple test cases consisting of all\\n possible corner cases and stress constraints.\"\n },\n {\n \"code\": null,\n \"e\": 12245,\n \"s\": 12099,\n \"text\": \"You can access the hints to get an idea about what is expected of you as well as\\n the final solution code.\"\n },\n {\n \"code\": null,\n \"e\": 12322,\n \"s\": 12245,\n \"text\": \"You can view the solutions submitted by other users from the submission tab.\"\n },\n {\n \"code\": null,\n \"e\": 12363,\n \"s\": 12322,\n \"text\": \"Make sure you are not using ad-blockers.\"\n },\n {\n \"code\": null,\n \"e\": 12391,\n \"s\": 12363,\n \"text\": \"Disable browser extensions.\"\n },\n {\n \"code\": null,\n \"e\": 12462,\n \"s\": 12391,\n \"text\": \"We recommend using latest version of your browser for best experience.\"\n },\n {\n \"code\": null,\n \"e\": 12649,\n \"s\": 12462,\n \"text\": \"Avoid using static/global variables in coding problems as your code is tested \\n against multiple test cases and these tend to retain their previous values.\"\n }\n]"}}},{"rowIdx":162,"cells":{"title":{"kind":"string","value":"Use of min() and max() in Python"},"text":{"kind":"string","value":"06 Jun, 2021\nPrerequisite: min() max() in Python Let’s see some interesting facts about min() and max() function. These functions are used to compute the maximum and minimum of the values as passed in its argument. or it gives the lexicographically largest value and lexicographically smallest value respectively, when we passed string or list of strings as arguments. \npython3\nl= [\"ab\", \"abc\", \"abd\", \"b\"] l1=\"abc\" # prints 'b'print(max(l)) # prints 'ab'print(min(l)) #prints 'c'print(max(l1)) #prints 'a'print(min(l1))\nHere you notice that output comes according to lexicographical order. but we can also find output according to length of string or as our requirement by simply passing function name or lambda expression. Parameters: By default, min() and max() doesn’t require any extra parameters. however, it has an optional parameters: \nkey – function that serves as a key for the min/max comparison \n \nSyntax: max(x1, x2, ..., xn, key=function_name)here x1, x2, x3.., xn passed arguments function_name : denotes which type of operation you want to perform on these arguments. Let function_name=len, so now output gives according to length of x1, x2.., xn. \nReturn value: \nIt returns a maximum or minimum of list according to the passed parameter.\n \nPython3\n# Python code explaining min() and max()l = [\"ab\", \"abc\", \"bc\", \"c\"] print(max(l, key = len))print(min(l, key = len))\nabc\nc\n \nExplanation: In the above program, max() function takes two arguments: l(list) and key = len(function_name).this key = len(function_name) function transforms each element before comparing, it takes the value and returns 1 value which is then used within max() or min() instead of the original value.Here key convert each element of the list to its length and then compare each element according to its length. \ninitially l = [“ab”, “abc”, “bc”, “c”] when we passed key=len as arguments then it works like l=[2,3,2,1] \n \n \nPython3\n# Python code explaining min() and max()def fun(element): return(len(element)) l =[\"ab\", \"abc\", \"bc\", \"c\"]print(max(l, key = fun)) # you can also write in this formprint(max(l, key = lambda element:len(element)))\nabc\nabc\n \nAnother example: \nPython3\n# Python code explaining min() and max()l = [{'name':'ramu', 'score':90, 'age':24}, {'name':'golu', 'score':70, 'age':19}] # here anonymous function takes item as an argument.print(max(l, key = lambda item:item.get('age')))\n{'age': 24, 'score': 90, 'name': 'ramu'}\n \nSimilar we can use min() function instead of max() function as per requirement. \nrrlinus\nAkanksha_Rai\nsimmytarika5\nPython function-programs\nPython\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nPython Dictionary\nDifferent ways to create Pandas Dataframe\nEnumerate() in Python\nPython String | replace()\nHow to Install PIP on Windows ?\n*args and **kwargs in Python\nPython Classes and Objects\nPython OOPs Concepts\nConvert integer to string in Python\nIntroduction To PYTHON"},"parsed":{"kind":"list like","value":[{"code":null,"e":52,"s":24,"text":"\n06 Jun, 2021"},{"code":null,"e":409,"s":52,"text":"Prerequisite: min() max() in Python Let’s see some interesting facts about min() and max() function. These functions are used to compute the maximum and minimum of the values as passed in its argument. or it gives the lexicographically largest value and lexicographically smallest value respectively, when we passed string or list of strings as arguments. "},{"code":null,"e":417,"s":409,"text":"python3"},{"code":"l= [\"ab\", \"abc\", \"abd\", \"b\"] l1=\"abc\" # prints 'b'print(max(l)) # prints 'ab'print(min(l)) #prints 'c'print(max(l1)) #prints 'a'print(min(l1))","e":560,"s":417,"text":null},{"code":null,"e":883,"s":560,"text":"Here you notice that output comes according to lexicographical order. but we can also find output according to length of string or as our requirement by simply passing function name or lambda expression. Parameters: By default, min() and max() doesn’t require any extra parameters. however, it has an optional parameters: "},{"code":null,"e":947,"s":883,"text":"key – function that serves as a key for the min/max comparison "},{"code":null,"e":1205,"s":949,"text":"Syntax: max(x1, x2, ..., xn, key=function_name)here x1, x2, x3.., xn passed arguments function_name : denotes which type of operation you want to perform on these arguments. Let function_name=len, so now output gives according to length of x1, x2.., xn. "},{"code":null,"e":1221,"s":1205,"text":"Return value: "},{"code":null,"e":1296,"s":1221,"text":"It returns a maximum or minimum of list according to the passed parameter."},{"code":null,"e":1306,"s":1298,"text":"Python3"},{"code":"# Python code explaining min() and max()l = [\"ab\", \"abc\", \"bc\", \"c\"] print(max(l, key = len))print(min(l, key = len))","e":1424,"s":1306,"text":null},{"code":null,"e":1430,"s":1424,"text":"abc\nc"},{"code":null,"e":1843,"s":1432,"text":"Explanation: In the above program, max() function takes two arguments: l(list) and key = len(function_name).this key = len(function_name) function transforms each element before comparing, it takes the value and returns 1 value which is then used within max() or min() instead of the original value.Here key convert each element of the list to its length and then compare each element according to its length. "},{"code":null,"e":1950,"s":1843,"text":"initially l = [“ab”, “abc”, “bc”, “c”] when we passed key=len as arguments then it works like l=[2,3,2,1] "},{"code":null,"e":1962,"s":1954,"text":"Python3"},{"code":"# Python code explaining min() and max()def fun(element): return(len(element)) l =[\"ab\", \"abc\", \"bc\", \"c\"]print(max(l, key = fun)) # you can also write in this formprint(max(l, key = lambda element:len(element)))","e":2178,"s":1962,"text":null},{"code":null,"e":2186,"s":2178,"text":"abc\nabc"},{"code":null,"e":2207,"s":2188,"text":"Another example: "},{"code":null,"e":2215,"s":2207,"text":"Python3"},{"code":"# Python code explaining min() and max()l = [{'name':'ramu', 'score':90, 'age':24}, {'name':'golu', 'score':70, 'age':19}] # here anonymous function takes item as an argument.print(max(l, key = lambda item:item.get('age')))","e":2443,"s":2215,"text":null},{"code":null,"e":2484,"s":2443,"text":"{'age': 24, 'score': 90, 'name': 'ramu'}"},{"code":null,"e":2567,"s":2486,"text":"Similar we can use min() function instead of max() function as per requirement. "},{"code":null,"e":2575,"s":2567,"text":"rrlinus"},{"code":null,"e":2588,"s":2575,"text":"Akanksha_Rai"},{"code":null,"e":2601,"s":2588,"text":"simmytarika5"},{"code":null,"e":2626,"s":2601,"text":"Python function-programs"},{"code":null,"e":2633,"s":2626,"text":"Python"},{"code":null,"e":2731,"s":2633,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":2749,"s":2731,"text":"Python Dictionary"},{"code":null,"e":2791,"s":2749,"text":"Different ways to create Pandas Dataframe"},{"code":null,"e":2813,"s":2791,"text":"Enumerate() in Python"},{"code":null,"e":2839,"s":2813,"text":"Python String | replace()"},{"code":null,"e":2871,"s":2839,"text":"How to Install PIP on Windows ?"},{"code":null,"e":2900,"s":2871,"text":"*args and **kwargs in Python"},{"code":null,"e":2927,"s":2900,"text":"Python Classes and Objects"},{"code":null,"e":2948,"s":2927,"text":"Python OOPs Concepts"},{"code":null,"e":2984,"s":2948,"text":"Convert integer to string in Python"}],"string":"[\n {\n \"code\": null,\n \"e\": 52,\n \"s\": 24,\n \"text\": \"\\n06 Jun, 2021\"\n },\n {\n \"code\": null,\n \"e\": 409,\n \"s\": 52,\n \"text\": \"Prerequisite: min() max() in Python Let’s see some interesting facts about min() and max() function. These functions are used to compute the maximum and minimum of the values as passed in its argument. or it gives the lexicographically largest value and lexicographically smallest value respectively, when we passed string or list of strings as arguments. \"\n },\n {\n \"code\": null,\n \"e\": 417,\n \"s\": 409,\n \"text\": \"python3\"\n },\n {\n \"code\": \"l= [\\\"ab\\\", \\\"abc\\\", \\\"abd\\\", \\\"b\\\"] l1=\\\"abc\\\" # prints 'b'print(max(l)) # prints 'ab'print(min(l)) #prints 'c'print(max(l1)) #prints 'a'print(min(l1))\",\n \"e\": 560,\n \"s\": 417,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 883,\n \"s\": 560,\n \"text\": \"Here you notice that output comes according to lexicographical order. but we can also find output according to length of string or as our requirement by simply passing function name or lambda expression. Parameters: By default, min() and max() doesn’t require any extra parameters. however, it has an optional parameters: \"\n },\n {\n \"code\": null,\n \"e\": 947,\n \"s\": 883,\n \"text\": \"key – function that serves as a key for the min/max comparison \"\n },\n {\n \"code\": null,\n \"e\": 1205,\n \"s\": 949,\n \"text\": \"Syntax: max(x1, x2, ..., xn, key=function_name)here x1, x2, x3.., xn passed arguments function_name : denotes which type of operation you want to perform on these arguments. Let function_name=len, so now output gives according to length of x1, x2.., xn. \"\n },\n {\n \"code\": null,\n \"e\": 1221,\n \"s\": 1205,\n \"text\": \"Return value: \"\n },\n {\n \"code\": null,\n \"e\": 1296,\n \"s\": 1221,\n \"text\": \"It returns a maximum or minimum of list according to the passed parameter.\"\n },\n {\n \"code\": null,\n \"e\": 1306,\n \"s\": 1298,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"# Python code explaining min() and max()l = [\\\"ab\\\", \\\"abc\\\", \\\"bc\\\", \\\"c\\\"] print(max(l, key = len))print(min(l, key = len))\",\n \"e\": 1424,\n \"s\": 1306,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 1430,\n \"s\": 1424,\n \"text\": \"abc\\nc\"\n },\n {\n \"code\": null,\n \"e\": 1843,\n \"s\": 1432,\n \"text\": \"Explanation: In the above program, max() function takes two arguments: l(list) and key = len(function_name).this key = len(function_name) function transforms each element before comparing, it takes the value and returns 1 value which is then used within max() or min() instead of the original value.Here key convert each element of the list to its length and then compare each element according to its length. \"\n },\n {\n \"code\": null,\n \"e\": 1950,\n \"s\": 1843,\n \"text\": \"initially l = [“ab”, “abc”, “bc”, “c”] when we passed key=len as arguments then it works like l=[2,3,2,1] \"\n },\n {\n \"code\": null,\n \"e\": 1962,\n \"s\": 1954,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"# Python code explaining min() and max()def fun(element): return(len(element)) l =[\\\"ab\\\", \\\"abc\\\", \\\"bc\\\", \\\"c\\\"]print(max(l, key = fun)) # you can also write in this formprint(max(l, key = lambda element:len(element)))\",\n \"e\": 2178,\n \"s\": 1962,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 2186,\n \"s\": 2178,\n \"text\": \"abc\\nabc\"\n },\n {\n \"code\": null,\n \"e\": 2207,\n \"s\": 2188,\n \"text\": \"Another example: \"\n },\n {\n \"code\": null,\n \"e\": 2215,\n \"s\": 2207,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"# Python code explaining min() and max()l = [{'name':'ramu', 'score':90, 'age':24}, {'name':'golu', 'score':70, 'age':19}] # here anonymous function takes item as an argument.print(max(l, key = lambda item:item.get('age')))\",\n \"e\": 2443,\n \"s\": 2215,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 2484,\n \"s\": 2443,\n \"text\": \"{'age': 24, 'score': 90, 'name': 'ramu'}\"\n },\n {\n \"code\": null,\n \"e\": 2567,\n \"s\": 2486,\n \"text\": \"Similar we can use min() function instead of max() function as per requirement. \"\n },\n {\n \"code\": null,\n \"e\": 2575,\n \"s\": 2567,\n \"text\": \"rrlinus\"\n },\n {\n \"code\": null,\n \"e\": 2588,\n \"s\": 2575,\n \"text\": \"Akanksha_Rai\"\n },\n {\n \"code\": null,\n \"e\": 2601,\n \"s\": 2588,\n \"text\": \"simmytarika5\"\n },\n {\n \"code\": null,\n \"e\": 2626,\n \"s\": 2601,\n \"text\": \"Python function-programs\"\n },\n {\n \"code\": null,\n \"e\": 2633,\n \"s\": 2626,\n \"text\": \"Python\"\n },\n {\n \"code\": null,\n \"e\": 2731,\n \"s\": 2633,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 2749,\n \"s\": 2731,\n \"text\": \"Python Dictionary\"\n },\n {\n \"code\": null,\n \"e\": 2791,\n \"s\": 2749,\n \"text\": \"Different ways to create Pandas Dataframe\"\n },\n {\n \"code\": null,\n \"e\": 2813,\n \"s\": 2791,\n \"text\": \"Enumerate() in Python\"\n },\n {\n \"code\": null,\n \"e\": 2839,\n \"s\": 2813,\n \"text\": \"Python String | replace()\"\n },\n {\n \"code\": null,\n \"e\": 2871,\n \"s\": 2839,\n \"text\": \"How to Install PIP on Windows ?\"\n },\n {\n \"code\": null,\n \"e\": 2900,\n \"s\": 2871,\n \"text\": \"*args and **kwargs in Python\"\n },\n {\n \"code\": null,\n \"e\": 2927,\n \"s\": 2900,\n \"text\": \"Python Classes and Objects\"\n },\n {\n \"code\": null,\n \"e\": 2948,\n \"s\": 2927,\n \"text\": \"Python OOPs Concepts\"\n },\n {\n \"code\": null,\n \"e\": 2984,\n \"s\": 2948,\n \"text\": \"Convert integer to string in Python\"\n }\n]"}}},{"rowIdx":163,"cells":{"title":{"kind":"string","value":"Modify given array to make sum of odd and even indexed elements same"},"text":{"kind":"string","value":"10 Sep, 2021\nGiven a binary array arr[] of size N, remove at most N/2 elements from the array such that the sum of elements at odd and even indices becomes equal. The task is to print the modified array.Note: N is always even. There can be more than one possible result, print any of them.\nExamples: \nInput: arr[] = {1, 1, 1, 0}Output: 1 1Explanation:For the given array arr[] = {1, 1, 1, 0}The sum of elements at odd position, Odd_Sum = arr[1] + arr[3] = 1 + 1 = 2.The sum of elements at even position, Even_Sum = arr[2] + arr[4] = 1 + 0 = 1.Since Odd_Sum & Even_Sum are not equal, remove some elements to make them equal.After removing arr[3] and arr[4] the array become arr[] = {1, 1} such that sum of elements at odd indices and even indices are equal.\nInput: arr[] = {1, 0}Output: 0Explanation:For the given array arr[] = {1, 0}The sum of elements at odd position, Odd_Sum = arr[1] = 0 = 0.The sum of elements at even position, Even_Sum = 1 = 1.Since Odd_Sum & Even_Sum are not equal, remove some elements to make them equal.After removing arr[0] the array become arr[] = {0} such that sum of elements at odd indices and even indices are equal.\nApproach: The idea is to count the number of 1s and 0s in the given array and then make the resultant sum equal by the following steps: \nCount the number of 0s and 1s in the given array arr[] and store them in variables say count_0 and count_1 respectively.If the sum of the elements at odd and even indices are equal, then no need to remove any array element. Print the original array as the answer.If count_0 ≥ N/2, then remove all 1s and print all the zeros count_0 number of times.Otherwise, if count_0 < N/2, by removing all the 0s, the sum of even and odd indices can be made the same as per the following conditions: If count_1 is odd, then print 1 as an element of the new array (count_1 – 1) number of times.Otherwise, print 1 as an element of the new array count_1 number of times.Print the resultant array as per the above conditions.\nCount the number of 0s and 1s in the given array arr[] and store them in variables say count_0 and count_1 respectively.\nIf the sum of the elements at odd and even indices are equal, then no need to remove any array element. Print the original array as the answer.\nIf count_0 ≥ N/2, then remove all 1s and print all the zeros count_0 number of times.\nOtherwise, if count_0 < N/2, by removing all the 0s, the sum of even and odd indices can be made the same as per the following conditions: If count_1 is odd, then print 1 as an element of the new array (count_1 – 1) number of times.Otherwise, print 1 as an element of the new array count_1 number of times.\nIf count_1 is odd, then print 1 as an element of the new array (count_1 – 1) number of times.\nOtherwise, print 1 as an element of the new array count_1 number of times.\nPrint the resultant array as per the above conditions.\nBelow is the implementation of the above approach:\nC++\nC\nJava\nPython3\nC#\nJavascript\n// C++ program for the above approach#include using namespace std; // Function to modify array to make// sum of odd and even indexed// elements equalvoid makeArraySumEqual(int a[], int N){ // Stores the count of 0s, 1s int count_0 = 0, count_1 = 0; // Stores sum of odd and even // indexed elements respectively int odd_sum = 0, even_sum = 0; for (int i = 0; i < N; i++) { // Count 0s if (a[i] == 0) count_0++; // Count 1s else count_1++; // Calculate odd_sum and even_sum if ((i + 1) % 2 == 0) even_sum += a[i]; else if ((i + 1) % 2 > 0) odd_sum += a[i]; } // If both are equal if (odd_sum == even_sum) { // Print the original array for (int i = 0; i < N; i++) cout <<\" \"<< a[i]; } // Otherwise else { if (count_0 >= N / 2) { // Print all the 0s for (int i = 0; i < count_0; i++) cout <<\"0 \"; } else { // For checking even or odd int is_Odd = count_1 % 2; // Update total count of 1s count_1 -= is_Odd; // Print all 1s for (int i = 0; i < count_1; i++) cout <<\"1 \"; } }} // Driver Codeint main(){ // Given array arr[] int arr[] = { 1, 1, 1, 0 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call makeArraySumEqual(arr, N); return 0;} // This code is contributed by shivanisinghss2110.\n// C++ program for the above approach #include // Function to modify array to make// sum of odd and even indexed// elements equalvoid makeArraySumEqual(int a[], int N){ // Stores the count of 0s, 1s int count_0 = 0, count_1 = 0; // Stores sum of odd and even // indexed elements respectively int odd_sum = 0, even_sum = 0; for (int i = 0; i < N; i++) { // Count 0s if (a[i] == 0) count_0++; // Count 1s else count_1++; // Calculate odd_sum and even_sum if ((i + 1) % 2 == 0) even_sum += a[i]; else if ((i + 1) % 2 > 0) odd_sum += a[i]; } // If both are equal if (odd_sum == even_sum) { // Print the original array for (int i = 0; i < N; i++) printf(\"%d \", a[i]); } // Otherwise else { if (count_0 >= N / 2) { // Print all the 0s for (int i = 0; i < count_0; i++) printf(\"0 \"); } else { // For checking even or odd int is_Odd = count_1 % 2; // Update total count of 1s count_1 -= is_Odd; // Print all 1s for (int i = 0; i < count_1; i++) printf(\"1 \"); } }} // Driver Codeint main(){ // Given array arr[] int arr[] = { 1, 1, 1, 0 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call makeArraySumEqual(arr, N); return 0;}\n// Java program for the above approach class GFG { // Function to modify array to make // sum of odd and even indexed // elements equal static void makeArraySumEqual(int a[], int N) { // Stores the count of 0s, 1s int count_0 = 0, count_1 = 0; // Stores sum of odd and even // indexed elements respectively int odd_sum = 0, even_sum = 0; for (int i = 0; i < N; i++) { // Count 0s if (a[i] == 0) count_0++; // Count 1s else count_1++; // Calculate odd_sum and even_sum if ((i + 1) % 2 == 0) even_sum += a[i]; else if ((i + 1) % 2 > 0) odd_sum += a[i]; } // If both are equal if (odd_sum == even_sum) { // Print the original array for (int i = 0; i < N; i++) System.out.print(a[i] + \" \"); } else { if (count_0 >= N / 2) { // Print all the 0s for (int i = 0; i < count_0; i++) System.out.print(\"0 \"); } else { // For checking even or odd int is_Odd = count_1 % 2; // Update total count of 1s count_1 -= is_Odd; // Print all 1s for (int i = 0; i < count_1; i++) System.out.print(\"1 \"); } } } // Driver Code public static void main(String[] args) { // Given array arr[] int arr[] = { 1, 1, 1, 0 }; int N = arr.length; // Function Call makeArraySumEqual(arr, N); }}\n# Python3 program for the above approach # Function to modify array to make# sum of odd and even indexed# elements equaldef makeArraySumEqual(a, N): # Stores the count of 0s, 1s count_0 = 0 count_1 = 0 # Stores sum of odd and even # indexed elements respectively odd_sum = 0 even_sum = 0 for i in range(N): # Count 0s if (a[i] == 0): count_0 += 1 # Count 1s else: count_1 += 1 # Calculate odd_sum and even_sum if ((i + 1) % 2 == 0): even_sum += a[i] elif ((i + 1) % 2 > 0): odd_sum += a[i] # If both are equal if (odd_sum == even_sum): # Print the original array for i in range(N): print(a[i], end = \" \") # Otherwise else: if (count_0 >= N / 2): # Print all the 0s for i in range(count_0): print(\"0\", end = \" \") else: # For checking even or odd is_Odd = count_1 % 2 # Update total count of 1s count_1 -= is_Odd # Print all 1s for i in range(count_1): print(\"1\", end = \" \") # Driver Code # Given array arr[]arr = [ 1, 1, 1, 0 ] N = len(arr) # Function callmakeArraySumEqual(arr, N) # This code is contributed by code_hunt\n// C# program for// the above approachusing System;class GFG{ // Function to modify array to make// sum of odd and even indexed// elements equalstatic void makeArraySumEqual(int []a, int N){ // Stores the count of 0s, 1s int count_0 = 0, count_1 = 0; // Stores sum of odd and even // indexed elements respectively int odd_sum = 0, even_sum = 0; for (int i = 0; i < N; i++) { // Count 0s if (a[i] == 0) count_0++; // Count 1s else count_1++; // Calculate odd_sum and even_sum if ((i + 1) % 2 == 0) even_sum += a[i]; else if ((i + 1) % 2 > 0) odd_sum += a[i]; } // If both are equal if (odd_sum == even_sum) { // Print the original array for (int i = 0; i < N; i++) Console.Write(a[i] + \" \"); } else { if (count_0 >= N / 2) { // Print all the 0s for (int i = 0; i < count_0; i++) Console.Write(\"0 \"); } else { // For checking even or odd int is_Odd = count_1 % 2; // Update total count of 1s count_1 -= is_Odd; // Print all 1s for (int i = 0; i < count_1; i++) Console.Write(\"1 \"); } }} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []arr = {1, 1, 1, 0}; int N = arr.Length; // Function Call makeArraySumEqual(arr, N);}} // This code is contributed by 29AjayKumar\n\n1 1\n \nTime Complexity: O(N)Auxiliary Space: O(1)\naimformohan\n29AjayKumar\ncode_hunt\navijitmondal1998\nkhushboogoyal499\nshivanisinghss2110\narray-rearrange\nArrays\nGreedy\nMathematical\nArrays\nGreedy\nMathematical\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},"parsed":{"kind":"list like","value":[{"code":null,"e":54,"s":26,"text":"\n10 Sep, 2021"},{"code":null,"e":331,"s":54,"text":"Given a binary array arr[] of size N, remove at most N/2 elements from the array such that the sum of elements at odd and even indices becomes equal. The task is to print the modified array.Note: N is always even. There can be more than one possible result, print any of them."},{"code":null,"e":342,"s":331,"text":"Examples: "},{"code":null,"e":798,"s":342,"text":"Input: arr[] = {1, 1, 1, 0}Output: 1 1Explanation:For the given array arr[] = {1, 1, 1, 0}The sum of elements at odd position, Odd_Sum = arr[1] + arr[3] = 1 + 1 = 2.The sum of elements at even position, Even_Sum = arr[2] + arr[4] = 1 + 0 = 1.Since Odd_Sum & Even_Sum are not equal, remove some elements to make them equal.After removing arr[3] and arr[4] the array become arr[] = {1, 1} such that sum of elements at odd indices and even indices are equal."},{"code":null,"e":1191,"s":798,"text":"Input: arr[] = {1, 0}Output: 0Explanation:For the given array arr[] = {1, 0}The sum of elements at odd position, Odd_Sum = arr[1] = 0 = 0.The sum of elements at even position, Even_Sum = 1 = 1.Since Odd_Sum & Even_Sum are not equal, remove some elements to make them equal.After removing arr[0] the array become arr[] = {0} such that sum of elements at odd indices and even indices are equal."},{"code":null,"e":1328,"s":1191,"text":"Approach: The idea is to count the number of 1s and 0s in the given array and then make the resultant sum equal by the following steps: "},{"code":null,"e":2037,"s":1328,"text":"Count the number of 0s and 1s in the given array arr[] and store them in variables say count_0 and count_1 respectively.If the sum of the elements at odd and even indices are equal, then no need to remove any array element. Print the original array as the answer.If count_0 ≥ N/2, then remove all 1s and print all the zeros count_0 number of times.Otherwise, if count_0 < N/2, by removing all the 0s, the sum of even and odd indices can be made the same as per the following conditions: If count_1 is odd, then print 1 as an element of the new array (count_1 – 1) number of times.Otherwise, print 1 as an element of the new array count_1 number of times.Print the resultant array as per the above conditions."},{"code":null,"e":2158,"s":2037,"text":"Count the number of 0s and 1s in the given array arr[] and store them in variables say count_0 and count_1 respectively."},{"code":null,"e":2302,"s":2158,"text":"If the sum of the elements at odd and even indices are equal, then no need to remove any array element. Print the original array as the answer."},{"code":null,"e":2388,"s":2302,"text":"If count_0 ≥ N/2, then remove all 1s and print all the zeros count_0 number of times."},{"code":null,"e":2695,"s":2388,"text":"Otherwise, if count_0 < N/2, by removing all the 0s, the sum of even and odd indices can be made the same as per the following conditions: If count_1 is odd, then print 1 as an element of the new array (count_1 – 1) number of times.Otherwise, print 1 as an element of the new array count_1 number of times."},{"code":null,"e":2789,"s":2695,"text":"If count_1 is odd, then print 1 as an element of the new array (count_1 – 1) number of times."},{"code":null,"e":2864,"s":2789,"text":"Otherwise, print 1 as an element of the new array count_1 number of times."},{"code":null,"e":2919,"s":2864,"text":"Print the resultant array as per the above conditions."},{"code":null,"e":2970,"s":2919,"text":"Below is the implementation of the above approach:"},{"code":null,"e":2974,"s":2970,"text":"C++"},{"code":null,"e":2976,"s":2974,"text":"C"},{"code":null,"e":2981,"s":2976,"text":"Java"},{"code":null,"e":2989,"s":2981,"text":"Python3"},{"code":null,"e":2992,"s":2989,"text":"C#"},{"code":null,"e":3003,"s":2992,"text":"Javascript"},{"code":"// C++ program for the above approach#include using namespace std; // Function to modify array to make// sum of odd and even indexed// elements equalvoid makeArraySumEqual(int a[], int N){ // Stores the count of 0s, 1s int count_0 = 0, count_1 = 0; // Stores sum of odd and even // indexed elements respectively int odd_sum = 0, even_sum = 0; for (int i = 0; i < N; i++) { // Count 0s if (a[i] == 0) count_0++; // Count 1s else count_1++; // Calculate odd_sum and even_sum if ((i + 1) % 2 == 0) even_sum += a[i]; else if ((i + 1) % 2 > 0) odd_sum += a[i]; } // If both are equal if (odd_sum == even_sum) { // Print the original array for (int i = 0; i < N; i++) cout <<\" \"<< a[i]; } // Otherwise else { if (count_0 >= N / 2) { // Print all the 0s for (int i = 0; i < count_0; i++) cout <<\"0 \"; } else { // For checking even or odd int is_Odd = count_1 % 2; // Update total count of 1s count_1 -= is_Odd; // Print all 1s for (int i = 0; i < count_1; i++) cout <<\"1 \"; } }} // Driver Codeint main(){ // Given array arr[] int arr[] = { 1, 1, 1, 0 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call makeArraySumEqual(arr, N); return 0;} // This code is contributed by shivanisinghss2110.","e":4545,"s":3003,"text":null},{"code":"// C++ program for the above approach #include // Function to modify array to make// sum of odd and even indexed// elements equalvoid makeArraySumEqual(int a[], int N){ // Stores the count of 0s, 1s int count_0 = 0, count_1 = 0; // Stores sum of odd and even // indexed elements respectively int odd_sum = 0, even_sum = 0; for (int i = 0; i < N; i++) { // Count 0s if (a[i] == 0) count_0++; // Count 1s else count_1++; // Calculate odd_sum and even_sum if ((i + 1) % 2 == 0) even_sum += a[i]; else if ((i + 1) % 2 > 0) odd_sum += a[i]; } // If both are equal if (odd_sum == even_sum) { // Print the original array for (int i = 0; i < N; i++) printf(\"%d \", a[i]); } // Otherwise else { if (count_0 >= N / 2) { // Print all the 0s for (int i = 0; i < count_0; i++) printf(\"0 \"); } else { // For checking even or odd int is_Odd = count_1 % 2; // Update total count of 1s count_1 -= is_Odd; // Print all 1s for (int i = 0; i < count_1; i++) printf(\"1 \"); } }} // Driver Codeint main(){ // Given array arr[] int arr[] = { 1, 1, 1, 0 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call makeArraySumEqual(arr, N); return 0;}","e":6017,"s":4545,"text":null},{"code":"// Java program for the above approach class GFG { // Function to modify array to make // sum of odd and even indexed // elements equal static void makeArraySumEqual(int a[], int N) { // Stores the count of 0s, 1s int count_0 = 0, count_1 = 0; // Stores sum of odd and even // indexed elements respectively int odd_sum = 0, even_sum = 0; for (int i = 0; i < N; i++) { // Count 0s if (a[i] == 0) count_0++; // Count 1s else count_1++; // Calculate odd_sum and even_sum if ((i + 1) % 2 == 0) even_sum += a[i]; else if ((i + 1) % 2 > 0) odd_sum += a[i]; } // If both are equal if (odd_sum == even_sum) { // Print the original array for (int i = 0; i < N; i++) System.out.print(a[i] + \" \"); } else { if (count_0 >= N / 2) { // Print all the 0s for (int i = 0; i < count_0; i++) System.out.print(\"0 \"); } else { // For checking even or odd int is_Odd = count_1 % 2; // Update total count of 1s count_1 -= is_Odd; // Print all 1s for (int i = 0; i < count_1; i++) System.out.print(\"1 \"); } } } // Driver Code public static void main(String[] args) { // Given array arr[] int arr[] = { 1, 1, 1, 0 }; int N = arr.length; // Function Call makeArraySumEqual(arr, N); }}","e":7727,"s":6017,"text":null},{"code":"# Python3 program for the above approach # Function to modify array to make# sum of odd and even indexed# elements equaldef makeArraySumEqual(a, N): # Stores the count of 0s, 1s count_0 = 0 count_1 = 0 # Stores sum of odd and even # indexed elements respectively odd_sum = 0 even_sum = 0 for i in range(N): # Count 0s if (a[i] == 0): count_0 += 1 # Count 1s else: count_1 += 1 # Calculate odd_sum and even_sum if ((i + 1) % 2 == 0): even_sum += a[i] elif ((i + 1) % 2 > 0): odd_sum += a[i] # If both are equal if (odd_sum == even_sum): # Print the original array for i in range(N): print(a[i], end = \" \") # Otherwise else: if (count_0 >= N / 2): # Print all the 0s for i in range(count_0): print(\"0\", end = \" \") else: # For checking even or odd is_Odd = count_1 % 2 # Update total count of 1s count_1 -= is_Odd # Print all 1s for i in range(count_1): print(\"1\", end = \" \") # Driver Code # Given array arr[]arr = [ 1, 1, 1, 0 ] N = len(arr) # Function callmakeArraySumEqual(arr, N) # This code is contributed by code_hunt","e":9091,"s":7727,"text":null},{"code":"// C# program for// the above approachusing System;class GFG{ // Function to modify array to make// sum of odd and even indexed// elements equalstatic void makeArraySumEqual(int []a, int N){ // Stores the count of 0s, 1s int count_0 = 0, count_1 = 0; // Stores sum of odd and even // indexed elements respectively int odd_sum = 0, even_sum = 0; for (int i = 0; i < N; i++) { // Count 0s if (a[i] == 0) count_0++; // Count 1s else count_1++; // Calculate odd_sum and even_sum if ((i + 1) % 2 == 0) even_sum += a[i]; else if ((i + 1) % 2 > 0) odd_sum += a[i]; } // If both are equal if (odd_sum == even_sum) { // Print the original array for (int i = 0; i < N; i++) Console.Write(a[i] + \" \"); } else { if (count_0 >= N / 2) { // Print all the 0s for (int i = 0; i < count_0; i++) Console.Write(\"0 \"); } else { // For checking even or odd int is_Odd = count_1 % 2; // Update total count of 1s count_1 -= is_Odd; // Print all 1s for (int i = 0; i < count_1; i++) Console.Write(\"1 \"); } }} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []arr = {1, 1, 1, 0}; int N = arr.Length; // Function Call makeArraySumEqual(arr, N);}} // This code is contributed by 29AjayKumar","e":10469,"s":9091,"text":null},{"code":"","e":12152,"s":10469,"text":null},{"code":null,"e":12156,"s":12152,"text":"1 1"},{"code":null,"e":12201,"s":12158,"text":"Time Complexity: O(N)Auxiliary Space: O(1)"},{"code":null,"e":12213,"s":12201,"text":"aimformohan"},{"code":null,"e":12225,"s":12213,"text":"29AjayKumar"},{"code":null,"e":12235,"s":12225,"text":"code_hunt"},{"code":null,"e":12252,"s":12235,"text":"avijitmondal1998"},{"code":null,"e":12269,"s":12252,"text":"khushboogoyal499"},{"code":null,"e":12288,"s":12269,"text":"shivanisinghss2110"},{"code":null,"e":12304,"s":12288,"text":"array-rearrange"},{"code":null,"e":12311,"s":12304,"text":"Arrays"},{"code":null,"e":12318,"s":12311,"text":"Greedy"},{"code":null,"e":12331,"s":12318,"text":"Mathematical"},{"code":null,"e":12338,"s":12331,"text":"Arrays"},{"code":null,"e":12345,"s":12338,"text":"Greedy"},{"code":null,"e":12358,"s":12345,"text":"Mathematical"}],"string":"[\n {\n \"code\": null,\n \"e\": 54,\n \"s\": 26,\n \"text\": \"\\n10 Sep, 2021\"\n },\n {\n \"code\": null,\n \"e\": 331,\n \"s\": 54,\n \"text\": \"Given a binary array arr[] of size N, remove at most N/2 elements from the array such that the sum of elements at odd and even indices becomes equal. The task is to print the modified array.Note: N is always even. There can be more than one possible result, print any of them.\"\n },\n {\n \"code\": null,\n \"e\": 342,\n \"s\": 331,\n \"text\": \"Examples: \"\n },\n {\n \"code\": null,\n \"e\": 798,\n \"s\": 342,\n \"text\": \"Input: arr[] = {1, 1, 1, 0}Output: 1 1Explanation:For the given array arr[] = {1, 1, 1, 0}The sum of elements at odd position, Odd_Sum = arr[1] + arr[3] = 1 + 1 = 2.The sum of elements at even position, Even_Sum = arr[2] + arr[4] = 1 + 0 = 1.Since Odd_Sum & Even_Sum are not equal, remove some elements to make them equal.After removing arr[3] and arr[4] the array become arr[] = {1, 1} such that sum of elements at odd indices and even indices are equal.\"\n },\n {\n \"code\": null,\n \"e\": 1191,\n \"s\": 798,\n \"text\": \"Input: arr[] = {1, 0}Output: 0Explanation:For the given array arr[] = {1, 0}The sum of elements at odd position, Odd_Sum = arr[1] = 0 = 0.The sum of elements at even position, Even_Sum = 1 = 1.Since Odd_Sum & Even_Sum are not equal, remove some elements to make them equal.After removing arr[0] the array become arr[] = {0} such that sum of elements at odd indices and even indices are equal.\"\n },\n {\n \"code\": null,\n \"e\": 1328,\n \"s\": 1191,\n \"text\": \"Approach: The idea is to count the number of 1s and 0s in the given array and then make the resultant sum equal by the following steps: \"\n },\n {\n \"code\": null,\n \"e\": 2037,\n \"s\": 1328,\n \"text\": \"Count the number of 0s and 1s in the given array arr[] and store them in variables say count_0 and count_1 respectively.If the sum of the elements at odd and even indices are equal, then no need to remove any array element. Print the original array as the answer.If count_0 ≥ N/2, then remove all 1s and print all the zeros count_0 number of times.Otherwise, if count_0 < N/2, by removing all the 0s, the sum of even and odd indices can be made the same as per the following conditions: If count_1 is odd, then print 1 as an element of the new array (count_1 – 1) number of times.Otherwise, print 1 as an element of the new array count_1 number of times.Print the resultant array as per the above conditions.\"\n },\n {\n \"code\": null,\n \"e\": 2158,\n \"s\": 2037,\n \"text\": \"Count the number of 0s and 1s in the given array arr[] and store them in variables say count_0 and count_1 respectively.\"\n },\n {\n \"code\": null,\n \"e\": 2302,\n \"s\": 2158,\n \"text\": \"If the sum of the elements at odd and even indices are equal, then no need to remove any array element. Print the original array as the answer.\"\n },\n {\n \"code\": null,\n \"e\": 2388,\n \"s\": 2302,\n \"text\": \"If count_0 ≥ N/2, then remove all 1s and print all the zeros count_0 number of times.\"\n },\n {\n \"code\": null,\n \"e\": 2695,\n \"s\": 2388,\n \"text\": \"Otherwise, if count_0 < N/2, by removing all the 0s, the sum of even and odd indices can be made the same as per the following conditions: If count_1 is odd, then print 1 as an element of the new array (count_1 – 1) number of times.Otherwise, print 1 as an element of the new array count_1 number of times.\"\n },\n {\n \"code\": null,\n \"e\": 2789,\n \"s\": 2695,\n \"text\": \"If count_1 is odd, then print 1 as an element of the new array (count_1 – 1) number of times.\"\n },\n {\n \"code\": null,\n \"e\": 2864,\n \"s\": 2789,\n \"text\": \"Otherwise, print 1 as an element of the new array count_1 number of times.\"\n },\n {\n \"code\": null,\n \"e\": 2919,\n \"s\": 2864,\n \"text\": \"Print the resultant array as per the above conditions.\"\n },\n {\n \"code\": null,\n \"e\": 2970,\n \"s\": 2919,\n \"text\": \"Below is the implementation of the above approach:\"\n },\n {\n \"code\": null,\n \"e\": 2974,\n \"s\": 2970,\n \"text\": \"C++\"\n },\n {\n \"code\": null,\n \"e\": 2976,\n \"s\": 2974,\n \"text\": \"C\"\n },\n {\n \"code\": null,\n \"e\": 2981,\n \"s\": 2976,\n \"text\": \"Java\"\n },\n {\n \"code\": null,\n \"e\": 2989,\n \"s\": 2981,\n \"text\": \"Python3\"\n },\n {\n \"code\": null,\n \"e\": 2992,\n \"s\": 2989,\n \"text\": \"C#\"\n },\n {\n \"code\": null,\n \"e\": 3003,\n \"s\": 2992,\n \"text\": \"Javascript\"\n },\n {\n \"code\": \"// C++ program for the above approach#include using namespace std; // Function to modify array to make// sum of odd and even indexed// elements equalvoid makeArraySumEqual(int a[], int N){ // Stores the count of 0s, 1s int count_0 = 0, count_1 = 0; // Stores sum of odd and even // indexed elements respectively int odd_sum = 0, even_sum = 0; for (int i = 0; i < N; i++) { // Count 0s if (a[i] == 0) count_0++; // Count 1s else count_1++; // Calculate odd_sum and even_sum if ((i + 1) % 2 == 0) even_sum += a[i]; else if ((i + 1) % 2 > 0) odd_sum += a[i]; } // If both are equal if (odd_sum == even_sum) { // Print the original array for (int i = 0; i < N; i++) cout <<\\\" \\\"<< a[i]; } // Otherwise else { if (count_0 >= N / 2) { // Print all the 0s for (int i = 0; i < count_0; i++) cout <<\\\"0 \\\"; } else { // For checking even or odd int is_Odd = count_1 % 2; // Update total count of 1s count_1 -= is_Odd; // Print all 1s for (int i = 0; i < count_1; i++) cout <<\\\"1 \\\"; } }} // Driver Codeint main(){ // Given array arr[] int arr[] = { 1, 1, 1, 0 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call makeArraySumEqual(arr, N); return 0;} // This code is contributed by shivanisinghss2110.\",\n \"e\": 4545,\n \"s\": 3003,\n \"text\": null\n },\n {\n \"code\": \"// C++ program for the above approach #include // Function to modify array to make// sum of odd and even indexed// elements equalvoid makeArraySumEqual(int a[], int N){ // Stores the count of 0s, 1s int count_0 = 0, count_1 = 0; // Stores sum of odd and even // indexed elements respectively int odd_sum = 0, even_sum = 0; for (int i = 0; i < N; i++) { // Count 0s if (a[i] == 0) count_0++; // Count 1s else count_1++; // Calculate odd_sum and even_sum if ((i + 1) % 2 == 0) even_sum += a[i]; else if ((i + 1) % 2 > 0) odd_sum += a[i]; } // If both are equal if (odd_sum == even_sum) { // Print the original array for (int i = 0; i < N; i++) printf(\\\"%d \\\", a[i]); } // Otherwise else { if (count_0 >= N / 2) { // Print all the 0s for (int i = 0; i < count_0; i++) printf(\\\"0 \\\"); } else { // For checking even or odd int is_Odd = count_1 % 2; // Update total count of 1s count_1 -= is_Odd; // Print all 1s for (int i = 0; i < count_1; i++) printf(\\\"1 \\\"); } }} // Driver Codeint main(){ // Given array arr[] int arr[] = { 1, 1, 1, 0 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call makeArraySumEqual(arr, N); return 0;}\",\n \"e\": 6017,\n \"s\": 4545,\n \"text\": null\n },\n {\n \"code\": \"// Java program for the above approach class GFG { // Function to modify array to make // sum of odd and even indexed // elements equal static void makeArraySumEqual(int a[], int N) { // Stores the count of 0s, 1s int count_0 = 0, count_1 = 0; // Stores sum of odd and even // indexed elements respectively int odd_sum = 0, even_sum = 0; for (int i = 0; i < N; i++) { // Count 0s if (a[i] == 0) count_0++; // Count 1s else count_1++; // Calculate odd_sum and even_sum if ((i + 1) % 2 == 0) even_sum += a[i]; else if ((i + 1) % 2 > 0) odd_sum += a[i]; } // If both are equal if (odd_sum == even_sum) { // Print the original array for (int i = 0; i < N; i++) System.out.print(a[i] + \\\" \\\"); } else { if (count_0 >= N / 2) { // Print all the 0s for (int i = 0; i < count_0; i++) System.out.print(\\\"0 \\\"); } else { // For checking even or odd int is_Odd = count_1 % 2; // Update total count of 1s count_1 -= is_Odd; // Print all 1s for (int i = 0; i < count_1; i++) System.out.print(\\\"1 \\\"); } } } // Driver Code public static void main(String[] args) { // Given array arr[] int arr[] = { 1, 1, 1, 0 }; int N = arr.length; // Function Call makeArraySumEqual(arr, N); }}\",\n \"e\": 7727,\n \"s\": 6017,\n \"text\": null\n },\n {\n \"code\": \"# Python3 program for the above approach # Function to modify array to make# sum of odd and even indexed# elements equaldef makeArraySumEqual(a, N): # Stores the count of 0s, 1s count_0 = 0 count_1 = 0 # Stores sum of odd and even # indexed elements respectively odd_sum = 0 even_sum = 0 for i in range(N): # Count 0s if (a[i] == 0): count_0 += 1 # Count 1s else: count_1 += 1 # Calculate odd_sum and even_sum if ((i + 1) % 2 == 0): even_sum += a[i] elif ((i + 1) % 2 > 0): odd_sum += a[i] # If both are equal if (odd_sum == even_sum): # Print the original array for i in range(N): print(a[i], end = \\\" \\\") # Otherwise else: if (count_0 >= N / 2): # Print all the 0s for i in range(count_0): print(\\\"0\\\", end = \\\" \\\") else: # For checking even or odd is_Odd = count_1 % 2 # Update total count of 1s count_1 -= is_Odd # Print all 1s for i in range(count_1): print(\\\"1\\\", end = \\\" \\\") # Driver Code # Given array arr[]arr = [ 1, 1, 1, 0 ] N = len(arr) # Function callmakeArraySumEqual(arr, N) # This code is contributed by code_hunt\",\n \"e\": 9091,\n \"s\": 7727,\n \"text\": null\n },\n {\n \"code\": \"// C# program for// the above approachusing System;class GFG{ // Function to modify array to make// sum of odd and even indexed// elements equalstatic void makeArraySumEqual(int []a, int N){ // Stores the count of 0s, 1s int count_0 = 0, count_1 = 0; // Stores sum of odd and even // indexed elements respectively int odd_sum = 0, even_sum = 0; for (int i = 0; i < N; i++) { // Count 0s if (a[i] == 0) count_0++; // Count 1s else count_1++; // Calculate odd_sum and even_sum if ((i + 1) % 2 == 0) even_sum += a[i]; else if ((i + 1) % 2 > 0) odd_sum += a[i]; } // If both are equal if (odd_sum == even_sum) { // Print the original array for (int i = 0; i < N; i++) Console.Write(a[i] + \\\" \\\"); } else { if (count_0 >= N / 2) { // Print all the 0s for (int i = 0; i < count_0; i++) Console.Write(\\\"0 \\\"); } else { // For checking even or odd int is_Odd = count_1 % 2; // Update total count of 1s count_1 -= is_Odd; // Print all 1s for (int i = 0; i < count_1; i++) Console.Write(\\\"1 \\\"); } }} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []arr = {1, 1, 1, 0}; int N = arr.Length; // Function Call makeArraySumEqual(arr, N);}} // This code is contributed by 29AjayKumar\",\n \"e\": 10469,\n \"s\": 9091,\n \"text\": null\n },\n {\n \"code\": \"\",\n \"e\": 12152,\n \"s\": 10469,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 12156,\n \"s\": 12152,\n \"text\": \"1 1\"\n },\n {\n \"code\": null,\n \"e\": 12201,\n \"s\": 12158,\n \"text\": \"Time Complexity: O(N)Auxiliary Space: O(1)\"\n },\n {\n \"code\": null,\n \"e\": 12213,\n \"s\": 12201,\n \"text\": \"aimformohan\"\n },\n {\n \"code\": null,\n \"e\": 12225,\n \"s\": 12213,\n \"text\": \"29AjayKumar\"\n },\n {\n \"code\": null,\n \"e\": 12235,\n \"s\": 12225,\n \"text\": \"code_hunt\"\n },\n {\n \"code\": null,\n \"e\": 12252,\n \"s\": 12235,\n \"text\": \"avijitmondal1998\"\n },\n {\n \"code\": null,\n \"e\": 12269,\n \"s\": 12252,\n \"text\": \"khushboogoyal499\"\n },\n {\n \"code\": null,\n \"e\": 12288,\n \"s\": 12269,\n \"text\": \"shivanisinghss2110\"\n },\n {\n \"code\": null,\n \"e\": 12304,\n \"s\": 12288,\n \"text\": \"array-rearrange\"\n },\n {\n \"code\": null,\n \"e\": 12311,\n \"s\": 12304,\n \"text\": \"Arrays\"\n },\n {\n \"code\": null,\n \"e\": 12318,\n \"s\": 12311,\n \"text\": \"Greedy\"\n },\n {\n \"code\": null,\n \"e\": 12331,\n \"s\": 12318,\n \"text\": \"Mathematical\"\n },\n {\n \"code\": null,\n \"e\": 12338,\n \"s\": 12331,\n \"text\": \"Arrays\"\n },\n {\n \"code\": null,\n \"e\": 12345,\n \"s\": 12338,\n \"text\": \"Greedy\"\n },\n {\n \"code\": null,\n \"e\": 12358,\n \"s\": 12345,\n \"text\": \"Mathematical\"\n }\n]"}}},{"rowIdx":164,"cells":{"title":{"kind":"string","value":"Introduction to Vaex in Python"},"text":{"kind":"string","value":"14 Sep, 2021\nWorking on Big Data has become very common today, So we require some libraries which can facilitate us to work on big data from our systems (i.e., desktops, laptops) with instantaneous execution of Code and low memory usage.\nVaex is a Python library which helps us achieve that and makes working with large datasets super easy. It is especially for lazy Out-of-Core DataFrames (similar to Pandas). It can visualize, explore, perform computations on big tabular datasets swiftly and with minimal memory usage.\nUsing Conda:\nconda install -c conda-forge vaex\nUsing pip:\npip install --upgrade vaex\nVaex helps us work with large datasets efficiently and swiftly by lazy computations, virtual columns, memory-mapping, zero memory copy policy, efficient data cleansing, etc. Vaex has efficient algorithms and it emphasizes aggregate data properties instead of looking at individual samples. It is able to overcome several shortcomings of other libraries (like:- pandas). So, Let’s Explore Vaex:-\nFor large tabular data, the reading performance of Vaex is much faster than pandas. Let’s analyze by importing same size dataset with both libraries. Link to the dataset\nReading Performance of Pandas:\nPython3\nimport pandas as pd%time df_pandas = pd.read_csv(\"dataset1.csv\")\nOutput:\nWall time: 1min 8s\nReading Performance of Vaex: (We read dataset in Vaex using vaex.open)\nPython3\nimport vaex%time df_vaex = vaex.open(\"dataset1.csv.hdf5\")\nOutput:\nWall time: 1.34 s\nVaex took very little time to read the same size dataset as compared to pandas:\nPython3\nprint(\"Size =\")print(df_pandas.shape)print(df_vaex.shape)\nOutput:\nSize = \n12852000, 36\n12852000, 36\nVaex uses a lazy computation technique (i.e., compute on the fly without wasting RAM). In this technique, Vaex does not do the complete calculations, instead, it creates a Vaex expression, and when printed out it shows some preview values. So Vaex performs calculations only when needed else it stores the expression. This makes the computation speed of Vaex exceptionally fast. Let’s Perform an example on a simple computation:\nPandas DataFrame:\nPython3\n%time df_pandas['column2'] + df_pandas['column3']\nOutput:\nVaex DataFrame:\nPython3\n%time df_vaex.column2 + df_vaex.column3\nOutput:\nVaex can calculate statistics such as mean, sum, count, standard deviation, etc., on an N-dimensional grid up to a billion (109) objects/rows per second. So, Let’s Compare the performance of pandas and Vaex while computing statistics:- \nPandas Dataframe:\nPython3\n%time df_pandas[\"column3\"].mean()\nOutput:\nWall time: 741 ms\n49.49811570183629\nVaex DataFrame:\nPython3\n%time df_vaex.mean(df_vaex.column3)\nOutput:\nWall time: 347 ms\narray(49.4981157)\nUnlike Pandas, No copies of memory are created in Vaex during data filtering, selections, subsets, cleansing. Let’s take the case of data filtering, in achieving this task Vaex uses very little memory as no memory copying is done in Vaex. and the time for execution is also minimal.\nPandas:\nPython3\n%time df_pandas_filtered = df_pandas[df_pandas['column5'] > 1]\nOutput:\nWall time: 24.1 s\nVaex:\nPython3\n%time df_vaex_filtered = df_vaex[df_vaex['column5'] > 1]\nOutput:\nWall time: 91.4 ms\nHere data filtering results in a reference to the existing data with a boolean mask which keeps track of selected rows and non-selected rows. Vaex performs multiple computations in single pass over the data:-\nPython3\ndf_vaex.select(df_vaex.column4 < 20, name='less_than')df_vaex.select(df_vaex.column4 >= 20, name='gr_than') %time df_vaex.mean(df_vaex.column4, selection=['less_than', 'gr_than'])\nOutput:\nWall time: 128 ms\narray([ 9.4940431, 59.49137605])\nWhen we create a new column by adding expression to a DataFrame, Virtual columns are created. These columns are just like regular columns but occupy no memory and just stores the expression that defines them. This makes the task very fast and reduces the wastage of RAM. And Vaex makes no distinction between regular or virtual columns.\nPython3\n%time df_vaex['new_col'] = df_vaex['column3']**2df_vaex.mean(df_vaex['new_col'])\nOutput:\nVaex provides a faster alternative to pandas’s groupby as ‘binby’ which can calculate statistics on a regular N-dimensional grid swiftly in regular bins. \nPython3\n%time df_vaex.count(binby=df_vaex.column7, limits=[0, 20], shape=10)\nOutput:\nVisualization of the large dataset is a tedious task. But Vaex can compute these visualizations pretty quickly. The dataset gives a better idea of data distribution when computed in bins and Vaex excels in group aggregate properties, selections, and bins. So, Vaex is able to visualize swiftly and interactively. By Vaex, visualizations can be done even in 3-dimensions on large datasets.Let’s plot a simple 1-dimensional graph:\nPython3\n%time df_vaex.viz.histogram(df_vaex.column1, limits = [0, 20])\nOutput:\nPython\ndf_vaex.viz.heatmap(df_vaex.column7, df_vaex.column8 + df_vaex.column9, limits=[-3, 20])\nOutput:\nWe can add statistics expression and visualize by passing the “what=()” argument. So let’s perform a slightly complicated visualization:\nPython3\ndf_vaex.viz.heatmap(df_vaex.column1, df_vaex.column2, what=(vaex.stat.mean(df_vaex.column4) / vaex.stat.std(df_vaex.column4)), limits='99.7%')\nOutput:\nHere, the ‘vaex.stat.’ objects are very similar to Vaex expressions, which represent an underlying calculation, and also we can apply typical arithmetic and Numpy functions to these calculations.\nBlogathon-2021\npython-modules\nBlogathon\nPython\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nHow to Import JSON Data into SQL Server?\nSQL Query to Convert Datetime to Date\nScrape LinkedIn Using Selenium And Beautiful Soup in Python\nPython program to convert XML to Dictionary\nShared ViewModel in Android\nRead JSON file using Python\nPython map() function\nAdding new column to existing DataFrame in Pandas\nPython Dictionary\nHow to get column names in Pandas dataframe"},"parsed":{"kind":"list like","value":[{"code":null,"e":54,"s":26,"text":"\n14 Sep, 2021"},{"code":null,"e":279,"s":54,"text":"Working on Big Data has become very common today, So we require some libraries which can facilitate us to work on big data from our systems (i.e., desktops, laptops) with instantaneous execution of Code and low memory usage."},{"code":null,"e":563,"s":279,"text":"Vaex is a Python library which helps us achieve that and makes working with large datasets super easy. It is especially for lazy Out-of-Core DataFrames (similar to Pandas). It can visualize, explore, perform computations on big tabular datasets swiftly and with minimal memory usage."},{"code":null,"e":576,"s":563,"text":"Using Conda:"},{"code":null,"e":610,"s":576,"text":"conda install -c conda-forge vaex"},{"code":null,"e":621,"s":610,"text":"Using pip:"},{"code":null,"e":648,"s":621,"text":"pip install --upgrade vaex"},{"code":null,"e":1043,"s":648,"text":"Vaex helps us work with large datasets efficiently and swiftly by lazy computations, virtual columns, memory-mapping, zero memory copy policy, efficient data cleansing, etc. Vaex has efficient algorithms and it emphasizes aggregate data properties instead of looking at individual samples. It is able to overcome several shortcomings of other libraries (like:- pandas). So, Let’s Explore Vaex:-"},{"code":null,"e":1213,"s":1043,"text":"For large tabular data, the reading performance of Vaex is much faster than pandas. Let’s analyze by importing same size dataset with both libraries. Link to the dataset"},{"code":null,"e":1244,"s":1213,"text":"Reading Performance of Pandas:"},{"code":null,"e":1252,"s":1244,"text":"Python3"},{"code":"import pandas as pd%time df_pandas = pd.read_csv(\"dataset1.csv\")","e":1317,"s":1252,"text":null},{"code":null,"e":1325,"s":1317,"text":"Output:"},{"code":null,"e":1344,"s":1325,"text":"Wall time: 1min 8s"},{"code":null,"e":1415,"s":1344,"text":"Reading Performance of Vaex: (We read dataset in Vaex using vaex.open)"},{"code":null,"e":1423,"s":1415,"text":"Python3"},{"code":"import vaex%time df_vaex = vaex.open(\"dataset1.csv.hdf5\")","e":1481,"s":1423,"text":null},{"code":null,"e":1489,"s":1481,"text":"Output:"},{"code":null,"e":1507,"s":1489,"text":"Wall time: 1.34 s"},{"code":null,"e":1587,"s":1507,"text":"Vaex took very little time to read the same size dataset as compared to pandas:"},{"code":null,"e":1595,"s":1587,"text":"Python3"},{"code":"print(\"Size =\")print(df_pandas.shape)print(df_vaex.shape)","e":1653,"s":1595,"text":null},{"code":null,"e":1661,"s":1653,"text":"Output:"},{"code":null,"e":1695,"s":1661,"text":"Size = \n12852000, 36\n12852000, 36"},{"code":null,"e":2124,"s":1695,"text":"Vaex uses a lazy computation technique (i.e., compute on the fly without wasting RAM). In this technique, Vaex does not do the complete calculations, instead, it creates a Vaex expression, and when printed out it shows some preview values. So Vaex performs calculations only when needed else it stores the expression. This makes the computation speed of Vaex exceptionally fast. Let’s Perform an example on a simple computation:"},{"code":null,"e":2142,"s":2124,"text":"Pandas DataFrame:"},{"code":null,"e":2150,"s":2142,"text":"Python3"},{"code":"%time df_pandas['column2'] + df_pandas['column3']","e":2200,"s":2150,"text":null},{"code":null,"e":2208,"s":2200,"text":"Output:"},{"code":null,"e":2224,"s":2208,"text":"Vaex DataFrame:"},{"code":null,"e":2232,"s":2224,"text":"Python3"},{"code":"%time df_vaex.column2 + df_vaex.column3","e":2272,"s":2232,"text":null},{"code":null,"e":2280,"s":2272,"text":"Output:"},{"code":null,"e":2517,"s":2280,"text":"Vaex can calculate statistics such as mean, sum, count, standard deviation, etc., on an N-dimensional grid up to a billion (109) objects/rows per second. So, Let’s Compare the performance of pandas and Vaex while computing statistics:- "},{"code":null,"e":2535,"s":2517,"text":"Pandas Dataframe:"},{"code":null,"e":2543,"s":2535,"text":"Python3"},{"code":"%time df_pandas[\"column3\"].mean()","e":2577,"s":2543,"text":null},{"code":null,"e":2585,"s":2577,"text":"Output:"},{"code":null,"e":2621,"s":2585,"text":"Wall time: 741 ms\n49.49811570183629"},{"code":null,"e":2637,"s":2621,"text":"Vaex DataFrame:"},{"code":null,"e":2645,"s":2637,"text":"Python3"},{"code":"%time df_vaex.mean(df_vaex.column3)","e":2681,"s":2645,"text":null},{"code":null,"e":2689,"s":2681,"text":"Output:"},{"code":null,"e":2725,"s":2689,"text":"Wall time: 347 ms\narray(49.4981157)"},{"code":null,"e":3008,"s":2725,"text":"Unlike Pandas, No copies of memory are created in Vaex during data filtering, selections, subsets, cleansing. Let’s take the case of data filtering, in achieving this task Vaex uses very little memory as no memory copying is done in Vaex. and the time for execution is also minimal."},{"code":null,"e":3016,"s":3008,"text":"Pandas:"},{"code":null,"e":3024,"s":3016,"text":"Python3"},{"code":"%time df_pandas_filtered = df_pandas[df_pandas['column5'] > 1]","e":3087,"s":3024,"text":null},{"code":null,"e":3095,"s":3087,"text":"Output:"},{"code":null,"e":3113,"s":3095,"text":"Wall time: 24.1 s"},{"code":null,"e":3119,"s":3113,"text":"Vaex:"},{"code":null,"e":3127,"s":3119,"text":"Python3"},{"code":"%time df_vaex_filtered = df_vaex[df_vaex['column5'] > 1]","e":3184,"s":3127,"text":null},{"code":null,"e":3192,"s":3184,"text":"Output:"},{"code":null,"e":3211,"s":3192,"text":"Wall time: 91.4 ms"},{"code":null,"e":3420,"s":3211,"text":"Here data filtering results in a reference to the existing data with a boolean mask which keeps track of selected rows and non-selected rows. Vaex performs multiple computations in single pass over the data:-"},{"code":null,"e":3428,"s":3420,"text":"Python3"},{"code":"df_vaex.select(df_vaex.column4 < 20, name='less_than')df_vaex.select(df_vaex.column4 >= 20, name='gr_than') %time df_vaex.mean(df_vaex.column4, selection=['less_than', 'gr_than'])","e":3656,"s":3428,"text":null},{"code":null,"e":3664,"s":3656,"text":"Output:"},{"code":null,"e":3715,"s":3664,"text":"Wall time: 128 ms\narray([ 9.4940431, 59.49137605])"},{"code":null,"e":4052,"s":3715,"text":"When we create a new column by adding expression to a DataFrame, Virtual columns are created. These columns are just like regular columns but occupy no memory and just stores the expression that defines them. This makes the task very fast and reduces the wastage of RAM. And Vaex makes no distinction between regular or virtual columns."},{"code":null,"e":4060,"s":4052,"text":"Python3"},{"code":"%time df_vaex['new_col'] = df_vaex['column3']**2df_vaex.mean(df_vaex['new_col'])","e":4141,"s":4060,"text":null},{"code":null,"e":4149,"s":4141,"text":"Output:"},{"code":null,"e":4304,"s":4149,"text":"Vaex provides a faster alternative to pandas’s groupby as ‘binby’ which can calculate statistics on a regular N-dimensional grid swiftly in regular bins. "},{"code":null,"e":4312,"s":4304,"text":"Python3"},{"code":"%time df_vaex.count(binby=df_vaex.column7, limits=[0, 20], shape=10)","e":4400,"s":4312,"text":null},{"code":null,"e":4408,"s":4400,"text":"Output:"},{"code":null,"e":4837,"s":4408,"text":"Visualization of the large dataset is a tedious task. But Vaex can compute these visualizations pretty quickly. The dataset gives a better idea of data distribution when computed in bins and Vaex excels in group aggregate properties, selections, and bins. So, Vaex is able to visualize swiftly and interactively. By Vaex, visualizations can be done even in 3-dimensions on large datasets.Let’s plot a simple 1-dimensional graph:"},{"code":null,"e":4845,"s":4837,"text":"Python3"},{"code":"%time df_vaex.viz.histogram(df_vaex.column1, limits = [0, 20])","e":4936,"s":4845,"text":null},{"code":null,"e":4944,"s":4936,"text":"Output:"},{"code":null,"e":4951,"s":4944,"text":"Python"},{"code":"df_vaex.viz.heatmap(df_vaex.column7, df_vaex.column8 + df_vaex.column9, limits=[-3, 20])","e":5059,"s":4951,"text":null},{"code":null,"e":5067,"s":5059,"text":"Output:"},{"code":null,"e":5227,"s":5067,"text":"We can add statistics expression and visualize by passing the “what=()” argument. So let’s perform a slightly complicated visualization:"},{"code":null,"e":5235,"s":5227,"text":"Python3"},{"code":"df_vaex.viz.heatmap(df_vaex.column1, df_vaex.column2, what=(vaex.stat.mean(df_vaex.column4) / vaex.stat.std(df_vaex.column4)), limits='99.7%')","e":5441,"s":5235,"text":null},{"code":null,"e":5449,"s":5441,"text":"Output:"},{"code":null,"e":5656,"s":5449,"text":"Here, the ‘vaex.stat.’ objects are very similar to Vaex expressions, which represent an underlying calculation, and also we can apply typical arithmetic and Numpy functions to these calculations."},{"code":null,"e":5671,"s":5656,"text":"Blogathon-2021"},{"code":null,"e":5686,"s":5671,"text":"python-modules"},{"code":null,"e":5696,"s":5686,"text":"Blogathon"},{"code":null,"e":5703,"s":5696,"text":"Python"},{"code":null,"e":5801,"s":5703,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":5842,"s":5801,"text":"How to Import JSON Data into SQL Server?"},{"code":null,"e":5880,"s":5842,"text":"SQL Query to Convert Datetime to Date"},{"code":null,"e":5940,"s":5880,"text":"Scrape LinkedIn Using Selenium And Beautiful Soup in Python"},{"code":null,"e":5984,"s":5940,"text":"Python program to convert XML to Dictionary"},{"code":null,"e":6012,"s":5984,"text":"Shared ViewModel in Android"},{"code":null,"e":6040,"s":6012,"text":"Read JSON file using Python"},{"code":null,"e":6062,"s":6040,"text":"Python map() function"},{"code":null,"e":6112,"s":6062,"text":"Adding new column to existing DataFrame in Pandas"},{"code":null,"e":6130,"s":6112,"text":"Python Dictionary"}],"string":"[\n {\n \"code\": null,\n \"e\": 54,\n \"s\": 26,\n \"text\": \"\\n14 Sep, 2021\"\n },\n {\n \"code\": null,\n \"e\": 279,\n \"s\": 54,\n \"text\": \"Working on Big Data has become very common today, So we require some libraries which can facilitate us to work on big data from our systems (i.e., desktops, laptops) with instantaneous execution of Code and low memory usage.\"\n },\n {\n \"code\": null,\n \"e\": 563,\n \"s\": 279,\n \"text\": \"Vaex is a Python library which helps us achieve that and makes working with large datasets super easy. It is especially for lazy Out-of-Core DataFrames (similar to Pandas). It can visualize, explore, perform computations on big tabular datasets swiftly and with minimal memory usage.\"\n },\n {\n \"code\": null,\n \"e\": 576,\n \"s\": 563,\n \"text\": \"Using Conda:\"\n },\n {\n \"code\": null,\n \"e\": 610,\n \"s\": 576,\n \"text\": \"conda install -c conda-forge vaex\"\n },\n {\n \"code\": null,\n \"e\": 621,\n \"s\": 610,\n \"text\": \"Using pip:\"\n },\n {\n \"code\": null,\n \"e\": 648,\n \"s\": 621,\n \"text\": \"pip install --upgrade vaex\"\n },\n {\n \"code\": null,\n \"e\": 1043,\n \"s\": 648,\n \"text\": \"Vaex helps us work with large datasets efficiently and swiftly by lazy computations, virtual columns, memory-mapping, zero memory copy policy, efficient data cleansing, etc. Vaex has efficient algorithms and it emphasizes aggregate data properties instead of looking at individual samples. It is able to overcome several shortcomings of other libraries (like:- pandas). So, Let’s Explore Vaex:-\"\n },\n {\n \"code\": null,\n \"e\": 1213,\n \"s\": 1043,\n \"text\": \"For large tabular data, the reading performance of Vaex is much faster than pandas. Let’s analyze by importing same size dataset with both libraries. Link to the dataset\"\n },\n {\n \"code\": null,\n \"e\": 1244,\n \"s\": 1213,\n \"text\": \"Reading Performance of Pandas:\"\n },\n {\n \"code\": null,\n \"e\": 1252,\n \"s\": 1244,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"import pandas as pd%time df_pandas = pd.read_csv(\\\"dataset1.csv\\\")\",\n \"e\": 1317,\n \"s\": 1252,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 1325,\n \"s\": 1317,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 1344,\n \"s\": 1325,\n \"text\": \"Wall time: 1min 8s\"\n },\n {\n \"code\": null,\n \"e\": 1415,\n \"s\": 1344,\n \"text\": \"Reading Performance of Vaex: (We read dataset in Vaex using vaex.open)\"\n },\n {\n \"code\": null,\n \"e\": 1423,\n \"s\": 1415,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"import vaex%time df_vaex = vaex.open(\\\"dataset1.csv.hdf5\\\")\",\n \"e\": 1481,\n \"s\": 1423,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 1489,\n \"s\": 1481,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 1507,\n \"s\": 1489,\n \"text\": \"Wall time: 1.34 s\"\n },\n {\n \"code\": null,\n \"e\": 1587,\n \"s\": 1507,\n \"text\": \"Vaex took very little time to read the same size dataset as compared to pandas:\"\n },\n {\n \"code\": null,\n \"e\": 1595,\n \"s\": 1587,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"print(\\\"Size =\\\")print(df_pandas.shape)print(df_vaex.shape)\",\n \"e\": 1653,\n \"s\": 1595,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 1661,\n \"s\": 1653,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 1695,\n \"s\": 1661,\n \"text\": \"Size = \\n12852000, 36\\n12852000, 36\"\n },\n {\n \"code\": null,\n \"e\": 2124,\n \"s\": 1695,\n \"text\": \"Vaex uses a lazy computation technique (i.e., compute on the fly without wasting RAM). In this technique, Vaex does not do the complete calculations, instead, it creates a Vaex expression, and when printed out it shows some preview values. So Vaex performs calculations only when needed else it stores the expression. This makes the computation speed of Vaex exceptionally fast. Let’s Perform an example on a simple computation:\"\n },\n {\n \"code\": null,\n \"e\": 2142,\n \"s\": 2124,\n \"text\": \"Pandas DataFrame:\"\n },\n {\n \"code\": null,\n \"e\": 2150,\n \"s\": 2142,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"%time df_pandas['column2'] + df_pandas['column3']\",\n \"e\": 2200,\n \"s\": 2150,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 2208,\n \"s\": 2200,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 2224,\n \"s\": 2208,\n \"text\": \"Vaex DataFrame:\"\n },\n {\n \"code\": null,\n \"e\": 2232,\n \"s\": 2224,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"%time df_vaex.column2 + df_vaex.column3\",\n \"e\": 2272,\n \"s\": 2232,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 2280,\n \"s\": 2272,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 2517,\n \"s\": 2280,\n \"text\": \"Vaex can calculate statistics such as mean, sum, count, standard deviation, etc., on an N-dimensional grid up to a billion (109) objects/rows per second. So, Let’s Compare the performance of pandas and Vaex while computing statistics:- \"\n },\n {\n \"code\": null,\n \"e\": 2535,\n \"s\": 2517,\n \"text\": \"Pandas Dataframe:\"\n },\n {\n \"code\": null,\n \"e\": 2543,\n \"s\": 2535,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"%time df_pandas[\\\"column3\\\"].mean()\",\n \"e\": 2577,\n \"s\": 2543,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 2585,\n \"s\": 2577,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 2621,\n \"s\": 2585,\n \"text\": \"Wall time: 741 ms\\n49.49811570183629\"\n },\n {\n \"code\": null,\n \"e\": 2637,\n \"s\": 2621,\n \"text\": \"Vaex DataFrame:\"\n },\n {\n \"code\": null,\n \"e\": 2645,\n \"s\": 2637,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"%time df_vaex.mean(df_vaex.column3)\",\n \"e\": 2681,\n \"s\": 2645,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 2689,\n \"s\": 2681,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 2725,\n \"s\": 2689,\n \"text\": \"Wall time: 347 ms\\narray(49.4981157)\"\n },\n {\n \"code\": null,\n \"e\": 3008,\n \"s\": 2725,\n \"text\": \"Unlike Pandas, No copies of memory are created in Vaex during data filtering, selections, subsets, cleansing. Let’s take the case of data filtering, in achieving this task Vaex uses very little memory as no memory copying is done in Vaex. and the time for execution is also minimal.\"\n },\n {\n \"code\": null,\n \"e\": 3016,\n \"s\": 3008,\n \"text\": \"Pandas:\"\n },\n {\n \"code\": null,\n \"e\": 3024,\n \"s\": 3016,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"%time df_pandas_filtered = df_pandas[df_pandas['column5'] > 1]\",\n \"e\": 3087,\n \"s\": 3024,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 3095,\n \"s\": 3087,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 3113,\n \"s\": 3095,\n \"text\": \"Wall time: 24.1 s\"\n },\n {\n \"code\": null,\n \"e\": 3119,\n \"s\": 3113,\n \"text\": \"Vaex:\"\n },\n {\n \"code\": null,\n \"e\": 3127,\n \"s\": 3119,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"%time df_vaex_filtered = df_vaex[df_vaex['column5'] > 1]\",\n \"e\": 3184,\n \"s\": 3127,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 3192,\n \"s\": 3184,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 3211,\n \"s\": 3192,\n \"text\": \"Wall time: 91.4 ms\"\n },\n {\n \"code\": null,\n \"e\": 3420,\n \"s\": 3211,\n \"text\": \"Here data filtering results in a reference to the existing data with a boolean mask which keeps track of selected rows and non-selected rows. Vaex performs multiple computations in single pass over the data:-\"\n },\n {\n \"code\": null,\n \"e\": 3428,\n \"s\": 3420,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"df_vaex.select(df_vaex.column4 < 20, name='less_than')df_vaex.select(df_vaex.column4 >= 20, name='gr_than') %time df_vaex.mean(df_vaex.column4, selection=['less_than', 'gr_than'])\",\n \"e\": 3656,\n \"s\": 3428,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 3664,\n \"s\": 3656,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 3715,\n \"s\": 3664,\n \"text\": \"Wall time: 128 ms\\narray([ 9.4940431, 59.49137605])\"\n },\n {\n \"code\": null,\n \"e\": 4052,\n \"s\": 3715,\n \"text\": \"When we create a new column by adding expression to a DataFrame, Virtual columns are created. These columns are just like regular columns but occupy no memory and just stores the expression that defines them. This makes the task very fast and reduces the wastage of RAM. And Vaex makes no distinction between regular or virtual columns.\"\n },\n {\n \"code\": null,\n \"e\": 4060,\n \"s\": 4052,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"%time df_vaex['new_col'] = df_vaex['column3']**2df_vaex.mean(df_vaex['new_col'])\",\n \"e\": 4141,\n \"s\": 4060,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 4149,\n \"s\": 4141,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 4304,\n \"s\": 4149,\n \"text\": \"Vaex provides a faster alternative to pandas’s groupby as ‘binby’ which can calculate statistics on a regular N-dimensional grid swiftly in regular bins. \"\n },\n {\n \"code\": null,\n \"e\": 4312,\n \"s\": 4304,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"%time df_vaex.count(binby=df_vaex.column7, limits=[0, 20], shape=10)\",\n \"e\": 4400,\n \"s\": 4312,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 4408,\n \"s\": 4400,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 4837,\n \"s\": 4408,\n \"text\": \"Visualization of the large dataset is a tedious task. But Vaex can compute these visualizations pretty quickly. The dataset gives a better idea of data distribution when computed in bins and Vaex excels in group aggregate properties, selections, and bins. So, Vaex is able to visualize swiftly and interactively. By Vaex, visualizations can be done even in 3-dimensions on large datasets.Let’s plot a simple 1-dimensional graph:\"\n },\n {\n \"code\": null,\n \"e\": 4845,\n \"s\": 4837,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"%time df_vaex.viz.histogram(df_vaex.column1, limits = [0, 20])\",\n \"e\": 4936,\n \"s\": 4845,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 4944,\n \"s\": 4936,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 4951,\n \"s\": 4944,\n \"text\": \"Python\"\n },\n {\n \"code\": \"df_vaex.viz.heatmap(df_vaex.column7, df_vaex.column8 + df_vaex.column9, limits=[-3, 20])\",\n \"e\": 5059,\n \"s\": 4951,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 5067,\n \"s\": 5059,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 5227,\n \"s\": 5067,\n \"text\": \"We can add statistics expression and visualize by passing the “what=()” argument. So let’s perform a slightly complicated visualization:\"\n },\n {\n \"code\": null,\n \"e\": 5235,\n \"s\": 5227,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"df_vaex.viz.heatmap(df_vaex.column1, df_vaex.column2, what=(vaex.stat.mean(df_vaex.column4) / vaex.stat.std(df_vaex.column4)), limits='99.7%')\",\n \"e\": 5441,\n \"s\": 5235,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 5449,\n \"s\": 5441,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 5656,\n \"s\": 5449,\n \"text\": \"Here, the ‘vaex.stat.’ objects are very similar to Vaex expressions, which represent an underlying calculation, and also we can apply typical arithmetic and Numpy functions to these calculations.\"\n },\n {\n \"code\": null,\n \"e\": 5671,\n \"s\": 5656,\n \"text\": \"Blogathon-2021\"\n },\n {\n \"code\": null,\n \"e\": 5686,\n \"s\": 5671,\n \"text\": \"python-modules\"\n },\n {\n \"code\": null,\n \"e\": 5696,\n \"s\": 5686,\n \"text\": \"Blogathon\"\n },\n {\n \"code\": null,\n \"e\": 5703,\n \"s\": 5696,\n \"text\": \"Python\"\n },\n {\n \"code\": null,\n \"e\": 5801,\n \"s\": 5703,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 5842,\n \"s\": 5801,\n \"text\": \"How to Import JSON Data into SQL Server?\"\n },\n {\n \"code\": null,\n \"e\": 5880,\n \"s\": 5842,\n \"text\": \"SQL Query to Convert Datetime to Date\"\n },\n {\n \"code\": null,\n \"e\": 5940,\n \"s\": 5880,\n \"text\": \"Scrape LinkedIn Using Selenium And Beautiful Soup in Python\"\n },\n {\n \"code\": null,\n \"e\": 5984,\n \"s\": 5940,\n \"text\": \"Python program to convert XML to Dictionary\"\n },\n {\n \"code\": null,\n \"e\": 6012,\n \"s\": 5984,\n \"text\": \"Shared ViewModel in Android\"\n },\n {\n \"code\": null,\n \"e\": 6040,\n \"s\": 6012,\n \"text\": \"Read JSON file using Python\"\n },\n {\n \"code\": null,\n \"e\": 6062,\n \"s\": 6040,\n \"text\": \"Python map() function\"\n },\n {\n \"code\": null,\n \"e\": 6112,\n \"s\": 6062,\n \"text\": \"Adding new column to existing DataFrame in Pandas\"\n },\n {\n \"code\": null,\n \"e\": 6130,\n \"s\": 6112,\n \"text\": \"Python Dictionary\"\n }\n]"}}},{"rowIdx":165,"cells":{"title":{"kind":"string","value":"How to install Ruby on Windows?"},"text":{"kind":"string","value":"06 Oct, 2021\nPrerequisite: Ruby Programming Language Before we start with the installation of Ruby on Windows, we must have first-hand knowledge of what Ruby is?. Ruby is a pure Object-Oriented language developed by Yukihiro Matsumoto (also known as Matz in the Ruby community) in the mid-1990s in Japan. Everything in Ruby is an object except the blocks but there are replacements too for it i.e procs and lambda. The objective of Ruby’s development was to make it act as a sensible buffer between human programmers and the underlying computing machinery. Ruby is based on many other languages like Perl, Lisp, Smalltalk, Eiffel and Ada. It is an interpreted scripting language which means most of its implementations execute instructions directly and freely, without previously compiling a program into machine-language instructions.\nAll the versions of Ruby for Windows can be downloaded from rubyinstaller.org. Download the latest version and follow the further instructions for its Installation.\nBeginning with the installation:\nGetting Started with License Agreement:\nSelecting Installation Destination:\nSelecting components to be installed:\nExtracting Files and Installing:\nFinishing Installation:\nInstalling MYSYS2 Components: \nChoose what to install:\nUpdating Database and signing keys:\nInstalling Files:\nDownloading Packages:\nInstalling Packages:\nTo check if Ruby installed correctly, perform a version check for the same using the following command on the command-line:\nruby -v\nHere’s a sample Program to begin with the use of Ruby Programming:Let’s consider a simple Hello World Program.\nputs \"Hello World\"\n Using command-line, run the irb command. After this we can write the ruby code and it will run on command line.\nhow-to-install\nRuby-Basics\nHow To\nInstallation Guide\nRuby\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},"parsed":{"kind":"list like","value":[{"code":null,"e":28,"s":0,"text":"\n06 Oct, 2021"},{"code":null,"e":851,"s":28,"text":"Prerequisite: Ruby Programming Language Before we start with the installation of Ruby on Windows, we must have first-hand knowledge of what Ruby is?. Ruby is a pure Object-Oriented language developed by Yukihiro Matsumoto (also known as Matz in the Ruby community) in the mid-1990s in Japan. Everything in Ruby is an object except the blocks but there are replacements too for it i.e procs and lambda. The objective of Ruby’s development was to make it act as a sensible buffer between human programmers and the underlying computing machinery. Ruby is based on many other languages like Perl, Lisp, Smalltalk, Eiffel and Ada. It is an interpreted scripting language which means most of its implementations execute instructions directly and freely, without previously compiling a program into machine-language instructions."},{"code":null,"e":1016,"s":851,"text":"All the versions of Ruby for Windows can be downloaded from rubyinstaller.org. Download the latest version and follow the further instructions for its Installation."},{"code":null,"e":1049,"s":1016,"text":"Beginning with the installation:"},{"code":null,"e":1089,"s":1049,"text":"Getting Started with License Agreement:"},{"code":null,"e":1125,"s":1089,"text":"Selecting Installation Destination:"},{"code":null,"e":1163,"s":1125,"text":"Selecting components to be installed:"},{"code":null,"e":1196,"s":1163,"text":"Extracting Files and Installing:"},{"code":null,"e":1220,"s":1196,"text":"Finishing Installation:"},{"code":null,"e":1251,"s":1220,"text":"Installing MYSYS2 Components: "},{"code":null,"e":1275,"s":1251,"text":"Choose what to install:"},{"code":null,"e":1311,"s":1275,"text":"Updating Database and signing keys:"},{"code":null,"e":1329,"s":1311,"text":"Installing Files:"},{"code":null,"e":1351,"s":1329,"text":"Downloading Packages:"},{"code":null,"e":1372,"s":1351,"text":"Installing Packages:"},{"code":null,"e":1496,"s":1372,"text":"To check if Ruby installed correctly, perform a version check for the same using the following command on the command-line:"},{"code":null,"e":1504,"s":1496,"text":"ruby -v"},{"code":null,"e":1615,"s":1504,"text":"Here’s a sample Program to begin with the use of Ruby Programming:Let’s consider a simple Hello World Program."},{"code":"puts \"Hello World\"","e":1634,"s":1615,"text":null},{"code":null,"e":1747,"s":1634,"text":" Using command-line, run the irb command. After this we can write the ruby code and it will run on command line."},{"code":null,"e":1762,"s":1747,"text":"how-to-install"},{"code":null,"e":1774,"s":1762,"text":"Ruby-Basics"},{"code":null,"e":1781,"s":1774,"text":"How To"},{"code":null,"e":1800,"s":1781,"text":"Installation Guide"},{"code":null,"e":1805,"s":1800,"text":"Ruby"}],"string":"[\n {\n \"code\": null,\n \"e\": 28,\n \"s\": 0,\n \"text\": \"\\n06 Oct, 2021\"\n },\n {\n \"code\": null,\n \"e\": 851,\n \"s\": 28,\n \"text\": \"Prerequisite: Ruby Programming Language Before we start with the installation of Ruby on Windows, we must have first-hand knowledge of what Ruby is?. Ruby is a pure Object-Oriented language developed by Yukihiro Matsumoto (also known as Matz in the Ruby community) in the mid-1990s in Japan. Everything in Ruby is an object except the blocks but there are replacements too for it i.e procs and lambda. The objective of Ruby’s development was to make it act as a sensible buffer between human programmers and the underlying computing machinery. Ruby is based on many other languages like Perl, Lisp, Smalltalk, Eiffel and Ada. It is an interpreted scripting language which means most of its implementations execute instructions directly and freely, without previously compiling a program into machine-language instructions.\"\n },\n {\n \"code\": null,\n \"e\": 1016,\n \"s\": 851,\n \"text\": \"All the versions of Ruby for Windows can be downloaded from rubyinstaller.org. Download the latest version and follow the further instructions for its Installation.\"\n },\n {\n \"code\": null,\n \"e\": 1049,\n \"s\": 1016,\n \"text\": \"Beginning with the installation:\"\n },\n {\n \"code\": null,\n \"e\": 1089,\n \"s\": 1049,\n \"text\": \"Getting Started with License Agreement:\"\n },\n {\n \"code\": null,\n \"e\": 1125,\n \"s\": 1089,\n \"text\": \"Selecting Installation Destination:\"\n },\n {\n \"code\": null,\n \"e\": 1163,\n \"s\": 1125,\n \"text\": \"Selecting components to be installed:\"\n },\n {\n \"code\": null,\n \"e\": 1196,\n \"s\": 1163,\n \"text\": \"Extracting Files and Installing:\"\n },\n {\n \"code\": null,\n \"e\": 1220,\n \"s\": 1196,\n \"text\": \"Finishing Installation:\"\n },\n {\n \"code\": null,\n \"e\": 1251,\n \"s\": 1220,\n \"text\": \"Installing MYSYS2 Components: \"\n },\n {\n \"code\": null,\n \"e\": 1275,\n \"s\": 1251,\n \"text\": \"Choose what to install:\"\n },\n {\n \"code\": null,\n \"e\": 1311,\n \"s\": 1275,\n \"text\": \"Updating Database and signing keys:\"\n },\n {\n \"code\": null,\n \"e\": 1329,\n \"s\": 1311,\n \"text\": \"Installing Files:\"\n },\n {\n \"code\": null,\n \"e\": 1351,\n \"s\": 1329,\n \"text\": \"Downloading Packages:\"\n },\n {\n \"code\": null,\n \"e\": 1372,\n \"s\": 1351,\n \"text\": \"Installing Packages:\"\n },\n {\n \"code\": null,\n \"e\": 1496,\n \"s\": 1372,\n \"text\": \"To check if Ruby installed correctly, perform a version check for the same using the following command on the command-line:\"\n },\n {\n \"code\": null,\n \"e\": 1504,\n \"s\": 1496,\n \"text\": \"ruby -v\"\n },\n {\n \"code\": null,\n \"e\": 1615,\n \"s\": 1504,\n \"text\": \"Here’s a sample Program to begin with the use of Ruby Programming:Let’s consider a simple Hello World Program.\"\n },\n {\n \"code\": \"puts \\\"Hello World\\\"\",\n \"e\": 1634,\n \"s\": 1615,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 1747,\n \"s\": 1634,\n \"text\": \" Using command-line, run the irb command. After this we can write the ruby code and it will run on command line.\"\n },\n {\n \"code\": null,\n \"e\": 1762,\n \"s\": 1747,\n \"text\": \"how-to-install\"\n },\n {\n \"code\": null,\n \"e\": 1774,\n \"s\": 1762,\n \"text\": \"Ruby-Basics\"\n },\n {\n \"code\": null,\n \"e\": 1781,\n \"s\": 1774,\n \"text\": \"How To\"\n },\n {\n \"code\": null,\n \"e\": 1800,\n \"s\": 1781,\n \"text\": \"Installation Guide\"\n },\n {\n \"code\": null,\n \"e\": 1805,\n \"s\": 1800,\n \"text\": \"Ruby\"\n }\n]"}}},{"rowIdx":166,"cells":{"title":{"kind":"string","value":"Node.js crypto.generateKeyPair() Method"},"text":{"kind":"string","value":"11 Oct, 2021\nThe crypto.generateKeyPair() method is an inbuilt application programming interface of crypto module which is used to generate a new asymmetric key pair of the specified type. For example, the currently supported key types are RSA, DSA, EC, Ed25519, Ed448, X25519, X448, and DH. Moreover, if option’s publicKeyEncoding or privateKeyEncoding is stated here, then this function acts as if keyObject.export() had been called on its output. Else, the particular part of the key is returned as a KeyObject.However, it is suggested to encode the public keys as ‘spki’ and private keys as ‘pkcs8’ with encryption for long-term storage.\nSyntax:\ncrypto.generateKeyPair( type, options, callback )\nParameters: This method accept three parameters as mentioned above and described below:\ntype: It holds a string and it must include one or more of the following algorithms: ‘rsa’, ‘dsa’, ‘ec’, ‘ed25519’, ‘ed448’, ‘x25519’, ‘x448’, or ‘dh’.\noptions: is of type object. It can hold the following parameters:modulusLength: It holds a number. It is the key size in bits and is applicable for RSA, and DSA algorithm only.publicExponent: It holds a number. It is the Public exponent of RSA algorithm. Its by default value is 0x10001.divisorLength: It holds a number. It is the size of q in bits of DSA algorithm.namedCurve: It holds a string. It is the name of the curve to be used in EC algorithm.prime: It holds a buffer. It is the prime parameter of DH algorithm.primeLength: It holds a number. It is the prime length of DH algorithm in bits.generator: It holds a number. It is the custom generator of DH algorithm. Its by default value is 2.groupName: It holds string. It is the Diffie-Hellman group name of DH algorithm.publicKeyEncoding: It holds a string.privateKeyEncoding: It holds an Object.\nmodulusLength: It holds a number. It is the key size in bits and is applicable for RSA, and DSA algorithm only.publicExponent: It holds a number. It is the Public exponent of RSA algorithm. Its by default value is 0x10001.divisorLength: It holds a number. It is the size of q in bits of DSA algorithm.namedCurve: It holds a string. It is the name of the curve to be used in EC algorithm.prime: It holds a buffer. It is the prime parameter of DH algorithm.primeLength: It holds a number. It is the prime length of DH algorithm in bits.generator: It holds a number. It is the custom generator of DH algorithm. Its by default value is 2.groupName: It holds string. It is the Diffie-Hellman group name of DH algorithm.publicKeyEncoding: It holds a string.privateKeyEncoding: It holds an Object.\nmodulusLength: It holds a number. It is the key size in bits and is applicable for RSA, and DSA algorithm only.\npublicExponent: It holds a number. It is the Public exponent of RSA algorithm. Its by default value is 0x10001.\ndivisorLength: It holds a number. It is the size of q in bits of DSA algorithm.\nnamedCurve: It holds a string. It is the name of the curve to be used in EC algorithm.\nprime: It holds a buffer. It is the prime parameter of DH algorithm.\nprimeLength: It holds a number. It is the prime length of DH algorithm in bits.\ngenerator: It holds a number. It is the custom generator of DH algorithm. Its by default value is 2.\ngroupName: It holds string. It is the Diffie-Hellman group name of DH algorithm.\npublicKeyEncoding: It holds a string.\nprivateKeyEncoding: It holds an Object.\ncallback: It is a function, with parameters publicKey, privateKey and err.err: holds an error.publicKey: It holds a string, buffer or a KeyObject.privateKey: holds a string, buffer or a KeyObject.\nerr: holds an error.publicKey: It holds a string, buffer or a KeyObject.privateKey: holds a string, buffer or a KeyObject.\nerr: holds an error.\npublicKey: It holds a string, buffer or a KeyObject.\nprivateKey: holds a string, buffer or a KeyObject.\nReturn Value: It returns a new asymmetric key pair of the given type.\nBelow examples illustrate the use of crypto.generateKeyPair() method in Node.js:\nExample 1:\n// Node.js program to demonstrate the// crypto.generateKeyPair() method // Including generateKeyPair from crypto moduleconst { generateKeyPair } = require('crypto'); // Calling generateKeyPair() method// with its parametersgenerateKeyPair('rsa', { modulusLength: 530, // options publicExponent: 0x10101, publicKeyEncoding: { type: 'pkcs1', format: 'der' }, privateKeyEncoding: { type: 'pkcs8', format: 'der', cipher: 'aes-192-cbc', passphrase: 'GeeksforGeeks is a CS-Portal!' }}, (err, publicKey, privateKey) => { // Callback function if(!err) { // Prints new asymmetric key pair console.log(\"Public Key is : \", publicKey); console.log(); console.log(\"Private Key is: \", privateKey); } else { // Prints error console.log(\"Errr is: \", err); } });\nOutput:\nPublic Key is : \n\nPrivate Key is: \n\nExample 2:\n// Node.js program to demonstrate the// crypto.generateKeyPair() method // Including generateKeyPair from crypto moduleconst { generateKeyPair } = require('crypto'); // Calling generateKeyPair() method// with its parametersgenerateKeyPair('ec', { namedCurve: 'secp256k1', // Options publicKeyEncoding: { type: 'spki', format: 'der' }, privateKeyEncoding: { type: 'pkcs8', format: 'der' }}, (err, publicKey, privateKey) => { // Callback function if(!err) { // Prints new asymmetric key // pair after encoding console.log(\"Public Key is: \", publicKey.toString('hex')); console.log(); console.log(\"Private Key is: \", privateKey.toString('hex')); } else { // Prints error console.log(\"Errr is: \", err); } });\nOutput:\nPublic Key is: 3056301006072a8648ce3d020106052b8104000a0342000499c5f442c3264bcdfb093b0bc820e3f0f6546972856ebec2f8ccc03f49abdb47ffcfcaf4f37e0ec53050760e74014767e30a8a3e891f4db8c83fa27627898f15\n\nPrivate Key is: 308184020100301006072a8648ce3d020106052b8104000a046d306b0201010420326b340a964512bfc3e010850ff05e077b2f016fce9eded11f40643e4231efc4a1440342000499c5f442c3264bcdfb093b0bc820e3f0f6546972856ebec2f8ccc03f49abdb47ffcfcaf4f37e0ec53050760e74014767e30a8a3e891f4db8c83fa27627898f15\n\nReference: https://nodejs.org/api/crypto.html#crypto_crypto_generatekeypair_type_options_callback\nNode.js-crypto-module\nNode.js\nWeb Technologies\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nNode.js fs.writeFile() Method\nHow to install the previous version of node.js and npm ?\nDifference between promise and async await in Node.js\nMongoose | findByIdAndUpdate() Function\nJWT Authentication with Node.js\nHow to insert spaces/tabs in text using HTML/CSS?\nTop 10 Projects For Beginners To Practice HTML and CSS Skills\nHow to set the default value for an HTML element ?"},{"code":null,"e":7298,"s":7237,"text":"How to set input type date in dd-mm-yyyy format using HTML ?"}],"string":"[\n {\n \"code\": null,\n \"e\": 28,\n \"s\": 0,\n \"text\": \"\\n11 Oct, 2021\"\n },\n {\n \"code\": null,\n \"e\": 657,\n \"s\": 28,\n \"text\": \"The crypto.generateKeyPair() method is an inbuilt application programming interface of crypto module which is used to generate a new asymmetric key pair of the specified type. For example, the currently supported key types are RSA, DSA, EC, Ed25519, Ed448, X25519, X448, and DH. Moreover, if option’s publicKeyEncoding or privateKeyEncoding is stated here, then this function acts as if keyObject.export() had been called on its output. Else, the particular part of the key is returned as a KeyObject.However, it is suggested to encode the public keys as ‘spki’ and private keys as ‘pkcs8’ with encryption for long-term storage.\"\n },\n {\n \"code\": null,\n \"e\": 665,\n \"s\": 657,\n \"text\": \"Syntax:\"\n },\n {\n \"code\": null,\n \"e\": 715,\n \"s\": 665,\n \"text\": \"crypto.generateKeyPair( type, options, callback )\"\n },\n {\n \"code\": null,\n \"e\": 803,\n \"s\": 715,\n \"text\": \"Parameters: This method accept three parameters as mentioned above and described below:\"\n },\n {\n \"code\": null,\n \"e\": 955,\n \"s\": 803,\n \"text\": \"type: It holds a string and it must include one or more of the following algorithms: ‘rsa’, ‘dsa’, ‘ec’, ‘ed25519’, ‘ed448’, ‘x25519’, ‘x448’, or ‘dh’.\"\n },\n {\n \"code\": null,\n \"e\": 1811,\n \"s\": 955,\n \"text\": \"options: is of type object. It can hold the following parameters:modulusLength: It holds a number. It is the key size in bits and is applicable for RSA, and DSA algorithm only.publicExponent: It holds a number. It is the Public exponent of RSA algorithm. Its by default value is 0x10001.divisorLength: It holds a number. It is the size of q in bits of DSA algorithm.namedCurve: It holds a string. It is the name of the curve to be used in EC algorithm.prime: It holds a buffer. It is the prime parameter of DH algorithm.primeLength: It holds a number. It is the prime length of DH algorithm in bits.generator: It holds a number. It is the custom generator of DH algorithm. Its by default value is 2.groupName: It holds string. It is the Diffie-Hellman group name of DH algorithm.publicKeyEncoding: It holds a string.privateKeyEncoding: It holds an Object.\"\n },\n {\n \"code\": null,\n \"e\": 2602,\n \"s\": 1811,\n \"text\": \"modulusLength: It holds a number. It is the key size in bits and is applicable for RSA, and DSA algorithm only.publicExponent: It holds a number. It is the Public exponent of RSA algorithm. Its by default value is 0x10001.divisorLength: It holds a number. It is the size of q in bits of DSA algorithm.namedCurve: It holds a string. It is the name of the curve to be used in EC algorithm.prime: It holds a buffer. It is the prime parameter of DH algorithm.primeLength: It holds a number. It is the prime length of DH algorithm in bits.generator: It holds a number. It is the custom generator of DH algorithm. Its by default value is 2.groupName: It holds string. It is the Diffie-Hellman group name of DH algorithm.publicKeyEncoding: It holds a string.privateKeyEncoding: It holds an Object.\"\n },\n {\n \"code\": null,\n \"e\": 2714,\n \"s\": 2602,\n \"text\": \"modulusLength: It holds a number. It is the key size in bits and is applicable for RSA, and DSA algorithm only.\"\n },\n {\n \"code\": null,\n \"e\": 2826,\n \"s\": 2714,\n \"text\": \"publicExponent: It holds a number. It is the Public exponent of RSA algorithm. Its by default value is 0x10001.\"\n },\n {\n \"code\": null,\n \"e\": 2906,\n \"s\": 2826,\n \"text\": \"divisorLength: It holds a number. It is the size of q in bits of DSA algorithm.\"\n },\n {\n \"code\": null,\n \"e\": 2993,\n \"s\": 2906,\n \"text\": \"namedCurve: It holds a string. It is the name of the curve to be used in EC algorithm.\"\n },\n {\n \"code\": null,\n \"e\": 3062,\n \"s\": 2993,\n \"text\": \"prime: It holds a buffer. It is the prime parameter of DH algorithm.\"\n },\n {\n \"code\": null,\n \"e\": 3142,\n \"s\": 3062,\n \"text\": \"primeLength: It holds a number. It is the prime length of DH algorithm in bits.\"\n },\n {\n \"code\": null,\n \"e\": 3243,\n \"s\": 3142,\n \"text\": \"generator: It holds a number. It is the custom generator of DH algorithm. Its by default value is 2.\"\n },\n {\n \"code\": null,\n \"e\": 3324,\n \"s\": 3243,\n \"text\": \"groupName: It holds string. It is the Diffie-Hellman group name of DH algorithm.\"\n },\n {\n \"code\": null,\n \"e\": 3362,\n \"s\": 3324,\n \"text\": \"publicKeyEncoding: It holds a string.\"\n },\n {\n \"code\": null,\n \"e\": 3402,\n \"s\": 3362,\n \"text\": \"privateKeyEncoding: It holds an Object.\"\n },\n {\n \"code\": null,\n \"e\": 3599,\n \"s\": 3402,\n \"text\": \"callback: It is a function, with parameters publicKey, privateKey and err.err: holds an error.publicKey: It holds a string, buffer or a KeyObject.privateKey: holds a string, buffer or a KeyObject.\"\n },\n {\n \"code\": null,\n \"e\": 3722,\n \"s\": 3599,\n \"text\": \"err: holds an error.publicKey: It holds a string, buffer or a KeyObject.privateKey: holds a string, buffer or a KeyObject.\"\n },\n {\n \"code\": null,\n \"e\": 3743,\n \"s\": 3722,\n \"text\": \"err: holds an error.\"\n },\n {\n \"code\": null,\n \"e\": 3796,\n \"s\": 3743,\n \"text\": \"publicKey: It holds a string, buffer or a KeyObject.\"\n },\n {\n \"code\": null,\n \"e\": 3847,\n \"s\": 3796,\n \"text\": \"privateKey: holds a string, buffer or a KeyObject.\"\n },\n {\n \"code\": null,\n \"e\": 3917,\n \"s\": 3847,\n \"text\": \"Return Value: It returns a new asymmetric key pair of the given type.\"\n },\n {\n \"code\": null,\n \"e\": 3998,\n \"s\": 3917,\n \"text\": \"Below examples illustrate the use of crypto.generateKeyPair() method in Node.js:\"\n },\n {\n \"code\": null,\n \"e\": 4009,\n \"s\": 3998,\n \"text\": \"Example 1:\"\n },\n {\n \"code\": \"// Node.js program to demonstrate the// crypto.generateKeyPair() method // Including generateKeyPair from crypto moduleconst { generateKeyPair } = require('crypto'); // Calling generateKeyPair() method// with its parametersgenerateKeyPair('rsa', { modulusLength: 530, // options publicExponent: 0x10101, publicKeyEncoding: { type: 'pkcs1', format: 'der' }, privateKeyEncoding: { type: 'pkcs8', format: 'der', cipher: 'aes-192-cbc', passphrase: 'GeeksforGeeks is a CS-Portal!' }}, (err, publicKey, privateKey) => { // Callback function if(!err) { // Prints new asymmetric key pair console.log(\\\"Public Key is : \\\", publicKey); console.log(); console.log(\\\"Private Key is: \\\", privateKey); } else { // Prints error console.log(\\\"Errr is: \\\", err); } });\",\n \"e\": 4878,\n \"s\": 4009,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 4886,\n \"s\": 4878,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 5246,\n \"s\": 4886,\n \"text\": \"Public Key is : \\n\\nPrivate Key is: \\n\"\n },\n {\n \"code\": null,\n \"e\": 5257,\n \"s\": 5246,\n \"text\": \"Example 2:\"\n },\n {\n \"code\": \"// Node.js program to demonstrate the// crypto.generateKeyPair() method // Including generateKeyPair from crypto moduleconst { generateKeyPair } = require('crypto'); // Calling generateKeyPair() method// with its parametersgenerateKeyPair('ec', { namedCurve: 'secp256k1', // Options publicKeyEncoding: { type: 'spki', format: 'der' }, privateKeyEncoding: { type: 'pkcs8', format: 'der' }}, (err, publicKey, privateKey) => { // Callback function if(!err) { // Prints new asymmetric key // pair after encoding console.log(\\\"Public Key is: \\\", publicKey.toString('hex')); console.log(); console.log(\\\"Private Key is: \\\", privateKey.toString('hex')); } else { // Prints error console.log(\\\"Errr is: \\\", err); } });\",\n \"e\": 6118,\n \"s\": 5257,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 6126,\n \"s\": 6118,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 6609,\n \"s\": 6126,\n \"text\": \"Public Key is: 3056301006072a8648ce3d020106052b8104000a0342000499c5f442c3264bcdfb093b0bc820e3f0f6546972856ebec2f8ccc03f49abdb47ffcfcaf4f37e0ec53050760e74014767e30a8a3e891f4db8c83fa27627898f15\\n\\nPrivate Key is: 308184020100301006072a8648ce3d020106052b8104000a046d306b0201010420326b340a964512bfc3e010850ff05e077b2f016fce9eded11f40643e4231efc4a1440342000499c5f442c3264bcdfb093b0bc820e3f0f6546972856ebec2f8ccc03f49abdb47ffcfcaf4f37e0ec53050760e74014767e30a8a3e891f4db8c83fa27627898f15\\n\"\n },\n {\n \"code\": null,\n \"e\": 6707,\n \"s\": 6609,\n \"text\": \"Reference: https://nodejs.org/api/crypto.html#crypto_crypto_generatekeypair_type_options_callback\"\n },\n {\n \"code\": null,\n \"e\": 6729,\n \"s\": 6707,\n \"text\": \"Node.js-crypto-module\"\n },\n {\n \"code\": null,\n \"e\": 6737,\n \"s\": 6729,\n \"text\": \"Node.js\"\n },\n {\n \"code\": null,\n \"e\": 6754,\n \"s\": 6737,\n \"text\": \"Web Technologies\"\n },\n {\n \"code\": null,\n \"e\": 6852,\n \"s\": 6754,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 6882,\n \"s\": 6852,\n \"text\": \"Node.js fs.writeFile() Method\"\n },\n {\n \"code\": null,\n \"e\": 6939,\n \"s\": 6882,\n \"text\": \"How to install the previous version of node.js and npm ?\"\n },\n {\n \"code\": null,\n \"e\": 6993,\n \"s\": 6939,\n \"text\": \"Difference between promise and async await in Node.js\"\n },\n {\n \"code\": null,\n \"e\": 7033,\n \"s\": 6993,\n \"text\": \"Mongoose | findByIdAndUpdate() Function\"\n },\n {\n \"code\": null,\n \"e\": 7065,\n \"s\": 7033,\n \"text\": \"JWT Authentication with Node.js\"\n },\n {\n \"code\": null,\n \"e\": 7115,\n \"s\": 7065,\n \"text\": \"How to insert spaces/tabs in text using HTML/CSS?\"\n },\n {\n \"code\": null,\n \"e\": 7177,\n \"s\": 7115,\n \"text\": \"Top 10 Projects For Beginners To Practice HTML and CSS Skills\"\n },\n {\n \"code\": null,\n \"e\": 7237,\n \"s\": 7177,\n \"text\": \"How to set the default value for an HTML element ?\nHow to set input type date in dd-mm-yyyy format using HTML ?\nTypes of CSS (Cascading Style Sheet)"},"parsed":{"kind":"list like","value":[{"code":null,"e":28,"s":0,"text":"\n29 Nov, 2021"},{"code":null,"e":242,"s":28,"text":"There are lots of javascript libraries like – anime.js, screenfull.js, moment.js, etc. JQuery is also a part of javascript libraries. It is used to simplify the code. It is a lightweight and feature-rich library. "},{"code":null,"e":340,"s":242,"text":"In this article, we will learn how to find all children with a specified class of each division. "},{"code":null,"e":533,"s":340,"text":".children(selector) – In jquery you can achieve this task by using the method named .children(). It takes the selector as a parameter and changes the children element with the specified name. "},{"code":null,"e":544,"s":533,"text":"Example 1:"},{"code":null,"e":549,"s":544,"text":"HTML"},{"code":"

GeeksForGeeks

This is a span in div element. (children but not specified)

This is a paragraph with specified class in a div element.

This is inner div with specified class in a div element.

This is another paragraph in div element.(children but not specified)

","e":1561,"s":549,"text":null},{"code":null,"e":1569,"s":1561,"text":"Output:"},{"code":null,"e":1853,"s":1569,"text":"Explanation: The div element has 5 children ( 1 heading, 1 span, 1 inner div, and 3 paragraphs). In the code, we have specified three-element with class=”child” i.e. two paragraphs and one div. You can notice that only specified elements get affected and change their style property."},{"code":null,"e":1864,"s":1853,"text":"Example 2:"},{"code":null,"e":1869,"s":1864,"text":"HTML"},{"code":"

GeeksForGeeks

class with prime will only get different style property

'1' is not a prime number.

'2' is a prime number.

'3' is a prime number.

'4' is not a prime number.

'5' is a prime number

","e":2737,"s":1869,"text":null},{"code":null,"e":2747,"s":2737,"text":"Output – "},{"code":null,"e":2766,"s":2747,"text":"surindertarika1234"},{"code":null,"e":2780,"s":2766,"text":"CSS-Questions"},{"code":null,"e":2794,"s":2780,"text":"HTML-Property"},{"code":null,"e":2809,"s":2794,"text":"HTML-Questions"},{"code":null,"e":2819,"s":2809,"text":"HTML-Tags"},{"code":null,"e":2834,"s":2819,"text":"jQuery-Methods"},{"code":null,"e":2851,"s":2834,"text":"jQuery-Questions"},{"code":null,"e":2858,"s":2851,"text":"Picked"},{"code":null,"e":2862,"s":2858,"text":"CSS"},{"code":null,"e":2867,"s":2862,"text":"HTML"},{"code":null,"e":2874,"s":2867,"text":"JQuery"},{"code":null,"e":2891,"s":2874,"text":"Web Technologies"},{"code":null,"e":2896,"s":2891,"text":"HTML"},{"code":null,"e":2994,"s":2896,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":3031,"s":2994,"text":"Types of CSS (Cascading Style Sheet)"},{"code":null,"e":3070,"s":3031,"text":"How to set space between the flexbox ?"},{"code":null,"e":3109,"s":3070,"text":"Design a Tribute Page using HTML & CSS"},{"code":null,"e":3173,"s":3109,"text":"How to position a div at the bottom of its container using CSS?"},{"code":null,"e":3234,"s":3173,"text":"How to Upload Image into Database and Display it using PHP ?"},{"code":null,"e":3258,"s":3234,"text":"REST API (Introduction)"},{"code":null,"e":3311,"s":3258,"text":"Hide or show elements in HTML using display property"},{"code":null,"e":3371,"s":3311,"text":"How to set the default value for an HTML element ?\"\n },\n {\n \"code\": null,\n \"e\": 3432,\n \"s\": 3371,\n \"text\": \"How to set input type date in dd-mm-yyyy format using HTML ?\"\n }\n]"}}},{"rowIdx":175,"cells":{"title":{"kind":"string","value":"Python | Pandas dataframe.mad()"},"text":{"kind":"string","value":"19 Nov, 2018\nPython is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.\nPandas dataframe.mad() function return the mean absolute deviation of the values for the requested axis. The mean absolute deviation of a dataset is the average distance between each data point and the mean. It gives us an idea about the variability in a dataset.\nSyntax: DataFrame.mad(axis=None, skipna=None, level=None)\nParameters :axis : {index (0), columns (1)}skipna : Exclude NA/null values when computing the resultlevel : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Seriesnumeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.\nReturns : mad : Series or DataFrame (if level specified)\nExample #1: Use mad() function to find the mean absolute deviation of the values over the index axis.\n# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[12, 4, 5, 44, 1], \"B\":[5, 2, 54, 3, 2], \"C\":[20, 16, 7, 3, 8], \"D\":[14, 3, 17, 2, 6]}) # Print the dataframedf\nLet’s use the dataframe.mad() function to find the mean absolute deviation.\n# find the mean absolute deviation # over the index axisdf.mad(axis = 0)\nOutput : \nExample #2: Use mad() function to find the mean absolute deviation of values over the column axis which is having some Na values in it.\n# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[12, 4, 5, None, 1], \"B\":[7, 2, 54, 3, None], \"C\":[20, 16, 11, 3, 8], \"D\":[14, 3, None, 2, 6]}) # To find the mean absolute deviation# skip the Na values when finding the mad valuedf.mad(axis = 1, skipna = True)\nOutput :\nPython pandas-dataFrame\nPython pandas-dataFrame-methods\nPython-pandas\nPython\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nPython Dictionary\nDifferent ways to create Pandas Dataframe\nEnumerate() in Python\nRead a file line by line in Python\nPython String | replace()\nHow to Install PIP on Windows ?\n*args and **kwargs in Python\nPython Classes and Objects\nIterate over a list in Python\nPython OOPs Concepts"},"parsed":{"kind":"list like","value":[{"code":null,"e":28,"s":0,"text":"\n19 Nov, 2018"},{"code":null,"e":242,"s":28,"text":"Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."},{"code":null,"e":506,"s":242,"text":"Pandas dataframe.mad() function return the mean absolute deviation of the values for the requested axis. The mean absolute deviation of a dataset is the average distance between each data point and the mean. It gives us an idea about the variability in a dataset."},{"code":null,"e":564,"s":506,"text":"Syntax: DataFrame.mad(axis=None, skipna=None, level=None)"},{"code":null,"e":926,"s":564,"text":"Parameters :axis : {index (0), columns (1)}skipna : Exclude NA/null values when computing the resultlevel : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Seriesnumeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series."},{"code":null,"e":983,"s":926,"text":"Returns : mad : Series or DataFrame (if level specified)"},{"code":null,"e":1085,"s":983,"text":"Example #1: Use mad() function to find the mean absolute deviation of the values over the index axis."},{"code":"# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[12, 4, 5, 44, 1], \"B\":[5, 2, 54, 3, 2], \"C\":[20, 16, 7, 3, 8], \"D\":[14, 3, 17, 2, 6]}) # Print the dataframedf","e":1346,"s":1085,"text":null},{"code":null,"e":1422,"s":1346,"text":"Let’s use the dataframe.mad() function to find the mean absolute deviation."},{"code":"# find the mean absolute deviation # over the index axisdf.mad(axis = 0)","e":1495,"s":1422,"text":null},{"code":null,"e":1505,"s":1495,"text":"Output : "},{"code":null,"e":1641,"s":1505,"text":"Example #2: Use mad() function to find the mean absolute deviation of values over the column axis which is having some Na values in it."},{"code":"# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[12, 4, 5, None, 1], \"B\":[7, 2, 54, 3, None], \"C\":[20, 16, 11, 3, 8], \"D\":[14, 3, None, 2, 6]}) # To find the mean absolute deviation# skip the Na values when finding the mad valuedf.mad(axis = 1, skipna = True)","e":2002,"s":1641,"text":null},{"code":null,"e":2011,"s":2002,"text":"Output :"},{"code":null,"e":2035,"s":2011,"text":"Python pandas-dataFrame"},{"code":null,"e":2067,"s":2035,"text":"Python pandas-dataFrame-methods"},{"code":null,"e":2081,"s":2067,"text":"Python-pandas"},{"code":null,"e":2088,"s":2081,"text":"Python"},{"code":null,"e":2186,"s":2088,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":2204,"s":2186,"text":"Python Dictionary"},{"code":null,"e":2246,"s":2204,"text":"Different ways to create Pandas Dataframe"},{"code":null,"e":2268,"s":2246,"text":"Enumerate() in Python"},{"code":null,"e":2303,"s":2268,"text":"Read a file line by line in Python"},{"code":null,"e":2329,"s":2303,"text":"Python String | replace()"},{"code":null,"e":2361,"s":2329,"text":"How to Install PIP on Windows ?"},{"code":null,"e":2390,"s":2361,"text":"*args and **kwargs in Python"},{"code":null,"e":2417,"s":2390,"text":"Python Classes and Objects"},{"code":null,"e":2447,"s":2417,"text":"Iterate over a list in Python"}],"string":"[\n {\n \"code\": null,\n \"e\": 28,\n \"s\": 0,\n \"text\": \"\\n19 Nov, 2018\"\n },\n {\n \"code\": null,\n \"e\": 242,\n \"s\": 28,\n \"text\": \"Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.\"\n },\n {\n \"code\": null,\n \"e\": 506,\n \"s\": 242,\n \"text\": \"Pandas dataframe.mad() function return the mean absolute deviation of the values for the requested axis. The mean absolute deviation of a dataset is the average distance between each data point and the mean. It gives us an idea about the variability in a dataset.\"\n },\n {\n \"code\": null,\n \"e\": 564,\n \"s\": 506,\n \"text\": \"Syntax: DataFrame.mad(axis=None, skipna=None, level=None)\"\n },\n {\n \"code\": null,\n \"e\": 926,\n \"s\": 564,\n \"text\": \"Parameters :axis : {index (0), columns (1)}skipna : Exclude NA/null values when computing the resultlevel : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Seriesnumeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.\"\n },\n {\n \"code\": null,\n \"e\": 983,\n \"s\": 926,\n \"text\": \"Returns : mad : Series or DataFrame (if level specified)\"\n },\n {\n \"code\": null,\n \"e\": 1085,\n \"s\": 983,\n \"text\": \"Example #1: Use mad() function to find the mean absolute deviation of the values over the index axis.\"\n },\n {\n \"code\": \"# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\\\"A\\\":[12, 4, 5, 44, 1], \\\"B\\\":[5, 2, 54, 3, 2], \\\"C\\\":[20, 16, 7, 3, 8], \\\"D\\\":[14, 3, 17, 2, 6]}) # Print the dataframedf\",\n \"e\": 1346,\n \"s\": 1085,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 1422,\n \"s\": 1346,\n \"text\": \"Let’s use the dataframe.mad() function to find the mean absolute deviation.\"\n },\n {\n \"code\": \"# find the mean absolute deviation # over the index axisdf.mad(axis = 0)\",\n \"e\": 1495,\n \"s\": 1422,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 1505,\n \"s\": 1495,\n \"text\": \"Output : \"\n },\n {\n \"code\": null,\n \"e\": 1641,\n \"s\": 1505,\n \"text\": \"Example #2: Use mad() function to find the mean absolute deviation of values over the column axis which is having some Na values in it.\"\n },\n {\n \"code\": \"# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\\\"A\\\":[12, 4, 5, None, 1], \\\"B\\\":[7, 2, 54, 3, None], \\\"C\\\":[20, 16, 11, 3, 8], \\\"D\\\":[14, 3, None, 2, 6]}) # To find the mean absolute deviation# skip the Na values when finding the mad valuedf.mad(axis = 1, skipna = True)\",\n \"e\": 2002,\n \"s\": 1641,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 2011,\n \"s\": 2002,\n \"text\": \"Output :\"\n },\n {\n \"code\": null,\n \"e\": 2035,\n \"s\": 2011,\n \"text\": \"Python pandas-dataFrame\"\n },\n {\n \"code\": null,\n \"e\": 2067,\n \"s\": 2035,\n \"text\": \"Python pandas-dataFrame-methods\"\n },\n {\n \"code\": null,\n \"e\": 2081,\n \"s\": 2067,\n \"text\": \"Python-pandas\"\n },\n {\n \"code\": null,\n \"e\": 2088,\n \"s\": 2081,\n \"text\": \"Python\"\n },\n {\n \"code\": null,\n \"e\": 2186,\n \"s\": 2088,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 2204,\n \"s\": 2186,\n \"text\": \"Python Dictionary\"\n },\n {\n \"code\": null,\n \"e\": 2246,\n \"s\": 2204,\n \"text\": \"Different ways to create Pandas Dataframe\"\n },\n {\n \"code\": null,\n \"e\": 2268,\n \"s\": 2246,\n \"text\": \"Enumerate() in Python\"\n },\n {\n \"code\": null,\n \"e\": 2303,\n \"s\": 2268,\n \"text\": \"Read a file line by line in Python\"\n },\n {\n \"code\": null,\n \"e\": 2329,\n \"s\": 2303,\n \"text\": \"Python String | replace()\"\n },\n {\n \"code\": null,\n \"e\": 2361,\n \"s\": 2329,\n \"text\": \"How to Install PIP on Windows ?\"\n },\n {\n \"code\": null,\n \"e\": 2390,\n \"s\": 2361,\n \"text\": \"*args and **kwargs in Python\"\n },\n {\n \"code\": null,\n \"e\": 2417,\n \"s\": 2390,\n \"text\": \"Python Classes and Objects\"\n },\n {\n \"code\": null,\n \"e\": 2447,\n \"s\": 2417,\n \"text\": \"Iterate over a list in Python\"\n }\n]"}}},{"rowIdx":176,"cells":{"title":{"kind":"string","value":"Maximum difference between two elements such that larger element appears after the smaller number"},"text":{"kind":"string","value":"21 Jun, 2022\nGiven an array arr[] of integers, find out the maximum difference between any two elements such that larger element appears after the smaller number. \nExamples : \nInput : arr = {2, 3, 10, 6, 4, 8, 1}\nOutput : 8\nExplanation : The maximum difference is between 10 and 2.\n\nInput : arr = {7, 9, 5, 6, 3, 2}\nOutput : 2\nExplanation : The maximum difference is between 9 and 7.\nMethod 1 (Simple) Use two loops. In the outer loop, pick elements one by one and in the inner loop calculate the difference of the picked element with every other element in the array and compare the difference with the maximum difference calculated so far. Below is the implementation of the above approach : \nC++\nC\nJava\nPython3\nC#\nPHP\nJavascript\n// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number#include using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */int maxDiff(int arr[], int arr_size){ int max_diff = arr[1] - arr[0]; for (int i = 0; i < arr_size; i++) { for (int j = i+1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff;} /* Driver program to test above function */int main(){ int arr[] = {1, 2, 90, 10, 110}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << \"Maximum difference is \" << maxDiff(arr, n); return 0;}\n#include /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order. Returns 0 if elements are equal */int maxDiff(int arr[], int arr_size){ int max_diff = arr[1] - arr[0]; int i, j; for (i = 0; i < arr_size; i++) { for (j = i+1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff;} /* Driver program to test above function */int main(){ int arr[] = {1, 2, 90, 10, 110}; printf(\"Maximum difference is %d\", maxDiff(arr, 5)); getchar(); return 0;}\n// Java program to find Maximum difference // between two elements such that larger // element appears after the smaller numberclass MaximumDifference { /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order. Returns 0 if elements are equal */ int maxDiff(int arr[], int arr_size) { int max_diff = arr[1] - arr[0]; int i, j; for (i = 0; i < arr_size; i++) { for (j = i + 1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff; } /* Driver program to test above functions */ public static void main(String[] args) { MaximumDifference maxdif = new MaximumDifference(); int arr[] = {1, 2, 90, 10, 110}; System.out.println(\"Maximum difference is \" + maxdif.maxDiff(arr, 5)); }} // This code has been contributed by Mayank Jaiswal\n# Python 3 code to find Maximum difference# between two elements such that larger # element appears after the smaller number # The function assumes that there are at # least two elements in array. The function # returns a negative value if the array is# sorted in decreasing order. Returns 0 # if elements are equaldef maxDiff(arr, arr_size): max_diff = arr[1] - arr[0] for i in range( arr_size ): for j in range( i+1, arr_size ): if(arr[j] - arr[i] > max_diff): max_diff = arr[j] - arr[i] return max_diff # Driver program to test above function arr = [1, 2, 90, 10, 110]size = len(arr)print (\"Maximum difference is\", maxDiff(arr, size)) # This code is contributed by Swetank Modi\n// C# code to find Maximum differenceusing System; class GFG { // The function assumes that there // are at least two elements in array. // The function returns a negative // value if the array is sorted in // decreasing order. Returns 0 if // elements are equal static int maxDiff(int[] arr, int arr_size) { int max_diff = arr[1] - arr[0]; int i, j; for (i = 0; i < arr_size; i++) { for (j = i + 1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff; } // Driver code public static void Main() { int[] arr = { 1, 2, 90, 10, 110 }; Console.Write(\"Maximum difference is \" + maxDiff(arr, 5)); }} // This code is contributed by Sam007\n $max_diff) $max_diff = $arr[$j] - $arr[$i]; } } return $max_diff;} // Driver Code$arr = array(1, 2, 90, 10, 110);$n = sizeof($arr); // Function callingecho \"Maximum difference is \" . maxDiff($arr, $n); // This code is contributed // by Akanksha Rai(Abby_akku)\n\nOutput :\nMaximum difference is 109\nTime Complexity : O(n^2) Auxiliary Space : O(1)\nMethod 2 (Tricky and Efficient) In this method, instead of taking difference of the picked element with every other element, we take the difference with the minimum element found so far. So we need to keep track of 2 things: 1) Maximum difference found so far (max_diff). 2) Minimum number visited so far (min_element).\nC++\nC\nJava\nPython3\nC#\nPHP\nJavascript\n// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number#include using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */int maxDiff(int arr[], int arr_size){ // Maximum difference found so far int max_diff = arr[1] - arr[0]; // Minimum number visited so far int min_element = arr[0]; for(int i = 1; i < arr_size; i++) { if (arr[i] - min_element > max_diff) max_diff = arr[i] - min_element; if (arr[i] < min_element) min_element = arr[i]; } return max_diff;} /* Driver program to test above function */int main(){ int arr[] = {1, 2, 90, 10, 110}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << \"Maximum difference is \" << maxDiff(arr, n); return 0;}\n#include /* The function assumes that there are at least twoelements in array.The function returns a negative value if the array issorted in decreasing order.Returns 0 if elements are equal */int maxDiff(int arr[], int arr_size){int max_diff = arr[1] - arr[0];int min_element = arr[0];int i;for(i = 1; i < arr_size; i++){ if (arr[i] - min_element > max_diff) max_diff = arr[i] - min_element; if (arr[i] < min_element) min_element = arr[i]; }return max_diff;} /* Driver program to test above function */int main(){int arr[] = {1, 2, 6, 80, 100};int size = sizeof(arr)/sizeof(arr[0]);printf(\"Maximum difference is %d\", maxDiff(arr, size));getchar();return 0;}\n// Java program to find Maximum difference // between two elements such that larger // element appears after the smaller numberclass MaximumDifference { /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order. Returns 0 if elements are equal */ int maxDiff(int arr[], int arr_size) { int max_diff = arr[1] - arr[0]; int min_element = arr[0]; int i; for (i = 1; i < arr_size; i++) { if (arr[i] - min_element > max_diff) max_diff = arr[i] - min_element; if (arr[i] < min_element) min_element = arr[i]; } return max_diff; } /* Driver program to test above functions */ public static void main(String[] args) { MaximumDifference maxdif = new MaximumDifference(); int arr[] = {1, 2, 90, 10, 110}; int size = arr.length; System.out.println(\"MaximumDifference is \" + maxdif.maxDiff(arr, size)); }} // This code has been contributed by Mayank Jaiswal\n# Python 3 code to find Maximum difference# between two elements such that larger # element appears after the smaller number # The function assumes that there are # at least two elements in array.# The function returns a negative # value if the array is sorted in # decreasing order. Returns 0 if # elements are equaldef maxDiff(arr, arr_size): max_diff = arr[1] - arr[0] min_element = arr[0] for i in range( 1, arr_size ): if (arr[i] - min_element > max_diff): max_diff = arr[i] - min_element if (arr[i] < min_element): min_element = arr[i] return max_diff # Driver program to test above function arr = [1, 2, 6, 80, 100]size = len(arr)print (\"Maximum difference is\", maxDiff(arr, size)) # This code is contributed by Swetank Modi\n// C# code to find Maximum differenceusing System; class GFG { // The function assumes that there // are at least two elements in array. // The function returns a negative // value if the array is sorted in // decreasing order.Returns 0 if // elements are equal static int maxDiff(int[] arr, int arr_size) { int max_diff = arr[1] - arr[0]; int min_element = arr[0]; int i; for (i = 1; i < arr_size; i++) { if (arr[i] - min_element > max_diff) max_diff = arr[i] - min_element; if (arr[i] < min_element) min_element = arr[i]; } return max_diff; } // Driver code public static void Main() { int[] arr = { 1, 2, 90, 10, 110 }; int size = arr.Length; Console.Write(\"MaximumDifference is \" + maxDiff(arr, size)); }} // This code is contributed by Sam007\n $max_diff) $max_diff = $arr[$i] - $min_element; if ($arr[$i] < $min_element) $min_element = $arr[$i]; } return $max_diff;} // Driver Code$arr = array(1, 2, 90, 10, 110);$n = count($arr); // Function callingecho \"Maximum difference is \" . maxDiff($arr, $n); // This code is contributed by Sam007?>\n\nOutput:\nMaximum difference is 109\nTime Complexity : O(n) Auxiliary Space : O(1)\nLike min element, we can also keep track of max element from right side. Thanks to Katamaran for suggesting this approach. Below is the implementation : \nC++\nJava\nPython3\nC#\nPHP\nJavascript\n// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number#include using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */int maxDiff(int arr[], int n){ // Initialize Result int maxDiff = -1; // Initialize max element from right side int maxRight = arr[n-1]; for (int i = n-2; i >= 0; i--) { if (arr[i] > maxRight) maxRight = arr[i]; else { int diff = maxRight - arr[i]; if (diff > maxDiff) { maxDiff = diff; } } } return maxDiff;} /* Driver program to test above function */int main(){ int arr[] = {1, 2, 90, 10, 110}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << \"Maximum difference is \" << maxDiff(arr, n); return 0;}\n// Java program to find Maximum difference // between two elements such that larger // element appears after the smaller number import java.io.*; class GFG {/* The function assumes that there are at least two elements in array. The function returns a negative value if thearray is sorted in decreasing order and returns 0 if elements are equal */static int maxDiff(int arr[], int n){ // Initialize Result int maxDiff = -1; // Initialize max element from right side int maxRight = arr[n-1]; for (int i = n-2; i >= 0; i--) { if (arr[i] > maxRight) maxRight = arr[i]; else { int diff = maxRight - arr[i]; if (diff > maxDiff) { maxDiff = diff; } } } return maxDiff;} /* Driver program to test above function */ public static void main (String[] args) { int arr[] = {1, 2, 90, 10, 110}; int n = arr.length; // Function calling System.out.println (\"Maximum difference is \" + maxDiff(arr, n)); }//This code is contributed by Tushil.. }\n# Python3 program to find Maximum difference # between two elements such that larger # element appears after the smaller number # The function assumes that there are # at least two elements in array. The # function returns a negative value if the# array is sorted in decreasing order and # returns 0 if elements are equaldef maxDiff(arr, n): # Initialize Result maxDiff = -1 # Initialize max element from # right side maxRight = arr[-1] for i in reversed(arr[:-1]): if (i > maxRight): maxRight = i else: diff = maxRight - i if (diff > maxDiff): maxDiff = diff return maxDiff # Driver Codeif __name__ == '__main__': arr = [1, 2, 90, 10, 110] n = len(arr) # Function calling print(\"Maximum difference is\", maxDiff(arr, n)) # This code is contributed by 29AjayKumar\n// C# program to find Maximum difference // between two elements such that larger // element appears after the smaller numberusing System; class GFG{/* The function assumes that there are at least two elements in array. The function returns a negative value if thearray is sorted in decreasing order and returns 0 if elements are equal */static int maxDiff(int[] arr, int n){ // Initialize Result int maxDiff = -1; // Initialize max element from right side int maxRight = arr[n-1]; for (int i = n-2; i >= 0; i--) { if (arr[i] > maxRight) maxRight = arr[i]; else { int diff = maxRight - arr[i]; if (diff > maxDiff) { maxDiff = diff; } } } return maxDiff;} // Driver Codepublic static void Main () { int[] arr = {1, 2, 90, 10, 110}; int n = arr.Length; // Function calling Console.WriteLine(\"Maximum difference is \" + maxDiff(arr, n));}} // This code is contributed // by Akanksha Rai\n= 0; $i--) { if ($arr[$i] > $maxRight) $maxRight = $arr[$i]; else { $diff = $maxRight - $arr[$i]; if ($diff > $maxDiff) { $maxDiff = $diff; } } } return $maxDiff; } // Driver Code$arr = array(1, 2, 90, 10, 110); $n = sizeof($arr); // Function calling echo \"Maximum difference is \", maxDiff($arr, $n); // This code is contributed by ajit?>\n\nOutput: \nMaximum difference is 109\nTime Complexity : O(n) Auxiliary Space : O(1)\nMethod 3 (Another Tricky Solution) First find the difference between the adjacent elements of the array and store all differences in an auxiliary array diff[] of size n-1. Now this problems turns into finding the maximum sum subarray of this difference array.Thanks to Shubham Mittal for suggesting this solution. Below is the implementation :\nC++\nC\nJava\nPython3\nC#\nPHP\nJavascript\n// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number#include using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */int maxDiff(int arr[], int n){ // Create a diff array of size n-1. // The array will hold the difference // of adjacent elements int diff[n-1]; for (int i=0; i < n-1; i++) diff[i] = arr[i+1] - arr[i]; // Now find the maximum sum // subarray in diff array int max_diff = diff[0]; for (int i=1; i 0) diff[i] += diff[i-1]; if (max_diff < diff[i]) max_diff = diff[i]; } return max_diff;} /* Driver program to test above function */int main(){ int arr[] = {80, 2, 6, 3, 100}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << \"Maximum difference is \" << maxDiff(arr, n); return 0;}\n#include int maxDiff(int arr[], int n){ // Create a diff array of size n-1. The array will hold // the difference of adjacent elements int diff[n-1]; for (int i=0; i < n-1; i++) diff[i] = arr[i+1] - arr[i]; // Now find the maximum sum subarray in diff array int max_diff = diff[0]; for (int i=1; i 0) diff[i] += diff[i-1]; if (max_diff < diff[i]) max_diff = diff[i]; } return max_diff;} /* Driver program to test above function */int main(){ int arr[] = {80, 2, 6, 3, 100}; int size = sizeof(arr)/sizeof(arr[0]); printf(\"Maximum difference is %d\", maxDiff(arr, size)); return 0;}\n// Java program to find Maximum difference // between two elements such that larger // element appears after the smaller numberclass MaximumDifference { int maxDiff(int arr[], int n) { // Create a diff array of size n-1. The array will hold // the difference of adjacent elements int diff[] = new int[n - 1]; for (int i = 0; i < n - 1; i++) diff[i] = arr[i + 1] - arr[i]; // Now find the maximum sum subarray in diff array int max_diff = diff[0]; for (int i = 1; i < n - 1; i++) { if (diff[i - 1] > 0) diff[i] += diff[i - 1]; if (max_diff < diff[i]) max_diff = diff[i]; } return max_diff; } // Driver program to test above functions public static void main(String[] args) { MaximumDifference mxdif = new MaximumDifference(); int arr[] = {80, 2, 6, 3, 100}; int size = arr.length; System.out.println(mxdif.maxDiff(arr, size)); }}// This code has been contributed by Mayank Jaiswal\n# Python 3 code to find Maximum difference# between two elements such that larger # element appears after the smaller number def maxDiff(arr, n): diff = [0] * (n - 1) for i in range (0, n-1): diff[i] = arr[i+1] - arr[i] # Now find the maximum sum # subarray in diff array max_diff = diff[0] for i in range(1, n-1): if (diff[i-1] > 0): diff[i] += diff[i-1] if (max_diff < diff[i]): max_diff = diff[i] return max_diff # Driver program to test above function arr = [80, 2, 6, 3, 100]size = len(arr)print (\"Maximum difference is\", maxDiff(arr, size)) # This code is contributed by Swetank Modi\n// C# code to find Maximum differenceusing System; class GFG { static int maxDiff(int[] arr, int n) { // Create a diff array of size n-1. // The array will hold the // difference of adjacent elements int[] diff = new int[n - 1]; for (int i = 0; i < n - 1; i++) diff[i] = arr[i + 1] - arr[i]; // Now find the maximum sum // subarray in diff array int max_diff = diff[0]; for (int i = 1; i < n - 1; i++) { if (diff[i - 1] > 0) diff[i] += diff[i - 1]; if (max_diff < diff[i]) max_diff = diff[i]; } return max_diff; } // Driver code public static void Main() { int[] arr = { 80, 2, 6, 3, 100 }; int size = arr.Length; Console.Write(maxDiff(arr, size)); }} // This code is contributed by Sam007\n 0) $diff[$i] += $diff[$i-1]; if ($max_diff < $diff[$i]) $max_diff = $diff[$i]; } return $max_diff;} // Driver Code$arr = array(80, 2, 6, 3, 100);$n = sizeof($arr); // Function callingecho \"Maximum difference is \" . maxDiff($arr, $n); // This code is contributed // by Akanksha Rai\n\nOutput:\nMaximum difference is 98\nTime Complexity : O(n) Auxiliary Space : O(n)\nWe can modify the above method to work in O(1) extra space. Instead of creating an auxiliary array, we can calculate diff and max sum in same loop. Following is the space optimized version.\nC++\nJava\nPython3\nC#\nPHP\nJavascript\n// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number#include using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */int maxDiff (int arr[], int n){ // Initialize diff, current sum and max sum int diff = arr[1]-arr[0]; int curr_sum = diff; int max_sum = curr_sum; for(int i=1; i 0) curr_sum += diff; else curr_sum = diff; // Update max sum, if needed if (curr_sum > max_sum) max_sum = curr_sum; } return max_sum;} /* Driver program to test above function */int main(){ int arr[] = {80, 2, 6, 3, 100}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << \"Maximum difference is \" << maxDiff(arr, n); return 0;}\n// Java program to find Maximum // difference between two elements // such that larger element appears // after the smaller number class GFG{ /* The function assumes that thereare at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 ifelements are equal */static int maxDiff (int arr[], int n) { // Initialize diff, current // sum and max sum int diff = arr[1] - arr[0]; int curr_sum = diff; int max_sum = curr_sum; for(int i = 1; i < n - 1; i++) { // Calculate current diff diff = arr[i + 1] - arr[i]; // Calculate current sum if (curr_sum > 0) curr_sum += diff; else curr_sum = diff; // Update max sum, if needed if (curr_sum > max_sum) max_sum = curr_sum; } return max_sum; } // Driver Codepublic static void main(String[] args) { int arr[] = {80, 2, 6, 3, 100}; int n = arr.length; // Function calling System.out.print(\"Maximum difference is \" + maxDiff(arr, n)); }} // This code is contributed by Smitha\n# Python3 program to find Maximum difference # between two elements such that larger # element appears after the smaller number # The function assumes that there are # at least two elements in array. The # function returns a negative value if # the array is sorted in decreasing # order and returns 0 if elements are equaldef maxDiff (arr, n): # Initialize diff, current # sum and max sum diff = arr[1] - arr[0] curr_sum = diff max_sum = curr_sum for i in range(1, n - 1): # Calculate current diff diff = arr[i + 1] - arr[i] # Calculate current sum if (curr_sum > 0): curr_sum += diff else: curr_sum = diff # Update max sum, if needed if (curr_sum > max_sum): max_sum = curr_sum return max_sum # Driver Codeif __name__ == '__main__': arr = [80, 2, 6, 3, 100] n = len(arr) # Function calling print(\"Maximum difference is\", maxDiff(arr, n)) # This code is contributed # by 29AjayKumar\n// C# program to find Maximum // difference between two elements // such that larger element appears // after the smaller number using System;class GFG{ /* The function assumes that thereare at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 ifelements are equal */static int maxDiff (int[] arr, int n) { // Initialize diff, current // sum and max sum int diff = arr[1] - arr[0]; int curr_sum = diff; int max_sum = curr_sum; for(int i = 1; i < n - 1; i++) { // Calculate current diff diff = arr[i + 1] - arr[i]; // Calculate current sum if (curr_sum > 0) curr_sum += diff; else curr_sum = diff; // Update max sum, if needed if (curr_sum > max_sum) max_sum = curr_sum; } return max_sum; } // Driver Codepublic static void Main() { int[] arr = {80, 2, 6, 3, 100}; int n = arr.Length; // Function calling Console.WriteLine(\"Maximum difference is \" + maxDiff(arr, n)); }} // This code is contributed // by Akanksha Rai(Abby_akku)\n 0) $curr_sum += $diff; else $curr_sum = $diff; // Update max sum, if needed if ($curr_sum > $max_sum) $max_sum = $curr_sum; } return $max_sum;} // Driver Code$arr = array(80, 2, 6, 3, 100);$n = sizeof($arr); // Function callingecho \"Maximum difference is \", maxDiff($arr, $n); // This code is contributed // by Sach_code?>\n\nOutput: \nMaximum difference is 98\nTime Complexity : O(n) Auxiliary Space : O(1) \nMaximum difference between two elements (larger element appears after smaller) | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersMaximum difference between two elements (larger element appears after smaller) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 11:18•Live•

An error occurred.

Try watching this video on www.youtube.com, or enable JavaScript if it is disabled in your browser.
\nBelow is a variation of this problem: Maximum difference of sum of elements in two rows in a matrixPlease write comments if you find any bug in above codes/algorithms, or find other ways to solve the same problem \nSam007\nSmitha Dinesh Semwal\nAkanksha_Rai\njit_t\nSach_Code\n29AjayKumar\njana_sayantan\ndecode2207\nsuresh07\nmayanktyagi1709\nrag2127\nsaurabh1990aror\ndevnawfalahmed\n202051178\n_shinchancode\nAmazon\nHike\nMakeMyTrip\nOla Cabs\nSAP Labs\nArrays\nAmazon\nHike\nMakeMyTrip\nOla Cabs\nSAP Labs\nArrays\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nMultidimensional Arrays in Java\nIntroduction to Arrays\nK'th Smallest/Largest Element in Unsorted Array | Set 1\nSubset Sum Problem | DP-25\nIntroduction to Data Structures\nPython | Using 2D arrays/lists the right way\nSearch an element in a sorted and rotated array\nFind Second largest element in an array\nFind the Missing Number\nCount Inversions in an array | Set 1 (Using Merge Sort)"},"parsed":{"kind":"list like","value":[{"code":null,"e":54,"s":26,"text":"\n21 Jun, 2022"},{"code":null,"e":205,"s":54,"text":"Given an array arr[] of integers, find out the maximum difference between any two elements such that larger element appears after the smaller number. "},{"code":null,"e":217,"s":205,"text":"Examples : "},{"code":null,"e":425,"s":217,"text":"Input : arr = {2, 3, 10, 6, 4, 8, 1}\nOutput : 8\nExplanation : The maximum difference is between 10 and 2.\n\nInput : arr = {7, 9, 5, 6, 3, 2}\nOutput : 2\nExplanation : The maximum difference is between 9 and 7."},{"code":null,"e":736,"s":425,"text":"Method 1 (Simple) Use two loops. In the outer loop, pick elements one by one and in the inner loop calculate the difference of the picked element with every other element in the array and compare the difference with the maximum difference calculated so far. Below is the implementation of the above approach : "},{"code":null,"e":740,"s":736,"text":"C++"},{"code":null,"e":742,"s":740,"text":"C"},{"code":null,"e":747,"s":742,"text":"Java"},{"code":null,"e":755,"s":747,"text":"Python3"},{"code":null,"e":758,"s":755,"text":"C#"},{"code":null,"e":762,"s":758,"text":"PHP"},{"code":null,"e":773,"s":762,"text":"Javascript"},{"code":"// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number#include using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */int maxDiff(int arr[], int arr_size){ int max_diff = arr[1] - arr[0]; for (int i = 0; i < arr_size; i++) { for (int j = i+1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff;} /* Driver program to test above function */int main(){ int arr[] = {1, 2, 90, 10, 110}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << \"Maximum difference is \" << maxDiff(arr, n); return 0;}","e":1645,"s":773,"text":null},{"code":"#include /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order. Returns 0 if elements are equal */int maxDiff(int arr[], int arr_size){ int max_diff = arr[1] - arr[0]; int i, j; for (i = 0; i < arr_size; i++) { for (j = i+1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff;} /* Driver program to test above function */int main(){ int arr[] = {1, 2, 90, 10, 110}; printf(\"Maximum difference is %d\", maxDiff(arr, 5)); getchar(); return 0;}","e":2321,"s":1645,"text":null},{"code":"// Java program to find Maximum difference // between two elements such that larger // element appears after the smaller numberclass MaximumDifference { /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order. Returns 0 if elements are equal */ int maxDiff(int arr[], int arr_size) { int max_diff = arr[1] - arr[0]; int i, j; for (i = 0; i < arr_size; i++) { for (j = i + 1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff; } /* Driver program to test above functions */ public static void main(String[] args) { MaximumDifference maxdif = new MaximumDifference(); int arr[] = {1, 2, 90, 10, 110}; System.out.println(\"Maximum difference is \" + maxdif.maxDiff(arr, 5)); }} // This code has been contributed by Mayank Jaiswal","e":3411,"s":2321,"text":null},{"code":"# Python 3 code to find Maximum difference# between two elements such that larger # element appears after the smaller number # The function assumes that there are at # least two elements in array. The function # returns a negative value if the array is# sorted in decreasing order. Returns 0 # if elements are equaldef maxDiff(arr, arr_size): max_diff = arr[1] - arr[0] for i in range( arr_size ): for j in range( i+1, arr_size ): if(arr[j] - arr[i] > max_diff): max_diff = arr[j] - arr[i] return max_diff # Driver program to test above function arr = [1, 2, 90, 10, 110]size = len(arr)print (\"Maximum difference is\", maxDiff(arr, size)) # This code is contributed by Swetank Modi","e":4154,"s":3411,"text":null},{"code":"// C# code to find Maximum differenceusing System; class GFG { // The function assumes that there // are at least two elements in array. // The function returns a negative // value if the array is sorted in // decreasing order. Returns 0 if // elements are equal static int maxDiff(int[] arr, int arr_size) { int max_diff = arr[1] - arr[0]; int i, j; for (i = 0; i < arr_size; i++) { for (j = i + 1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff; } // Driver code public static void Main() { int[] arr = { 1, 2, 90, 10, 110 }; Console.Write(\"Maximum difference is \" + maxDiff(arr, 5)); }} // This code is contributed by Sam007","e":5024,"s":4154,"text":null},{"code":" $max_diff) $max_diff = $arr[$j] - $arr[$i]; } } return $max_diff;} // Driver Code$arr = array(1, 2, 90, 10, 110);$n = sizeof($arr); // Function callingecho \"Maximum difference is \" . maxDiff($arr, $n); // This code is contributed // by Akanksha Rai(Abby_akku)","e":5815,"s":5024,"text":null},{"code":"","e":6694,"s":5815,"text":null},{"code":null,"e":6703,"s":6694,"text":"Output :"},{"code":null,"e":6729,"s":6703,"text":"Maximum difference is 109"},{"code":null,"e":6777,"s":6729,"text":"Time Complexity : O(n^2) Auxiliary Space : O(1)"},{"code":null,"e":7097,"s":6777,"text":"Method 2 (Tricky and Efficient) In this method, instead of taking difference of the picked element with every other element, we take the difference with the minimum element found so far. So we need to keep track of 2 things: 1) Maximum difference found so far (max_diff). 2) Minimum number visited so far (min_element)."},{"code":null,"e":7101,"s":7097,"text":"C++"},{"code":null,"e":7103,"s":7101,"text":"C"},{"code":null,"e":7108,"s":7103,"text":"Java"},{"code":null,"e":7116,"s":7108,"text":"Python3"},{"code":null,"e":7119,"s":7116,"text":"C#"},{"code":null,"e":7123,"s":7119,"text":"PHP"},{"code":null,"e":7134,"s":7123,"text":"Javascript"},{"code":"// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number#include using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */int maxDiff(int arr[], int arr_size){ // Maximum difference found so far int max_diff = arr[1] - arr[0]; // Minimum number visited so far int min_element = arr[0]; for(int i = 1; i < arr_size; i++) { if (arr[i] - min_element > max_diff) max_diff = arr[i] - min_element; if (arr[i] < min_element) min_element = arr[i]; } return max_diff;} /* Driver program to test above function */int main(){ int arr[] = {1, 2, 90, 10, 110}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << \"Maximum difference is \" << maxDiff(arr, n); return 0;}","e":8204,"s":7134,"text":null},{"code":"#include /* The function assumes that there are at least twoelements in array.The function returns a negative value if the array issorted in decreasing order.Returns 0 if elements are equal */int maxDiff(int arr[], int arr_size){int max_diff = arr[1] - arr[0];int min_element = arr[0];int i;for(i = 1; i < arr_size; i++){ if (arr[i] - min_element > max_diff) max_diff = arr[i] - min_element; if (arr[i] < min_element) min_element = arr[i]; }return max_diff;} /* Driver program to test above function */int main(){int arr[] = {1, 2, 6, 80, 100};int size = sizeof(arr)/sizeof(arr[0]);printf(\"Maximum difference is %d\", maxDiff(arr, size));getchar();return 0;}","e":8944,"s":8204,"text":null},{"code":"// Java program to find Maximum difference // between two elements such that larger // element appears after the smaller numberclass MaximumDifference { /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order. Returns 0 if elements are equal */ int maxDiff(int arr[], int arr_size) { int max_diff = arr[1] - arr[0]; int min_element = arr[0]; int i; for (i = 1; i < arr_size; i++) { if (arr[i] - min_element > max_diff) max_diff = arr[i] - min_element; if (arr[i] < min_element) min_element = arr[i]; } return max_diff; } /* Driver program to test above functions */ public static void main(String[] args) { MaximumDifference maxdif = new MaximumDifference(); int arr[] = {1, 2, 90, 10, 110}; int size = arr.length; System.out.println(\"MaximumDifference is \" + maxdif.maxDiff(arr, size)); }} // This code has been contributed by Mayank Jaiswal","e":10099,"s":8944,"text":null},{"code":"# Python 3 code to find Maximum difference# between two elements such that larger # element appears after the smaller number # The function assumes that there are # at least two elements in array.# The function returns a negative # value if the array is sorted in # decreasing order. Returns 0 if # elements are equaldef maxDiff(arr, arr_size): max_diff = arr[1] - arr[0] min_element = arr[0] for i in range( 1, arr_size ): if (arr[i] - min_element > max_diff): max_diff = arr[i] - min_element if (arr[i] < min_element): min_element = arr[i] return max_diff # Driver program to test above function arr = [1, 2, 6, 80, 100]size = len(arr)print (\"Maximum difference is\", maxDiff(arr, size)) # This code is contributed by Swetank Modi","e":10906,"s":10099,"text":null},{"code":"// C# code to find Maximum differenceusing System; class GFG { // The function assumes that there // are at least two elements in array. // The function returns a negative // value if the array is sorted in // decreasing order.Returns 0 if // elements are equal static int maxDiff(int[] arr, int arr_size) { int max_diff = arr[1] - arr[0]; int min_element = arr[0]; int i; for (i = 1; i < arr_size; i++) { if (arr[i] - min_element > max_diff) max_diff = arr[i] - min_element; if (arr[i] < min_element) min_element = arr[i]; } return max_diff; } // Driver code public static void Main() { int[] arr = { 1, 2, 90, 10, 110 }; int size = arr.Length; Console.Write(\"MaximumDifference is \" + maxDiff(arr, size)); }} // This code is contributed by Sam007","e":11852,"s":10906,"text":null},{"code":" $max_diff) $max_diff = $arr[$i] - $min_element; if ($arr[$i] < $min_element) $min_element = $arr[$i]; } return $max_diff;} // Driver Code$arr = array(1, 2, 90, 10, 110);$n = count($arr); // Function callingecho \"Maximum difference is \" . maxDiff($arr, $n); // This code is contributed by Sam007?>","e":12841,"s":11852,"text":null},{"code":"","e":13767,"s":12841,"text":null},{"code":null,"e":13775,"s":13767,"text":"Output:"},{"code":null,"e":13801,"s":13775,"text":"Maximum difference is 109"},{"code":null,"e":13847,"s":13801,"text":"Time Complexity : O(n) Auxiliary Space : O(1)"},{"code":null,"e":14001,"s":13847,"text":"Like min element, we can also keep track of max element from right side. Thanks to Katamaran for suggesting this approach. Below is the implementation : "},{"code":null,"e":14005,"s":14001,"text":"C++"},{"code":null,"e":14010,"s":14005,"text":"Java"},{"code":null,"e":14018,"s":14010,"text":"Python3"},{"code":null,"e":14021,"s":14018,"text":"C#"},{"code":null,"e":14025,"s":14021,"text":"PHP"},{"code":null,"e":14036,"s":14025,"text":"Javascript"},{"code":"// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number#include using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */int maxDiff(int arr[], int n){ // Initialize Result int maxDiff = -1; // Initialize max element from right side int maxRight = arr[n-1]; for (int i = n-2; i >= 0; i--) { if (arr[i] > maxRight) maxRight = arr[i]; else { int diff = maxRight - arr[i]; if (diff > maxDiff) { maxDiff = diff; } } } return maxDiff;} /* Driver program to test above function */int main(){ int arr[] = {1, 2, 90, 10, 110}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << \"Maximum difference is \" << maxDiff(arr, n); return 0;}","e":15074,"s":14036,"text":null},{"code":"// Java program to find Maximum difference // between two elements such that larger // element appears after the smaller number import java.io.*; class GFG {/* The function assumes that there are at least two elements in array. The function returns a negative value if thearray is sorted in decreasing order and returns 0 if elements are equal */static int maxDiff(int arr[], int n){ // Initialize Result int maxDiff = -1; // Initialize max element from right side int maxRight = arr[n-1]; for (int i = n-2; i >= 0; i--) { if (arr[i] > maxRight) maxRight = arr[i]; else { int diff = maxRight - arr[i]; if (diff > maxDiff) { maxDiff = diff; } } } return maxDiff;} /* Driver program to test above function */ public static void main (String[] args) { int arr[] = {1, 2, 90, 10, 110}; int n = arr.length; // Function calling System.out.println (\"Maximum difference is \" + maxDiff(arr, n)); }//This code is contributed by Tushil.. }","e":16166,"s":15074,"text":null},{"code":"# Python3 program to find Maximum difference # between two elements such that larger # element appears after the smaller number # The function assumes that there are # at least two elements in array. The # function returns a negative value if the# array is sorted in decreasing order and # returns 0 if elements are equaldef maxDiff(arr, n): # Initialize Result maxDiff = -1 # Initialize max element from # right side maxRight = arr[-1] for i in reversed(arr[:-1]): if (i > maxRight): maxRight = i else: diff = maxRight - i if (diff > maxDiff): maxDiff = diff return maxDiff # Driver Codeif __name__ == '__main__': arr = [1, 2, 90, 10, 110] n = len(arr) # Function calling print(\"Maximum difference is\", maxDiff(arr, n)) # This code is contributed by 29AjayKumar","e":17066,"s":16166,"text":null},{"code":"// C# program to find Maximum difference // between two elements such that larger // element appears after the smaller numberusing System; class GFG{/* The function assumes that there are at least two elements in array. The function returns a negative value if thearray is sorted in decreasing order and returns 0 if elements are equal */static int maxDiff(int[] arr, int n){ // Initialize Result int maxDiff = -1; // Initialize max element from right side int maxRight = arr[n-1]; for (int i = n-2; i >= 0; i--) { if (arr[i] > maxRight) maxRight = arr[i]; else { int diff = maxRight - arr[i]; if (diff > maxDiff) { maxDiff = diff; } } } return maxDiff;} // Driver Codepublic static void Main () { int[] arr = {1, 2, 90, 10, 110}; int n = arr.Length; // Function calling Console.WriteLine(\"Maximum difference is \" + maxDiff(arr, n));}} // This code is contributed // by Akanksha Rai","e":18129,"s":17066,"text":null},{"code":"= 0; $i--) { if ($arr[$i] > $maxRight) $maxRight = $arr[$i]; else { $diff = $maxRight - $arr[$i]; if ($diff > $maxDiff) { $maxDiff = $diff; } } } return $maxDiff; } // Driver Code$arr = array(1, 2, 90, 10, 110); $n = sizeof($arr); // Function calling echo \"Maximum difference is \", maxDiff($arr, $n); // This code is contributed by ajit?>","e":19121,"s":18129,"text":null},{"code":"","e":20168,"s":19121,"text":null},{"code":null,"e":20177,"s":20168,"text":"Output: "},{"code":null,"e":20203,"s":20177,"text":"Maximum difference is 109"},{"code":null,"e":20249,"s":20203,"text":"Time Complexity : O(n) Auxiliary Space : O(1)"},{"code":null,"e":20593,"s":20249,"text":"Method 3 (Another Tricky Solution) First find the difference between the adjacent elements of the array and store all differences in an auxiliary array diff[] of size n-1. Now this problems turns into finding the maximum sum subarray of this difference array.Thanks to Shubham Mittal for suggesting this solution. Below is the implementation :"},{"code":null,"e":20597,"s":20593,"text":"C++"},{"code":null,"e":20599,"s":20597,"text":"C"},{"code":null,"e":20604,"s":20599,"text":"Java"},{"code":null,"e":20612,"s":20604,"text":"Python3"},{"code":null,"e":20615,"s":20612,"text":"C#"},{"code":null,"e":20619,"s":20615,"text":"PHP"},{"code":null,"e":20630,"s":20619,"text":"Javascript"},{"code":"// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number#include using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */int maxDiff(int arr[], int n){ // Create a diff array of size n-1. // The array will hold the difference // of adjacent elements int diff[n-1]; for (int i=0; i < n-1; i++) diff[i] = arr[i+1] - arr[i]; // Now find the maximum sum // subarray in diff array int max_diff = diff[0]; for (int i=1; i 0) diff[i] += diff[i-1]; if (max_diff < diff[i]) max_diff = diff[i]; } return max_diff;} /* Driver program to test above function */int main(){ int arr[] = {80, 2, 6, 3, 100}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << \"Maximum difference is \" << maxDiff(arr, n); return 0;}","e":21721,"s":20630,"text":null},{"code":"#include int maxDiff(int arr[], int n){ // Create a diff array of size n-1. The array will hold // the difference of adjacent elements int diff[n-1]; for (int i=0; i < n-1; i++) diff[i] = arr[i+1] - arr[i]; // Now find the maximum sum subarray in diff array int max_diff = diff[0]; for (int i=1; i 0) diff[i] += diff[i-1]; if (max_diff < diff[i]) max_diff = diff[i]; } return max_diff;} /* Driver program to test above function */int main(){ int arr[] = {80, 2, 6, 3, 100}; int size = sizeof(arr)/sizeof(arr[0]); printf(\"Maximum difference is %d\", maxDiff(arr, size)); return 0;}","e":22429,"s":21721,"text":null},{"code":"// Java program to find Maximum difference // between two elements such that larger // element appears after the smaller numberclass MaximumDifference { int maxDiff(int arr[], int n) { // Create a diff array of size n-1. The array will hold // the difference of adjacent elements int diff[] = new int[n - 1]; for (int i = 0; i < n - 1; i++) diff[i] = arr[i + 1] - arr[i]; // Now find the maximum sum subarray in diff array int max_diff = diff[0]; for (int i = 1; i < n - 1; i++) { if (diff[i - 1] > 0) diff[i] += diff[i - 1]; if (max_diff < diff[i]) max_diff = diff[i]; } return max_diff; } // Driver program to test above functions public static void main(String[] args) { MaximumDifference mxdif = new MaximumDifference(); int arr[] = {80, 2, 6, 3, 100}; int size = arr.length; System.out.println(mxdif.maxDiff(arr, size)); }}// This code has been contributed by Mayank Jaiswal","e":23500,"s":22429,"text":null},{"code":"# Python 3 code to find Maximum difference# between two elements such that larger # element appears after the smaller number def maxDiff(arr, n): diff = [0] * (n - 1) for i in range (0, n-1): diff[i] = arr[i+1] - arr[i] # Now find the maximum sum # subarray in diff array max_diff = diff[0] for i in range(1, n-1): if (diff[i-1] > 0): diff[i] += diff[i-1] if (max_diff < diff[i]): max_diff = diff[i] return max_diff # Driver program to test above function arr = [80, 2, 6, 3, 100]size = len(arr)print (\"Maximum difference is\", maxDiff(arr, size)) # This code is contributed by Swetank Modi","e":24191,"s":23500,"text":null},{"code":"// C# code to find Maximum differenceusing System; class GFG { static int maxDiff(int[] arr, int n) { // Create a diff array of size n-1. // The array will hold the // difference of adjacent elements int[] diff = new int[n - 1]; for (int i = 0; i < n - 1; i++) diff[i] = arr[i + 1] - arr[i]; // Now find the maximum sum // subarray in diff array int max_diff = diff[0]; for (int i = 1; i < n - 1; i++) { if (diff[i - 1] > 0) diff[i] += diff[i - 1]; if (max_diff < diff[i]) max_diff = diff[i]; } return max_diff; } // Driver code public static void Main() { int[] arr = { 80, 2, 6, 3, 100 }; int size = arr.Length; Console.Write(maxDiff(arr, size)); }} // This code is contributed by Sam007","e":25079,"s":24191,"text":null},{"code":" 0) $diff[$i] += $diff[$i-1]; if ($max_diff < $diff[$i]) $max_diff = $diff[$i]; } return $max_diff;} // Driver Code$arr = array(80, 2, 6, 3, 100);$n = sizeof($arr); // Function callingecho \"Maximum difference is \" . maxDiff($arr, $n); // This code is contributed // by Akanksha Rai","e":26116,"s":25079,"text":null},{"code":"","e":27184,"s":26116,"text":null},{"code":null,"e":27192,"s":27184,"text":"Output:"},{"code":null,"e":27217,"s":27192,"text":"Maximum difference is 98"},{"code":null,"e":27263,"s":27217,"text":"Time Complexity : O(n) Auxiliary Space : O(n)"},{"code":null,"e":27453,"s":27263,"text":"We can modify the above method to work in O(1) extra space. Instead of creating an auxiliary array, we can calculate diff and max sum in same loop. Following is the space optimized version."},{"code":null,"e":27457,"s":27453,"text":"C++"},{"code":null,"e":27462,"s":27457,"text":"Java"},{"code":null,"e":27470,"s":27462,"text":"Python3"},{"code":null,"e":27473,"s":27470,"text":"C#"},{"code":null,"e":27477,"s":27473,"text":"PHP"},{"code":null,"e":27488,"s":27477,"text":"Javascript"},{"code":"// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number#include using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */int maxDiff (int arr[], int n){ // Initialize diff, current sum and max sum int diff = arr[1]-arr[0]; int curr_sum = diff; int max_sum = curr_sum; for(int i=1; i 0) curr_sum += diff; else curr_sum = diff; // Update max sum, if needed if (curr_sum > max_sum) max_sum = curr_sum; } return max_sum;} /* Driver program to test above function */int main(){ int arr[] = {80, 2, 6, 3, 100}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << \"Maximum difference is \" << maxDiff(arr, n); return 0;}","e":28584,"s":27488,"text":null},{"code":"// Java program to find Maximum // difference between two elements // such that larger element appears // after the smaller number class GFG{ /* The function assumes that thereare at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 ifelements are equal */static int maxDiff (int arr[], int n) { // Initialize diff, current // sum and max sum int diff = arr[1] - arr[0]; int curr_sum = diff; int max_sum = curr_sum; for(int i = 1; i < n - 1; i++) { // Calculate current diff diff = arr[i + 1] - arr[i]; // Calculate current sum if (curr_sum > 0) curr_sum += diff; else curr_sum = diff; // Update max sum, if needed if (curr_sum > max_sum) max_sum = curr_sum; } return max_sum; } // Driver Codepublic static void main(String[] args) { int arr[] = {80, 2, 6, 3, 100}; int n = arr.length; // Function calling System.out.print(\"Maximum difference is \" + maxDiff(arr, n)); }} // This code is contributed by Smitha","e":29731,"s":28584,"text":null},{"code":"# Python3 program to find Maximum difference # between two elements such that larger # element appears after the smaller number # The function assumes that there are # at least two elements in array. The # function returns a negative value if # the array is sorted in decreasing # order and returns 0 if elements are equaldef maxDiff (arr, n): # Initialize diff, current # sum and max sum diff = arr[1] - arr[0] curr_sum = diff max_sum = curr_sum for i in range(1, n - 1): # Calculate current diff diff = arr[i + 1] - arr[i] # Calculate current sum if (curr_sum > 0): curr_sum += diff else: curr_sum = diff # Update max sum, if needed if (curr_sum > max_sum): max_sum = curr_sum return max_sum # Driver Codeif __name__ == '__main__': arr = [80, 2, 6, 3, 100] n = len(arr) # Function calling print(\"Maximum difference is\", maxDiff(arr, n)) # This code is contributed # by 29AjayKumar","e":30782,"s":29731,"text":null},{"code":"// C# program to find Maximum // difference between two elements // such that larger element appears // after the smaller number using System;class GFG{ /* The function assumes that thereare at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 ifelements are equal */static int maxDiff (int[] arr, int n) { // Initialize diff, current // sum and max sum int diff = arr[1] - arr[0]; int curr_sum = diff; int max_sum = curr_sum; for(int i = 1; i < n - 1; i++) { // Calculate current diff diff = arr[i + 1] - arr[i]; // Calculate current sum if (curr_sum > 0) curr_sum += diff; else curr_sum = diff; // Update max sum, if needed if (curr_sum > max_sum) max_sum = curr_sum; } return max_sum; } // Driver Codepublic static void Main() { int[] arr = {80, 2, 6, 3, 100}; int n = arr.Length; // Function calling Console.WriteLine(\"Maximum difference is \" + maxDiff(arr, n)); }} // This code is contributed // by Akanksha Rai(Abby_akku)","e":31946,"s":30782,"text":null},{"code":" 0) $curr_sum += $diff; else $curr_sum = $diff; // Update max sum, if needed if ($curr_sum > $max_sum) $max_sum = $curr_sum; } return $max_sum;} // Driver Code$arr = array(80, 2, 6, 3, 100);$n = sizeof($arr); // Function callingecho \"Maximum difference is \", maxDiff($arr, $n); // This code is contributed // by Sach_code?>","e":32996,"s":31946,"text":null},{"code":"","e":34084,"s":32996,"text":null},{"code":null,"e":34093,"s":34084,"text":"Output: "},{"code":null,"e":34118,"s":34093,"text":"Maximum difference is 98"},{"code":null,"e":34165,"s":34118,"text":"Time Complexity : O(n) Auxiliary Space : O(1) "},{"code":null,"e":35140,"s":34165,"text":"Maximum difference between two elements (larger element appears after smaller) | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersMaximum difference between two elements (larger element appears after smaller) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 11:18•Live•

An error occurred.

Try watching this video on www.youtube.com, or enable JavaScript if it is disabled in your browser.
"},{"code":null,"e":35354,"s":35140,"text":"Below is a variation of this problem: Maximum difference of sum of elements in two rows in a matrixPlease write comments if you find any bug in above codes/algorithms, or find other ways to solve the same problem "},{"code":null,"e":35361,"s":35354,"text":"Sam007"},{"code":null,"e":35382,"s":35361,"text":"Smitha Dinesh Semwal"},{"code":null,"e":35395,"s":35382,"text":"Akanksha_Rai"},{"code":null,"e":35401,"s":35395,"text":"jit_t"},{"code":null,"e":35411,"s":35401,"text":"Sach_Code"},{"code":null,"e":35423,"s":35411,"text":"29AjayKumar"},{"code":null,"e":35437,"s":35423,"text":"jana_sayantan"},{"code":null,"e":35448,"s":35437,"text":"decode2207"},{"code":null,"e":35457,"s":35448,"text":"suresh07"},{"code":null,"e":35473,"s":35457,"text":"mayanktyagi1709"},{"code":null,"e":35481,"s":35473,"text":"rag2127"},{"code":null,"e":35497,"s":35481,"text":"saurabh1990aror"},{"code":null,"e":35512,"s":35497,"text":"devnawfalahmed"},{"code":null,"e":35522,"s":35512,"text":"202051178"},{"code":null,"e":35536,"s":35522,"text":"_shinchancode"},{"code":null,"e":35543,"s":35536,"text":"Amazon"},{"code":null,"e":35548,"s":35543,"text":"Hike"},{"code":null,"e":35559,"s":35548,"text":"MakeMyTrip"},{"code":null,"e":35568,"s":35559,"text":"Ola Cabs"},{"code":null,"e":35577,"s":35568,"text":"SAP Labs"},{"code":null,"e":35584,"s":35577,"text":"Arrays"},{"code":null,"e":35591,"s":35584,"text":"Amazon"},{"code":null,"e":35596,"s":35591,"text":"Hike"},{"code":null,"e":35607,"s":35596,"text":"MakeMyTrip"},{"code":null,"e":35616,"s":35607,"text":"Ola Cabs"},{"code":null,"e":35625,"s":35616,"text":"SAP Labs"},{"code":null,"e":35632,"s":35625,"text":"Arrays"},{"code":null,"e":35730,"s":35632,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":35762,"s":35730,"text":"Multidimensional Arrays in Java"},{"code":null,"e":35785,"s":35762,"text":"Introduction to Arrays"},{"code":null,"e":35841,"s":35785,"text":"K'th Smallest/Largest Element in Unsorted Array | Set 1"},{"code":null,"e":35868,"s":35841,"text":"Subset Sum Problem | DP-25"},{"code":null,"e":35900,"s":35868,"text":"Introduction to Data Structures"},{"code":null,"e":35945,"s":35900,"text":"Python | Using 2D arrays/lists the right way"},{"code":null,"e":35993,"s":35945,"text":"Search an element in a sorted and rotated array"},{"code":null,"e":36033,"s":35993,"text":"Find Second largest element in an array"},{"code":null,"e":36057,"s":36033,"text":"Find the Missing Number"}],"string":"[\n {\n \"code\": null,\n \"e\": 54,\n \"s\": 26,\n \"text\": \"\\n21 Jun, 2022\"\n },\n {\n \"code\": null,\n \"e\": 205,\n \"s\": 54,\n \"text\": \"Given an array arr[] of integers, find out the maximum difference between any two elements such that larger element appears after the smaller number. \"\n },\n {\n \"code\": null,\n \"e\": 217,\n \"s\": 205,\n \"text\": \"Examples : \"\n },\n {\n \"code\": null,\n \"e\": 425,\n \"s\": 217,\n \"text\": \"Input : arr = {2, 3, 10, 6, 4, 8, 1}\\nOutput : 8\\nExplanation : The maximum difference is between 10 and 2.\\n\\nInput : arr = {7, 9, 5, 6, 3, 2}\\nOutput : 2\\nExplanation : The maximum difference is between 9 and 7.\"\n },\n {\n \"code\": null,\n \"e\": 736,\n \"s\": 425,\n \"text\": \"Method 1 (Simple) Use two loops. In the outer loop, pick elements one by one and in the inner loop calculate the difference of the picked element with every other element in the array and compare the difference with the maximum difference calculated so far. Below is the implementation of the above approach : \"\n },\n {\n \"code\": null,\n \"e\": 740,\n \"s\": 736,\n \"text\": \"C++\"\n },\n {\n \"code\": null,\n \"e\": 742,\n \"s\": 740,\n \"text\": \"C\"\n },\n {\n \"code\": null,\n \"e\": 747,\n \"s\": 742,\n \"text\": \"Java\"\n },\n {\n \"code\": null,\n \"e\": 755,\n \"s\": 747,\n \"text\": \"Python3\"\n },\n {\n \"code\": null,\n \"e\": 758,\n \"s\": 755,\n \"text\": \"C#\"\n },\n {\n \"code\": null,\n \"e\": 762,\n \"s\": 758,\n \"text\": \"PHP\"\n },\n {\n \"code\": null,\n \"e\": 773,\n \"s\": 762,\n \"text\": \"Javascript\"\n },\n {\n \"code\": \"// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number#include using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */int maxDiff(int arr[], int arr_size){ int max_diff = arr[1] - arr[0]; for (int i = 0; i < arr_size; i++) { for (int j = i+1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff;} /* Driver program to test above function */int main(){ int arr[] = {1, 2, 90, 10, 110}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << \\\"Maximum difference is \\\" << maxDiff(arr, n); return 0;}\",\n \"e\": 1645,\n \"s\": 773,\n \"text\": null\n },\n {\n \"code\": \"#include /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order. Returns 0 if elements are equal */int maxDiff(int arr[], int arr_size){ int max_diff = arr[1] - arr[0]; int i, j; for (i = 0; i < arr_size; i++) { for (j = i+1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff;} /* Driver program to test above function */int main(){ int arr[] = {1, 2, 90, 10, 110}; printf(\\\"Maximum difference is %d\\\", maxDiff(arr, 5)); getchar(); return 0;}\",\n \"e\": 2321,\n \"s\": 1645,\n \"text\": null\n },\n {\n \"code\": \"// Java program to find Maximum difference // between two elements such that larger // element appears after the smaller numberclass MaximumDifference { /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order. Returns 0 if elements are equal */ int maxDiff(int arr[], int arr_size) { int max_diff = arr[1] - arr[0]; int i, j; for (i = 0; i < arr_size; i++) { for (j = i + 1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff; } /* Driver program to test above functions */ public static void main(String[] args) { MaximumDifference maxdif = new MaximumDifference(); int arr[] = {1, 2, 90, 10, 110}; System.out.println(\\\"Maximum difference is \\\" + maxdif.maxDiff(arr, 5)); }} // This code has been contributed by Mayank Jaiswal\",\n \"e\": 3411,\n \"s\": 2321,\n \"text\": null\n },\n {\n \"code\": \"# Python 3 code to find Maximum difference# between two elements such that larger # element appears after the smaller number # The function assumes that there are at # least two elements in array. The function # returns a negative value if the array is# sorted in decreasing order. Returns 0 # if elements are equaldef maxDiff(arr, arr_size): max_diff = arr[1] - arr[0] for i in range( arr_size ): for j in range( i+1, arr_size ): if(arr[j] - arr[i] > max_diff): max_diff = arr[j] - arr[i] return max_diff # Driver program to test above function arr = [1, 2, 90, 10, 110]size = len(arr)print (\\\"Maximum difference is\\\", maxDiff(arr, size)) # This code is contributed by Swetank Modi\",\n \"e\": 4154,\n \"s\": 3411,\n \"text\": null\n },\n {\n \"code\": \"// C# code to find Maximum differenceusing System; class GFG { // The function assumes that there // are at least two elements in array. // The function returns a negative // value if the array is sorted in // decreasing order. Returns 0 if // elements are equal static int maxDiff(int[] arr, int arr_size) { int max_diff = arr[1] - arr[0]; int i, j; for (i = 0; i < arr_size; i++) { for (j = i + 1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff; } // Driver code public static void Main() { int[] arr = { 1, 2, 90, 10, 110 }; Console.Write(\\\"Maximum difference is \\\" + maxDiff(arr, 5)); }} // This code is contributed by Sam007\",\n \"e\": 5024,\n \"s\": 4154,\n \"text\": null\n },\n {\n \"code\": \" $max_diff) $max_diff = $arr[$j] - $arr[$i]; } } return $max_diff;} // Driver Code$arr = array(1, 2, 90, 10, 110);$n = sizeof($arr); // Function callingecho \\\"Maximum difference is \\\" . maxDiff($arr, $n); // This code is contributed // by Akanksha Rai(Abby_akku)\",\n \"e\": 5815,\n \"s\": 5024,\n \"text\": null\n },\n {\n \"code\": \"\",\n \"e\": 6694,\n \"s\": 5815,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 6703,\n \"s\": 6694,\n \"text\": \"Output :\"\n },\n {\n \"code\": null,\n \"e\": 6729,\n \"s\": 6703,\n \"text\": \"Maximum difference is 109\"\n },\n {\n \"code\": null,\n \"e\": 6777,\n \"s\": 6729,\n \"text\": \"Time Complexity : O(n^2) Auxiliary Space : O(1)\"\n },\n {\n \"code\": null,\n \"e\": 7097,\n \"s\": 6777,\n \"text\": \"Method 2 (Tricky and Efficient) In this method, instead of taking difference of the picked element with every other element, we take the difference with the minimum element found so far. So we need to keep track of 2 things: 1) Maximum difference found so far (max_diff). 2) Minimum number visited so far (min_element).\"\n },\n {\n \"code\": null,\n \"e\": 7101,\n \"s\": 7097,\n \"text\": \"C++\"\n },\n {\n \"code\": null,\n \"e\": 7103,\n \"s\": 7101,\n \"text\": \"C\"\n },\n {\n \"code\": null,\n \"e\": 7108,\n \"s\": 7103,\n \"text\": \"Java\"\n },\n {\n \"code\": null,\n \"e\": 7116,\n \"s\": 7108,\n \"text\": \"Python3\"\n },\n {\n \"code\": null,\n \"e\": 7119,\n \"s\": 7116,\n \"text\": \"C#\"\n },\n {\n \"code\": null,\n \"e\": 7123,\n \"s\": 7119,\n \"text\": \"PHP\"\n },\n {\n \"code\": null,\n \"e\": 7134,\n \"s\": 7123,\n \"text\": \"Javascript\"\n },\n {\n \"code\": \"// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number#include using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */int maxDiff(int arr[], int arr_size){ // Maximum difference found so far int max_diff = arr[1] - arr[0]; // Minimum number visited so far int min_element = arr[0]; for(int i = 1; i < arr_size; i++) { if (arr[i] - min_element > max_diff) max_diff = arr[i] - min_element; if (arr[i] < min_element) min_element = arr[i]; } return max_diff;} /* Driver program to test above function */int main(){ int arr[] = {1, 2, 90, 10, 110}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << \\\"Maximum difference is \\\" << maxDiff(arr, n); return 0;}\",\n \"e\": 8204,\n \"s\": 7134,\n \"text\": null\n },\n {\n \"code\": \"#include /* The function assumes that there are at least twoelements in array.The function returns a negative value if the array issorted in decreasing order.Returns 0 if elements are equal */int maxDiff(int arr[], int arr_size){int max_diff = arr[1] - arr[0];int min_element = arr[0];int i;for(i = 1; i < arr_size; i++){ if (arr[i] - min_element > max_diff) max_diff = arr[i] - min_element; if (arr[i] < min_element) min_element = arr[i]; }return max_diff;} /* Driver program to test above function */int main(){int arr[] = {1, 2, 6, 80, 100};int size = sizeof(arr)/sizeof(arr[0]);printf(\\\"Maximum difference is %d\\\", maxDiff(arr, size));getchar();return 0;}\",\n \"e\": 8944,\n \"s\": 8204,\n \"text\": null\n },\n {\n \"code\": \"// Java program to find Maximum difference // between two elements such that larger // element appears after the smaller numberclass MaximumDifference { /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order. Returns 0 if elements are equal */ int maxDiff(int arr[], int arr_size) { int max_diff = arr[1] - arr[0]; int min_element = arr[0]; int i; for (i = 1; i < arr_size; i++) { if (arr[i] - min_element > max_diff) max_diff = arr[i] - min_element; if (arr[i] < min_element) min_element = arr[i]; } return max_diff; } /* Driver program to test above functions */ public static void main(String[] args) { MaximumDifference maxdif = new MaximumDifference(); int arr[] = {1, 2, 90, 10, 110}; int size = arr.length; System.out.println(\\\"MaximumDifference is \\\" + maxdif.maxDiff(arr, size)); }} // This code has been contributed by Mayank Jaiswal\",\n \"e\": 10099,\n \"s\": 8944,\n \"text\": null\n },\n {\n \"code\": \"# Python 3 code to find Maximum difference# between two elements such that larger # element appears after the smaller number # The function assumes that there are # at least two elements in array.# The function returns a negative # value if the array is sorted in # decreasing order. Returns 0 if # elements are equaldef maxDiff(arr, arr_size): max_diff = arr[1] - arr[0] min_element = arr[0] for i in range( 1, arr_size ): if (arr[i] - min_element > max_diff): max_diff = arr[i] - min_element if (arr[i] < min_element): min_element = arr[i] return max_diff # Driver program to test above function arr = [1, 2, 6, 80, 100]size = len(arr)print (\\\"Maximum difference is\\\", maxDiff(arr, size)) # This code is contributed by Swetank Modi\",\n \"e\": 10906,\n \"s\": 10099,\n \"text\": null\n },\n {\n \"code\": \"// C# code to find Maximum differenceusing System; class GFG { // The function assumes that there // are at least two elements in array. // The function returns a negative // value if the array is sorted in // decreasing order.Returns 0 if // elements are equal static int maxDiff(int[] arr, int arr_size) { int max_diff = arr[1] - arr[0]; int min_element = arr[0]; int i; for (i = 1; i < arr_size; i++) { if (arr[i] - min_element > max_diff) max_diff = arr[i] - min_element; if (arr[i] < min_element) min_element = arr[i]; } return max_diff; } // Driver code public static void Main() { int[] arr = { 1, 2, 90, 10, 110 }; int size = arr.Length; Console.Write(\\\"MaximumDifference is \\\" + maxDiff(arr, size)); }} // This code is contributed by Sam007\",\n \"e\": 11852,\n \"s\": 10906,\n \"text\": null\n },\n {\n \"code\": \" $max_diff) $max_diff = $arr[$i] - $min_element; if ($arr[$i] < $min_element) $min_element = $arr[$i]; } return $max_diff;} // Driver Code$arr = array(1, 2, 90, 10, 110);$n = count($arr); // Function callingecho \\\"Maximum difference is \\\" . maxDiff($arr, $n); // This code is contributed by Sam007?>\",\n \"e\": 12841,\n \"s\": 11852,\n \"text\": null\n },\n {\n \"code\": \"\",\n \"e\": 13767,\n \"s\": 12841,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 13775,\n \"s\": 13767,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 13801,\n \"s\": 13775,\n \"text\": \"Maximum difference is 109\"\n },\n {\n \"code\": null,\n \"e\": 13847,\n \"s\": 13801,\n \"text\": \"Time Complexity : O(n) Auxiliary Space : O(1)\"\n },\n {\n \"code\": null,\n \"e\": 14001,\n \"s\": 13847,\n \"text\": \"Like min element, we can also keep track of max element from right side. Thanks to Katamaran for suggesting this approach. Below is the implementation : \"\n },\n {\n \"code\": null,\n \"e\": 14005,\n \"s\": 14001,\n \"text\": \"C++\"\n },\n {\n \"code\": null,\n \"e\": 14010,\n \"s\": 14005,\n \"text\": \"Java\"\n },\n {\n \"code\": null,\n \"e\": 14018,\n \"s\": 14010,\n \"text\": \"Python3\"\n },\n {\n \"code\": null,\n \"e\": 14021,\n \"s\": 14018,\n \"text\": \"C#\"\n },\n {\n \"code\": null,\n \"e\": 14025,\n \"s\": 14021,\n \"text\": \"PHP\"\n },\n {\n \"code\": null,\n \"e\": 14036,\n \"s\": 14025,\n \"text\": \"Javascript\"\n },\n {\n \"code\": \"// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number#include using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */int maxDiff(int arr[], int n){ // Initialize Result int maxDiff = -1; // Initialize max element from right side int maxRight = arr[n-1]; for (int i = n-2; i >= 0; i--) { if (arr[i] > maxRight) maxRight = arr[i]; else { int diff = maxRight - arr[i]; if (diff > maxDiff) { maxDiff = diff; } } } return maxDiff;} /* Driver program to test above function */int main(){ int arr[] = {1, 2, 90, 10, 110}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << \\\"Maximum difference is \\\" << maxDiff(arr, n); return 0;}\",\n \"e\": 15074,\n \"s\": 14036,\n \"text\": null\n },\n {\n \"code\": \"// Java program to find Maximum difference // between two elements such that larger // element appears after the smaller number import java.io.*; class GFG {/* The function assumes that there are at least two elements in array. The function returns a negative value if thearray is sorted in decreasing order and returns 0 if elements are equal */static int maxDiff(int arr[], int n){ // Initialize Result int maxDiff = -1; // Initialize max element from right side int maxRight = arr[n-1]; for (int i = n-2; i >= 0; i--) { if (arr[i] > maxRight) maxRight = arr[i]; else { int diff = maxRight - arr[i]; if (diff > maxDiff) { maxDiff = diff; } } } return maxDiff;} /* Driver program to test above function */ public static void main (String[] args) { int arr[] = {1, 2, 90, 10, 110}; int n = arr.length; // Function calling System.out.println (\\\"Maximum difference is \\\" + maxDiff(arr, n)); }//This code is contributed by Tushil.. }\",\n \"e\": 16166,\n \"s\": 15074,\n \"text\": null\n },\n {\n \"code\": \"# Python3 program to find Maximum difference # between two elements such that larger # element appears after the smaller number # The function assumes that there are # at least two elements in array. The # function returns a negative value if the# array is sorted in decreasing order and # returns 0 if elements are equaldef maxDiff(arr, n): # Initialize Result maxDiff = -1 # Initialize max element from # right side maxRight = arr[-1] for i in reversed(arr[:-1]): if (i > maxRight): maxRight = i else: diff = maxRight - i if (diff > maxDiff): maxDiff = diff return maxDiff # Driver Codeif __name__ == '__main__': arr = [1, 2, 90, 10, 110] n = len(arr) # Function calling print(\\\"Maximum difference is\\\", maxDiff(arr, n)) # This code is contributed by 29AjayKumar\",\n \"e\": 17066,\n \"s\": 16166,\n \"text\": null\n },\n {\n \"code\": \"// C# program to find Maximum difference // between two elements such that larger // element appears after the smaller numberusing System; class GFG{/* The function assumes that there are at least two elements in array. The function returns a negative value if thearray is sorted in decreasing order and returns 0 if elements are equal */static int maxDiff(int[] arr, int n){ // Initialize Result int maxDiff = -1; // Initialize max element from right side int maxRight = arr[n-1]; for (int i = n-2; i >= 0; i--) { if (arr[i] > maxRight) maxRight = arr[i]; else { int diff = maxRight - arr[i]; if (diff > maxDiff) { maxDiff = diff; } } } return maxDiff;} // Driver Codepublic static void Main () { int[] arr = {1, 2, 90, 10, 110}; int n = arr.Length; // Function calling Console.WriteLine(\\\"Maximum difference is \\\" + maxDiff(arr, n));}} // This code is contributed // by Akanksha Rai\",\n \"e\": 18129,\n \"s\": 17066,\n \"text\": null\n },\n {\n \"code\": \"= 0; $i--) { if ($arr[$i] > $maxRight) $maxRight = $arr[$i]; else { $diff = $maxRight - $arr[$i]; if ($diff > $maxDiff) { $maxDiff = $diff; } } } return $maxDiff; } // Driver Code$arr = array(1, 2, 90, 10, 110); $n = sizeof($arr); // Function calling echo \\\"Maximum difference is \\\", maxDiff($arr, $n); // This code is contributed by ajit?>\",\n \"e\": 19121,\n \"s\": 18129,\n \"text\": null\n },\n {\n \"code\": \"\",\n \"e\": 20168,\n \"s\": 19121,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 20177,\n \"s\": 20168,\n \"text\": \"Output: \"\n },\n {\n \"code\": null,\n \"e\": 20203,\n \"s\": 20177,\n \"text\": \"Maximum difference is 109\"\n },\n {\n \"code\": null,\n \"e\": 20249,\n \"s\": 20203,\n \"text\": \"Time Complexity : O(n) Auxiliary Space : O(1)\"\n },\n {\n \"code\": null,\n \"e\": 20593,\n \"s\": 20249,\n \"text\": \"Method 3 (Another Tricky Solution) First find the difference between the adjacent elements of the array and store all differences in an auxiliary array diff[] of size n-1. Now this problems turns into finding the maximum sum subarray of this difference array.Thanks to Shubham Mittal for suggesting this solution. Below is the implementation :\"\n },\n {\n \"code\": null,\n \"e\": 20597,\n \"s\": 20593,\n \"text\": \"C++\"\n },\n {\n \"code\": null,\n \"e\": 20599,\n \"s\": 20597,\n \"text\": \"C\"\n },\n {\n \"code\": null,\n \"e\": 20604,\n \"s\": 20599,\n \"text\": \"Java\"\n },\n {\n \"code\": null,\n \"e\": 20612,\n \"s\": 20604,\n \"text\": \"Python3\"\n },\n {\n \"code\": null,\n \"e\": 20615,\n \"s\": 20612,\n \"text\": \"C#\"\n },\n {\n \"code\": null,\n \"e\": 20619,\n \"s\": 20615,\n \"text\": \"PHP\"\n },\n {\n \"code\": null,\n \"e\": 20630,\n \"s\": 20619,\n \"text\": \"Javascript\"\n },\n {\n \"code\": \"// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number#include using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */int maxDiff(int arr[], int n){ // Create a diff array of size n-1. // The array will hold the difference // of adjacent elements int diff[n-1]; for (int i=0; i < n-1; i++) diff[i] = arr[i+1] - arr[i]; // Now find the maximum sum // subarray in diff array int max_diff = diff[0]; for (int i=1; i 0) diff[i] += diff[i-1]; if (max_diff < diff[i]) max_diff = diff[i]; } return max_diff;} /* Driver program to test above function */int main(){ int arr[] = {80, 2, 6, 3, 100}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << \\\"Maximum difference is \\\" << maxDiff(arr, n); return 0;}\",\n \"e\": 21721,\n \"s\": 20630,\n \"text\": null\n },\n {\n \"code\": \"#include int maxDiff(int arr[], int n){ // Create a diff array of size n-1. The array will hold // the difference of adjacent elements int diff[n-1]; for (int i=0; i < n-1; i++) diff[i] = arr[i+1] - arr[i]; // Now find the maximum sum subarray in diff array int max_diff = diff[0]; for (int i=1; i 0) diff[i] += diff[i-1]; if (max_diff < diff[i]) max_diff = diff[i]; } return max_diff;} /* Driver program to test above function */int main(){ int arr[] = {80, 2, 6, 3, 100}; int size = sizeof(arr)/sizeof(arr[0]); printf(\\\"Maximum difference is %d\\\", maxDiff(arr, size)); return 0;}\",\n \"e\": 22429,\n \"s\": 21721,\n \"text\": null\n },\n {\n \"code\": \"// Java program to find Maximum difference // between two elements such that larger // element appears after the smaller numberclass MaximumDifference { int maxDiff(int arr[], int n) { // Create a diff array of size n-1. The array will hold // the difference of adjacent elements int diff[] = new int[n - 1]; for (int i = 0; i < n - 1; i++) diff[i] = arr[i + 1] - arr[i]; // Now find the maximum sum subarray in diff array int max_diff = diff[0]; for (int i = 1; i < n - 1; i++) { if (diff[i - 1] > 0) diff[i] += diff[i - 1]; if (max_diff < diff[i]) max_diff = diff[i]; } return max_diff; } // Driver program to test above functions public static void main(String[] args) { MaximumDifference mxdif = new MaximumDifference(); int arr[] = {80, 2, 6, 3, 100}; int size = arr.length; System.out.println(mxdif.maxDiff(arr, size)); }}// This code has been contributed by Mayank Jaiswal\",\n \"e\": 23500,\n \"s\": 22429,\n \"text\": null\n },\n {\n \"code\": \"# Python 3 code to find Maximum difference# between two elements such that larger # element appears after the smaller number def maxDiff(arr, n): diff = [0] * (n - 1) for i in range (0, n-1): diff[i] = arr[i+1] - arr[i] # Now find the maximum sum # subarray in diff array max_diff = diff[0] for i in range(1, n-1): if (diff[i-1] > 0): diff[i] += diff[i-1] if (max_diff < diff[i]): max_diff = diff[i] return max_diff # Driver program to test above function arr = [80, 2, 6, 3, 100]size = len(arr)print (\\\"Maximum difference is\\\", maxDiff(arr, size)) # This code is contributed by Swetank Modi\",\n \"e\": 24191,\n \"s\": 23500,\n \"text\": null\n },\n {\n \"code\": \"// C# code to find Maximum differenceusing System; class GFG { static int maxDiff(int[] arr, int n) { // Create a diff array of size n-1. // The array will hold the // difference of adjacent elements int[] diff = new int[n - 1]; for (int i = 0; i < n - 1; i++) diff[i] = arr[i + 1] - arr[i]; // Now find the maximum sum // subarray in diff array int max_diff = diff[0]; for (int i = 1; i < n - 1; i++) { if (diff[i - 1] > 0) diff[i] += diff[i - 1]; if (max_diff < diff[i]) max_diff = diff[i]; } return max_diff; } // Driver code public static void Main() { int[] arr = { 80, 2, 6, 3, 100 }; int size = arr.Length; Console.Write(maxDiff(arr, size)); }} // This code is contributed by Sam007\",\n \"e\": 25079,\n \"s\": 24191,\n \"text\": null\n },\n {\n \"code\": \" 0) $diff[$i] += $diff[$i-1]; if ($max_diff < $diff[$i]) $max_diff = $diff[$i]; } return $max_diff;} // Driver Code$arr = array(80, 2, 6, 3, 100);$n = sizeof($arr); // Function callingecho \\\"Maximum difference is \\\" . maxDiff($arr, $n); // This code is contributed // by Akanksha Rai\",\n \"e\": 26116,\n \"s\": 25079,\n \"text\": null\n },\n {\n \"code\": \"\",\n \"e\": 27184,\n \"s\": 26116,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 27192,\n \"s\": 27184,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 27217,\n \"s\": 27192,\n \"text\": \"Maximum difference is 98\"\n },\n {\n \"code\": null,\n \"e\": 27263,\n \"s\": 27217,\n \"text\": \"Time Complexity : O(n) Auxiliary Space : O(n)\"\n },\n {\n \"code\": null,\n \"e\": 27453,\n \"s\": 27263,\n \"text\": \"We can modify the above method to work in O(1) extra space. Instead of creating an auxiliary array, we can calculate diff and max sum in same loop. Following is the space optimized version.\"\n },\n {\n \"code\": null,\n \"e\": 27457,\n \"s\": 27453,\n \"text\": \"C++\"\n },\n {\n \"code\": null,\n \"e\": 27462,\n \"s\": 27457,\n \"text\": \"Java\"\n },\n {\n \"code\": null,\n \"e\": 27470,\n \"s\": 27462,\n \"text\": \"Python3\"\n },\n {\n \"code\": null,\n \"e\": 27473,\n \"s\": 27470,\n \"text\": \"C#\"\n },\n {\n \"code\": null,\n \"e\": 27477,\n \"s\": 27473,\n \"text\": \"PHP\"\n },\n {\n \"code\": null,\n \"e\": 27488,\n \"s\": 27477,\n \"text\": \"Javascript\"\n },\n {\n \"code\": \"// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number#include using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */int maxDiff (int arr[], int n){ // Initialize diff, current sum and max sum int diff = arr[1]-arr[0]; int curr_sum = diff; int max_sum = curr_sum; for(int i=1; i 0) curr_sum += diff; else curr_sum = diff; // Update max sum, if needed if (curr_sum > max_sum) max_sum = curr_sum; } return max_sum;} /* Driver program to test above function */int main(){ int arr[] = {80, 2, 6, 3, 100}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << \\\"Maximum difference is \\\" << maxDiff(arr, n); return 0;}\",\n \"e\": 28584,\n \"s\": 27488,\n \"text\": null\n },\n {\n \"code\": \"// Java program to find Maximum // difference between two elements // such that larger element appears // after the smaller number class GFG{ /* The function assumes that thereare at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 ifelements are equal */static int maxDiff (int arr[], int n) { // Initialize diff, current // sum and max sum int diff = arr[1] - arr[0]; int curr_sum = diff; int max_sum = curr_sum; for(int i = 1; i < n - 1; i++) { // Calculate current diff diff = arr[i + 1] - arr[i]; // Calculate current sum if (curr_sum > 0) curr_sum += diff; else curr_sum = diff; // Update max sum, if needed if (curr_sum > max_sum) max_sum = curr_sum; } return max_sum; } // Driver Codepublic static void main(String[] args) { int arr[] = {80, 2, 6, 3, 100}; int n = arr.length; // Function calling System.out.print(\\\"Maximum difference is \\\" + maxDiff(arr, n)); }} // This code is contributed by Smitha\",\n \"e\": 29731,\n \"s\": 28584,\n \"text\": null\n },\n {\n \"code\": \"# Python3 program to find Maximum difference # between two elements such that larger # element appears after the smaller number # The function assumes that there are # at least two elements in array. The # function returns a negative value if # the array is sorted in decreasing # order and returns 0 if elements are equaldef maxDiff (arr, n): # Initialize diff, current # sum and max sum diff = arr[1] - arr[0] curr_sum = diff max_sum = curr_sum for i in range(1, n - 1): # Calculate current diff diff = arr[i + 1] - arr[i] # Calculate current sum if (curr_sum > 0): curr_sum += diff else: curr_sum = diff # Update max sum, if needed if (curr_sum > max_sum): max_sum = curr_sum return max_sum # Driver Codeif __name__ == '__main__': arr = [80, 2, 6, 3, 100] n = len(arr) # Function calling print(\\\"Maximum difference is\\\", maxDiff(arr, n)) # This code is contributed # by 29AjayKumar\",\n \"e\": 30782,\n \"s\": 29731,\n \"text\": null\n },\n {\n \"code\": \"// C# program to find Maximum // difference between two elements // such that larger element appears // after the smaller number using System;class GFG{ /* The function assumes that thereare at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 ifelements are equal */static int maxDiff (int[] arr, int n) { // Initialize diff, current // sum and max sum int diff = arr[1] - arr[0]; int curr_sum = diff; int max_sum = curr_sum; for(int i = 1; i < n - 1; i++) { // Calculate current diff diff = arr[i + 1] - arr[i]; // Calculate current sum if (curr_sum > 0) curr_sum += diff; else curr_sum = diff; // Update max sum, if needed if (curr_sum > max_sum) max_sum = curr_sum; } return max_sum; } // Driver Codepublic static void Main() { int[] arr = {80, 2, 6, 3, 100}; int n = arr.Length; // Function calling Console.WriteLine(\\\"Maximum difference is \\\" + maxDiff(arr, n)); }} // This code is contributed // by Akanksha Rai(Abby_akku)\",\n \"e\": 31946,\n \"s\": 30782,\n \"text\": null\n },\n {\n \"code\": \" 0) $curr_sum += $diff; else $curr_sum = $diff; // Update max sum, if needed if ($curr_sum > $max_sum) $max_sum = $curr_sum; } return $max_sum;} // Driver Code$arr = array(80, 2, 6, 3, 100);$n = sizeof($arr); // Function callingecho \\\"Maximum difference is \\\", maxDiff($arr, $n); // This code is contributed // by Sach_code?>\",\n \"e\": 32996,\n \"s\": 31946,\n \"text\": null\n },\n {\n \"code\": \"\",\n \"e\": 34084,\n \"s\": 32996,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 34093,\n \"s\": 34084,\n \"text\": \"Output: \"\n },\n {\n \"code\": null,\n \"e\": 34118,\n \"s\": 34093,\n \"text\": \"Maximum difference is 98\"\n },\n {\n \"code\": null,\n \"e\": 34165,\n \"s\": 34118,\n \"text\": \"Time Complexity : O(n) Auxiliary Space : O(1) \"\n },\n {\n \"code\": null,\n \"e\": 35140,\n \"s\": 34165,\n \"text\": \"Maximum difference between two elements (larger element appears after smaller) | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersMaximum difference between two elements (larger element appears after smaller) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 11:18•Live•

An error occurred.

Try watching this video on www.youtube.com, or enable JavaScript if it is disabled in your browser.
\"\n },\n {\n \"code\": null,\n \"e\": 35354,\n \"s\": 35140,\n \"text\": \"Below is a variation of this problem: Maximum difference of sum of elements in two rows in a matrixPlease write comments if you find any bug in above codes/algorithms, or find other ways to solve the same problem \"\n },\n {\n \"code\": null,\n \"e\": 35361,\n \"s\": 35354,\n \"text\": \"Sam007\"\n },\n {\n \"code\": null,\n \"e\": 35382,\n \"s\": 35361,\n \"text\": \"Smitha Dinesh Semwal\"\n },\n {\n \"code\": null,\n \"e\": 35395,\n \"s\": 35382,\n \"text\": \"Akanksha_Rai\"\n },\n {\n \"code\": null,\n \"e\": 35401,\n \"s\": 35395,\n \"text\": \"jit_t\"\n },\n {\n \"code\": null,\n \"e\": 35411,\n \"s\": 35401,\n \"text\": \"Sach_Code\"\n },\n {\n \"code\": null,\n \"e\": 35423,\n \"s\": 35411,\n \"text\": \"29AjayKumar\"\n },\n {\n \"code\": null,\n \"e\": 35437,\n \"s\": 35423,\n \"text\": \"jana_sayantan\"\n },\n {\n \"code\": null,\n \"e\": 35448,\n \"s\": 35437,\n \"text\": \"decode2207\"\n },\n {\n \"code\": null,\n \"e\": 35457,\n \"s\": 35448,\n \"text\": \"suresh07\"\n },\n {\n \"code\": null,\n \"e\": 35473,\n \"s\": 35457,\n \"text\": \"mayanktyagi1709\"\n },\n {\n \"code\": null,\n \"e\": 35481,\n \"s\": 35473,\n \"text\": \"rag2127\"\n },\n {\n \"code\": null,\n \"e\": 35497,\n \"s\": 35481,\n \"text\": \"saurabh1990aror\"\n },\n {\n \"code\": null,\n \"e\": 35512,\n \"s\": 35497,\n \"text\": \"devnawfalahmed\"\n },\n {\n \"code\": null,\n \"e\": 35522,\n \"s\": 35512,\n \"text\": \"202051178\"\n },\n {\n \"code\": null,\n \"e\": 35536,\n \"s\": 35522,\n \"text\": \"_shinchancode\"\n },\n {\n \"code\": null,\n \"e\": 35543,\n \"s\": 35536,\n \"text\": \"Amazon\"\n },\n {\n \"code\": null,\n \"e\": 35548,\n \"s\": 35543,\n \"text\": \"Hike\"\n },\n {\n \"code\": null,\n \"e\": 35559,\n \"s\": 35548,\n \"text\": \"MakeMyTrip\"\n },\n {\n \"code\": null,\n \"e\": 35568,\n \"s\": 35559,\n \"text\": \"Ola Cabs\"\n },\n {\n \"code\": null,\n \"e\": 35577,\n \"s\": 35568,\n \"text\": \"SAP Labs\"\n },\n {\n \"code\": null,\n \"e\": 35584,\n \"s\": 35577,\n \"text\": \"Arrays\"\n },\n {\n \"code\": null,\n \"e\": 35591,\n \"s\": 35584,\n \"text\": \"Amazon\"\n },\n {\n \"code\": null,\n \"e\": 35596,\n \"s\": 35591,\n \"text\": \"Hike\"\n },\n {\n \"code\": null,\n \"e\": 35607,\n \"s\": 35596,\n \"text\": \"MakeMyTrip\"\n },\n {\n \"code\": null,\n \"e\": 35616,\n \"s\": 35607,\n \"text\": \"Ola Cabs\"\n },\n {\n \"code\": null,\n \"e\": 35625,\n \"s\": 35616,\n \"text\": \"SAP Labs\"\n },\n {\n \"code\": null,\n \"e\": 35632,\n \"s\": 35625,\n \"text\": \"Arrays\"\n },\n {\n \"code\": null,\n \"e\": 35730,\n \"s\": 35632,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 35762,\n \"s\": 35730,\n \"text\": \"Multidimensional Arrays in Java\"\n },\n {\n \"code\": null,\n \"e\": 35785,\n \"s\": 35762,\n \"text\": \"Introduction to Arrays\"\n },\n {\n \"code\": null,\n \"e\": 35841,\n \"s\": 35785,\n \"text\": \"K'th Smallest/Largest Element in Unsorted Array | Set 1\"\n },\n {\n \"code\": null,\n \"e\": 35868,\n \"s\": 35841,\n \"text\": \"Subset Sum Problem | DP-25\"\n },\n {\n \"code\": null,\n \"e\": 35900,\n \"s\": 35868,\n \"text\": \"Introduction to Data Structures\"\n },\n {\n \"code\": null,\n \"e\": 35945,\n \"s\": 35900,\n \"text\": \"Python | Using 2D arrays/lists the right way\"\n },\n {\n \"code\": null,\n \"e\": 35993,\n \"s\": 35945,\n \"text\": \"Search an element in a sorted and rotated array\"\n },\n {\n \"code\": null,\n \"e\": 36033,\n \"s\": 35993,\n \"text\": \"Find Second largest element in an array\"\n },\n {\n \"code\": null,\n \"e\": 36057,\n \"s\": 36033,\n \"text\": \"Find the Missing Number\"\n }\n]"}}},{"rowIdx":177,"cells":{"title":{"kind":"string","value":"MITM (Man in The Middle) Attack using ARP Poisoning"},"text":{"kind":"string","value":"15 Apr, 2021\nIntroduction :Man In The Middle Attack implies an active attack where the attacker/Hacker creates a connection between the victims and sends messages between them or may capture all the data packets from the victims. In this case, the victims think that they are communicating with each other, but in reality, the malicious attacker/hacker controls the communication i.e. a third person exists to control and monitor the traffic of communication between the two parties i.e. Client and Server.\nTypes of Man In The Middle Attack :Here, we will discuss the types of Man In The Middle Attack as follows.\nARP Spoofing – ARP Stands for Address Resolution Protocol. This protocol is used for resolving IP addresses to machine MAC addresses. All the devices which want to communicate in the network, broadcast ARP-queries in the system to find out the MAC addresses of other machines. ARP Spoofing is also known as ARP Poisoning. In this, ARP poisoning, ARP packets are forced to send data to the attacker’s machine. ARP Spoofing constructs a huge number of forced ARP requests and replies packets to overload the switch. The intention of the attacker all the network packets and switch set in forwarding mode. DNS Spoofing – Similar to ARP, DNS resolves domain names to IP addresses. DNS spoofing is very dangerous because in this case a hacker will be able to hijack and spoof any DNS request made by the user and can serve the user fake web pages, fake websites, fake login pages, fake updates, and so on.\nARP Spoofing – ARP Stands for Address Resolution Protocol. This protocol is used for resolving IP addresses to machine MAC addresses. All the devices which want to communicate in the network, broadcast ARP-queries in the system to find out the MAC addresses of other machines. ARP Spoofing is also known as ARP Poisoning. In this, ARP poisoning, ARP packets are forced to send data to the attacker’s machine. ARP Spoofing constructs a huge number of forced ARP requests and replies packets to overload the switch. The intention of the attacker all the network packets and switch set in forwarding mode. \nDNS Spoofing – Similar to ARP, DNS resolves domain names to IP addresses. DNS spoofing is very dangerous because in this case a hacker will be able to hijack and spoof any DNS request made by the user and can serve the user fake web pages, fake websites, fake login pages, fake updates, and so on.\nMan In The Middle Attack Techniques :Here, we will discuss the Man In The middle attack techniques as follows.\nPacket Sniffing\nSession Hijacking\nSSL stripping\nPacket Injection\nMan in Middle Attack using ARP spoofing : Here we will discuss the steps for Man in Middle Attack using ARP spoofing as follows.\nStep-1: ARP spoofing -It allows us to redirect the flow of packets in a computer network. Example of a typical Network as follows.\nA Typical Computer Network\nStep-2 :But when a hacker becomes Man-In-The-Middle by ARP Spoofing then all the requests and responses start flowing through the hacker’s system as shown below – \ncomputer network after ARP spoofing\nStep-3 :By doing this a hacker spoof’s the router by pretending to be the victim, and similarly, he spoofs the victim by pretending to be the router.\nHow to do an ARP Spoof Attack :We can do an ARP Spoof attack using the built-in tool called ARPSPOOF in Kali Linux, or we can also create an ARP Spoof attack using a python program.\nExecution steps :Here, we will discuss the execution steps as follows.\nStep-1: We can run the built-in “ARPSPOOF’” tool in Kali Linux. In case the ARPSPOOF tool is not present, install the tool by running the following command as follows.\napt install dsniff\nStep-2 : To run this attack we need two things Victim machine’s IP address & the IP of Gateway. In this example, we are using a Windows Machine as our victim and Kali Machine to run the attack. To know the victim machines IP address and gateway IP by running the following command in both the Windows machine and Linux Machine as follows.\narp -a\nOutput :This will show us the following Outputs as follows.Victim Machine (Windows Machine) –\nwindows machine \nAttacker Machine (Kali Linux) –From these, we can observe that the IP address of the Windows machine is 10.0.2.8 and the IP and MAC addresses of the gateway are 10.0.2.1 and 52:54:00:12:35:00, also the MAC address of our Kali Machine is 08:00:27:a6:1f:86.\nStep-3 : Now, write the following commands to perform the ARP Spoof attack.\narpspoof -i eth0 -t 10.0.2.8 10.0.2.1\nHere eth0 is the name of the interface, 10.0.2.8 is the IP of the Windows machine and 10.0.2.1 is the IP of the gateway. This will fool the victim by pretending to be the router. So again we will run the above command one more time by switching its IP addresses as follows.\narpspoof -i eth0 -t 10.0.2.1 10.0.2.8\nOutput :Attacker Machine (Kali Linux) – This shows that our ARP Spoof attack is running, and we have successfully placed our system in the middle of the client and server. \nARP Spoof attack running\n We can also check it by running the command as follows.\narp -a \nOutput :In the output screen, you can observe that the MAC address of the gateway is changed to the MAC address of Kali Machine. Now all the data packets will flow through our Kali machine. Also, you can see that the internet connection of the victim machine is not working because it’s the security feature of Linux, which does not allow the flow of packets through it. So we need to enable Port Forwarding so that this computer will allow the packets to flow through it just like a router.\nStep-4 : To enable Port Forwarding to run the command as follows.\necho 1 > /proc/sys/net/ipv4/ip_forward \nOutput :This command will again establish the Internet connectivity of the victim computer. In this way, we can become the Man-In-The-Middle by using the ARP Spoof attack. So all the requests from the victim’s computer will not directly go to the router it will flow through the attacker’s machine and the attacker can sniff or extract useful information by using various tools like Wire Shark, etc. as shown below as follows.\nWire Shark – used to sniff useful information from the packets.\nInformation-Security\nlinux\nComputer Networks\nComputer Networks\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nSecure Socket Layer (SSL)\nGSM in Wireless Communication\nWireless Application Protocol\nMobile Internet Protocol (or Mobile IP)\nIntroduction of Mobile Ad hoc Network (MANET)\nAdvanced Encryption Standard (AES)\nCryptography and its Types\nBluetooth\nIntrusion Detection System (IDS)\nDynamic Host Configuration Protocol (DHCP)"},"parsed":{"kind":"list like","value":[{"code":null,"e":28,"s":0,"text":"\n15 Apr, 2021"},{"code":null,"e":522,"s":28,"text":"Introduction :Man In The Middle Attack implies an active attack where the attacker/Hacker creates a connection between the victims and sends messages between them or may capture all the data packets from the victims. In this case, the victims think that they are communicating with each other, but in reality, the malicious attacker/hacker controls the communication i.e. a third person exists to control and monitor the traffic of communication between the two parties i.e. Client and Server."},{"code":null,"e":629,"s":522,"text":"Types of Man In The Middle Attack :Here, we will discuss the types of Man In The Middle Attack as follows."},{"code":null,"e":1533,"s":629,"text":"ARP Spoofing – ARP Stands for Address Resolution Protocol. This protocol is used for resolving IP addresses to machine MAC addresses. All the devices which want to communicate in the network, broadcast ARP-queries in the system to find out the MAC addresses of other machines. ARP Spoofing is also known as ARP Poisoning. In this, ARP poisoning, ARP packets are forced to send data to the attacker’s machine. ARP Spoofing constructs a huge number of forced ARP requests and replies packets to overload the switch. The intention of the attacker all the network packets and switch set in forwarding mode. DNS Spoofing – Similar to ARP, DNS resolves domain names to IP addresses. DNS spoofing is very dangerous because in this case a hacker will be able to hijack and spoof any DNS request made by the user and can serve the user fake web pages, fake websites, fake login pages, fake updates, and so on."},{"code":null,"e":2140,"s":1533,"text":"ARP Spoofing – ARP Stands for Address Resolution Protocol. This protocol is used for resolving IP addresses to machine MAC addresses. All the devices which want to communicate in the network, broadcast ARP-queries in the system to find out the MAC addresses of other machines. ARP Spoofing is also known as ARP Poisoning. In this, ARP poisoning, ARP packets are forced to send data to the attacker’s machine. ARP Spoofing constructs a huge number of forced ARP requests and replies packets to overload the switch. The intention of the attacker all the network packets and switch set in forwarding mode. "},{"code":null,"e":2438,"s":2140,"text":"DNS Spoofing – Similar to ARP, DNS resolves domain names to IP addresses. DNS spoofing is very dangerous because in this case a hacker will be able to hijack and spoof any DNS request made by the user and can serve the user fake web pages, fake websites, fake login pages, fake updates, and so on."},{"code":null,"e":2549,"s":2438,"text":"Man In The Middle Attack Techniques :Here, we will discuss the Man In The middle attack techniques as follows."},{"code":null,"e":2565,"s":2549,"text":"Packet Sniffing"},{"code":null,"e":2583,"s":2565,"text":"Session Hijacking"},{"code":null,"e":2597,"s":2583,"text":"SSL stripping"},{"code":null,"e":2614,"s":2597,"text":"Packet Injection"},{"code":null,"e":2743,"s":2614,"text":"Man in Middle Attack using ARP spoofing : Here we will discuss the steps for Man in Middle Attack using ARP spoofing as follows."},{"code":null,"e":2874,"s":2743,"text":"Step-1: ARP spoofing -It allows us to redirect the flow of packets in a computer network. Example of a typical Network as follows."},{"code":null,"e":2901,"s":2874,"text":"A Typical Computer Network"},{"code":null,"e":3065,"s":2901,"text":"Step-2 :But when a hacker becomes Man-In-The-Middle by ARP Spoofing then all the requests and responses start flowing through the hacker’s system as shown below – "},{"code":null,"e":3101,"s":3065,"text":"computer network after ARP spoofing"},{"code":null,"e":3251,"s":3101,"text":"Step-3 :By doing this a hacker spoof’s the router by pretending to be the victim, and similarly, he spoofs the victim by pretending to be the router."},{"code":null,"e":3433,"s":3251,"text":"How to do an ARP Spoof Attack :We can do an ARP Spoof attack using the built-in tool called ARPSPOOF in Kali Linux, or we can also create an ARP Spoof attack using a python program."},{"code":null,"e":3504,"s":3433,"text":"Execution steps :Here, we will discuss the execution steps as follows."},{"code":null,"e":3672,"s":3504,"text":"Step-1: We can run the built-in “ARPSPOOF’” tool in Kali Linux. In case the ARPSPOOF tool is not present, install the tool by running the following command as follows."},{"code":null,"e":3691,"s":3672,"text":"apt install dsniff"},{"code":null,"e":4032,"s":3691,"text":"Step-2 : To run this attack we need two things Victim machine’s IP address & the IP of Gateway. In this example, we are using a Windows Machine as our victim and Kali Machine to run the attack. To know the victim machines IP address and gateway IP by running the following command in both the Windows machine and Linux Machine as follows."},{"code":null,"e":4039,"s":4032,"text":"arp -a"},{"code":null,"e":4133,"s":4039,"text":"Output :This will show us the following Outputs as follows.Victim Machine (Windows Machine) –"},{"code":null,"e":4150,"s":4133,"text":"windows machine "},{"code":null,"e":4406,"s":4150,"text":"Attacker Machine (Kali Linux) –From these, we can observe that the IP address of the Windows machine is 10.0.2.8 and the IP and MAC addresses of the gateway are 10.0.2.1 and 52:54:00:12:35:00, also the MAC address of our Kali Machine is 08:00:27:a6:1f:86."},{"code":null,"e":4483,"s":4406,"text":"Step-3 : Now, write the following commands to perform the ARP Spoof attack."},{"code":null,"e":4521,"s":4483,"text":"arpspoof -i eth0 -t 10.0.2.8 10.0.2.1"},{"code":null,"e":4795,"s":4521,"text":"Here eth0 is the name of the interface, 10.0.2.8 is the IP of the Windows machine and 10.0.2.1 is the IP of the gateway. This will fool the victim by pretending to be the router. So again we will run the above command one more time by switching its IP addresses as follows."},{"code":null,"e":4833,"s":4795,"text":"arpspoof -i eth0 -t 10.0.2.1 10.0.2.8"},{"code":null,"e":5006,"s":4833,"text":"Output :Attacker Machine (Kali Linux) – This shows that our ARP Spoof attack is running, and we have successfully placed our system in the middle of the client and server. "},{"code":null,"e":5031,"s":5006,"text":"ARP Spoof attack running"},{"code":null,"e":5088,"s":5031,"text":" We can also check it by running the command as follows."},{"code":null,"e":5096,"s":5088,"text":"arp -a "},{"code":null,"e":5588,"s":5096,"text":"Output :In the output screen, you can observe that the MAC address of the gateway is changed to the MAC address of Kali Machine. Now all the data packets will flow through our Kali machine. Also, you can see that the internet connection of the victim machine is not working because it’s the security feature of Linux, which does not allow the flow of packets through it. So we need to enable Port Forwarding so that this computer will allow the packets to flow through it just like a router."},{"code":null,"e":5654,"s":5588,"text":"Step-4 : To enable Port Forwarding to run the command as follows."},{"code":null,"e":5694,"s":5654,"text":"echo 1 > /proc/sys/net/ipv4/ip_forward "},{"code":null,"e":6121,"s":5694,"text":"Output :This command will again establish the Internet connectivity of the victim computer. In this way, we can become the Man-In-The-Middle by using the ARP Spoof attack. So all the requests from the victim’s computer will not directly go to the router it will flow through the attacker’s machine and the attacker can sniff or extract useful information by using various tools like Wire Shark, etc. as shown below as follows."},{"code":null,"e":6185,"s":6121,"text":"Wire Shark – used to sniff useful information from the packets."},{"code":null,"e":6206,"s":6185,"text":"Information-Security"},{"code":null,"e":6212,"s":6206,"text":"linux"},{"code":null,"e":6230,"s":6212,"text":"Computer Networks"},{"code":null,"e":6248,"s":6230,"text":"Computer Networks"},{"code":null,"e":6346,"s":6248,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":6372,"s":6346,"text":"Secure Socket Layer (SSL)"},{"code":null,"e":6402,"s":6372,"text":"GSM in Wireless Communication"},{"code":null,"e":6432,"s":6402,"text":"Wireless Application Protocol"},{"code":null,"e":6472,"s":6432,"text":"Mobile Internet Protocol (or Mobile IP)"},{"code":null,"e":6518,"s":6472,"text":"Introduction of Mobile Ad hoc Network (MANET)"},{"code":null,"e":6553,"s":6518,"text":"Advanced Encryption Standard (AES)"},{"code":null,"e":6580,"s":6553,"text":"Cryptography and its Types"},{"code":null,"e":6590,"s":6580,"text":"Bluetooth"},{"code":null,"e":6623,"s":6590,"text":"Intrusion Detection System (IDS)"}],"string":"[\n {\n \"code\": null,\n \"e\": 28,\n \"s\": 0,\n \"text\": \"\\n15 Apr, 2021\"\n },\n {\n \"code\": null,\n \"e\": 522,\n \"s\": 28,\n \"text\": \"Introduction :Man In The Middle Attack implies an active attack where the attacker/Hacker creates a connection between the victims and sends messages between them or may capture all the data packets from the victims. In this case, the victims think that they are communicating with each other, but in reality, the malicious attacker/hacker controls the communication i.e. a third person exists to control and monitor the traffic of communication between the two parties i.e. Client and Server.\"\n },\n {\n \"code\": null,\n \"e\": 629,\n \"s\": 522,\n \"text\": \"Types of Man In The Middle Attack :Here, we will discuss the types of Man In The Middle Attack as follows.\"\n },\n {\n \"code\": null,\n \"e\": 1533,\n \"s\": 629,\n \"text\": \"ARP Spoofing – ARP Stands for Address Resolution Protocol. This protocol is used for resolving IP addresses to machine MAC addresses. All the devices which want to communicate in the network, broadcast ARP-queries in the system to find out the MAC addresses of other machines. ARP Spoofing is also known as ARP Poisoning. In this, ARP poisoning, ARP packets are forced to send data to the attacker’s machine. ARP Spoofing constructs a huge number of forced ARP requests and replies packets to overload the switch. The intention of the attacker all the network packets and switch set in forwarding mode. DNS Spoofing – Similar to ARP, DNS resolves domain names to IP addresses. DNS spoofing is very dangerous because in this case a hacker will be able to hijack and spoof any DNS request made by the user and can serve the user fake web pages, fake websites, fake login pages, fake updates, and so on.\"\n },\n {\n \"code\": null,\n \"e\": 2140,\n \"s\": 1533,\n \"text\": \"ARP Spoofing – ARP Stands for Address Resolution Protocol. This protocol is used for resolving IP addresses to machine MAC addresses. All the devices which want to communicate in the network, broadcast ARP-queries in the system to find out the MAC addresses of other machines. ARP Spoofing is also known as ARP Poisoning. In this, ARP poisoning, ARP packets are forced to send data to the attacker’s machine. ARP Spoofing constructs a huge number of forced ARP requests and replies packets to overload the switch. The intention of the attacker all the network packets and switch set in forwarding mode. \"\n },\n {\n \"code\": null,\n \"e\": 2438,\n \"s\": 2140,\n \"text\": \"DNS Spoofing – Similar to ARP, DNS resolves domain names to IP addresses. DNS spoofing is very dangerous because in this case a hacker will be able to hijack and spoof any DNS request made by the user and can serve the user fake web pages, fake websites, fake login pages, fake updates, and so on.\"\n },\n {\n \"code\": null,\n \"e\": 2549,\n \"s\": 2438,\n \"text\": \"Man In The Middle Attack Techniques :Here, we will discuss the Man In The middle attack techniques as follows.\"\n },\n {\n \"code\": null,\n \"e\": 2565,\n \"s\": 2549,\n \"text\": \"Packet Sniffing\"\n },\n {\n \"code\": null,\n \"e\": 2583,\n \"s\": 2565,\n \"text\": \"Session Hijacking\"\n },\n {\n \"code\": null,\n \"e\": 2597,\n \"s\": 2583,\n \"text\": \"SSL stripping\"\n },\n {\n \"code\": null,\n \"e\": 2614,\n \"s\": 2597,\n \"text\": \"Packet Injection\"\n },\n {\n \"code\": null,\n \"e\": 2743,\n \"s\": 2614,\n \"text\": \"Man in Middle Attack using ARP spoofing : Here we will discuss the steps for Man in Middle Attack using ARP spoofing as follows.\"\n },\n {\n \"code\": null,\n \"e\": 2874,\n \"s\": 2743,\n \"text\": \"Step-1: ARP spoofing -It allows us to redirect the flow of packets in a computer network. Example of a typical Network as follows.\"\n },\n {\n \"code\": null,\n \"e\": 2901,\n \"s\": 2874,\n \"text\": \"A Typical Computer Network\"\n },\n {\n \"code\": null,\n \"e\": 3065,\n \"s\": 2901,\n \"text\": \"Step-2 :But when a hacker becomes Man-In-The-Middle by ARP Spoofing then all the requests and responses start flowing through the hacker’s system as shown below – \"\n },\n {\n \"code\": null,\n \"e\": 3101,\n \"s\": 3065,\n \"text\": \"computer network after ARP spoofing\"\n },\n {\n \"code\": null,\n \"e\": 3251,\n \"s\": 3101,\n \"text\": \"Step-3 :By doing this a hacker spoof’s the router by pretending to be the victim, and similarly, he spoofs the victim by pretending to be the router.\"\n },\n {\n \"code\": null,\n \"e\": 3433,\n \"s\": 3251,\n \"text\": \"How to do an ARP Spoof Attack :We can do an ARP Spoof attack using the built-in tool called ARPSPOOF in Kali Linux, or we can also create an ARP Spoof attack using a python program.\"\n },\n {\n \"code\": null,\n \"e\": 3504,\n \"s\": 3433,\n \"text\": \"Execution steps :Here, we will discuss the execution steps as follows.\"\n },\n {\n \"code\": null,\n \"e\": 3672,\n \"s\": 3504,\n \"text\": \"Step-1: We can run the built-in “ARPSPOOF’” tool in Kali Linux. In case the ARPSPOOF tool is not present, install the tool by running the following command as follows.\"\n },\n {\n \"code\": null,\n \"e\": 3691,\n \"s\": 3672,\n \"text\": \"apt install dsniff\"\n },\n {\n \"code\": null,\n \"e\": 4032,\n \"s\": 3691,\n \"text\": \"Step-2 : To run this attack we need two things Victim machine’s IP address & the IP of Gateway. In this example, we are using a Windows Machine as our victim and Kali Machine to run the attack. To know the victim machines IP address and gateway IP by running the following command in both the Windows machine and Linux Machine as follows.\"\n },\n {\n \"code\": null,\n \"e\": 4039,\n \"s\": 4032,\n \"text\": \"arp -a\"\n },\n {\n \"code\": null,\n \"e\": 4133,\n \"s\": 4039,\n \"text\": \"Output :This will show us the following Outputs as follows.Victim Machine (Windows Machine) –\"\n },\n {\n \"code\": null,\n \"e\": 4150,\n \"s\": 4133,\n \"text\": \"windows machine \"\n },\n {\n \"code\": null,\n \"e\": 4406,\n \"s\": 4150,\n \"text\": \"Attacker Machine (Kali Linux) –From these, we can observe that the IP address of the Windows machine is 10.0.2.8 and the IP and MAC addresses of the gateway are 10.0.2.1 and 52:54:00:12:35:00, also the MAC address of our Kali Machine is 08:00:27:a6:1f:86.\"\n },\n {\n \"code\": null,\n \"e\": 4483,\n \"s\": 4406,\n \"text\": \"Step-3 : Now, write the following commands to perform the ARP Spoof attack.\"\n },\n {\n \"code\": null,\n \"e\": 4521,\n \"s\": 4483,\n \"text\": \"arpspoof -i eth0 -t 10.0.2.8 10.0.2.1\"\n },\n {\n \"code\": null,\n \"e\": 4795,\n \"s\": 4521,\n \"text\": \"Here eth0 is the name of the interface, 10.0.2.8 is the IP of the Windows machine and 10.0.2.1 is the IP of the gateway. This will fool the victim by pretending to be the router. So again we will run the above command one more time by switching its IP addresses as follows.\"\n },\n {\n \"code\": null,\n \"e\": 4833,\n \"s\": 4795,\n \"text\": \"arpspoof -i eth0 -t 10.0.2.1 10.0.2.8\"\n },\n {\n \"code\": null,\n \"e\": 5006,\n \"s\": 4833,\n \"text\": \"Output :Attacker Machine (Kali Linux) – This shows that our ARP Spoof attack is running, and we have successfully placed our system in the middle of the client and server. \"\n },\n {\n \"code\": null,\n \"e\": 5031,\n \"s\": 5006,\n \"text\": \"ARP Spoof attack running\"\n },\n {\n \"code\": null,\n \"e\": 5088,\n \"s\": 5031,\n \"text\": \" We can also check it by running the command as follows.\"\n },\n {\n \"code\": null,\n \"e\": 5096,\n \"s\": 5088,\n \"text\": \"arp -a \"\n },\n {\n \"code\": null,\n \"e\": 5588,\n \"s\": 5096,\n \"text\": \"Output :In the output screen, you can observe that the MAC address of the gateway is changed to the MAC address of Kali Machine. Now all the data packets will flow through our Kali machine. Also, you can see that the internet connection of the victim machine is not working because it’s the security feature of Linux, which does not allow the flow of packets through it. So we need to enable Port Forwarding so that this computer will allow the packets to flow through it just like a router.\"\n },\n {\n \"code\": null,\n \"e\": 5654,\n \"s\": 5588,\n \"text\": \"Step-4 : To enable Port Forwarding to run the command as follows.\"\n },\n {\n \"code\": null,\n \"e\": 5694,\n \"s\": 5654,\n \"text\": \"echo 1 > /proc/sys/net/ipv4/ip_forward \"\n },\n {\n \"code\": null,\n \"e\": 6121,\n \"s\": 5694,\n \"text\": \"Output :This command will again establish the Internet connectivity of the victim computer. In this way, we can become the Man-In-The-Middle by using the ARP Spoof attack. So all the requests from the victim’s computer will not directly go to the router it will flow through the attacker’s machine and the attacker can sniff or extract useful information by using various tools like Wire Shark, etc. as shown below as follows.\"\n },\n {\n \"code\": null,\n \"e\": 6185,\n \"s\": 6121,\n \"text\": \"Wire Shark – used to sniff useful information from the packets.\"\n },\n {\n \"code\": null,\n \"e\": 6206,\n \"s\": 6185,\n \"text\": \"Information-Security\"\n },\n {\n \"code\": null,\n \"e\": 6212,\n \"s\": 6206,\n \"text\": \"linux\"\n },\n {\n \"code\": null,\n \"e\": 6230,\n \"s\": 6212,\n \"text\": \"Computer Networks\"\n },\n {\n \"code\": null,\n \"e\": 6248,\n \"s\": 6230,\n \"text\": \"Computer Networks\"\n },\n {\n \"code\": null,\n \"e\": 6346,\n \"s\": 6248,\n \"text\": \"Writing code in comment?\\nPlease use ide.geeksforgeeks.org,\\ngenerate link and share the link here.\"\n },\n {\n \"code\": null,\n \"e\": 6372,\n \"s\": 6346,\n \"text\": \"Secure Socket Layer (SSL)\"\n },\n {\n \"code\": null,\n \"e\": 6402,\n \"s\": 6372,\n \"text\": \"GSM in Wireless Communication\"\n },\n {\n \"code\": null,\n \"e\": 6432,\n \"s\": 6402,\n \"text\": \"Wireless Application Protocol\"\n },\n {\n \"code\": null,\n \"e\": 6472,\n \"s\": 6432,\n \"text\": \"Mobile Internet Protocol (or Mobile IP)\"\n },\n {\n \"code\": null,\n \"e\": 6518,\n \"s\": 6472,\n \"text\": \"Introduction of Mobile Ad hoc Network (MANET)\"\n },\n {\n \"code\": null,\n \"e\": 6553,\n \"s\": 6518,\n \"text\": \"Advanced Encryption Standard (AES)\"\n },\n {\n \"code\": null,\n \"e\": 6580,\n \"s\": 6553,\n \"text\": \"Cryptography and its Types\"\n },\n {\n \"code\": null,\n \"e\": 6590,\n \"s\": 6580,\n \"text\": \"Bluetooth\"\n },\n {\n \"code\": null,\n \"e\": 6623,\n \"s\": 6590,\n \"text\": \"Intrusion Detection System (IDS)\"\n }\n]"}}},{"rowIdx":178,"cells":{"title":{"kind":"string","value":"PHP | extract() Function"},"text":{"kind":"string","value":"29 Mar, 2022\nThe extract() Function is an inbuilt function in PHP. The extract() function does array to variable conversion. That is it converts array keys into variable names and array values into variable value. In other words, we can say that the extract() function imports variables from an array to the symbol table.Syntax: \nint extract($input_array, $extract_rule, $prefix)\nParameters: The extract() function accepts three parameters, out of which one is compulsory and other two are optional. All three parameters are described below: \n$input_array: This parameter is required. This specifies the array to use.$extract_rule: This parameter is optional. The extract() function checks for invalid variable names and collisions with existing variable names. This parameter specifies how invalid and colliding names will be treated. This parameter can take the following values: EXTR_OVERWRITE: This rule tells that if there is a collision, overwrite the existing variable.EXTR_SKIP: This rule tells that if there is a collision, don’t overwrite the existing variable.EXTR_PREFIX_SAME: This rule tells that if there is a collision then prefix the variable name according to $prefix parameter.EXTR_PREFIX_ALL: This rule tells that prefix all variable names according to $prefix parameter.EXTR_PREFIX_INVALID: This rule tells that only prefix invalid/numeric variable names according to parameter $prefix.EXTR_IF_EXISTS: This rule tells that to overwrite the variable only if it already exists in the current symbol table, otherwise do nothing.EXTR_PREFIX_IF_EXISTS: This rule tells to create prefixed variable names only if the non-prefixed version of the same variable exists in the current symbol table.$prefix: This parameter is optional. This parameter specifies the prefix. The prefix is automatically separated from the array key by an underscore character. Also this parameter is required only when the parameter $extract_rule is set to EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID or EXTR_PREFIX_IF_EXISTS.\n$input_array: This parameter is required. This specifies the array to use.\n$extract_rule: This parameter is optional. The extract() function checks for invalid variable names and collisions with existing variable names. This parameter specifies how invalid and colliding names will be treated. This parameter can take the following values: EXTR_OVERWRITE: This rule tells that if there is a collision, overwrite the existing variable.EXTR_SKIP: This rule tells that if there is a collision, don’t overwrite the existing variable.EXTR_PREFIX_SAME: This rule tells that if there is a collision then prefix the variable name according to $prefix parameter.EXTR_PREFIX_ALL: This rule tells that prefix all variable names according to $prefix parameter.EXTR_PREFIX_INVALID: This rule tells that only prefix invalid/numeric variable names according to parameter $prefix.EXTR_IF_EXISTS: This rule tells that to overwrite the variable only if it already exists in the current symbol table, otherwise do nothing.EXTR_PREFIX_IF_EXISTS: This rule tells to create prefixed variable names only if the non-prefixed version of the same variable exists in the current symbol table.\nEXTR_OVERWRITE: This rule tells that if there is a collision, overwrite the existing variable.\nEXTR_SKIP: This rule tells that if there is a collision, don’t overwrite the existing variable.\nEXTR_PREFIX_SAME: This rule tells that if there is a collision then prefix the variable name according to $prefix parameter.\nEXTR_PREFIX_ALL: This rule tells that prefix all variable names according to $prefix parameter.\nEXTR_PREFIX_INVALID: This rule tells that only prefix invalid/numeric variable names according to parameter $prefix.\nEXTR_IF_EXISTS: This rule tells that to overwrite the variable only if it already exists in the current symbol table, otherwise do nothing.\nEXTR_PREFIX_IF_EXISTS: This rule tells to create prefixed variable names only if the non-prefixed version of the same variable exists in the current symbol table.\n$prefix: This parameter is optional. This parameter specifies the prefix. The prefix is automatically separated from the array key by an underscore character. Also this parameter is required only when the parameter $extract_rule is set to EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID or EXTR_PREFIX_IF_EXISTS.\nReturn Value: The return value of extract() function is an integer and it represents the number of variables successfully extracted or imported from the array.Examples: \nInput : array(\"a\" => \"one\", \"b\" => \"two\", \"c\" => \"three\")\nOutput :$a = \"one\" , $b = \"two\" , $c = \"three\"\nExplanation: The keys in the input array will become the \nvariable names and their values will be assigned to these\nnew variables.\nBelow programs illustrates working of extract() in PHP:Example-1: \nPHP\n\"ASSAM\", \"OR\"=>\"ORISSA\", \"KR\"=>\"KERELA\"); extract($state); // after using extract() function echo\"\\$AS is $AS\\n\\$KR is $KR\\n\\$OR is $OR\"; ?>\nOutput: \n$AS is ASSAM\n$KR is KERELA\n$OR is ORISSA\nExample-2: \nPHP\n\"ASSAM\", \"OR\"=>\"ORISSA\", \"KR\"=>\"KERELA\"); // handling collisions with extract() function extract($state, EXTR_PREFIX_SAME, \"dup\"); echo\"\\$AS is $AS\\n\\$KR is $KR\\n\\$OR if $OR \\n\\$dup_AS = $dup_AS\"; ?>\nOutput: \n$AS is Original\n$KR is KERELA\n$OR is ORISSA \n$dup_AS = ASSAM\nReference: http://php.net/manual/en/function.extract.php\nnnr223442\nrkbhola5\nPHP-array\nPHP-function\nPHP\nWeb Technologies\nPHP\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},"parsed":{"kind":"list like","value":[{"code":null,"e":28,"s":0,"text":"\n29 Mar, 2022"},{"code":null,"e":345,"s":28,"text":"The extract() Function is an inbuilt function in PHP. The extract() function does array to variable conversion. That is it converts array keys into variable names and array values into variable value. In other words, we can say that the extract() function imports variables from an array to the symbol table.Syntax: "},{"code":null,"e":395,"s":345,"text":"int extract($input_array, $extract_rule, $prefix)"},{"code":null,"e":558,"s":395,"text":"Parameters: The extract() function accepts three parameters, out of which one is compulsory and other two are optional. All three parameters are described below: "},{"code":null,"e":2042,"s":558,"text":"$input_array: This parameter is required. This specifies the array to use.$extract_rule: This parameter is optional. The extract() function checks for invalid variable names and collisions with existing variable names. This parameter specifies how invalid and colliding names will be treated. This parameter can take the following values: EXTR_OVERWRITE: This rule tells that if there is a collision, overwrite the existing variable.EXTR_SKIP: This rule tells that if there is a collision, don’t overwrite the existing variable.EXTR_PREFIX_SAME: This rule tells that if there is a collision then prefix the variable name according to $prefix parameter.EXTR_PREFIX_ALL: This rule tells that prefix all variable names according to $prefix parameter.EXTR_PREFIX_INVALID: This rule tells that only prefix invalid/numeric variable names according to parameter $prefix.EXTR_IF_EXISTS: This rule tells that to overwrite the variable only if it already exists in the current symbol table, otherwise do nothing.EXTR_PREFIX_IF_EXISTS: This rule tells to create prefixed variable names only if the non-prefixed version of the same variable exists in the current symbol table.$prefix: This parameter is optional. This parameter specifies the prefix. The prefix is automatically separated from the array key by an underscore character. Also this parameter is required only when the parameter $extract_rule is set to EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID or EXTR_PREFIX_IF_EXISTS."},{"code":null,"e":2117,"s":2042,"text":"$input_array: This parameter is required. This specifies the array to use."},{"code":null,"e":3208,"s":2117,"text":"$extract_rule: This parameter is optional. The extract() function checks for invalid variable names and collisions with existing variable names. This parameter specifies how invalid and colliding names will be treated. This parameter can take the following values: EXTR_OVERWRITE: This rule tells that if there is a collision, overwrite the existing variable.EXTR_SKIP: This rule tells that if there is a collision, don’t overwrite the existing variable.EXTR_PREFIX_SAME: This rule tells that if there is a collision then prefix the variable name according to $prefix parameter.EXTR_PREFIX_ALL: This rule tells that prefix all variable names according to $prefix parameter.EXTR_PREFIX_INVALID: This rule tells that only prefix invalid/numeric variable names according to parameter $prefix.EXTR_IF_EXISTS: This rule tells that to overwrite the variable only if it already exists in the current symbol table, otherwise do nothing.EXTR_PREFIX_IF_EXISTS: This rule tells to create prefixed variable names only if the non-prefixed version of the same variable exists in the current symbol table."},{"code":null,"e":3303,"s":3208,"text":"EXTR_OVERWRITE: This rule tells that if there is a collision, overwrite the existing variable."},{"code":null,"e":3399,"s":3303,"text":"EXTR_SKIP: This rule tells that if there is a collision, don’t overwrite the existing variable."},{"code":null,"e":3524,"s":3399,"text":"EXTR_PREFIX_SAME: This rule tells that if there is a collision then prefix the variable name according to $prefix parameter."},{"code":null,"e":3620,"s":3524,"text":"EXTR_PREFIX_ALL: This rule tells that prefix all variable names according to $prefix parameter."},{"code":null,"e":3737,"s":3620,"text":"EXTR_PREFIX_INVALID: This rule tells that only prefix invalid/numeric variable names according to parameter $prefix."},{"code":null,"e":3877,"s":3737,"text":"EXTR_IF_EXISTS: This rule tells that to overwrite the variable only if it already exists in the current symbol table, otherwise do nothing."},{"code":null,"e":4040,"s":3877,"text":"EXTR_PREFIX_IF_EXISTS: This rule tells to create prefixed variable names only if the non-prefixed version of the same variable exists in the current symbol table."},{"code":null,"e":4360,"s":4040,"text":"$prefix: This parameter is optional. This parameter specifies the prefix. The prefix is automatically separated from the array key by an underscore character. Also this parameter is required only when the parameter $extract_rule is set to EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID or EXTR_PREFIX_IF_EXISTS."},{"code":null,"e":4530,"s":4360,"text":"Return Value: The return value of extract() function is an integer and it represents the number of variables successfully extracted or imported from the array.Examples: "},{"code":null,"e":4766,"s":4530,"text":"Input : array(\"a\" => \"one\", \"b\" => \"two\", \"c\" => \"three\")\nOutput :$a = \"one\" , $b = \"two\" , $c = \"three\"\nExplanation: The keys in the input array will become the \nvariable names and their values will be assigned to these\nnew variables."},{"code":null,"e":4833,"s":4766,"text":"Below programs illustrates working of extract() in PHP:Example-1: "},{"code":null,"e":4837,"s":4833,"text":"PHP"},{"code":"\"ASSAM\", \"OR\"=>\"ORISSA\", \"KR\"=>\"KERELA\"); extract($state); // after using extract() function echo\"\\$AS is $AS\\n\\$KR is $KR\\n\\$OR is $OR\"; ?>","e":5054,"s":4837,"text":null},{"code":null,"e":5064,"s":5054,"text":"Output: "},{"code":null,"e":5105,"s":5064,"text":"$AS is ASSAM\n$KR is KERELA\n$OR is ORISSA"},{"code":null,"e":5117,"s":5105,"text":"Example-2: "},{"code":null,"e":5121,"s":5117,"text":"PHP"},{"code":"\"ASSAM\", \"OR\"=>\"ORISSA\", \"KR\"=>\"KERELA\"); // handling collisions with extract() function extract($state, EXTR_PREFIX_SAME, \"dup\"); echo\"\\$AS is $AS\\n\\$KR is $KR\\n\\$OR if $OR \\n\\$dup_AS = $dup_AS\"; ?>","e":5403,"s":5121,"text":null},{"code":null,"e":5413,"s":5403,"text":"Output: "},{"code":null,"e":5474,"s":5413,"text":"$AS is Original\n$KR is KERELA\n$OR is ORISSA \n$dup_AS = ASSAM"},{"code":null,"e":5531,"s":5474,"text":"Reference: http://php.net/manual/en/function.extract.php"},{"code":null,"e":5541,"s":5531,"text":"nnr223442"},{"code":null,"e":5550,"s":5541,"text":"rkbhola5"},{"code":null,"e":5560,"s":5550,"text":"PHP-array"},{"code":null,"e":5573,"s":5560,"text":"PHP-function"},{"code":null,"e":5577,"s":5573,"text":"PHP"},{"code":null,"e":5594,"s":5577,"text":"Web Technologies"},{"code":null,"e":5598,"s":5594,"text":"PHP"}],"string":"[\n {\n \"code\": null,\n \"e\": 28,\n \"s\": 0,\n \"text\": \"\\n29 Mar, 2022\"\n },\n {\n \"code\": null,\n \"e\": 345,\n \"s\": 28,\n \"text\": \"The extract() Function is an inbuilt function in PHP. The extract() function does array to variable conversion. That is it converts array keys into variable names and array values into variable value. In other words, we can say that the extract() function imports variables from an array to the symbol table.Syntax: \"\n },\n {\n \"code\": null,\n \"e\": 395,\n \"s\": 345,\n \"text\": \"int extract($input_array, $extract_rule, $prefix)\"\n },\n {\n \"code\": null,\n \"e\": 558,\n \"s\": 395,\n \"text\": \"Parameters: The extract() function accepts three parameters, out of which one is compulsory and other two are optional. All three parameters are described below: \"\n },\n {\n \"code\": null,\n \"e\": 2042,\n \"s\": 558,\n \"text\": \"$input_array: This parameter is required. This specifies the array to use.$extract_rule: This parameter is optional. The extract() function checks for invalid variable names and collisions with existing variable names. This parameter specifies how invalid and colliding names will be treated. This parameter can take the following values: EXTR_OVERWRITE: This rule tells that if there is a collision, overwrite the existing variable.EXTR_SKIP: This rule tells that if there is a collision, don’t overwrite the existing variable.EXTR_PREFIX_SAME: This rule tells that if there is a collision then prefix the variable name according to $prefix parameter.EXTR_PREFIX_ALL: This rule tells that prefix all variable names according to $prefix parameter.EXTR_PREFIX_INVALID: This rule tells that only prefix invalid/numeric variable names according to parameter $prefix.EXTR_IF_EXISTS: This rule tells that to overwrite the variable only if it already exists in the current symbol table, otherwise do nothing.EXTR_PREFIX_IF_EXISTS: This rule tells to create prefixed variable names only if the non-prefixed version of the same variable exists in the current symbol table.$prefix: This parameter is optional. This parameter specifies the prefix. The prefix is automatically separated from the array key by an underscore character. Also this parameter is required only when the parameter $extract_rule is set to EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID or EXTR_PREFIX_IF_EXISTS.\"\n },\n {\n \"code\": null,\n \"e\": 2117,\n \"s\": 2042,\n \"text\": \"$input_array: This parameter is required. This specifies the array to use.\"\n },\n {\n \"code\": null,\n \"e\": 3208,\n \"s\": 2117,\n \"text\": \"$extract_rule: This parameter is optional. The extract() function checks for invalid variable names and collisions with existing variable names. This parameter specifies how invalid and colliding names will be treated. This parameter can take the following values: EXTR_OVERWRITE: This rule tells that if there is a collision, overwrite the existing variable.EXTR_SKIP: This rule tells that if there is a collision, don’t overwrite the existing variable.EXTR_PREFIX_SAME: This rule tells that if there is a collision then prefix the variable name according to $prefix parameter.EXTR_PREFIX_ALL: This rule tells that prefix all variable names according to $prefix parameter.EXTR_PREFIX_INVALID: This rule tells that only prefix invalid/numeric variable names according to parameter $prefix.EXTR_IF_EXISTS: This rule tells that to overwrite the variable only if it already exists in the current symbol table, otherwise do nothing.EXTR_PREFIX_IF_EXISTS: This rule tells to create prefixed variable names only if the non-prefixed version of the same variable exists in the current symbol table.\"\n },\n {\n \"code\": null,\n \"e\": 3303,\n \"s\": 3208,\n \"text\": \"EXTR_OVERWRITE: This rule tells that if there is a collision, overwrite the existing variable.\"\n },\n {\n \"code\": null,\n \"e\": 3399,\n \"s\": 3303,\n \"text\": \"EXTR_SKIP: This rule tells that if there is a collision, don’t overwrite the existing variable.\"\n },\n {\n \"code\": null,\n \"e\": 3524,\n \"s\": 3399,\n \"text\": \"EXTR_PREFIX_SAME: This rule tells that if there is a collision then prefix the variable name according to $prefix parameter.\"\n },\n {\n \"code\": null,\n \"e\": 3620,\n \"s\": 3524,\n \"text\": \"EXTR_PREFIX_ALL: This rule tells that prefix all variable names according to $prefix parameter.\"\n },\n {\n \"code\": null,\n \"e\": 3737,\n \"s\": 3620,\n \"text\": \"EXTR_PREFIX_INVALID: This rule tells that only prefix invalid/numeric variable names according to parameter $prefix.\"\n },\n {\n \"code\": null,\n \"e\": 3877,\n \"s\": 3737,\n \"text\": \"EXTR_IF_EXISTS: This rule tells that to overwrite the variable only if it already exists in the current symbol table, otherwise do nothing.\"\n },\n {\n \"code\": null,\n \"e\": 4040,\n \"s\": 3877,\n \"text\": \"EXTR_PREFIX_IF_EXISTS: This rule tells to create prefixed variable names only if the non-prefixed version of the same variable exists in the current symbol table.\"\n },\n {\n \"code\": null,\n \"e\": 4360,\n \"s\": 4040,\n \"text\": \"$prefix: This parameter is optional. This parameter specifies the prefix. The prefix is automatically separated from the array key by an underscore character. Also this parameter is required only when the parameter $extract_rule is set to EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID or EXTR_PREFIX_IF_EXISTS.\"\n },\n {\n \"code\": null,\n \"e\": 4530,\n \"s\": 4360,\n \"text\": \"Return Value: The return value of extract() function is an integer and it represents the number of variables successfully extracted or imported from the array.Examples: \"\n },\n {\n \"code\": null,\n \"e\": 4766,\n \"s\": 4530,\n \"text\": \"Input : array(\\\"a\\\" => \\\"one\\\", \\\"b\\\" => \\\"two\\\", \\\"c\\\" => \\\"three\\\")\\nOutput :$a = \\\"one\\\" , $b = \\\"two\\\" , $c = \\\"three\\\"\\nExplanation: The keys in the input array will become the \\nvariable names and their values will be assigned to these\\nnew variables.\"\n },\n {\n \"code\": null,\n \"e\": 4833,\n \"s\": 4766,\n \"text\": \"Below programs illustrates working of extract() in PHP:Example-1: \"\n },\n {\n \"code\": null,\n \"e\": 4837,\n \"s\": 4833,\n \"text\": \"PHP\"\n },\n {\n \"code\": \"\\\"ASSAM\\\", \\\"OR\\\"=>\\\"ORISSA\\\", \\\"KR\\\"=>\\\"KERELA\\\"); extract($state); // after using extract() function echo\\\"\\\\$AS is $AS\\\\n\\\\$KR is $KR\\\\n\\\\$OR is $OR\\\"; ?>\",\n \"e\": 5054,\n \"s\": 4837,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 5064,\n \"s\": 5054,\n \"text\": \"Output: \"\n },\n {\n \"code\": null,\n \"e\": 5105,\n \"s\": 5064,\n \"text\": \"$AS is ASSAM\\n$KR is KERELA\\n$OR is ORISSA\"\n },\n {\n \"code\": null,\n \"e\": 5117,\n \"s\": 5105,\n \"text\": \"Example-2: \"\n },\n {\n \"code\": null,\n \"e\": 5121,\n \"s\": 5117,\n \"text\": \"PHP\"\n },\n {\n \"code\": \"\\\"ASSAM\\\", \\\"OR\\\"=>\\\"ORISSA\\\", \\\"KR\\\"=>\\\"KERELA\\\"); // handling collisions with extract() function extract($state, EXTR_PREFIX_SAME, \\\"dup\\\"); echo\\\"\\\\$AS is $AS\\\\n\\\\$KR is $KR\\\\n\\\\$OR if $OR \\\\n\\\\$dup_AS = $dup_AS\\\"; ?>\",\n \"e\": 5403,\n \"s\": 5121,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 5413,\n \"s\": 5403,\n \"text\": \"Output: \"\n },\n {\n \"code\": null,\n \"e\": 5474,\n \"s\": 5413,\n \"text\": \"$AS is Original\\n$KR is KERELA\\n$OR is ORISSA \\n$dup_AS = ASSAM\"\n },\n {\n \"code\": null,\n \"e\": 5531,\n \"s\": 5474,\n \"text\": \"Reference: http://php.net/manual/en/function.extract.php\"\n },\n {\n \"code\": null,\n \"e\": 5541,\n \"s\": 5531,\n \"text\": \"nnr223442\"\n },\n {\n \"code\": null,\n \"e\": 5550,\n \"s\": 5541,\n \"text\": \"rkbhola5\"\n },\n {\n \"code\": null,\n \"e\": 5560,\n \"s\": 5550,\n \"text\": \"PHP-array\"\n },\n {\n \"code\": null,\n \"e\": 5573,\n \"s\": 5560,\n \"text\": \"PHP-function\"\n },\n {\n \"code\": null,\n \"e\": 5577,\n \"s\": 5573,\n \"text\": \"PHP\"\n },\n {\n \"code\": null,\n \"e\": 5594,\n \"s\": 5577,\n \"text\": \"Web Technologies\"\n },\n {\n \"code\": null,\n \"e\": 5598,\n \"s\": 5594,\n \"text\": \"PHP\"\n }\n]"}}},{"rowIdx":179,"cells":{"title":{"kind":"string","value":"Tryit Editor v3.7"},"text":{"kind":"string","value":"Tryit: HTML table - colgroup"},"parsed":{"kind":"list like","value":[],"string":"[]"}}},{"rowIdx":180,"cells":{"title":{"kind":"string","value":"How to integrate Android Snackbar?"},"text":{"kind":"string","value":"Snackbar is just like Toast in android but it going to interact with action. It going to show the message at the bottom of the screen without any interaction with other views and close automatically after a time-out.\nThis example demonstrates how to integrate Android Snackbar.\nStep 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.\nStep 2 − Open build.gradle and add design support library dependency.\napply plugin: 'com.android.application'\nandroid {\n compileSdkVersion 28\n defaultConfig {\n applicationId \"com.example.andy.myapplication\"\n minSdkVersion 19\n targetSdkVersion 28\n versionCode 1\n versionName \"1.0\"\n testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\n }\n buildTypes {\n release {\n minifyEnabled false\n proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n }\n }\n}\ndependencies {\n implementation fileTree(dir: 'libs', include: ['*.jar'])\n implementation 'com.android.support:appcompat-v7:28.0.0'\n implementation 'com.android.support:design:28.0.0'\n implementation 'com.android.support.constraint:constraint-layout:1.1.3'\n testImplementation 'junit:junit:4.12'\n androidTestImplementation 'com.android.support.test:runner:1.0.2'\n androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'\n}\nStep 3 − Add the following code to res/layout/activity_main.xml.\n\n\n \n\nIn the above code, we have declare layout id because snackback required parent view. when user click on button it will open snackbar at the bottom.\nStep 4 − Add the following code to src/MainActivity.java\nimport android.annotation.TargetApi;\nimport android.content.Intent;\nimport android.graphics.Color;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.design.widget.CoordinatorLayout;\nimport android.support.design.widget.Snackbar;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n CoordinatorLayout coordinatorLayout;\n @TargetApi(Build.VERSION_CODES.O)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n coordinatorLayout=findViewById(R.id.layout);\n Button button=findViewById(R.id.button);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Snackbar snackbar = Snackbar\n .make(coordinatorLayout, \"Welcome to tutorialspoint.com\", Snackbar.LENGTH_LONG)\n .setAction(\"Click\", new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n String url = \"http://www.tutorialspoint.com\";\n Intent i = new Intent(Intent.ACTION_VIEW);\n i.setData(Uri.parse(url));\n startActivity(i);\n }\n });\n // Changing message text color\n snackbar.setActionTextColor(Color.RED);\n // Changing action button text color\n View sbView = snackbar.getView();\n TextView textView = (TextView) sbView.findViewById(\n android.support.design.R.id.snackbar_text);\n textView.setTextColor(Color.YELLOW);\n snackbar.show();\n }\n });\n }\n}\nIn the above when user click on button, it will show snackbar as shown below -\nSnackbar snackbar = Snackbar\n.make(coordinatorLayout, \"Welcome to tutorialspoint.com\", Snackbar.LENGTH_LONG)\n.setAction(\"Click\", new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n String url = \"http://www.tutorialspoint.com\";\n Intent i = new Intent(Intent.ACTION_VIEW);\n i.setData(Uri.parse(url));\n startActivity(i);\n }\n});\n// Changing message text color\nsnackbar.setActionTextColor(Color.RED);\n// Changing action button text color\nView sbView = snackbar.getView();\nTextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);\ntextView.setTextColor(Color.YELLOW);\nsnackbar.show();\nIn the above code, we have declare snackbar with message as welcome to tutorialspoint.com and a button as \"click\". when user clicks on click button it will open a tutorialspoint web site in the default browser.\nStep 5 − Add the following code to manifest.xml\n\n\n \n \n \n \n \n \n \n \n \n\nIn the above code, we have declare internet permission to show web site.\nLet's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from an 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 −\nWhen you click on a button, it will show snackbar message with click button as shown above.\nWhen you click on \"click\" button it will open default browser with tutorialspoint.com website.\nClick here to download the project code"},"parsed":{"kind":"list like","value":[{"code":null,"e":1279,"s":1062,"text":"Snackbar is just like Toast in android but it going to interact with action. It going to show the message at the bottom of the screen without any interaction with other views and close automatically after a time-out."},{"code":null,"e":1340,"s":1279,"text":"This example demonstrates how to integrate Android Snackbar."},{"code":null,"e":1469,"s":1340,"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":1539,"s":1469,"text":"Step 2 − Open build.gradle and add design support library dependency."},{"code":null,"e":2493,"s":1539,"text":"apply plugin: 'com.android.application'\nandroid {\n compileSdkVersion 28\n defaultConfig {\n applicationId \"com.example.andy.myapplication\"\n minSdkVersion 19\n targetSdkVersion 28\n versionCode 1\n versionName \"1.0\"\n testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\n }\n buildTypes {\n release {\n minifyEnabled false\n proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n }\n }\n}\ndependencies {\n implementation fileTree(dir: 'libs', include: ['*.jar'])\n implementation 'com.android.support:appcompat-v7:28.0.0'\n implementation 'com.android.support:design:28.0.0'\n implementation 'com.android.support.constraint:constraint-layout:1.1.3'\n testImplementation 'junit:junit:4.12'\n androidTestImplementation 'com.android.support.test:runner:1.0.2'\n androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'\n}"},{"code":null,"e":2558,"s":2493,"text":"Step 3 − Add the following code to res/layout/activity_main.xml."},{"code":null,"e":3071,"s":2558,"text":"\n\n \n"},{"code":null,"e":3219,"s":3071,"text":"In the above code, we have declare layout id because snackback required parent view. when user click on button it will open snackbar at the bottom."},{"code":null,"e":3276,"s":3219,"text":"Step 4 − Add the following code to src/MainActivity.java"},{"code":null,"e":5117,"s":3276,"text":"import android.annotation.TargetApi;\nimport android.content.Intent;\nimport android.graphics.Color;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.design.widget.CoordinatorLayout;\nimport android.support.design.widget.Snackbar;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n CoordinatorLayout coordinatorLayout;\n @TargetApi(Build.VERSION_CODES.O)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n coordinatorLayout=findViewById(R.id.layout);\n Button button=findViewById(R.id.button);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Snackbar snackbar = Snackbar\n .make(coordinatorLayout, \"Welcome to tutorialspoint.com\", Snackbar.LENGTH_LONG)\n .setAction(\"Click\", new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n String url = \"http://www.tutorialspoint.com\";\n Intent i = new Intent(Intent.ACTION_VIEW);\n i.setData(Uri.parse(url));\n startActivity(i);\n }\n });\n // Changing message text color\n snackbar.setActionTextColor(Color.RED);\n // Changing action button text color\n View sbView = snackbar.getView();\n TextView textView = (TextView) sbView.findViewById(\n android.support.design.R.id.snackbar_text);\n textView.setTextColor(Color.YELLOW);\n snackbar.show();\n }\n });\n }\n}"},{"code":null,"e":5196,"s":5117,"text":"In the above when user click on button, it will show snackbar as shown below -"},{"code":null,"e":5861,"s":5196,"text":"Snackbar snackbar = Snackbar\n.make(coordinatorLayout, \"Welcome to tutorialspoint.com\", Snackbar.LENGTH_LONG)\n.setAction(\"Click\", new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n String url = \"http://www.tutorialspoint.com\";\n Intent i = new Intent(Intent.ACTION_VIEW);\n i.setData(Uri.parse(url));\n startActivity(i);\n }\n});\n// Changing message text color\nsnackbar.setActionTextColor(Color.RED);\n// Changing action button text color\nView sbView = snackbar.getView();\nTextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);\ntextView.setTextColor(Color.YELLOW);\nsnackbar.show();"},{"code":null,"e":6072,"s":5861,"text":"In the above code, we have declare snackbar with message as welcome to tutorialspoint.com and a button as \"click\". when user clicks on click button it will open a tutorialspoint web site in the default browser."},{"code":null,"e":6120,"s":6072,"text":"Step 5 − Add the following code to manifest.xml"},{"code":null,"e":6861,"s":6120,"text":"\n\n \n \n \n \n \n \n \n \n \n"},{"code":null,"e":6934,"s":6861,"text":"In the above code, we have declare internet permission to show web site."},{"code":null,"e":7284,"s":6934,"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 an 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":7376,"s":7284,"text":"When you click on a button, it will show snackbar message with click button as shown above."},{"code":null,"e":7471,"s":7376,"text":"When you click on \"click\" button it will open default browser with tutorialspoint.com website."},{"code":null,"e":7511,"s":7471,"text":"Click here to download the project code"}],"string":"[\n {\n \"code\": null,\n \"e\": 1279,\n \"s\": 1062,\n \"text\": \"Snackbar is just like Toast in android but it going to interact with action. It going to show the message at the bottom of the screen without any interaction with other views and close automatically after a time-out.\"\n },\n {\n \"code\": null,\n \"e\": 1340,\n \"s\": 1279,\n \"text\": \"This example demonstrates how to integrate Android Snackbar.\"\n },\n {\n \"code\": null,\n \"e\": 1469,\n \"s\": 1340,\n \"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.\"\n },\n {\n \"code\": null,\n \"e\": 1539,\n \"s\": 1469,\n \"text\": \"Step 2 − Open build.gradle and add design support library dependency.\"\n },\n {\n \"code\": null,\n \"e\": 2493,\n \"s\": 1539,\n \"text\": \"apply plugin: 'com.android.application'\\nandroid {\\n compileSdkVersion 28\\n defaultConfig {\\n applicationId \\\"com.example.andy.myapplication\\\"\\n minSdkVersion 19\\n targetSdkVersion 28\\n versionCode 1\\n versionName \\\"1.0\\\"\\n testInstrumentationRunner \\\"android.support.test.runner.AndroidJUnitRunner\\\"\\n }\\n buildTypes {\\n release {\\n minifyEnabled false\\n proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\\n }\\n }\\n}\\ndependencies {\\n implementation fileTree(dir: 'libs', include: ['*.jar'])\\n implementation 'com.android.support:appcompat-v7:28.0.0'\\n implementation 'com.android.support:design:28.0.0'\\n implementation 'com.android.support.constraint:constraint-layout:1.1.3'\\n testImplementation 'junit:junit:4.12'\\n androidTestImplementation 'com.android.support.test:runner:1.0.2'\\n androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'\\n}\"\n },\n {\n \"code\": null,\n \"e\": 2558,\n \"s\": 2493,\n \"text\": \"Step 3 − Add the following code to res/layout/activity_main.xml.\"\n },\n {\n \"code\": null,\n \"e\": 3071,\n \"s\": 2558,\n \"text\": \"\\n\\n \\n\"\n },\n {\n \"code\": null,\n \"e\": 3219,\n \"s\": 3071,\n \"text\": \"In the above code, we have declare layout id because snackback required parent view. when user click on button it will open snackbar at the bottom.\"\n },\n {\n \"code\": null,\n \"e\": 3276,\n \"s\": 3219,\n \"text\": \"Step 4 − Add the following code to src/MainActivity.java\"\n },\n {\n \"code\": null,\n \"e\": 5117,\n \"s\": 3276,\n \"text\": \"import android.annotation.TargetApi;\\nimport android.content.Intent;\\nimport android.graphics.Color;\\nimport android.net.Uri;\\nimport android.os.Build;\\nimport android.os.Bundle;\\nimport android.support.design.widget.CoordinatorLayout;\\nimport android.support.design.widget.Snackbar;\\nimport android.support.v7.app.AppCompatActivity;\\nimport android.view.View;\\nimport android.widget.Button;\\nimport android.widget.TextView;\\npublic class MainActivity extends AppCompatActivity {\\n CoordinatorLayout coordinatorLayout;\\n @TargetApi(Build.VERSION_CODES.O)\\n @Override\\n protected void onCreate(Bundle savedInstanceState) {\\n super.onCreate(savedInstanceState);\\n setContentView(R.layout.activity_main);\\n coordinatorLayout=findViewById(R.id.layout);\\n Button button=findViewById(R.id.button);\\n button.setOnClickListener(new View.OnClickListener() {\\n @Override\\n public void onClick(View v) {\\n Snackbar snackbar = Snackbar\\n .make(coordinatorLayout, \\\"Welcome to tutorialspoint.com\\\", Snackbar.LENGTH_LONG)\\n .setAction(\\\"Click\\\", new View.OnClickListener() {\\n @Override\\n public void onClick(View view) {\\n String url = \\\"http://www.tutorialspoint.com\\\";\\n Intent i = new Intent(Intent.ACTION_VIEW);\\n i.setData(Uri.parse(url));\\n startActivity(i);\\n }\\n });\\n // Changing message text color\\n snackbar.setActionTextColor(Color.RED);\\n // Changing action button text color\\n View sbView = snackbar.getView();\\n TextView textView = (TextView) sbView.findViewById(\\n android.support.design.R.id.snackbar_text);\\n textView.setTextColor(Color.YELLOW);\\n snackbar.show();\\n }\\n });\\n }\\n}\"\n },\n {\n \"code\": null,\n \"e\": 5196,\n \"s\": 5117,\n \"text\": \"In the above when user click on button, it will show snackbar as shown below -\"\n },\n {\n \"code\": null,\n \"e\": 5861,\n \"s\": 5196,\n \"text\": \"Snackbar snackbar = Snackbar\\n.make(coordinatorLayout, \\\"Welcome to tutorialspoint.com\\\", Snackbar.LENGTH_LONG)\\n.setAction(\\\"Click\\\", new View.OnClickListener() {\\n @Override\\n public void onClick(View view) {\\n String url = \\\"http://www.tutorialspoint.com\\\";\\n Intent i = new Intent(Intent.ACTION_VIEW);\\n i.setData(Uri.parse(url));\\n startActivity(i);\\n }\\n});\\n// Changing message text color\\nsnackbar.setActionTextColor(Color.RED);\\n// Changing action button text color\\nView sbView = snackbar.getView();\\nTextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);\\ntextView.setTextColor(Color.YELLOW);\\nsnackbar.show();\"\n },\n {\n \"code\": null,\n \"e\": 6072,\n \"s\": 5861,\n \"text\": \"In the above code, we have declare snackbar with message as welcome to tutorialspoint.com and a button as \\\"click\\\". when user clicks on click button it will open a tutorialspoint web site in the default browser.\"\n },\n {\n \"code\": null,\n \"e\": 6120,\n \"s\": 6072,\n \"text\": \"Step 5 − Add the following code to manifest.xml\"\n },\n {\n \"code\": null,\n \"e\": 6861,\n \"s\": 6120,\n \"text\": \"\\n\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n\"\n },\n {\n \"code\": null,\n \"e\": 6934,\n \"s\": 6861,\n \"text\": \"In the above code, we have declare internet permission to show web site.\"\n },\n {\n \"code\": null,\n \"e\": 7284,\n \"s\": 6934,\n \"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 an 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 −\"\n },\n {\n \"code\": null,\n \"e\": 7376,\n \"s\": 7284,\n \"text\": \"When you click on a button, it will show snackbar message with click button as shown above.\"\n },\n {\n \"code\": null,\n \"e\": 7471,\n \"s\": 7376,\n \"text\": \"When you click on \\\"click\\\" button it will open default browser with tutorialspoint.com website.\"\n },\n {\n \"code\": null,\n \"e\": 7511,\n \"s\": 7471,\n \"text\": \"Click here to download the project code\"\n }\n]"}}},{"rowIdx":181,"cells":{"title":{"kind":"string","value":"WML - Quick Guide"},"text":{"kind":"string","value":"The topmost layer in the WAP (Wireless Application Protocol) architecture is made up of WAE (Wireless Application Environment), which consists of WML and WML scripting language.\nWML stands for Wireless Markup Language\nWML stands for Wireless Markup Language\nWML is an application of XML, which is defined in a document-type definition.\nWML is an application of XML, which is defined in a document-type definition.\nWML is based on HDML and is modified so that it can be compared with HTML.\nWML is based on HDML and is modified so that it can be compared with HTML.\nWML takes care of the small screen and the low bandwidth of transmission.\nWML takes care of the small screen and the low bandwidth of transmission.\nWML is the markup language defined in the WAP specification.\nWML is the markup language defined in the WAP specification.\nWAP sites are written in WML, while web sites are written in HTML.\nWAP sites are written in WML, while web sites are written in HTML.\nWML is very similar to HTML. Both of them use tags and are written in plain text format.\nWML is very similar to HTML. Both of them use tags and are written in plain text format.\nWML files have the extension \".wml\". The MIME type of WML is \"text/vnd.wap.wml\".\nWML files have the extension \".wml\". The MIME type of WML is \"text/vnd.wap.wml\".\nWML supports client-side scripting. The scripting language supported is called WMLScript.\nWML supports client-side scripting. The scripting language supported is called WMLScript.\nWAP Forum has released a latest version WAP 2.0. The markup language defined in WAP 2.0 is XHTML Mobile Profile (MP). The WML MP is a subset of the XHTML. A style sheet called WCSS (WAP CSS) has been introduced alongwith XHTML MP. The WCSS is a subset of the CSS2.\nMost of the new mobile phone models released are WAP 2.0-enabled. Because WAP 2.0 is backward compatible to WAP 1.x, WAP 2.0-enabled mobile devices can display both XHTML MP and WML documents.\nWML 1.x is an earlier technology. However, that does not mean it is of no use, since a lot of wireless devices that only supports WML 1.x are still being used. Latest version of WML is 2.0 and it is created for backward compatibility purposes. So WAP site developers need not to worry about WML 2.0.\nA main difference between HTML and WML is that the basic unit of navigation in HTML is a page, while that in WML is a card. A WML file can contain multiple cards and they form a deck.\nWhen a WML page is accessed from a mobile phone, all the cards in the page are downloaded from the WAP server. So if the user goes to another card of the same deck, the mobile browser does not have to send any requests to the server since the file that contains the deck is already stored in the wireless device.\nYou can put links, text, images, input fields, option boxes and many other elements in a card.\nFollowing is the basic structure of a WML program:\n\n\n\n\n\n\n

\nThis is the first card in the deck\n

\n
\n\n\n

\nThs is the second card in the deck\n

\n
\n\n
\nThe first line of this text says that this is an XML document and the version is 1.0. The second line selects\nthe document type and gives the URL of the document type definition (DTD).\nOne WML deck (i.e. page ) can have one or more cards as shown above. We will see complete details on WML document structure in subsequent chapter.\nUnlike HTML 4.01 Transitional, text cannot be enclosed directly in the ... tag pair. So you need to put a content inside

...

as shown above.\nWireless devices are limited by the size of their displays and keypads. It's therefore very important to take this into account when designing a WAP Site.\nWhile designing a WAP site you must ensure that you keep things simple and easy to use. You should always keep in mind that there are no standard microbrowser behaviors and that the data link may be relatively slow, at around 10Kbps. However, with GPRS, EDGE, and UMTS, this may not be the case for long, depending on where you are located.\nThe following are general design tips that you should keep in mind when designing a service:\nKeep the WML decks and images to less than 1.5KB.\nKeep the WML decks and images to less than 1.5KB.\nKeep text brief and meaningful, and as far as possible try to precode options to minimize the rather painful experience of user data entry.\nKeep text brief and meaningful, and as far as possible try to precode options to minimize the rather painful experience of user data entry.\nKeep URLs brief and easy to recall.\nKeep URLs brief and easy to recall.\nMinimize menu levels to prevent users from getting lost and the system from slowing down.\nMinimize menu levels to prevent users from getting lost and the system from slowing down.\nUse standard layout tags such as and , and logically structure your information.\nUse standard layout tags such as and , and logically structure your information.\nDon't go overboard with the use of graphics, as many target devices may not support them.\nDon't go overboard with the use of graphics, as many target devices may not support them.\nTo develop WAP applications, you will need the following:\nA WAP enabled Web Server: You can enable your Apache or Microsoft IIS to serve all the WAP client request.\nA WAP enabled Web Server: You can enable your Apache or Microsoft IIS to serve all the WAP client request.\nA WAP Gateway Simulator: This is required to interact to your WAP server.\nA WAP Gateway Simulator: This is required to interact to your WAP server.\nA WAP Phone Simulator: This is required to test your WAP Pages and to show all the WAP pages.\nA WAP Phone Simulator: This is required to test your WAP Pages and to show all the WAP pages.\nYou can write your WAP pages using the following languages:\nWireless Markup Language(WML) to develop WAP application.\nWML Script to enhance the functionality of WAP application.\nIn normal web applications, MIME type is set to text/html, designating normal HTML code. Images, on the other hand, could be specified as image/gif or image/jpeg, for instance. With this content type specification, the web browser knows the data type that the web server returns.\nTo make your Apache WAP compatible, you have nothing to do very much. You simply need to add support for the MIME types and extensions listed below.\nAssuming you have Apache Web server installed on your machine. So now we will tell you how to enable WAP functionality in your Apache web server.\nSo locate Apache's file httpd.conf which is usually in /etc/httpd/conf, and add the following lines to the file and restart the server:\nAddType text/vnd.wap.wml .wml\nAddType text/vnd.wap.wmlscript .wmls\nAddType application/vnd.wap.wmlc .wmlc\nAddType application/vnd.wap.wmlscriptc .wmlsc\nAddType image/vnd.wap.wbmp .wbmp\nIn dynamic applications, the MIME type must be set on the fly, whereas in static WAP applications the web server must be configured appropriately.\nTo configure a Microsoft IIS server to deliver WAP content, you need to perform the following:\n\nOpen the Internet Service Manager console and expand the tree to view your Web site entry. You can add the WAP MIME types to a whole server or individual directories.\nOpen the Properties dialog box by right-clicking the appropriate server or directory, then choose Properties from the menu.\nFrom the Properties dialog, choose the HTTP Headers tab, then select the File Types button at the bottom right.\nFor each MIME type listed earlier in the above table, supply the extension with or without the dot (it will be automatically added for you), then click OK in the Properties dialog box to accept your changes.\n\nOpen the Internet Service Manager console and expand the tree to view your Web site entry. You can add the WAP MIME types to a whole server or individual directories.\nOpen the Properties dialog box by right-clicking the appropriate server or directory, then choose Properties from the menu.\nFrom the Properties dialog, choose the HTTP Headers tab, then select the File Types button at the bottom right.\nFor each MIME type listed earlier in the above table, supply the extension with or without the dot (it will be automatically added for you), then click OK in the Properties dialog box to accept your changes.\nThere are many WAP Gateway Simulator available on the Internet so download any of them and install on your PC. You would need to run this gateway before starting WAP Mobile simulator.\nWAP Gateway will take your request and will pass it to the Web Server and whatever response will be received from the Web server that will be passed to the Mobile Simulator.\nYou can download it from Nokia web site:\nNokia WAP Gateway simulator - Download Nokia WAP Gateway simulator.\nNokia WAP Gateway simulator - Download Nokia WAP Gateway simulator.\nThere are many WAP Simulator available on the Internet so download any of them and install on your PC which you will use as a WAP client. Here are popular links to download simulator:\nNokia WAP simulator - Download Nokia WAP simulator.\nNokia WAP simulator - Download Nokia WAP simulator.\nWinWAP simulator - Download WinWAP browser from their official website.\nWinWAP simulator - Download WinWAP browser from their official website.\nNOTE: If you have WAP enabled phone then you do not need to install this simulator. But while doing development it is more convenient and economic to use a simulator.\nI am giving this section just for your reference, if you are not interested then you can skip this section.\nThe figure below shows the WAP programming model. Note the similarities with the Internet model. Without the WAP Gateway/Proxy the two models would have been practically identical.\nWAP Gateway/Proxy is the entity that connects the wireless domain with the Internet. You should make a note that the request that is sent from the wireless client to the WAP Gateway/Proxy uses the Wireless Session Protocol (WSP). In its essence, WSP is a binary version of HTTP.\nA markup language - the Wireless Markup Language (WML) has been adapted to develop optimized WAP applications. In order to save valuable bandwidth in the wireless network, WML can be encoded into a compact binary format. Encoding WML is one of the tasks performed by the WAP Gateway/Proxy.\nWhen it comes to actual use, WAP works like this:\n\nThe user selects an option on their mobile device that has a URL with Wireless Markup language (WML) content assigned to it.\nThe phone sends the URL request via the phone network to a WAP gateway, using the binary encoded WAP protocol.\nThe gateway translates this WAP request into a conventional HTTP request for the specified URL, and sends it on to the Internet.\nThe appropriate Web server picks up the HTTP request.\nThe server processes the request, just as it would any other request. If the URL refers to a static WML file, the server delivers it. If a CGI script is requested, it is processed and the content returned as usual.\nThe Web server adds the HTTP header to the WML content and returns it to the gateway.\nThe WAP gateway compiles the WML into binary form.\nThe gateway then sends the WML response back to the phone.\nThe phone receives the WML via the WAP protocol.\nThe micro-browser processes the WML and displays the content on the screen.\n\nThe user selects an option on their mobile device that has a URL with Wireless Markup language (WML) content assigned to it.\nThe user selects an option on their mobile device that has a URL with Wireless Markup language (WML) content assigned to it.\nThe phone sends the URL request via the phone network to a WAP gateway, using the binary encoded WAP protocol.\nThe phone sends the URL request via the phone network to a WAP gateway, using the binary encoded WAP protocol.\nThe gateway translates this WAP request into a conventional HTTP request for the specified URL, and sends it on to the Internet.\nThe gateway translates this WAP request into a conventional HTTP request for the specified URL, and sends it on to the Internet.\nThe appropriate Web server picks up the HTTP request.\nThe appropriate Web server picks up the HTTP request.\nThe server processes the request, just as it would any other request. If the URL refers to a static WML file, the server delivers it. If a CGI script is requested, it is processed and the content returned as usual.\nThe server processes the request, just as it would any other request. If the URL refers to a static WML file, the server delivers it. If a CGI script is requested, it is processed and the content returned as usual.\nThe Web server adds the HTTP header to the WML content and returns it to the gateway.\nThe Web server adds the HTTP header to the WML content and returns it to the gateway.\nThe WAP gateway compiles the WML into binary form.\nThe WAP gateway compiles the WML into binary form.\nThe gateway then sends the WML response back to the phone.\nThe gateway then sends the WML response back to the phone.\nThe phone receives the WML via the WAP protocol.\nThe phone receives the WML via the WAP protocol.\nThe micro-browser processes the WML and displays the content on the screen.\nThe micro-browser processes the WML and displays the content on the screen.\nA WML program is typically divided into two parts: the document prolog and the body. Consider the following code:\nFollowing is the basic structure of a WML program:\n\n\n\n\n\n\n

\nThis is the first card in the deck\n\n

\n
\n\n\n

\nThs is the second card in the deck\n

\n
\n\n
\nThe first line of this text says that this is an XML document and the version is 1.0. The second line selects\nthe document type and gives the URL of the document type definition (DTD). The DTD referenced is defined in WAP 1.2, but this header changes with the versions of the WML. The header must be copied exactly so that the tool kits automatically generate this prolog.\nThe prolog components are not WML elements and they should not be closed, i.e. you should not give them an end tag or finish them with />.\nThe body is enclosed within a tag pair. The body of a WML document can consist of one or more of the following:\nDeck\nDeck\nCard\nCard\nContent to be shown\nContent to be shown\nNavigation instructions\nNavigation instructions\nUnlike HTML 4.01 Transitional, text cannot be enclosed directly in the ... tag pair. So you need to put a content inside

...

as shown above.\nPut above code in a file called test.wml file, and put this WML file locally on your hard disk, then view it using an emulator.\nThis is by far the most efficient way of developing and testing WML files. Since your aim is, however, to develop a service that is going to be available to WAP phone users, you should upload your WML files onto a server once you have developed them locally and test them over a real Internet connection. As you start developing more complex WAP services, this is how you will identify and rectify performance problems, which could, if left alone, lose your site visitors.\nIn uploading the file test.wml to a server, you will be testing your WML emulator to see how it looks and behaves, and checking your Web server to see that it is set up correctly. Now start your emulator and use it to access the URL of test.wml. For example, the URL might look something like this:\nhttp://websitename.com/wapstuff/test.wml\nNOTE: Before accessing any URL, make sure WAP Gateway Simulator is running on your PC.\nWhen you will download your WAP program, then you will see only first card at your mobile. Following is the output of the above example on Nokia Mobile Browser 4.0. This mobile supports horizontal scrolling. You can see the text off the screen by pressing the \"Left\" or \"Right\" button.\nWhen you press right button, then second card will be visible as follows:\nWML is defined by a set of elements that specify all markup and structural information for a WML\ndeck. Elements are identified by tags, which are each enclosed in a pair of angle brackets.\nUnlike HTML, WML strictly adheres to the XML hierarchical structure, and thus, elements must contain a start tag; any content such as text and/or other elements; and an end tag. Elements have one of the following two structures:\n content : This form is identical to HTML.\n content : This form is identical to HTML.\n: This is used when an element cannot contain visible content or is empty, such as a line break. WML document's prolog part does not have any element which has closing element.\n: This is used when an element cannot contain visible content or is empty, such as a line break. WML document's prolog part does not have any element which has closing element.\nFollowing table lists the majority of valid elements. A complete detail of all these elements is given in WML Tags Reference.\nAs with most programming languages, WML also provides a means of placing comment text within the code.\nComments are used by developers as a means of documenting programming decisions within the code to allow for easier code maintenance.\nWML comments use the same format as HTML comments and use the following syntax:\n\nA multiline comment can be given as follows:\n\nThe WML author can use comments anywhere, and they are not displayed to the user by the user agent. Some emulators may complain if comments are placed before the XML prolog.\nNote that comments are not compiled or sent to the user agent, and thus have no effect on the size of the compiled deck.\nBecause multiple cards can be contained within one deck, some mechanism needs to be in place to hold data as the user traverses from card to card. This mechanism is provided via WML variables.\nWML is case sensitive. No case folding is performed when parsing a WML deck. All enumerated attribute values are case sensitive. For example, the following attribute values are all different: id=\"Card1\", id=\"card1\", and id=\"CARD1\".\nVariables can be created and set using several different methods. Following are two examples:\nThe element is used as a result of the user executing some task. The >setvar> element can be used to set a variable's state within the following elements: , , and .\nThis element supports the following attributes:\nThe following element would create a variable named a with a value of 1000:\n\nVariables are also set through any input element like input,select, option, etc. A variable is automatically created that corresponds with the named attribute of an input element.\nFor example, the following element would create a variable named b:\n\nVariable expansion occurs at runtime, in the microbrowser or emulator. This means it can be concatenated with or embedded in other text.\nVariables are referenced with a preceding dollar sign, and any single dollar sign in your WML deck is interpreted as a variable reference.\n

Selected option value is $(b)

\nThis section will describe basic text formatting elements of WML.\nThe
element defines a line break and almost all WAP browsers supports a line break tag.\nThe
element supports the following attributes:\nFollowing is the example showing usage of
element.\n\n\n\n\n\n\n

\nThis is a
paragraph with a line break.\n

\n
\n\n
\nThis will produce the following result:\nThe

element defines a paragraph of text and WAP browsers always render a paragraph in a new line.\nA

element is required to define any text, image or a table in WML.\nThe

element supports the following attributes:\nleft\nright\ncenter\nwrap\nnowrap\nFollowing is the example showing usage of

element.\n\n\n\n\n\n\n

\nThis is first paragraph\n

\n

\nThis is second paragraph\n

\n\n\n\nThis will produce the following result:\nThe element along with and
is used to create a table in WML. WML does not allow the nesting of tables \nA element should be put with-in

...

elements.\nThe
element supports the following attributes:\nL\nC\nR\nFirst table column -- Left-aligned\nFirst table column -- Left-aligned\nSecond table column -- Center-aligned\nSecond table column -- Center-aligned\nThird table column -- Right-aligned\nThird table column -- Right-aligned\nThen you should set the value of the align attribute to LCR.\nFollowing is the example showing usage of
element.\n\n\n\n\n\n\n

\n

\n\t\n\t \n\t \n\t \n\t\n\n\t\n\t \n\t \n\t \n\t\n\n\t\n\t \n\t \n\t \n\t\n
Col 1Col 2Col 3
ABC
DEF
\n

\n\n\n\nThis will produce the following result:\nThe
 element is used to specify preformatted text in WML. Preformatted text is text of which the format follows the way it is typed in the WML document. \nThis tag preserves all the white spaces enclosed inside this tag. Make sure you are not putting this tag inside 

...

\nThe
 element supports following attributes:\nFollowing is the example showing usage of 
 element.\n\n\n\n\n\n\n   
\n   This is     preformatted\n        text and will appear\n as it it.\n
\n
\n\n
\nThis will produce the following result:\nWML does not support element, but there are other WML elements, which you can use to create different font effects like underlined text, bold text and italic text, etc.\nThese tags are given in the following table:\nThese elements support the following attributes:\nFollowing is the example showing usage of these elements.\n\n\n\n\n\n\n

\n bold text
\n big text
\n emphasized text
\n italic text
\n small text
\n strong text
\n underlined text\n

\n
\n\n
\nThis will produce the following result:\nThe element is used to include an image in a WAP card. WAP-enabled wireless devices only supported the Wireless Bitmap (WBMP) image format. \nWBMP images can only contain two colors: black and white. The file extension of WBMP is \".wbmp\" and the MIME type of WBMP is \"image/vnd.wap.wbmp\".\nThe element supports the following attributes:\ntop\nmiddle\nbottom\npx\n%\npx\n%\npx\n%\npx\n%\nThere are free tools available on the Internet to make \".wbmp\" images.\nThe Nokia Mobile Internet Toolkit (NMIT) comes with a WBMP image editor that you can use. You can convert existing GIF or JPG image files into WBMP file using NMIT.\nAnother free tool is ImageMagick, which can help you to create WBMP images.\nFollowing is the example showing usage of element.\n\n\n\n\n\n\n

\nThis is Thumb image\n\"Thumb\n

\n\n

\nThis is Heart image\n\"Heart\n

\n\n
\n\n
\nThis will produce the following result:\nThe element along with and
is used to create a table in WML. WML does not allow the nesting of tables \nA element should be put with-in

...

elements.\nThe
element supports the following attributes:\nL\nC\nR\nFirst table column -- Left-aligned\nFirst table column -- Left-aligned\nSecond table column -- Center-aligned\nSecond table column -- Center-aligned\nThird table column -- Right-aligned\nThird table column -- Right-aligned\nThen you should set the value of the align attribute to LCR.\nFollowing is the example showing usage of
element.\n\n\n\n\n\n\n

\n

\n\t\n\t \n\t \n\t \n\t\n\n\t\n\t \n\t \n\t \n\t\n\n\t\n\t \n\t \n\t \n\t\n
Col 1Col 2Col 3
ABC
DEF
\n

\n\n\n\nThis will produce the following result:\nWML provides you an option to link various cards using links and then navigate through different cards.\nThere are two WML elements, and , which can be used to create WML links.\nThe ... tag pair is used to create an anchor link. It is used together with other WML elements called , or . These elements are called task elements and tell WAP browsers what to do when a user selects the anchor link\nYou can enclose Text or image along with a task tag inside ... tag pair.\nThe element supports the following attributes:\nFollowing is the example showing usage of element.\n\n\n\n\n\n\n

\n \n \n \n

\n

\n \n \n \n

\n
\n\n
\nThis will produce the following result:\nThe
... tag pair can also be used to create an anchor link and always a preferred way of creating links.\nYou can enclose Text or image inside ... tags.\nThe element supports the following attributes:\nFollowing is the example showing usage of element.\n\n\n\n\n\n\n

Link to Next Page: \n Next Page\n

\n\n\n\nThis will produce the following result:\nA WML task is an element that specifies an action to be performed by the browser, rather than something to be displayed. For example, the action of changing to a new card is represented by a task element, and the action of returning to the previous card visited is represented by a task element. Task elements encapsulate all the information required to perform the action.\nWML provides following four elements to handle four WML tasks called go task, pre task, refresh task and noop taks.\nAs the name suggests, the task represents the action of going to a new card.\nThe element supports the following attributes:\nget\npost\nWhen using method=\"get\", the data is sent as an request with ? data appended to the url. The method has a disadvantage, that it can be used only for a limited amount of data, and if you send sensitive information it will be displayed on the screen and saved in the web server's logs. So do not use this method if you are sending password etc.\nWith method=\"post\", the data is sent as an request with the data sent in the body of the request. This method has no limit, and sensitive information is not visible in the URL\ntrue\nfalse\nFollowing is the example showing usage of element.\n\n\n\n\n\n\n

\n \n Chapter 2 : \n \n

\n
\n
\nAnother example showing how to upload data using Get Method\n\n\n\n\n\n\n

\n \n Using Get Method \n \n \n

\n
\n
\nAnother example showing how to upload data using element.\n\n\n\n\n\n\n

\n \n Using setvar:\n\t \n\t \n \t \n\t \n \n

\n
\n
\nAnother example showing how to upload data using element\n\n\n\n\n\n\n

\n \n Using setvar:\n\t \n \n \n\t \n \n

\n
\n
\nThe task represents the action of returning to the previously visited card on the history stack. When this action is performed, the top entry is removed from the history stack, and that card is displayed again, after any variable assignments in the task have taken effect.\nIf no previous URL exists, specifying has no effect.\nThe element supports the following attributes:\nFollowing is the example showing usage of element.\n\n\n\n\n\n\n

\n \n Previous Page :\n \n

\n
\n
\nOne situation where it can be useful to include variables in a task is a login page, which prompts for a username and password. In some situations, you may want to clear out the password field when returning to the login card, forcing the user to reenter it. This can be done with a construct such as:\n\n\n\n\n\n\n

\n \n \n \n \n \n

\n
\n
\nThe task is the simplest task that actually does something. Its effect is simply to perform the variable assignments specified by its elements, then redisplay the current card with the new values. The and tasks perform the same action just before displaying the new card.\nThe task is most often used to perform some sort of \"reset\" action on the card.\nThe element supports the following attributes:\nFollowing is the example showing usage of element.\n\n\n\n\n\n\n

\n \n Refresh this page:\n \n \n \n \n \n

\n
\n
\nThe purpose of the task is to do nothing (no operation).\nThe only real use for this task is in connection with templates\nThe element supports the following attributes:\nFollowing is the example showing usage of element.\n\n\n\n\n\n\n

\n \n \n \n

\n
\n
\nWML provides various options to let a user enter information through WAP application.\nFirst of all, we are going to look at the different options for allowing the user to make straight choices between items. These are usually in the form of menus and submenus, allowing users to drill down to the exact data that they want.\nThe WML elements are used to define a selection list and the tags are used to define an item in a selection list. Items are presented as radiobuttons in some WAP browsers. The tag pair should be enclosed within the tags.\nThis element support the following attributes:\ntrue\nfalse\nFollowing is the example showing usage of these two elements.\n\n\n\n\n\n\n

Select a Tutorial :\n \n

\n
\n\n
\nWhen you will load this program, it will show you the following screen:\nOnce you highlight and enter on the options, it will display the following screen:\nYou want to provide option to select multiple options, then set multiple attribute to true as follows:\n\n\n\n\n\n\n

Select a Tutorial :\n \n

\n
\n\n
\nThis will give you a screen to select multiple options as follows:\nThe element is used to create input fields and input fields are used to obtain alphanumeric data from users.\nThis element support the following attributes:\ntrue\nfalse\nA = uppercase alphabetic or punctuation characters\n a = lowercase alphabetic or punctuation characters\n N = numeric characters\n X = uppercase characters\n x = lowercase characters\n M = all characters\n m = all characters\n *f = Any number of characters. Replace the f with one of the letters above to specify what characters the user can enter\nnf = Replace the n with a number from 1 to 9 to specify the number of characters the user can enter. Replace the f with one of the letters above to specify what characters the user can enter\ntext\npassword\nFollowing is the example showing usage of this element.\n\n\n\n\n\n\n

Enter Following Information:
\n Name: \n Age : \n Sex : \n

\n
\n\n
\nThis will provide you the following screen to enter required information:\nThe
element is used to group various input fields or selectable lists.\nThis element support the following attributes:\nFollowing is the example showing usage of this element.\n\n\n\n\n\n\n

\n

\n Name: \n Age : \n Sex : \n
\n

\n
\n\n
\nThis will provide you the following screen to enter required information. This result may differ browser to browser.\nThe element is used to group various options together inside a selectable list.\nThis element support the following attributes:\nFollowing is the example showing usage of this element.\n\n\n\n\n\n \n

\n \n

\n
\n\n
\nWhen a user loads above code, then it will give two options to be selected:\nWhen a user selects any of the options, then only it will give final options to be selected. So if user selects India, then it will show you following options to be selected:\nMany times, you will want your users to submit some data to your server. Similar to HTML Form WML also provide a mechanism to submit user data to web server.\nTo submit data to the server in WML, you need the ... along with tags. The tag should be enclosed in the ... tag pair. \nTo submit data to a server, we collect all the set WML variables and use elements to send them to the server. The ... elements are used to set posting method to either POST or GET and to specify a server side script to handle uploaded data.\nIn previous chapters we have explained various ways of taking inputs form the users. These input elements sets WML variables to the entered values. We also know how to take values from WML variables. So now following example shows how to submit three fields name, age and sex to the server.\n\n\n\n\n\n\n

\n Name: \n Sex : \n Age : \n \n \n \n \n \n \n Submit Data\n \n

\n
\n\n
\nWhen you download above code on your WAP device, it will provide you option to enter three fields name, age and sex and one link Submit Data. You will enter three fields and then finally you will select Submit Data link to send entered data to the server.\nThe method attribute of the tag specifies which HTTP method should be used to send the form data.\nIf the HTTP POST method is used, the form data to be sent will be placed in the message body of the request. If the HTTP GET method is used, the form data to be sent will be appended to the URL. Since a URL can only contain a limited number of characters, the GET method has the disadvantage that there is a size limit for the data to be sent. If the user data contains non-ASCII characters, you should make use of the POST method to avoid encoding problems.\nThere is one major difference between HTML and WML. In HTML, the name attribute of the and and \n Sex : \n Age : \n \n \n \n \n \n \n Submit Data\n \n

\n\n\n\nNow, we can write a server side script to handle this submitted data in using either PHP, PERL, ASP or JSP. I will show you a server side script written in PHP with HTTP GET method.\nPut the following PHP code in process.php file in same directory where you have your WML file.\n\n'; ?>\n\n\n\n \n \n

\n Data received at the server:
\n Name:
\n Age:
\n Sex:
\n

\n
\n\n
\nIf you are using HTTP POST method, then you have to write PHP script accordingly to handle received data. While sending output back to the browser, remember to set the MIME type of the document to \"text/vnd.wap.wml\".\nThis way, you can write full fledged Web Application where lot of database transactions are involved.\nYou can use PERL CGI Concepts to write a dynamic WAP site.\nEvent in ordinary language can be defined as something happened. In programming, event is identical in meaning, but with one major difference. When something happens in a computer system, the system itself has to (1) detect that something has happened and (2) know what to do about it.\nWML language also supports events and you can specify an action to be taken whenever an event occurs. This action could be in terms of WMLScript or simply in terms of WML. \nWML supports following four event types:\nonenterbackward: This event occurs when the user hits a card by normal backward navigational means. That is, user presses the Back key on a later card and arrives back at this card in the history stack.\nonenterbackward: This event occurs when the user hits a card by normal backward navigational means. That is, user presses the Back key on a later card and arrives back at this card in the history stack.\nonenterforward: This event occurs when the user hits a card by normal forward navigational means.\nonenterforward: This event occurs when the user hits a card by normal forward navigational means.\nonpick: This is more like an attribute but it is being used like an event. This event occurs when an item of a selection list is selected or deselected.\nonpick: This is more like an attribute but it is being used like an event. This event occurs when an item of a selection list is selected or deselected.\nontimer: This event is used to trigger an event after a given time period.\nontimer: This event is used to trigger an event after a given time period.\nThese event names are case sensitive and they must be lowercase. \nThe ... tags are used to create event handlers. Its usage takes the following form:\n\n A task to be performed.\n\nYou can use either go, prev or refresh task inside ... tags against an event.\nThe element supports the following attributes:\nonenterbackward\nonenterforward\nonpick\nontimer\nFollowing is the example showing usage of element. In this example, whenever you try to go back from second card to first card then onenterbackward occurs which moves you to card number three. Copy and paste this program and try to play with it.\n\n\n\n\n\n \n\n\n\n

\n \n \n Go to card 2\n \n

\n
\n\n

\n \n \n Going backwards\n \n

\n
\n\n

\nHello World!\n

\n
\n
\nPrevious chapter has described how events are triggered by the users and how do we handle them using event handlers.\nSometime, you may want something to happen without the user explicitly having to activate a control. Yes, WML provides you ontimer event to handle this.\nThe ontimer event is triggered when a card's timer counts down from one to zero, which means that it doesn't occur if the timer is initialized to a timeout of zero.\nYou can bind a task to this event with the element. Here is the syntax:\n\n A task to be performed.\n\nHere, a task could be , or .\nA timer is declared inside a WML card with the element. It must follow the elements if they\nare present. (If there are no elements, the must be the first element inside the .) No\nmore than one may be present in a card.\nThe element supports the following attributes:\nFollowing is the example showing usage of element.\n\n\n\n\n\n\n \n \n \n \n

\n Enter\n

\n
\n\n\n

\nWelcome to the main screen.\n

\n
\n
\nWhen you load this program it shows you following screen:\nIf you do not select given Enter option then after 5 seconds, you will be directed to Welcome page and following screen will be displayed automatically.\nThe