{ // 获取包含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: \n \nExample 2: This example changes text color of “h2” element on button click. \nHTML\n

GeeksForGeeks

\nOutput:\n \n \nSupported Browsers:\nGoogle Chrome 90.0+\nInternet Explorer 9.0\nFirefox 3.6\nSafari 4.0\nOpera 10.5\nysachin2314\nsahilintern\njQuery-Selectors\nPicked\nJQuery\nWeb Technologies\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":"\n11 Jul, 2022"},{"code":null,"e":383,"s":28,"text":"jQuery is an open-source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM), and JavaScript. Elaborating the terms, it simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Ajax interactions, and cross-browser JavaScript development."},{"code":null,"e":478,"s":383,"text":"jQuery element selector is used to select and modify HTML elements based on the element name. "},{"code":null,"e":486,"s":478,"text":"Syntax:"},{"code":null,"e":505,"s":486,"text":"$(\"element_name\") "},{"code":null,"e":578,"s":505,"text":"Example 1: This example selects the “h2” element and adds border to it. "},{"code":null,"e":583,"s":578,"text":"HTML"},{"code":"

GeeksForGeeks

","e":871,"s":583,"text":null},{"code":null,"e":880,"s":871,"text":"Output: "},{"code":null,"e":959,"s":882,"text":"Example 2: This example changes text color of “h2” element on button click. "},{"code":null,"e":964,"s":959,"text":"HTML"},{"code":"

GeeksForGeeks

","e":1327,"s":964,"text":null},{"code":null,"e":1335,"s":1327,"text":"Output:"},{"code":null,"e":1359,"s":1339,"text":"Supported Browsers:"},{"code":null,"e":1379,"s":1359,"text":"Google Chrome 90.0+"},{"code":null,"e":1401,"s":1379,"text":"Internet Explorer 9.0"},{"code":null,"e":1413,"s":1401,"text":"Firefox 3.6"},{"code":null,"e":1424,"s":1413,"text":"Safari 4.0"},{"code":null,"e":1435,"s":1424,"text":"Opera 10.5"},{"code":null,"e":1447,"s":1435,"text":"ysachin2314"},{"code":null,"e":1459,"s":1447,"text":"sahilintern"},{"code":null,"e":1476,"s":1459,"text":"jQuery-Selectors"},{"code":null,"e":1483,"s":1476,"text":"Picked"},{"code":null,"e":1490,"s":1483,"text":"JQuery"},{"code":null,"e":1507,"s":1490,"text":"Web Technologies"}],"string":"[\n {\n \"code\": null,\n \"e\": 28,\n \"s\": 0,\n \"text\": \"\\n11 Jul, 2022\"\n },\n {\n \"code\": null,\n \"e\": 383,\n \"s\": 28,\n \"text\": \"jQuery is an open-source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM), and JavaScript. Elaborating the terms, it simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Ajax interactions, and cross-browser JavaScript development.\"\n },\n {\n \"code\": null,\n \"e\": 478,\n \"s\": 383,\n \"text\": \"jQuery element selector is used to select and modify HTML elements based on the element name. \"\n },\n {\n \"code\": null,\n \"e\": 486,\n \"s\": 478,\n \"text\": \"Syntax:\"\n },\n {\n \"code\": null,\n \"e\": 505,\n \"s\": 486,\n \"text\": \"$(\\\"element_name\\\") \"\n },\n {\n \"code\": null,\n \"e\": 578,\n \"s\": 505,\n \"text\": \"Example 1: This example selects the “h2” element and adds border to it. \"\n },\n {\n \"code\": null,\n \"e\": 583,\n \"s\": 578,\n \"text\": \"HTML\"\n },\n {\n \"code\": \"

GeeksForGeeks

\",\n \"e\": 871,\n \"s\": 583,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 880,\n \"s\": 871,\n \"text\": \"Output: \"\n },\n {\n \"code\": null,\n \"e\": 959,\n \"s\": 882,\n \"text\": \"Example 2: This example changes text color of “h2” element on button click. \"\n },\n {\n \"code\": null,\n \"e\": 964,\n \"s\": 959,\n \"text\": \"HTML\"\n },\n {\n \"code\": \"

GeeksForGeeks

\",\n \"e\": 1327,\n \"s\": 964,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 1335,\n \"s\": 1327,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 1359,\n \"s\": 1339,\n \"text\": \"Supported Browsers:\"\n },\n {\n \"code\": null,\n \"e\": 1379,\n \"s\": 1359,\n \"text\": \"Google Chrome 90.0+\"\n },\n {\n \"code\": null,\n \"e\": 1401,\n \"s\": 1379,\n \"text\": \"Internet Explorer 9.0\"\n },\n {\n \"code\": null,\n \"e\": 1413,\n \"s\": 1401,\n \"text\": \"Firefox 3.6\"\n },\n {\n \"code\": null,\n \"e\": 1424,\n \"s\": 1413,\n \"text\": \"Safari 4.0\"\n },\n {\n \"code\": null,\n \"e\": 1435,\n \"s\": 1424,\n \"text\": \"Opera 10.5\"\n },\n {\n \"code\": null,\n \"e\": 1447,\n \"s\": 1435,\n \"text\": \"ysachin2314\"\n },\n {\n \"code\": null,\n \"e\": 1459,\n \"s\": 1447,\n \"text\": \"sahilintern\"\n },\n {\n \"code\": null,\n \"e\": 1476,\n \"s\": 1459,\n \"text\": \"jQuery-Selectors\"\n },\n {\n \"code\": null,\n \"e\": 1483,\n \"s\": 1476,\n \"text\": \"Picked\"\n },\n {\n \"code\": null,\n \"e\": 1490,\n \"s\": 1483,\n \"text\": \"JQuery\"\n },\n {\n \"code\": null,\n \"e\": 1507,\n \"s\": 1490,\n \"text\": \"Web Technologies\"\n }\n]"}}},{"rowIdx":403,"cells":{"title":{"kind":"string","value":"How to plot a simple vector field in Matplotlib ?"},"text":{"kind":"string","value":"20 Apr, 2022\nThe quantity incorporating both magnitude and direction is known as Vectors. In simple words, we can say, Vector Field is an engagement or collaboration of such vectors in a subset of space. Vector fields are the key aspects of understanding our real-life surrounding.\nFor more intuition, you can think of a vector field as representing a multivariable function whose input and output spaces each have the same dimension. The length of arrows drawn in a vector field is usually not to scale, but the ratio of the length of one vector to another should be accurate.\nIn this article, we are going to discuss how to plot a vector field in python. In order to perform this task we are going to use the quiver() method and the streamplot() method in matplotlib module.\nSyntax:\nTo plot a vector field using the quiver() method:\nmatplotlib.pyplot.quiver(X, Y, U, V, **kw) \nWhere X, Y define the Vector location and U, V are directional arrows with respect of the Vector location.\nTo plot a vector field using the streamplot() method:\nmatplotlib.pyplot.streamplot(X, Y, U, V, density=1, linewidth=None, color=None, **kw)\nWhere X, Y are evenly spaced grid[1D array] and U and V represent the stream velocity of each point present on the grid. Density is the no. of vector per area of the plot. Line width represents the thickness of streamlines.\nBelow are some examples which depict how to plot vector fields using matplotlib module:\nExample 1: Plotting a single vector using quiver() method in matplotlib module.\nPython3\n# Import librariesimport numpy as npimport matplotlib.pyplot as plt # Vector origin locationX = [0]Y = [0] # Directional vectorsU = [2] V = [1] # Creating plotplt.quiver(X, Y, U, V, color='b', units='xy', scale=1)plt.title('Single Vector') # x-lim and y-limplt.xlim(-2, 5)plt.ylim(-2, 2.5) # Show plot with gridplt.grid()plt.show()\nOutput:\nExample 2: Generating multiple vectors using quiver() method.\nPython3\n# Import required modulesimport numpy as npimport matplotlib.pyplot as plt # Meshgridx, y = np.meshgrid(np.linspace(-5, 5, 10), np.linspace(-5, 5, 10)) # Directional vectorsu = -y/np.sqrt(x**2 + y**2)v = x/(x**2 + y**2) # Plotting Vector Field with QUIVERplt.quiver(x, y, u, v, color='g')plt.title('Vector Field') # Setting x, y boundary limitsplt.xlim(-7, 7)plt.ylim(-7, 7) # Show plot with gridplt.grid()plt.show()\nOutput:\nExample 3: Plotting multiple vectors using streamplot() method in matplotlib module.\nPython3\n# Import required modulesimport numpy as npimport matplotlib.pyplot as plt # 1D arraysx = np.arange(-5,5,0.1)y = np.arange(-5,5,0.1) # MeshgridX,Y = np.meshgrid(x,y) # Assign vector directionsEx = (X + 1)/((X+1)**2 + Y**2) - (X - 1)/((X-1)**2 + Y**2)Ey = Y/((X+1)**2 + Y**2) - Y/((X-1)**2 + Y**2) # Depict illustrationplt.figure(figsize=(10, 10))plt.streamplot(X,Y,Ex,Ey, density=1.4, linewidth=None, color='#A23BEC')plt.plot(-1,0,'-or')plt.plot(1,0,'-og')plt.title('Electromagnetic Field') # Show plot with gridplt.grid()plt.show()\nOutput:\ngabaa406\nPicked\nPython-matplotlib\nTechnical Scripter 2020\nPython\nTechnical Scripter\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 | os.path.join() method\nIntroduction To PYTHON\nPython OOPs Concepts\nHow to drop one or multiple columns in Pandas Dataframe\nHow To Convert Python Dictionary To JSON?\nCheck if element exists in list in Python\nPython | Get unique values from a list\nCreate a directory in Python"},"parsed":{"kind":"list like","value":[{"code":null,"e":52,"s":24,"text":"\n20 Apr, 2022"},{"code":null,"e":321,"s":52,"text":"The quantity incorporating both magnitude and direction is known as Vectors. In simple words, we can say, Vector Field is an engagement or collaboration of such vectors in a subset of space. Vector fields are the key aspects of understanding our real-life surrounding."},{"code":null,"e":617,"s":321,"text":"For more intuition, you can think of a vector field as representing a multivariable function whose input and output spaces each have the same dimension. The length of arrows drawn in a vector field is usually not to scale, but the ratio of the length of one vector to another should be accurate."},{"code":null,"e":816,"s":617,"text":"In this article, we are going to discuss how to plot a vector field in python. In order to perform this task we are going to use the quiver() method and the streamplot() method in matplotlib module."},{"code":null,"e":824,"s":816,"text":"Syntax:"},{"code":null,"e":874,"s":824,"text":"To plot a vector field using the quiver() method:"},{"code":null,"e":918,"s":874,"text":"matplotlib.pyplot.quiver(X, Y, U, V, **kw) "},{"code":null,"e":1025,"s":918,"text":"Where X, Y define the Vector location and U, V are directional arrows with respect of the Vector location."},{"code":null,"e":1079,"s":1025,"text":"To plot a vector field using the streamplot() method:"},{"code":null,"e":1165,"s":1079,"text":"matplotlib.pyplot.streamplot(X, Y, U, V, density=1, linewidth=None, color=None, **kw)"},{"code":null,"e":1389,"s":1165,"text":"Where X, Y are evenly spaced grid[1D array] and U and V represent the stream velocity of each point present on the grid. Density is the no. of vector per area of the plot. Line width represents the thickness of streamlines."},{"code":null,"e":1477,"s":1389,"text":"Below are some examples which depict how to plot vector fields using matplotlib module:"},{"code":null,"e":1557,"s":1477,"text":"Example 1: Plotting a single vector using quiver() method in matplotlib module."},{"code":null,"e":1565,"s":1557,"text":"Python3"},{"code":"# Import librariesimport numpy as npimport matplotlib.pyplot as plt # Vector origin locationX = [0]Y = [0] # Directional vectorsU = [2] V = [1] # Creating plotplt.quiver(X, Y, U, V, color='b', units='xy', scale=1)plt.title('Single Vector') # x-lim and y-limplt.xlim(-2, 5)plt.ylim(-2, 2.5) # Show plot with gridplt.grid()plt.show()","e":1905,"s":1565,"text":null},{"code":null,"e":1913,"s":1905,"text":"Output:"},{"code":null,"e":1975,"s":1913,"text":"Example 2: Generating multiple vectors using quiver() method."},{"code":null,"e":1983,"s":1975,"text":"Python3"},{"code":"# Import required modulesimport numpy as npimport matplotlib.pyplot as plt # Meshgridx, y = np.meshgrid(np.linspace(-5, 5, 10), np.linspace(-5, 5, 10)) # Directional vectorsu = -y/np.sqrt(x**2 + y**2)v = x/(x**2 + y**2) # Plotting Vector Field with QUIVERplt.quiver(x, y, u, v, color='g')plt.title('Vector Field') # Setting x, y boundary limitsplt.xlim(-7, 7)plt.ylim(-7, 7) # Show plot with gridplt.grid()plt.show()","e":2424,"s":1983,"text":null},{"code":null,"e":2432,"s":2424,"text":"Output:"},{"code":null,"e":2517,"s":2432,"text":"Example 3: Plotting multiple vectors using streamplot() method in matplotlib module."},{"code":null,"e":2525,"s":2517,"text":"Python3"},{"code":"# Import required modulesimport numpy as npimport matplotlib.pyplot as plt # 1D arraysx = np.arange(-5,5,0.1)y = np.arange(-5,5,0.1) # MeshgridX,Y = np.meshgrid(x,y) # Assign vector directionsEx = (X + 1)/((X+1)**2 + Y**2) - (X - 1)/((X-1)**2 + Y**2)Ey = Y/((X+1)**2 + Y**2) - Y/((X-1)**2 + Y**2) # Depict illustrationplt.figure(figsize=(10, 10))plt.streamplot(X,Y,Ex,Ey, density=1.4, linewidth=None, color='#A23BEC')plt.plot(-1,0,'-or')plt.plot(1,0,'-og')plt.title('Electromagnetic Field') # Show plot with gridplt.grid()plt.show()","e":3063,"s":2525,"text":null},{"code":null,"e":3071,"s":3063,"text":"Output:"},{"code":null,"e":3080,"s":3071,"text":"gabaa406"},{"code":null,"e":3087,"s":3080,"text":"Picked"},{"code":null,"e":3105,"s":3087,"text":"Python-matplotlib"},{"code":null,"e":3129,"s":3105,"text":"Technical Scripter 2020"},{"code":null,"e":3136,"s":3129,"text":"Python"},{"code":null,"e":3155,"s":3136,"text":"Technical Scripter"},{"code":null,"e":3253,"s":3155,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":3285,"s":3253,"text":"How to Install PIP on Windows ?"},{"code":null,"e":3312,"s":3285,"text":"Python Classes and Objects"},{"code":null,"e":3343,"s":3312,"text":"Python | os.path.join() method"},{"code":null,"e":3366,"s":3343,"text":"Introduction To PYTHON"},{"code":null,"e":3387,"s":3366,"text":"Python OOPs Concepts"},{"code":null,"e":3443,"s":3387,"text":"How to drop one or multiple columns in Pandas Dataframe"},{"code":null,"e":3485,"s":3443,"text":"How To Convert Python Dictionary To JSON?"},{"code":null,"e":3527,"s":3485,"text":"Check if element exists in list in Python"},{"code":null,"e":3566,"s":3527,"text":"Python | Get unique values from a list"}],"string":"[\n {\n \"code\": null,\n \"e\": 52,\n \"s\": 24,\n \"text\": \"\\n20 Apr, 2022\"\n },\n {\n \"code\": null,\n \"e\": 321,\n \"s\": 52,\n \"text\": \"The quantity incorporating both magnitude and direction is known as Vectors. In simple words, we can say, Vector Field is an engagement or collaboration of such vectors in a subset of space. Vector fields are the key aspects of understanding our real-life surrounding.\"\n },\n {\n \"code\": null,\n \"e\": 617,\n \"s\": 321,\n \"text\": \"For more intuition, you can think of a vector field as representing a multivariable function whose input and output spaces each have the same dimension. The length of arrows drawn in a vector field is usually not to scale, but the ratio of the length of one vector to another should be accurate.\"\n },\n {\n \"code\": null,\n \"e\": 816,\n \"s\": 617,\n \"text\": \"In this article, we are going to discuss how to plot a vector field in python. In order to perform this task we are going to use the quiver() method and the streamplot() method in matplotlib module.\"\n },\n {\n \"code\": null,\n \"e\": 824,\n \"s\": 816,\n \"text\": \"Syntax:\"\n },\n {\n \"code\": null,\n \"e\": 874,\n \"s\": 824,\n \"text\": \"To plot a vector field using the quiver() method:\"\n },\n {\n \"code\": null,\n \"e\": 918,\n \"s\": 874,\n \"text\": \"matplotlib.pyplot.quiver(X, Y, U, V, **kw) \"\n },\n {\n \"code\": null,\n \"e\": 1025,\n \"s\": 918,\n \"text\": \"Where X, Y define the Vector location and U, V are directional arrows with respect of the Vector location.\"\n },\n {\n \"code\": null,\n \"e\": 1079,\n \"s\": 1025,\n \"text\": \"To plot a vector field using the streamplot() method:\"\n },\n {\n \"code\": null,\n \"e\": 1165,\n \"s\": 1079,\n \"text\": \"matplotlib.pyplot.streamplot(X, Y, U, V, density=1, linewidth=None, color=None, **kw)\"\n },\n {\n \"code\": null,\n \"e\": 1389,\n \"s\": 1165,\n \"text\": \"Where X, Y are evenly spaced grid[1D array] and U and V represent the stream velocity of each point present on the grid. Density is the no. of vector per area of the plot. Line width represents the thickness of streamlines.\"\n },\n {\n \"code\": null,\n \"e\": 1477,\n \"s\": 1389,\n \"text\": \"Below are some examples which depict how to plot vector fields using matplotlib module:\"\n },\n {\n \"code\": null,\n \"e\": 1557,\n \"s\": 1477,\n \"text\": \"Example 1: Plotting a single vector using quiver() method in matplotlib module.\"\n },\n {\n \"code\": null,\n \"e\": 1565,\n \"s\": 1557,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"# Import librariesimport numpy as npimport matplotlib.pyplot as plt # Vector origin locationX = [0]Y = [0] # Directional vectorsU = [2] V = [1] # Creating plotplt.quiver(X, Y, U, V, color='b', units='xy', scale=1)plt.title('Single Vector') # x-lim and y-limplt.xlim(-2, 5)plt.ylim(-2, 2.5) # Show plot with gridplt.grid()plt.show()\",\n \"e\": 1905,\n \"s\": 1565,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 1913,\n \"s\": 1905,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 1975,\n \"s\": 1913,\n \"text\": \"Example 2: Generating multiple vectors using quiver() method.\"\n },\n {\n \"code\": null,\n \"e\": 1983,\n \"s\": 1975,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"# Import required modulesimport numpy as npimport matplotlib.pyplot as plt # Meshgridx, y = np.meshgrid(np.linspace(-5, 5, 10), np.linspace(-5, 5, 10)) # Directional vectorsu = -y/np.sqrt(x**2 + y**2)v = x/(x**2 + y**2) # Plotting Vector Field with QUIVERplt.quiver(x, y, u, v, color='g')plt.title('Vector Field') # Setting x, y boundary limitsplt.xlim(-7, 7)plt.ylim(-7, 7) # Show plot with gridplt.grid()plt.show()\",\n \"e\": 2424,\n \"s\": 1983,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 2432,\n \"s\": 2424,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 2517,\n \"s\": 2432,\n \"text\": \"Example 3: Plotting multiple vectors using streamplot() method in matplotlib module.\"\n },\n {\n \"code\": null,\n \"e\": 2525,\n \"s\": 2517,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"# Import required modulesimport numpy as npimport matplotlib.pyplot as plt # 1D arraysx = np.arange(-5,5,0.1)y = np.arange(-5,5,0.1) # MeshgridX,Y = np.meshgrid(x,y) # Assign vector directionsEx = (X + 1)/((X+1)**2 + Y**2) - (X - 1)/((X-1)**2 + Y**2)Ey = Y/((X+1)**2 + Y**2) - Y/((X-1)**2 + Y**2) # Depict illustrationplt.figure(figsize=(10, 10))plt.streamplot(X,Y,Ex,Ey, density=1.4, linewidth=None, color='#A23BEC')plt.plot(-1,0,'-or')plt.plot(1,0,'-og')plt.title('Electromagnetic Field') # Show plot with gridplt.grid()plt.show()\",\n \"e\": 3063,\n \"s\": 2525,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 3071,\n \"s\": 3063,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 3080,\n \"s\": 3071,\n \"text\": \"gabaa406\"\n },\n {\n \"code\": null,\n \"e\": 3087,\n \"s\": 3080,\n \"text\": \"Picked\"\n },\n {\n \"code\": null,\n \"e\": 3105,\n \"s\": 3087,\n \"text\": \"Python-matplotlib\"\n },\n {\n \"code\": null,\n \"e\": 3129,\n \"s\": 3105,\n \"text\": \"Technical Scripter 2020\"\n },\n {\n \"code\": null,\n \"e\": 3136,\n \"s\": 3129,\n \"text\": \"Python\"\n },\n {\n \"code\": null,\n \"e\": 3155,\n \"s\": 3136,\n \"text\": \"Technical Scripter\"\n },\n {\n \"code\": null,\n \"e\": 3253,\n \"s\": 3155,\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\": 3285,\n \"s\": 3253,\n \"text\": \"How to Install PIP on Windows ?\"\n },\n {\n \"code\": null,\n \"e\": 3312,\n \"s\": 3285,\n \"text\": \"Python Classes and Objects\"\n },\n {\n \"code\": null,\n \"e\": 3343,\n \"s\": 3312,\n \"text\": \"Python | os.path.join() method\"\n },\n {\n \"code\": null,\n \"e\": 3366,\n \"s\": 3343,\n \"text\": \"Introduction To PYTHON\"\n },\n {\n \"code\": null,\n \"e\": 3387,\n \"s\": 3366,\n \"text\": \"Python OOPs Concepts\"\n },\n {\n \"code\": null,\n \"e\": 3443,\n \"s\": 3387,\n \"text\": \"How to drop one or multiple columns in Pandas Dataframe\"\n },\n {\n \"code\": null,\n \"e\": 3485,\n \"s\": 3443,\n \"text\": \"How To Convert Python Dictionary To JSON?\"\n },\n {\n \"code\": null,\n \"e\": 3527,\n \"s\": 3485,\n \"text\": \"Check if element exists in list in Python\"\n },\n {\n \"code\": null,\n \"e\": 3566,\n \"s\": 3527,\n \"text\": \"Python | Get unique values from a list\"\n }\n]"}}},{"rowIdx":404,"cells":{"title":{"kind":"string","value":"matplotlib.pyplot.polar() in Python"},"text":{"kind":"string","value":"22 Apr, 2020\nMatplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.\nThe polar() function in pyplot module of matplotlib library is used to make a polar plot.\nSyntax: matplotlib.pyplot.polar(*args, **kwargs)\nParameters: This method does not accept any parameters.\nReturns: This method does not returns any value.\nBelow examples illustrate the matplotlib.pyplot.polar() function in matplotlib.pyplot:\nExample #1:\n# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.transforms as mtransformsimport numpy as np from matplotlib.transforms import offset_copy xs = np.arange(-2, 2)ys = np.cos(xs**2)plt.polar(xs, ys) plt.title('matplotlib.pyplot.polar() function Example', fontweight =\"bold\")plt.show()\nOutput:\nExample #2:\n# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.transforms as mtransformsimport numpy as np from matplotlib.transforms import offset_copy xs = np.arange(8)ys = np.cos(xs**2) fig = plt.figure(figsize =(5, 10))ax = plt.subplot(1, 1, 1) trans_offset = mtransforms.offset_copy(ax.transData, fig = fig, y = 6, units ='dots') for x, y in zip(xs, ys): plt.polar(x, y, 'go') plt.text(x, y, '% d, % d' % (int(x), int(y)), transform = trans_offset, horizontalalignment ='center', verticalalignment ='bottom') plt.title('matplotlib.pyplot.polar() function Example', fontweight =\"bold\")plt.show()\nOutput:\nPython-matplotlib\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":28,"s":0,"text":"\n22 Apr, 2020"},{"code":null,"e":223,"s":28,"text":"Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface."},{"code":null,"e":313,"s":223,"text":"The polar() function in pyplot module of matplotlib library is used to make a polar plot."},{"code":null,"e":362,"s":313,"text":"Syntax: matplotlib.pyplot.polar(*args, **kwargs)"},{"code":null,"e":418,"s":362,"text":"Parameters: This method does not accept any parameters."},{"code":null,"e":467,"s":418,"text":"Returns: This method does not returns any value."},{"code":null,"e":554,"s":467,"text":"Below examples illustrate the matplotlib.pyplot.polar() function in matplotlib.pyplot:"},{"code":null,"e":566,"s":554,"text":"Example #1:"},{"code":"# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.transforms as mtransformsimport numpy as np from matplotlib.transforms import offset_copy xs = np.arange(-2, 2)ys = np.cos(xs**2)plt.polar(xs, ys) plt.title('matplotlib.pyplot.polar() function Example', fontweight =\"bold\")plt.show()","e":929,"s":566,"text":null},{"code":null,"e":937,"s":929,"text":"Output:"},{"code":null,"e":949,"s":937,"text":"Example #2:"},{"code":"# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.transforms as mtransformsimport numpy as np from matplotlib.transforms import offset_copy xs = np.arange(8)ys = np.cos(xs**2) fig = plt.figure(figsize =(5, 10))ax = plt.subplot(1, 1, 1) trans_offset = mtransforms.offset_copy(ax.transData, fig = fig, y = 6, units ='dots') for x, y in zip(xs, ys): plt.polar(x, y, 'go') plt.text(x, y, '% d, % d' % (int(x), int(y)), transform = trans_offset, horizontalalignment ='center', verticalalignment ='bottom') plt.title('matplotlib.pyplot.polar() function Example', fontweight =\"bold\")plt.show()","e":1722,"s":949,"text":null},{"code":null,"e":1730,"s":1722,"text":"Output:"},{"code":null,"e":1748,"s":1730,"text":"Python-matplotlib"},{"code":null,"e":1755,"s":1748,"text":"Python"},{"code":null,"e":1853,"s":1755,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":1885,"s":1853,"text":"How to Install PIP on Windows ?"},{"code":null,"e":1912,"s":1885,"text":"Python Classes and Objects"},{"code":null,"e":1933,"s":1912,"text":"Python OOPs Concepts"},{"code":null,"e":1964,"s":1933,"text":"Python | os.path.join() method"},{"code":null,"e":2020,"s":1964,"text":"How to drop one or multiple columns in Pandas Dataframe"},{"code":null,"e":2043,"s":2020,"text":"Introduction To PYTHON"},{"code":null,"e":2085,"s":2043,"text":"How To Convert Python Dictionary To JSON?"},{"code":null,"e":2127,"s":2085,"text":"Check if element exists in list in Python"},{"code":null,"e":2166,"s":2127,"text":"Python | datetime.timedelta() function"}],"string":"[\n {\n \"code\": null,\n \"e\": 28,\n \"s\": 0,\n \"text\": \"\\n22 Apr, 2020\"\n },\n {\n \"code\": null,\n \"e\": 223,\n \"s\": 28,\n \"text\": \"Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.\"\n },\n {\n \"code\": null,\n \"e\": 313,\n \"s\": 223,\n \"text\": \"The polar() function in pyplot module of matplotlib library is used to make a polar plot.\"\n },\n {\n \"code\": null,\n \"e\": 362,\n \"s\": 313,\n \"text\": \"Syntax: matplotlib.pyplot.polar(*args, **kwargs)\"\n },\n {\n \"code\": null,\n \"e\": 418,\n \"s\": 362,\n \"text\": \"Parameters: This method does not accept any parameters.\"\n },\n {\n \"code\": null,\n \"e\": 467,\n \"s\": 418,\n \"text\": \"Returns: This method does not returns any value.\"\n },\n {\n \"code\": null,\n \"e\": 554,\n \"s\": 467,\n \"text\": \"Below examples illustrate the matplotlib.pyplot.polar() function in matplotlib.pyplot:\"\n },\n {\n \"code\": null,\n \"e\": 566,\n \"s\": 554,\n \"text\": \"Example #1:\"\n },\n {\n \"code\": \"# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.transforms as mtransformsimport numpy as np from matplotlib.transforms import offset_copy xs = np.arange(-2, 2)ys = np.cos(xs**2)plt.polar(xs, ys) plt.title('matplotlib.pyplot.polar() function Example', fontweight =\\\"bold\\\")plt.show()\",\n \"e\": 929,\n \"s\": 566,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 937,\n \"s\": 929,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 949,\n \"s\": 937,\n \"text\": \"Example #2:\"\n },\n {\n \"code\": \"# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.transforms as mtransformsimport numpy as np from matplotlib.transforms import offset_copy xs = np.arange(8)ys = np.cos(xs**2) fig = plt.figure(figsize =(5, 10))ax = plt.subplot(1, 1, 1) trans_offset = mtransforms.offset_copy(ax.transData, fig = fig, y = 6, units ='dots') for x, y in zip(xs, ys): plt.polar(x, y, 'go') plt.text(x, y, '% d, % d' % (int(x), int(y)), transform = trans_offset, horizontalalignment ='center', verticalalignment ='bottom') plt.title('matplotlib.pyplot.polar() function Example', fontweight =\\\"bold\\\")plt.show()\",\n \"e\": 1722,\n \"s\": 949,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 1730,\n \"s\": 1722,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 1748,\n \"s\": 1730,\n \"text\": \"Python-matplotlib\"\n },\n {\n \"code\": null,\n \"e\": 1755,\n \"s\": 1748,\n \"text\": \"Python\"\n },\n {\n \"code\": null,\n \"e\": 1853,\n \"s\": 1755,\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\": 1885,\n \"s\": 1853,\n \"text\": \"How to Install PIP on Windows ?\"\n },\n {\n \"code\": null,\n \"e\": 1912,\n \"s\": 1885,\n \"text\": \"Python Classes and Objects\"\n },\n {\n \"code\": null,\n \"e\": 1933,\n \"s\": 1912,\n \"text\": \"Python OOPs Concepts\"\n },\n {\n \"code\": null,\n \"e\": 1964,\n \"s\": 1933,\n \"text\": \"Python | os.path.join() method\"\n },\n {\n \"code\": null,\n \"e\": 2020,\n \"s\": 1964,\n \"text\": \"How to drop one or multiple columns in Pandas Dataframe\"\n },\n {\n \"code\": null,\n \"e\": 2043,\n \"s\": 2020,\n \"text\": \"Introduction To PYTHON\"\n },\n {\n \"code\": null,\n \"e\": 2085,\n \"s\": 2043,\n \"text\": \"How To Convert Python Dictionary To JSON?\"\n },\n {\n \"code\": null,\n \"e\": 2127,\n \"s\": 2085,\n \"text\": \"Check if element exists in list in Python\"\n },\n {\n \"code\": null,\n \"e\": 2166,\n \"s\": 2127,\n \"text\": \"Python | datetime.timedelta() function\"\n }\n]"}}},{"rowIdx":405,"cells":{"title":{"kind":"string","value":"Tailwind CSS Height"},"text":{"kind":"string","value":"23 Mar, 2022\nThis class accepts lots of values in tailwind CSS in which all the properties are covered in class form. It is the alternative to the CSS height Property. This class is used to set the height of an element. The height class does not contain padding, margin, and the border of elements.\nHeight classes:\nh-0: This class sets the height to zero.\nh-auto: This class sets the height according to the content.\nh-px: This class is used to set the height in 1px fix.\nh-1/2: This class sets the height to half of the window.\nh-1/3: This class sets the height to one-third of the window.\nh-1/4: This class sets the height to one-fourth of the window.\nh-1/5: This class sets the height to one-fifth of the window.\nh-1/6: This class sets the height to one-sixth of the window.\nh-full: This class sets an element’s height to 100% of its parent, as long as the parent has a defined height.\nh-screen: This class used to make an element span the entire height of the viewport.\nNote: You can change the number with the valid “rem” values or set the percentage value.\nh-0: This class is used to set the specific height for any element, you can change the number with a valid number of rem units to fix the height of the element.\nSyntax:\n...\nExample:\nHTML\n

GeeksforGeeks

Tailwind CSS Height Class
h-8
h-12
h-16
h-20
h-24
h-32
h-40
h-48
h-52
\nOutput:\nh-auto: This class is used to let the browser determine the height of the element.\nSyntax:\n...\nExample:\nHTML\n

GeeksforGeeks

Tailwind CSS Height Class
h-auto
\nOutput:\nh-screen: This class is used to make an element span the entire height of the viewport.\nSyntax:\n...\nExample:\nHTML\n

GeeksforGeeks

Tailwind CSS Height Class
h-screen
\nOutput:\nh-full: This class is used to set an element’s height to 100% of its parent, as long as the parent has a defined height.\nSyntax:\n...\nExample:\nHTML\n

GeeksforGeeks

Tailwind CSS Height Class
h-full
\nOutput:\nTailwind CSS\nTailwind-Sizing\nCSS\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 ?\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?\nCSS to put icon inside an input element in a form\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":"\n23 Mar, 2022"},{"code":null,"e":315,"s":28,"text":"This class accepts lots of values in tailwind CSS in which all the properties are covered in class form. It is the alternative to the CSS height Property. This class is used to set the height of an element. The height class does not contain padding, margin, and the border of elements."},{"code":null,"e":331,"s":315,"text":"Height classes:"},{"code":null,"e":372,"s":331,"text":"h-0: This class sets the height to zero."},{"code":null,"e":433,"s":372,"text":"h-auto: This class sets the height according to the content."},{"code":null,"e":488,"s":433,"text":"h-px: This class is used to set the height in 1px fix."},{"code":null,"e":545,"s":488,"text":"h-1/2: This class sets the height to half of the window."},{"code":null,"e":607,"s":545,"text":"h-1/3: This class sets the height to one-third of the window."},{"code":null,"e":670,"s":607,"text":"h-1/4: This class sets the height to one-fourth of the window."},{"code":null,"e":732,"s":670,"text":"h-1/5: This class sets the height to one-fifth of the window."},{"code":null,"e":794,"s":732,"text":"h-1/6: This class sets the height to one-sixth of the window."},{"code":null,"e":905,"s":794,"text":"h-full: This class sets an element’s height to 100% of its parent, as long as the parent has a defined height."},{"code":null,"e":990,"s":905,"text":"h-screen: This class used to make an element span the entire height of the viewport."},{"code":null,"e":1079,"s":990,"text":"Note: You can change the number with the valid “rem” values or set the percentage value."},{"code":null,"e":1240,"s":1079,"text":"h-0: This class is used to set the specific height for any element, you can change the number with a valid number of rem units to fix the height of the element."},{"code":null,"e":1248,"s":1240,"text":"Syntax:"},{"code":null,"e":1283,"s":1248,"text":"..."},{"code":null,"e":1292,"s":1283,"text":"Example:"},{"code":null,"e":1297,"s":1292,"text":"HTML"},{"code":"

GeeksforGeeks

Tailwind CSS Height Class
h-8
h-12
h-16
h-20
h-24
h-32
h-40
h-48
h-52
","e":2477,"s":1297,"text":null},{"code":null,"e":2485,"s":2477,"text":"Output:"},{"code":null,"e":2568,"s":2485,"text":"h-auto: This class is used to let the browser determine the height of the element."},{"code":null,"e":2576,"s":2568,"text":"Syntax:"},{"code":null,"e":2614,"s":2576,"text":"..."},{"code":null,"e":2623,"s":2614,"text":"Example:"},{"code":null,"e":2628,"s":2623,"text":"HTML"},{"code":"

GeeksforGeeks

Tailwind CSS Height Class
h-auto
","e":3075,"s":2628,"text":null},{"code":null,"e":3083,"s":3075,"text":"Output:"},{"code":null,"e":3171,"s":3083,"text":"h-screen: This class is used to make an element span the entire height of the viewport."},{"code":null,"e":3179,"s":3171,"text":"Syntax:"},{"code":null,"e":3219,"s":3179,"text":"..."},{"code":null,"e":3228,"s":3219,"text":"Example:"},{"code":null,"e":3233,"s":3228,"text":"HTML"},{"code":"

GeeksforGeeks

Tailwind CSS Height Class
h-screen
","e":3684,"s":3233,"text":null},{"code":null,"e":3692,"s":3684,"text":"Output:"},{"code":null,"e":3813,"s":3692,"text":"h-full: This class is used to set an element’s height to 100% of its parent, as long as the parent has a defined height."},{"code":null,"e":3821,"s":3813,"text":"Syntax:"},{"code":null,"e":3859,"s":3821,"text":"..."},{"code":null,"e":3868,"s":3859,"text":"Example:"},{"code":null,"e":3873,"s":3868,"text":"HTML"},{"code":"

GeeksforGeeks

Tailwind CSS Height Class
h-full
","e":4325,"s":3873,"text":null},{"code":null,"e":4333,"s":4325,"text":"Output:"},{"code":null,"e":4346,"s":4333,"text":"Tailwind CSS"},{"code":null,"e":4362,"s":4346,"text":"Tailwind-Sizing"},{"code":null,"e":4366,"s":4362,"text":"CSS"},{"code":null,"e":4383,"s":4366,"text":"Web Technologies"},{"code":null,"e":4481,"s":4383,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":4529,"s":4481,"text":"How to update Node.js and NPM to next version ?"},{"code":null,"e":4591,"s":4529,"text":"Top 10 Projects For Beginners To Practice HTML and CSS Skills"},{"code":null,"e":4641,"s":4591,"text":"How to insert spaces/tabs in text using HTML/CSS?"},{"code":null,"e":4699,"s":4641,"text":"How to create footer to stay at the bottom of a Web page?"},{"code":null,"e":4749,"s":4699,"text":"CSS to put icon inside an input element in a form"},{"code":null,"e":4811,"s":4749,"text":"Top 10 Projects For Beginners To Practice HTML and CSS Skills"},{"code":null,"e":4844,"s":4811,"text":"Installation of Node.js on Linux"},{"code":null,"e":4905,"s":4844,"text":"Difference between var, let and const keywords in JavaScript"},{"code":null,"e":4955,"s":4905,"text":"How to insert spaces/tabs in text using HTML/CSS?"}],"string":"[\n {\n \"code\": null,\n \"e\": 28,\n \"s\": 0,\n \"text\": \"\\n23 Mar, 2022\"\n },\n {\n \"code\": null,\n \"e\": 315,\n \"s\": 28,\n \"text\": \"This class accepts lots of values in tailwind CSS in which all the properties are covered in class form. It is the alternative to the CSS height Property. This class is used to set the height of an element. The height class does not contain padding, margin, and the border of elements.\"\n },\n {\n \"code\": null,\n \"e\": 331,\n \"s\": 315,\n \"text\": \"Height classes:\"\n },\n {\n \"code\": null,\n \"e\": 372,\n \"s\": 331,\n \"text\": \"h-0: This class sets the height to zero.\"\n },\n {\n \"code\": null,\n \"e\": 433,\n \"s\": 372,\n \"text\": \"h-auto: This class sets the height according to the content.\"\n },\n {\n \"code\": null,\n \"e\": 488,\n \"s\": 433,\n \"text\": \"h-px: This class is used to set the height in 1px fix.\"\n },\n {\n \"code\": null,\n \"e\": 545,\n \"s\": 488,\n \"text\": \"h-1/2: This class sets the height to half of the window.\"\n },\n {\n \"code\": null,\n \"e\": 607,\n \"s\": 545,\n \"text\": \"h-1/3: This class sets the height to one-third of the window.\"\n },\n {\n \"code\": null,\n \"e\": 670,\n \"s\": 607,\n \"text\": \"h-1/4: This class sets the height to one-fourth of the window.\"\n },\n {\n \"code\": null,\n \"e\": 732,\n \"s\": 670,\n \"text\": \"h-1/5: This class sets the height to one-fifth of the window.\"\n },\n {\n \"code\": null,\n \"e\": 794,\n \"s\": 732,\n \"text\": \"h-1/6: This class sets the height to one-sixth of the window.\"\n },\n {\n \"code\": null,\n \"e\": 905,\n \"s\": 794,\n \"text\": \"h-full: This class sets an element’s height to 100% of its parent, as long as the parent has a defined height.\"\n },\n {\n \"code\": null,\n \"e\": 990,\n \"s\": 905,\n \"text\": \"h-screen: This class used to make an element span the entire height of the viewport.\"\n },\n {\n \"code\": null,\n \"e\": 1079,\n \"s\": 990,\n \"text\": \"Note: You can change the number with the valid “rem” values or set the percentage value.\"\n },\n {\n \"code\": null,\n \"e\": 1240,\n \"s\": 1079,\n \"text\": \"h-0: This class is used to set the specific height for any element, you can change the number with a valid number of rem units to fix the height of the element.\"\n },\n {\n \"code\": null,\n \"e\": 1248,\n \"s\": 1240,\n \"text\": \"Syntax:\"\n },\n {\n \"code\": null,\n \"e\": 1283,\n \"s\": 1248,\n \"text\": \"...\"\n },\n {\n \"code\": null,\n \"e\": 1292,\n \"s\": 1283,\n \"text\": \"Example:\"\n },\n {\n \"code\": null,\n \"e\": 1297,\n \"s\": 1292,\n \"text\": \"HTML\"\n },\n {\n \"code\": \"

GeeksforGeeks

Tailwind CSS Height Class
h-8
h-12
h-16
h-20
h-24
h-32
h-40
h-48
h-52
\",\n \"e\": 2477,\n \"s\": 1297,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 2485,\n \"s\": 2477,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 2568,\n \"s\": 2485,\n \"text\": \"h-auto: This class is used to let the browser determine the height of the element.\"\n },\n {\n \"code\": null,\n \"e\": 2576,\n \"s\": 2568,\n \"text\": \"Syntax:\"\n },\n {\n \"code\": null,\n \"e\": 2614,\n \"s\": 2576,\n \"text\": \"...\"\n },\n {\n \"code\": null,\n \"e\": 2623,\n \"s\": 2614,\n \"text\": \"Example:\"\n },\n {\n \"code\": null,\n \"e\": 2628,\n \"s\": 2623,\n \"text\": \"HTML\"\n },\n {\n \"code\": \"

GeeksforGeeks

Tailwind CSS Height Class
h-auto
\",\n \"e\": 3075,\n \"s\": 2628,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 3083,\n \"s\": 3075,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 3171,\n \"s\": 3083,\n \"text\": \"h-screen: This class is used to make an element span the entire height of the viewport.\"\n },\n {\n \"code\": null,\n \"e\": 3179,\n \"s\": 3171,\n \"text\": \"Syntax:\"\n },\n {\n \"code\": null,\n \"e\": 3219,\n \"s\": 3179,\n \"text\": \"...\"\n },\n {\n \"code\": null,\n \"e\": 3228,\n \"s\": 3219,\n \"text\": \"Example:\"\n },\n {\n \"code\": null,\n \"e\": 3233,\n \"s\": 3228,\n \"text\": \"HTML\"\n },\n {\n \"code\": \"

GeeksforGeeks

Tailwind CSS Height Class
h-screen
\",\n \"e\": 3684,\n \"s\": 3233,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 3692,\n \"s\": 3684,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 3813,\n \"s\": 3692,\n \"text\": \"h-full: This class is used to set an element’s height to 100% of its parent, as long as the parent has a defined height.\"\n },\n {\n \"code\": null,\n \"e\": 3821,\n \"s\": 3813,\n \"text\": \"Syntax:\"\n },\n {\n \"code\": null,\n \"e\": 3859,\n \"s\": 3821,\n \"text\": \"...\"\n },\n {\n \"code\": null,\n \"e\": 3868,\n \"s\": 3859,\n \"text\": \"Example:\"\n },\n {\n \"code\": null,\n \"e\": 3873,\n \"s\": 3868,\n \"text\": \"HTML\"\n },\n {\n \"code\": \"

GeeksforGeeks

Tailwind CSS Height Class
h-full
\",\n \"e\": 4325,\n \"s\": 3873,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 4333,\n \"s\": 4325,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 4346,\n \"s\": 4333,\n \"text\": \"Tailwind CSS\"\n },\n {\n \"code\": null,\n \"e\": 4362,\n \"s\": 4346,\n \"text\": \"Tailwind-Sizing\"\n },\n {\n \"code\": null,\n \"e\": 4366,\n \"s\": 4362,\n \"text\": \"CSS\"\n },\n {\n \"code\": null,\n \"e\": 4383,\n \"s\": 4366,\n \"text\": \"Web Technologies\"\n },\n {\n \"code\": null,\n \"e\": 4481,\n \"s\": 4383,\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\": 4529,\n \"s\": 4481,\n \"text\": \"How to update Node.js and NPM to next version ?\"\n },\n {\n \"code\": null,\n \"e\": 4591,\n \"s\": 4529,\n \"text\": \"Top 10 Projects For Beginners To Practice HTML and CSS Skills\"\n },\n {\n \"code\": null,\n \"e\": 4641,\n \"s\": 4591,\n \"text\": \"How to insert spaces/tabs in text using HTML/CSS?\"\n },\n {\n \"code\": null,\n \"e\": 4699,\n \"s\": 4641,\n \"text\": \"How to create footer to stay at the bottom of a Web page?\"\n },\n {\n \"code\": null,\n \"e\": 4749,\n \"s\": 4699,\n \"text\": \"CSS to put icon inside an input element in a form\"\n },\n {\n \"code\": null,\n \"e\": 4811,\n \"s\": 4749,\n \"text\": \"Top 10 Projects For Beginners To Practice HTML and CSS Skills\"\n },\n {\n \"code\": null,\n \"e\": 4844,\n \"s\": 4811,\n \"text\": \"Installation of Node.js on Linux\"\n },\n {\n \"code\": null,\n \"e\": 4905,\n \"s\": 4844,\n \"text\": \"Difference between var, let and const keywords in JavaScript\"\n },\n {\n \"code\": null,\n \"e\": 4955,\n \"s\": 4905,\n \"text\": \"How to insert spaces/tabs in text using HTML/CSS?\"\n }\n]"}}},{"rowIdx":406,"cells":{"title":{"kind":"string","value":"ASP.NET Core - Identity Configuration"},"text":{"kind":"string","value":"In this chapter, we will install and configure the Identity framework, which takes just a little bit of work. If you go to the Visual Studio and create a new ASP.NET Core application, and you select the full web application template with authentication set to individual user accounts, that new project will include all the bits of the Identity framework set up for you.\nWe started from an empty project. We will now set up the Identity framework from scratch, which is a good way to learn about all the pieces that are in the full application template because it can be confusing if you haven't worked your way through all the codes in detail.\nTo get started, we will need to install the dependency, which is Microsoft.AspNet.Identity. We will proceed by installing Microsoft.AspNet.Identity.EntityFramework and then, implement the Identity framework that works with the Entity Framework.\nIf we take a dependency on Identity.EntityFramework, the package is inclusive of the Identity package.\nIf we take a dependency on Identity.EntityFramework, the package is inclusive of the Identity package.\nIf you build your own data stores, you can work just with the Identity package.\nIf you build your own data stores, you can work just with the Identity package.\nOnce our dependencies are installed, we can create a customer User class with all the information we want to store about a user.\nOnce our dependencies are installed, we can create a customer User class with all the information we want to store about a user.\nFor this application, we are going to inherit from a class provided by the Identity framework and that class will give us all the essentials like the Username property and a place to store the hashed passwords.\nFor this application, we are going to inherit from a class provided by the Identity framework and that class will give us all the essentials like the Username property and a place to store the hashed passwords.\nWe will also need to modify our FirstAppDemoDbContext class to inherit from the Identity framework's IdentityDb class.\nWe will also need to modify our FirstAppDemoDbContext class to inherit from the Identity framework's IdentityDb class.\nThe IdentityDb gives us everything we need to store as user information with the Entity Framework. Once we have a User class and a DBContext set up, we will need to configure the Identity services into the application with the ConfigureServices method of the Startup class.\nThe IdentityDb gives us everything we need to store as user information with the Entity Framework. Once we have a User class and a DBContext set up, we will need to configure the Identity services into the application with the ConfigureServices method of the Startup class.\nJust like when we needed to add services to support the MVC framework, the Identity framework needs services added to the application in order to work.\nJust like when we needed to add services to support the MVC framework, the Identity framework needs services added to the application in order to work.\nThese services include services like the UserStore service and the SignInManager.\nThese services include services like the UserStore service and the SignInManager.\nWe will be injecting those services into our controller to create users and issue cookies at the appropriate time.\nWe will be injecting those services into our controller to create users and issue cookies at the appropriate time.\nFinally, during the Configure method of startup, we will need to add the Identity middleware.\nFinally, during the Configure method of startup, we will need to add the Identity middleware.\nThis middleware will not only help to turn cookies into a user identity, but also make sure that the user doesn't see an empty page with a 401 response.\nThis middleware will not only help to turn cookies into a user identity, but also make sure that the user doesn't see an empty page with a 401 response.\nLet us now follow the steps given below.\nStep 1 − We need to proceed by adding a dependency on the Identity framework. Let us add Microsoft.AspNet.Identity.EntityFramework dependency into the project.json file. This will include all of the other necessary Identity packages that we need.\n{ \n \"version\": \"1.0.0-*\", \n \"compilationOptions\": { \n \"emitEntryPoint\": true \n }, \n \n \"dependencies\": { \n \"Microsoft.AspNet.Mvc\": \"6.0.0-rc1-final\", \n \"Microsoft.AspNet.Diagnostics\": \"1.0.0-rc1-final\", \n \"Microsoft.AspNet.IISPlatformHandler\": \"1.0.0-rc1-final\", \n \"Microsoft.AspNet.Server.Kestrel\": \"1.0.0-rc1-final\", \n \"Microsoft.AspNet.StaticFiles\": \"1.0.0-rc1-final\", \n \"EntityFramework.MicrosoftSqlServer\": \"7.0.0-rc1-final\", \n \"EntityFramework.Commands\": \"7.0.0-rc1-final\", \n \"Microsoft.AspNet.Mvc.TagHelpers\": \"6.0.0-rc1-final\", \n \"Microsoft.AspNet.Identity.EntityFramework\": \"3.0.0-rc1-final\" \n }, \n \n \"commands\": { \n \"web\": \"Microsoft.AspNet.Server.Kestrel\", \n \"ef\": \"EntityFramework.Commands\" \n }, \n \n \"frameworks\": { \n \"dnx451\": { }, \n \"dnxcore50\": { } \n }, \n \n \"exclude\": [ \n \"wwwroot\", \n \"node_modules\" \n ], \n \n \"publishExclude\": [ \n \"**.user\", \n \"**.vspscc\" \n ] \n} \nStep 2 − Save this file. The Visual Studio restores the packages and now, we can add our User class. Let us add the User class by right-clicking on the Models folder and selecting Add → Class.\nCall this class User and click on the Add button as in the above screenshot. In this class, you can add properties to hold any information that you want to store about a user.\nStep 3 − Let us derive the User class from a class provided by the Identity framework. It is the IdentityUser class that is in the Identity.EntityFramework namespace.\nusing Microsoft.AspNet.Identity.EntityFramework; \n\nusing System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Threading.Tasks; \n\nnamespace FirstAppDemo.Models { \n public class User : IdentityUser { \n } \n}\nStep 4− Let us now go to the IdentityUser, put the cursor on that symbol, and press F12 to see the Visual Studio's metadata view.\n#region Assembly Microsoft.AspNet.Identity.EntityFramework, Version = 3.0.0.0, \n\nnamespace Microsoft.AspNet.Identity.EntityFramework { \n public class IdentityUser : IdentityUser { \n public IdentityUser(); \n public IdentityUser(string userName); \n } \n}\nStep 5 − You can see that IdentityUser is derived from the IdentityUser of the string. You can change the type of the primary key by deriving from the IdentityUser and specifying our generic type parameter. You can also store things with a primary key that is ideally an integer value.\nStep 6 − Let us now place the cursor on the IdentityUser of string and press F12 again to go to the metadata view.\nYou can now see all the information related to a user by default. The information includes the following −\nThe fields that we won't use in this application, but are available for use.\nThe fields that we won't use in this application, but are available for use.\nThe Identity framework can keep track of the number of failed login attempts for a particular user and can lock that account over a period of time.\nThe Identity framework can keep track of the number of failed login attempts for a particular user and can lock that account over a period of time.\nThe fields to store the PasswordHash, the PhoneNumber. The two important fields that we will be using are the PasswordHash and the UserName.\nThe fields to store the PasswordHash, the PhoneNumber. The two important fields that we will be using are the PasswordHash and the UserName.\nWe will also be implicitly using the primary key and the ID property of a user. You can also use that property if you need to query for a specific user.\nWe will also be implicitly using the primary key and the ID property of a user. You can also use that property if you need to query for a specific user.\nStep 7 − Now, we need to make sure that the User is included in our DBContext. So, let us open the FirstAppDemoDBContext that we have in our application, and instead of deriving it directly from the DBContext, which is the built-in Entity Framework base class, we now need to derive it from the IdentityDbContext.\nusing Microsoft.AspNet.Identity.EntityFramework; \nusing Microsoft.Data.Entity; \n\nnamespace FirstAppDemo.Models { \n public class FirstAppDemoDbContext : IdentityDbContext { \n public DbSet Employees { get; set; } \n \n protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { \n optionsBuilder.UseSqlServer(\"Data Source = (localdb)\\\\MSSQLLocalDB;\n Initial Catalog = FirstAppDemo;Integrated Security = True;\n Connect Timeout = 30;Encrypt = False;TrustServerCertificate = True;\n ApplicationIntent = ReadWrite;MultiSubnetFailover = False\"); \n } \n } \n} \nStep 8 − The IdentityDbContext class is also in the Microsoft.AspNet.Identity.EntityFramework namespace and we can specify the type of user it should store. This way, any additional fields we add to the User class gets into the database.\nThe IdentityDbContext brings additional DbSets, not just to store a user but also information about the user roles and the user claims.\nThe IdentityDbContext brings additional DbSets, not just to store a user but also information about the user roles and the user claims.\nOur User class is ready now. Our FirstAppDemoDbContext class is configured to work with the Identity framework.\nOur User class is ready now. Our FirstAppDemoDbContext class is configured to work with the Identity framework.\nWe can now go into Configure and ConfigureServices to set up the Identity framework.\nWe can now go into Configure and ConfigureServices to set up the Identity framework.\nstep 9 − Let us now start with ConfigureServices. In addition to our MVC services and our Entity Framework services, we need to add our Identity services. This will add all the services that the Identity framework relies on to do its work.\npublic void ConfigureServices(IServiceCollection services) { \n services.AddMvc(); \n \n services.AddEntityFramework() \n .AddSqlServer() \n .AddDbContext\n (option => option.UseSqlServer(Configuration[\"database:connection\"])); \n \n services.AddIdentity() \n .AddEntityFrameworkStores(); \n}\nThe AddIdentity method takes two generic type parameters — the type of user entity and the type of role entity.\nThe AddIdentity method takes two generic type parameters — the type of user entity and the type of role entity.\nThe two generic type parameters are the types of our user — the User class we just created and the Role class that we want to work with. We will now use the built-in IdentityRole. This class is in the EntityFramework namespace.\nThe two generic type parameters are the types of our user — the User class we just created and the Role class that we want to work with. We will now use the built-in IdentityRole. This class is in the EntityFramework namespace.\nWhen we are using the Entity Framework with Identity, we also need to invoke a second method − the AddEntityFrameworkStores.\nWhen we are using the Entity Framework with Identity, we also need to invoke a second method − the AddEntityFrameworkStores.\nThe AddEntityFrameworkStores method will configure services like the UserStore, the service used to create users and validate their passwords.\nThe AddEntityFrameworkStores method will configure services like the UserStore, the service used to create users and validate their passwords.\nStep 10 − The following two lines are all we need to configure the services for the application.\nservices.AddIdentity() \n .AddEntityFrameworkStores();\n\nStep 11 − We also need to add the middleware. The location of where we insert the middleware is important because if we insert the middleware too late in the pipeline, it will never have the chance to process a request.\nAnd if we require authorization checks inside our MVC controllers, we need to have the Identity middleware inserted before the MVC framework to make sure that cookies and also the 401 errors are processed successfully.\npublic void Configure(IApplicationBuilder app) { \n app.UseIISPlatformHandler(); \n \n app.UseDeveloperExceptionPage(); \n app.UseRuntimeInfoPage(); \n \n app.UseFileServer(); \n \n app.UseIdentity(); \n app.UseMvc(ConfigureRoute); \n \n app.Run(async (context) => { \n var msg = Configuration[\"message\"]; \n await context.Response.WriteAsync(msg); \n }); \n} \nStep 12 − The location where we insert the middleware is where we will add the Identity middleware. The following is the complete implementation of the Startup.cs file.\nusing Microsoft.AspNet.Builder; \nusing Microsoft.AspNet.Hosting; \nusing Microsoft.AspNet.Http;\n\nusing Microsoft.Extensions.DependencyInjection; \nusing Microsoft.Extensions.Configuration; \n\nusing FirstAppDemo.Services; \nusing Microsoft.AspNet.Routing; \nusing System; \n\nusing FirstAppDemo.Entities; \nusing Microsoft.Data.Entity; \n\nusing FirstAppDemo.Models; \nusing Microsoft.AspNet.Identity.EntityFramework; \n\nnamespace FirstAppDemo { \n public class Startup { \n public Startup() { \n var builder = new ConfigurationBuilder() \n .AddJsonFile(\"AppSettings.json\"); \n Configuration = builder.Build(); \n } \n public IConfiguration Configuration { get; set; } \n \n // This method gets called by the runtime.\n // Use this method to add services to the container. \n // For more information on how to configure your application, \n // visit http://go.microsoft.com/fwlink/?LinkID = 398940 \n public void ConfigureServices(IServiceCollection services) { \n services.AddMvc(); \n services.AddEntityFramework() \n .AddSqlServer() \n .AddDbContext(option => \n option.UseSqlServer(Configuration[\"database:connection\"])); \n \n services.AddIdentity() \n .AddEntityFrameworkStores(); \n }\n // This method gets called by the runtime. \n // Use this method to configure the HTTP request pipeline. \n public void Configure(IApplicationBuilder app) { \n app.UseIISPlatformHandler(); \n app.UseDeveloperExceptionPage(); \n app.UseRuntimeInfoPage(); \n app.UseFileServer(); \n app.UseIdentity(); \n app.UseMvc(ConfigureRoute); \n \n app.Run(async (context) => { \n var msg = Configuration[\"message\"]; \n await context.Response.WriteAsync(msg); \n }); \n } \n private void ConfigureRoute(IRouteBuilder routeBuilder) { \n //Home/Index \n routeBuilder.MapRoute(\"Default\", \"{controller=Home}/{action=Index}/{id?}\"); \n } \n // Entry point for the application. \n public static void Main(string[] args) => WebApplication.Run(args); \n } \n}\nStep 13 − Let us now move ahead by building the application. In the next chapter, we need to add another Entity Framework migration to make sure we have the Identity schema in our SQL Server database."},"parsed":{"kind":"list like","value":[{"code":null,"e":2966,"s":2595,"text":"In this chapter, we will install and configure the Identity framework, which takes just a little bit of work. If you go to the Visual Studio and create a new ASP.NET Core application, and you select the full web application template with authentication set to individual user accounts, that new project will include all the bits of the Identity framework set up for you."},{"code":null,"e":3240,"s":2966,"text":"We started from an empty project. We will now set up the Identity framework from scratch, which is a good way to learn about all the pieces that are in the full application template because it can be confusing if you haven't worked your way through all the codes in detail."},{"code":null,"e":3485,"s":3240,"text":"To get started, we will need to install the dependency, which is Microsoft.AspNet.Identity. We will proceed by installing Microsoft.AspNet.Identity.EntityFramework and then, implement the Identity framework that works with the Entity Framework."},{"code":null,"e":3588,"s":3485,"text":"If we take a dependency on Identity.EntityFramework, the package is inclusive of the Identity package."},{"code":null,"e":3691,"s":3588,"text":"If we take a dependency on Identity.EntityFramework, the package is inclusive of the Identity package."},{"code":null,"e":3771,"s":3691,"text":"If you build your own data stores, you can work just with the Identity package."},{"code":null,"e":3851,"s":3771,"text":"If you build your own data stores, you can work just with the Identity package."},{"code":null,"e":3980,"s":3851,"text":"Once our dependencies are installed, we can create a customer User class with all the information we want to store about a user."},{"code":null,"e":4109,"s":3980,"text":"Once our dependencies are installed, we can create a customer User class with all the information we want to store about a user."},{"code":null,"e":4320,"s":4109,"text":"For this application, we are going to inherit from a class provided by the Identity framework and that class will give us all the essentials like the Username property and a place to store the hashed passwords."},{"code":null,"e":4531,"s":4320,"text":"For this application, we are going to inherit from a class provided by the Identity framework and that class will give us all the essentials like the Username property and a place to store the hashed passwords."},{"code":null,"e":4650,"s":4531,"text":"We will also need to modify our FirstAppDemoDbContext class to inherit from the Identity framework's IdentityDb class."},{"code":null,"e":4769,"s":4650,"text":"We will also need to modify our FirstAppDemoDbContext class to inherit from the Identity framework's IdentityDb class."},{"code":null,"e":5043,"s":4769,"text":"The IdentityDb gives us everything we need to store as user information with the Entity Framework. Once we have a User class and a DBContext set up, we will need to configure the Identity services into the application with the ConfigureServices method of the Startup class."},{"code":null,"e":5317,"s":5043,"text":"The IdentityDb gives us everything we need to store as user information with the Entity Framework. Once we have a User class and a DBContext set up, we will need to configure the Identity services into the application with the ConfigureServices method of the Startup class."},{"code":null,"e":5469,"s":5317,"text":"Just like when we needed to add services to support the MVC framework, the Identity framework needs services added to the application in order to work."},{"code":null,"e":5621,"s":5469,"text":"Just like when we needed to add services to support the MVC framework, the Identity framework needs services added to the application in order to work."},{"code":null,"e":5703,"s":5621,"text":"These services include services like the UserStore service and the SignInManager."},{"code":null,"e":5785,"s":5703,"text":"These services include services like the UserStore service and the SignInManager."},{"code":null,"e":5900,"s":5785,"text":"We will be injecting those services into our controller to create users and issue cookies at the appropriate time."},{"code":null,"e":6015,"s":5900,"text":"We will be injecting those services into our controller to create users and issue cookies at the appropriate time."},{"code":null,"e":6109,"s":6015,"text":"Finally, during the Configure method of startup, we will need to add the Identity middleware."},{"code":null,"e":6203,"s":6109,"text":"Finally, during the Configure method of startup, we will need to add the Identity middleware."},{"code":null,"e":6356,"s":6203,"text":"This middleware will not only help to turn cookies into a user identity, but also make sure that the user doesn't see an empty page with a 401 response."},{"code":null,"e":6509,"s":6356,"text":"This middleware will not only help to turn cookies into a user identity, but also make sure that the user doesn't see an empty page with a 401 response."},{"code":null,"e":6550,"s":6509,"text":"Let us now follow the steps given below."},{"code":null,"e":6797,"s":6550,"text":"Step 1 − We need to proceed by adding a dependency on the Identity framework. Let us add Microsoft.AspNet.Identity.EntityFramework dependency into the project.json file. This will include all of the other necessary Identity packages that we need."},{"code":null,"e":7806,"s":6797,"text":"{ \n \"version\": \"1.0.0-*\", \n \"compilationOptions\": { \n \"emitEntryPoint\": true \n }, \n \n \"dependencies\": { \n \"Microsoft.AspNet.Mvc\": \"6.0.0-rc1-final\", \n \"Microsoft.AspNet.Diagnostics\": \"1.0.0-rc1-final\", \n \"Microsoft.AspNet.IISPlatformHandler\": \"1.0.0-rc1-final\", \n \"Microsoft.AspNet.Server.Kestrel\": \"1.0.0-rc1-final\", \n \"Microsoft.AspNet.StaticFiles\": \"1.0.0-rc1-final\", \n \"EntityFramework.MicrosoftSqlServer\": \"7.0.0-rc1-final\", \n \"EntityFramework.Commands\": \"7.0.0-rc1-final\", \n \"Microsoft.AspNet.Mvc.TagHelpers\": \"6.0.0-rc1-final\", \n \"Microsoft.AspNet.Identity.EntityFramework\": \"3.0.0-rc1-final\" \n }, \n \n \"commands\": { \n \"web\": \"Microsoft.AspNet.Server.Kestrel\", \n \"ef\": \"EntityFramework.Commands\" \n }, \n \n \"frameworks\": { \n \"dnx451\": { }, \n \"dnxcore50\": { } \n }, \n \n \"exclude\": [ \n \"wwwroot\", \n \"node_modules\" \n ], \n \n \"publishExclude\": [ \n \"**.user\", \n \"**.vspscc\" \n ] \n} "},{"code":null,"e":7999,"s":7806,"text":"Step 2 − Save this file. The Visual Studio restores the packages and now, we can add our User class. Let us add the User class by right-clicking on the Models folder and selecting Add → Class."},{"code":null,"e":8175,"s":7999,"text":"Call this class User and click on the Add button as in the above screenshot. In this class, you can add properties to hold any information that you want to store about a user."},{"code":null,"e":8342,"s":8175,"text":"Step 3 − Let us derive the User class from a class provided by the Identity framework. It is the IdentityUser class that is in the Identity.EntityFramework namespace."},{"code":null,"e":8576,"s":8342,"text":"using Microsoft.AspNet.Identity.EntityFramework; \n\nusing System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Threading.Tasks; \n\nnamespace FirstAppDemo.Models { \n public class User : IdentityUser { \n } \n}"},{"code":null,"e":8706,"s":8576,"text":"Step 4− Let us now go to the IdentityUser, put the cursor on that symbol, and press F12 to see the Visual Studio's metadata view."},{"code":null,"e":8982,"s":8706,"text":"#region Assembly Microsoft.AspNet.Identity.EntityFramework, Version = 3.0.0.0, \n\nnamespace Microsoft.AspNet.Identity.EntityFramework { \n public class IdentityUser : IdentityUser { \n public IdentityUser(); \n public IdentityUser(string userName); \n } \n}"},{"code":null,"e":9268,"s":8982,"text":"Step 5 − You can see that IdentityUser is derived from the IdentityUser of the string. You can change the type of the primary key by deriving from the IdentityUser and specifying our generic type parameter. You can also store things with a primary key that is ideally an integer value."},{"code":null,"e":9383,"s":9268,"text":"Step 6 − Let us now place the cursor on the IdentityUser of string and press F12 again to go to the metadata view."},{"code":null,"e":9490,"s":9383,"text":"You can now see all the information related to a user by default. The information includes the following −"},{"code":null,"e":9567,"s":9490,"text":"The fields that we won't use in this application, but are available for use."},{"code":null,"e":9644,"s":9567,"text":"The fields that we won't use in this application, but are available for use."},{"code":null,"e":9792,"s":9644,"text":"The Identity framework can keep track of the number of failed login attempts for a particular user and can lock that account over a period of time."},{"code":null,"e":9940,"s":9792,"text":"The Identity framework can keep track of the number of failed login attempts for a particular user and can lock that account over a period of time."},{"code":null,"e":10081,"s":9940,"text":"The fields to store the PasswordHash, the PhoneNumber. The two important fields that we will be using are the PasswordHash and the UserName."},{"code":null,"e":10222,"s":10081,"text":"The fields to store the PasswordHash, the PhoneNumber. The two important fields that we will be using are the PasswordHash and the UserName."},{"code":null,"e":10375,"s":10222,"text":"We will also be implicitly using the primary key and the ID property of a user. You can also use that property if you need to query for a specific user."},{"code":null,"e":10528,"s":10375,"text":"We will also be implicitly using the primary key and the ID property of a user. You can also use that property if you need to query for a specific user."},{"code":null,"e":10842,"s":10528,"text":"Step 7 − Now, we need to make sure that the User is included in our DBContext. So, let us open the FirstAppDemoDBContext that we have in our application, and instead of deriving it directly from the DBContext, which is the built-in Entity Framework base class, we now need to derive it from the IdentityDbContext."},{"code":null,"e":11500,"s":10842,"text":"using Microsoft.AspNet.Identity.EntityFramework; \nusing Microsoft.Data.Entity; \n\nnamespace FirstAppDemo.Models { \n public class FirstAppDemoDbContext : IdentityDbContext { \n public DbSet Employees { get; set; } \n \n protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { \n optionsBuilder.UseSqlServer(\"Data Source = (localdb)\\\\MSSQLLocalDB;\n Initial Catalog = FirstAppDemo;Integrated Security = True;\n Connect Timeout = 30;Encrypt = False;TrustServerCertificate = True;\n ApplicationIntent = ReadWrite;MultiSubnetFailover = False\"); \n } \n } \n} "},{"code":null,"e":11738,"s":11500,"text":"Step 8 − The IdentityDbContext class is also in the Microsoft.AspNet.Identity.EntityFramework namespace and we can specify the type of user it should store. This way, any additional fields we add to the User class gets into the database."},{"code":null,"e":11874,"s":11738,"text":"The IdentityDbContext brings additional DbSets, not just to store a user but also information about the user roles and the user claims."},{"code":null,"e":12010,"s":11874,"text":"The IdentityDbContext brings additional DbSets, not just to store a user but also information about the user roles and the user claims."},{"code":null,"e":12122,"s":12010,"text":"Our User class is ready now. Our FirstAppDemoDbContext class is configured to work with the Identity framework."},{"code":null,"e":12234,"s":12122,"text":"Our User class is ready now. Our FirstAppDemoDbContext class is configured to work with the Identity framework."},{"code":null,"e":12319,"s":12234,"text":"We can now go into Configure and ConfigureServices to set up the Identity framework."},{"code":null,"e":12404,"s":12319,"text":"We can now go into Configure and ConfigureServices to set up the Identity framework."},{"code":null,"e":12644,"s":12404,"text":"step 9 − Let us now start with ConfigureServices. In addition to our MVC services and our Entity Framework services, we need to add our Identity services. This will add all the services that the Identity framework relies on to do its work."},{"code":null,"e":13027,"s":12644,"text":"public void ConfigureServices(IServiceCollection services) { \n services.AddMvc(); \n \n services.AddEntityFramework() \n .AddSqlServer() \n .AddDbContext\n (option => option.UseSqlServer(Configuration[\"database:connection\"])); \n \n services.AddIdentity() \n .AddEntityFrameworkStores(); \n}"},{"code":null,"e":13139,"s":13027,"text":"The AddIdentity method takes two generic type parameters — the type of user entity and the type of role entity."},{"code":null,"e":13251,"s":13139,"text":"The AddIdentity method takes two generic type parameters — the type of user entity and the type of role entity."},{"code":null,"e":13479,"s":13251,"text":"The two generic type parameters are the types of our user — the User class we just created and the Role class that we want to work with. We will now use the built-in IdentityRole. This class is in the EntityFramework namespace."},{"code":null,"e":13707,"s":13479,"text":"The two generic type parameters are the types of our user — the User class we just created and the Role class that we want to work with. We will now use the built-in IdentityRole. This class is in the EntityFramework namespace."},{"code":null,"e":13832,"s":13707,"text":"When we are using the Entity Framework with Identity, we also need to invoke a second method − the AddEntityFrameworkStores."},{"code":null,"e":13957,"s":13832,"text":"When we are using the Entity Framework with Identity, we also need to invoke a second method − the AddEntityFrameworkStores."},{"code":null,"e":14101,"s":13957,"text":"The AddEntityFrameworkStores method will configure services like the UserStore, the service used to create users and validate their passwords."},{"code":null,"e":14245,"s":14101,"text":"The AddEntityFrameworkStores method will configure services like the UserStore, the service used to create users and validate their passwords."},{"code":null,"e":14342,"s":14245,"text":"Step 10 − The following two lines are all we need to configure the services for the application."},{"code":null,"e":14442,"s":14342,"text":"services.AddIdentity() \n .AddEntityFrameworkStores();\n"},{"code":null,"e":14662,"s":14442,"text":"Step 11 − We also need to add the middleware. The location of where we insert the middleware is important because if we insert the middleware too late in the pipeline, it will never have the chance to process a request."},{"code":null,"e":14881,"s":14662,"text":"And if we require authorization checks inside our MVC controllers, we need to have the Identity middleware inserted before the MVC framework to make sure that cookies and also the 401 errors are processed successfully."},{"code":null,"e":15265,"s":14881,"text":"public void Configure(IApplicationBuilder app) { \n app.UseIISPlatformHandler(); \n \n app.UseDeveloperExceptionPage(); \n app.UseRuntimeInfoPage(); \n \n app.UseFileServer(); \n \n app.UseIdentity(); \n app.UseMvc(ConfigureRoute); \n \n app.Run(async (context) => { \n var msg = Configuration[\"message\"]; \n await context.Response.WriteAsync(msg); \n }); \n} "},{"code":null,"e":15434,"s":15265,"text":"Step 12 − The location where we insert the middleware is where we will add the Identity middleware. The following is the complete implementation of the Startup.cs file."},{"code":null,"e":17708,"s":15434,"text":"using Microsoft.AspNet.Builder; \nusing Microsoft.AspNet.Hosting; \nusing Microsoft.AspNet.Http;\n\nusing Microsoft.Extensions.DependencyInjection; \nusing Microsoft.Extensions.Configuration; \n\nusing FirstAppDemo.Services; \nusing Microsoft.AspNet.Routing; \nusing System; \n\nusing FirstAppDemo.Entities; \nusing Microsoft.Data.Entity; \n\nusing FirstAppDemo.Models; \nusing Microsoft.AspNet.Identity.EntityFramework; \n\nnamespace FirstAppDemo { \n public class Startup { \n public Startup() { \n var builder = new ConfigurationBuilder() \n .AddJsonFile(\"AppSettings.json\"); \n Configuration = builder.Build(); \n } \n public IConfiguration Configuration { get; set; } \n \n // This method gets called by the runtime.\n // Use this method to add services to the container. \n // For more information on how to configure your application, \n // visit http://go.microsoft.com/fwlink/?LinkID = 398940 \n public void ConfigureServices(IServiceCollection services) { \n services.AddMvc(); \n services.AddEntityFramework() \n .AddSqlServer() \n .AddDbContext(option => \n option.UseSqlServer(Configuration[\"database:connection\"])); \n \n services.AddIdentity() \n .AddEntityFrameworkStores(); \n }\n // This method gets called by the runtime. \n // Use this method to configure the HTTP request pipeline. \n public void Configure(IApplicationBuilder app) { \n app.UseIISPlatformHandler(); \n app.UseDeveloperExceptionPage(); \n app.UseRuntimeInfoPage(); \n app.UseFileServer(); \n app.UseIdentity(); \n app.UseMvc(ConfigureRoute); \n \n app.Run(async (context) => { \n var msg = Configuration[\"message\"]; \n await context.Response.WriteAsync(msg); \n }); \n } \n private void ConfigureRoute(IRouteBuilder routeBuilder) { \n //Home/Index \n routeBuilder.MapRoute(\"Default\", \"{controller=Home}/{action=Index}/{id?}\"); \n } \n // Entry point for the application. \n public static void Main(string[] args) => WebApplication.Run(args); \n } \n}"}],"string":"[\n {\n \"code\": null,\n \"e\": 2966,\n \"s\": 2595,\n \"text\": \"In this chapter, we will install and configure the Identity framework, which takes just a little bit of work. If you go to the Visual Studio and create a new ASP.NET Core application, and you select the full web application template with authentication set to individual user accounts, that new project will include all the bits of the Identity framework set up for you.\"\n },\n {\n \"code\": null,\n \"e\": 3240,\n \"s\": 2966,\n \"text\": \"We started from an empty project. We will now set up the Identity framework from scratch, which is a good way to learn about all the pieces that are in the full application template because it can be confusing if you haven't worked your way through all the codes in detail.\"\n },\n {\n \"code\": null,\n \"e\": 3485,\n \"s\": 3240,\n \"text\": \"To get started, we will need to install the dependency, which is Microsoft.AspNet.Identity. We will proceed by installing Microsoft.AspNet.Identity.EntityFramework and then, implement the Identity framework that works with the Entity Framework.\"\n },\n {\n \"code\": null,\n \"e\": 3588,\n \"s\": 3485,\n \"text\": \"If we take a dependency on Identity.EntityFramework, the package is inclusive of the Identity package.\"\n },\n {\n \"code\": null,\n \"e\": 3691,\n \"s\": 3588,\n \"text\": \"If we take a dependency on Identity.EntityFramework, the package is inclusive of the Identity package.\"\n },\n {\n \"code\": null,\n \"e\": 3771,\n \"s\": 3691,\n \"text\": \"If you build your own data stores, you can work just with the Identity package.\"\n },\n {\n \"code\": null,\n \"e\": 3851,\n \"s\": 3771,\n \"text\": \"If you build your own data stores, you can work just with the Identity package.\"\n },\n {\n \"code\": null,\n \"e\": 3980,\n \"s\": 3851,\n \"text\": \"Once our dependencies are installed, we can create a customer User class with all the information we want to store about a user.\"\n },\n {\n \"code\": null,\n \"e\": 4109,\n \"s\": 3980,\n \"text\": \"Once our dependencies are installed, we can create a customer User class with all the information we want to store about a user.\"\n },\n {\n \"code\": null,\n \"e\": 4320,\n \"s\": 4109,\n \"text\": \"For this application, we are going to inherit from a class provided by the Identity framework and that class will give us all the essentials like the Username property and a place to store the hashed passwords.\"\n },\n {\n \"code\": null,\n \"e\": 4531,\n \"s\": 4320,\n \"text\": \"For this application, we are going to inherit from a class provided by the Identity framework and that class will give us all the essentials like the Username property and a place to store the hashed passwords.\"\n },\n {\n \"code\": null,\n \"e\": 4650,\n \"s\": 4531,\n \"text\": \"We will also need to modify our FirstAppDemoDbContext class to inherit from the Identity framework's IdentityDb class.\"\n },\n {\n \"code\": null,\n \"e\": 4769,\n \"s\": 4650,\n \"text\": \"We will also need to modify our FirstAppDemoDbContext class to inherit from the Identity framework's IdentityDb class.\"\n },\n {\n \"code\": null,\n \"e\": 5043,\n \"s\": 4769,\n \"text\": \"The IdentityDb gives us everything we need to store as user information with the Entity Framework. Once we have a User class and a DBContext set up, we will need to configure the Identity services into the application with the ConfigureServices method of the Startup class.\"\n },\n {\n \"code\": null,\n \"e\": 5317,\n \"s\": 5043,\n \"text\": \"The IdentityDb gives us everything we need to store as user information with the Entity Framework. Once we have a User class and a DBContext set up, we will need to configure the Identity services into the application with the ConfigureServices method of the Startup class.\"\n },\n {\n \"code\": null,\n \"e\": 5469,\n \"s\": 5317,\n \"text\": \"Just like when we needed to add services to support the MVC framework, the Identity framework needs services added to the application in order to work.\"\n },\n {\n \"code\": null,\n \"e\": 5621,\n \"s\": 5469,\n \"text\": \"Just like when we needed to add services to support the MVC framework, the Identity framework needs services added to the application in order to work.\"\n },\n {\n \"code\": null,\n \"e\": 5703,\n \"s\": 5621,\n \"text\": \"These services include services like the UserStore service and the SignInManager.\"\n },\n {\n \"code\": null,\n \"e\": 5785,\n \"s\": 5703,\n \"text\": \"These services include services like the UserStore service and the SignInManager.\"\n },\n {\n \"code\": null,\n \"e\": 5900,\n \"s\": 5785,\n \"text\": \"We will be injecting those services into our controller to create users and issue cookies at the appropriate time.\"\n },\n {\n \"code\": null,\n \"e\": 6015,\n \"s\": 5900,\n \"text\": \"We will be injecting those services into our controller to create users and issue cookies at the appropriate time.\"\n },\n {\n \"code\": null,\n \"e\": 6109,\n \"s\": 6015,\n \"text\": \"Finally, during the Configure method of startup, we will need to add the Identity middleware.\"\n },\n {\n \"code\": null,\n \"e\": 6203,\n \"s\": 6109,\n \"text\": \"Finally, during the Configure method of startup, we will need to add the Identity middleware.\"\n },\n {\n \"code\": null,\n \"e\": 6356,\n \"s\": 6203,\n \"text\": \"This middleware will not only help to turn cookies into a user identity, but also make sure that the user doesn't see an empty page with a 401 response.\"\n },\n {\n \"code\": null,\n \"e\": 6509,\n \"s\": 6356,\n \"text\": \"This middleware will not only help to turn cookies into a user identity, but also make sure that the user doesn't see an empty page with a 401 response.\"\n },\n {\n \"code\": null,\n \"e\": 6550,\n \"s\": 6509,\n \"text\": \"Let us now follow the steps given below.\"\n },\n {\n \"code\": null,\n \"e\": 6797,\n \"s\": 6550,\n \"text\": \"Step 1 − We need to proceed by adding a dependency on the Identity framework. Let us add Microsoft.AspNet.Identity.EntityFramework dependency into the project.json file. This will include all of the other necessary Identity packages that we need.\"\n },\n {\n \"code\": null,\n \"e\": 7806,\n \"s\": 6797,\n \"text\": \"{ \\n \\\"version\\\": \\\"1.0.0-*\\\", \\n \\\"compilationOptions\\\": { \\n \\\"emitEntryPoint\\\": true \\n }, \\n \\n \\\"dependencies\\\": { \\n \\\"Microsoft.AspNet.Mvc\\\": \\\"6.0.0-rc1-final\\\", \\n \\\"Microsoft.AspNet.Diagnostics\\\": \\\"1.0.0-rc1-final\\\", \\n \\\"Microsoft.AspNet.IISPlatformHandler\\\": \\\"1.0.0-rc1-final\\\", \\n \\\"Microsoft.AspNet.Server.Kestrel\\\": \\\"1.0.0-rc1-final\\\", \\n \\\"Microsoft.AspNet.StaticFiles\\\": \\\"1.0.0-rc1-final\\\", \\n \\\"EntityFramework.MicrosoftSqlServer\\\": \\\"7.0.0-rc1-final\\\", \\n \\\"EntityFramework.Commands\\\": \\\"7.0.0-rc1-final\\\", \\n \\\"Microsoft.AspNet.Mvc.TagHelpers\\\": \\\"6.0.0-rc1-final\\\", \\n \\\"Microsoft.AspNet.Identity.EntityFramework\\\": \\\"3.0.0-rc1-final\\\" \\n }, \\n \\n \\\"commands\\\": { \\n \\\"web\\\": \\\"Microsoft.AspNet.Server.Kestrel\\\", \\n \\\"ef\\\": \\\"EntityFramework.Commands\\\" \\n }, \\n \\n \\\"frameworks\\\": { \\n \\\"dnx451\\\": { }, \\n \\\"dnxcore50\\\": { } \\n }, \\n \\n \\\"exclude\\\": [ \\n \\\"wwwroot\\\", \\n \\\"node_modules\\\" \\n ], \\n \\n \\\"publishExclude\\\": [ \\n \\\"**.user\\\", \\n \\\"**.vspscc\\\" \\n ] \\n} \"\n },\n {\n \"code\": null,\n \"e\": 7999,\n \"s\": 7806,\n \"text\": \"Step 2 − Save this file. The Visual Studio restores the packages and now, we can add our User class. Let us add the User class by right-clicking on the Models folder and selecting Add → Class.\"\n },\n {\n \"code\": null,\n \"e\": 8175,\n \"s\": 7999,\n \"text\": \"Call this class User and click on the Add button as in the above screenshot. In this class, you can add properties to hold any information that you want to store about a user.\"\n },\n {\n \"code\": null,\n \"e\": 8342,\n \"s\": 8175,\n \"text\": \"Step 3 − Let us derive the User class from a class provided by the Identity framework. It is the IdentityUser class that is in the Identity.EntityFramework namespace.\"\n },\n {\n \"code\": null,\n \"e\": 8576,\n \"s\": 8342,\n \"text\": \"using Microsoft.AspNet.Identity.EntityFramework; \\n\\nusing System; \\nusing System.Collections.Generic; \\nusing System.Linq; \\nusing System.Threading.Tasks; \\n\\nnamespace FirstAppDemo.Models { \\n public class User : IdentityUser { \\n } \\n}\"\n },\n {\n \"code\": null,\n \"e\": 8706,\n \"s\": 8576,\n \"text\": \"Step 4− Let us now go to the IdentityUser, put the cursor on that symbol, and press F12 to see the Visual Studio's metadata view.\"\n },\n {\n \"code\": null,\n \"e\": 8982,\n \"s\": 8706,\n \"text\": \"#region Assembly Microsoft.AspNet.Identity.EntityFramework, Version = 3.0.0.0, \\n\\nnamespace Microsoft.AspNet.Identity.EntityFramework { \\n public class IdentityUser : IdentityUser { \\n public IdentityUser(); \\n public IdentityUser(string userName); \\n } \\n}\"\n },\n {\n \"code\": null,\n \"e\": 9268,\n \"s\": 8982,\n \"text\": \"Step 5 − You can see that IdentityUser is derived from the IdentityUser of the string. You can change the type of the primary key by deriving from the IdentityUser and specifying our generic type parameter. You can also store things with a primary key that is ideally an integer value.\"\n },\n {\n \"code\": null,\n \"e\": 9383,\n \"s\": 9268,\n \"text\": \"Step 6 − Let us now place the cursor on the IdentityUser of string and press F12 again to go to the metadata view.\"\n },\n {\n \"code\": null,\n \"e\": 9490,\n \"s\": 9383,\n \"text\": \"You can now see all the information related to a user by default. The information includes the following −\"\n },\n {\n \"code\": null,\n \"e\": 9567,\n \"s\": 9490,\n \"text\": \"The fields that we won't use in this application, but are available for use.\"\n },\n {\n \"code\": null,\n \"e\": 9644,\n \"s\": 9567,\n \"text\": \"The fields that we won't use in this application, but are available for use.\"\n },\n {\n \"code\": null,\n \"e\": 9792,\n \"s\": 9644,\n \"text\": \"The Identity framework can keep track of the number of failed login attempts for a particular user and can lock that account over a period of time.\"\n },\n {\n \"code\": null,\n \"e\": 9940,\n \"s\": 9792,\n \"text\": \"The Identity framework can keep track of the number of failed login attempts for a particular user and can lock that account over a period of time.\"\n },\n {\n \"code\": null,\n \"e\": 10081,\n \"s\": 9940,\n \"text\": \"The fields to store the PasswordHash, the PhoneNumber. The two important fields that we will be using are the PasswordHash and the UserName.\"\n },\n {\n \"code\": null,\n \"e\": 10222,\n \"s\": 10081,\n \"text\": \"The fields to store the PasswordHash, the PhoneNumber. The two important fields that we will be using are the PasswordHash and the UserName.\"\n },\n {\n \"code\": null,\n \"e\": 10375,\n \"s\": 10222,\n \"text\": \"We will also be implicitly using the primary key and the ID property of a user. You can also use that property if you need to query for a specific user.\"\n },\n {\n \"code\": null,\n \"e\": 10528,\n \"s\": 10375,\n \"text\": \"We will also be implicitly using the primary key and the ID property of a user. You can also use that property if you need to query for a specific user.\"\n },\n {\n \"code\": null,\n \"e\": 10842,\n \"s\": 10528,\n \"text\": \"Step 7 − Now, we need to make sure that the User is included in our DBContext. So, let us open the FirstAppDemoDBContext that we have in our application, and instead of deriving it directly from the DBContext, which is the built-in Entity Framework base class, we now need to derive it from the IdentityDbContext.\"\n },\n {\n \"code\": null,\n \"e\": 11500,\n \"s\": 10842,\n \"text\": \"using Microsoft.AspNet.Identity.EntityFramework; \\nusing Microsoft.Data.Entity; \\n\\nnamespace FirstAppDemo.Models { \\n public class FirstAppDemoDbContext : IdentityDbContext { \\n public DbSet Employees { get; set; } \\n \\n protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { \\n optionsBuilder.UseSqlServer(\\\"Data Source = (localdb)\\\\\\\\MSSQLLocalDB;\\n Initial Catalog = FirstAppDemo;Integrated Security = True;\\n Connect Timeout = 30;Encrypt = False;TrustServerCertificate = True;\\n ApplicationIntent = ReadWrite;MultiSubnetFailover = False\\\"); \\n } \\n } \\n} \"\n },\n {\n \"code\": null,\n \"e\": 11738,\n \"s\": 11500,\n \"text\": \"Step 8 − The IdentityDbContext class is also in the Microsoft.AspNet.Identity.EntityFramework namespace and we can specify the type of user it should store. This way, any additional fields we add to the User class gets into the database.\"\n },\n {\n \"code\": null,\n \"e\": 11874,\n \"s\": 11738,\n \"text\": \"The IdentityDbContext brings additional DbSets, not just to store a user but also information about the user roles and the user claims.\"\n },\n {\n \"code\": null,\n \"e\": 12010,\n \"s\": 11874,\n \"text\": \"The IdentityDbContext brings additional DbSets, not just to store a user but also information about the user roles and the user claims.\"\n },\n {\n \"code\": null,\n \"e\": 12122,\n \"s\": 12010,\n \"text\": \"Our User class is ready now. Our FirstAppDemoDbContext class is configured to work with the Identity framework.\"\n },\n {\n \"code\": null,\n \"e\": 12234,\n \"s\": 12122,\n \"text\": \"Our User class is ready now. Our FirstAppDemoDbContext class is configured to work with the Identity framework.\"\n },\n {\n \"code\": null,\n \"e\": 12319,\n \"s\": 12234,\n \"text\": \"We can now go into Configure and ConfigureServices to set up the Identity framework.\"\n },\n {\n \"code\": null,\n \"e\": 12404,\n \"s\": 12319,\n \"text\": \"We can now go into Configure and ConfigureServices to set up the Identity framework.\"\n },\n {\n \"code\": null,\n \"e\": 12644,\n \"s\": 12404,\n \"text\": \"step 9 − Let us now start with ConfigureServices. In addition to our MVC services and our Entity Framework services, we need to add our Identity services. This will add all the services that the Identity framework relies on to do its work.\"\n },\n {\n \"code\": null,\n \"e\": 13027,\n \"s\": 12644,\n \"text\": \"public void ConfigureServices(IServiceCollection services) { \\n services.AddMvc(); \\n \\n services.AddEntityFramework() \\n .AddSqlServer() \\n .AddDbContext\\n (option => option.UseSqlServer(Configuration[\\\"database:connection\\\"])); \\n \\n services.AddIdentity() \\n .AddEntityFrameworkStores(); \\n}\"\n },\n {\n \"code\": null,\n \"e\": 13139,\n \"s\": 13027,\n \"text\": \"The AddIdentity method takes two generic type parameters — the type of user entity and the type of role entity.\"\n },\n {\n \"code\": null,\n \"e\": 13251,\n \"s\": 13139,\n \"text\": \"The AddIdentity method takes two generic type parameters — the type of user entity and the type of role entity.\"\n },\n {\n \"code\": null,\n \"e\": 13479,\n \"s\": 13251,\n \"text\": \"The two generic type parameters are the types of our user — the User class we just created and the Role class that we want to work with. We will now use the built-in IdentityRole. This class is in the EntityFramework namespace.\"\n },\n {\n \"code\": null,\n \"e\": 13707,\n \"s\": 13479,\n \"text\": \"The two generic type parameters are the types of our user — the User class we just created and the Role class that we want to work with. We will now use the built-in IdentityRole. This class is in the EntityFramework namespace.\"\n },\n {\n \"code\": null,\n \"e\": 13832,\n \"s\": 13707,\n \"text\": \"When we are using the Entity Framework with Identity, we also need to invoke a second method − the AddEntityFrameworkStores.\"\n },\n {\n \"code\": null,\n \"e\": 13957,\n \"s\": 13832,\n \"text\": \"When we are using the Entity Framework with Identity, we also need to invoke a second method − the AddEntityFrameworkStores.\"\n },\n {\n \"code\": null,\n \"e\": 14101,\n \"s\": 13957,\n \"text\": \"The AddEntityFrameworkStores method will configure services like the UserStore, the service used to create users and validate their passwords.\"\n },\n {\n \"code\": null,\n \"e\": 14245,\n \"s\": 14101,\n \"text\": \"The AddEntityFrameworkStores method will configure services like the UserStore, the service used to create users and validate their passwords.\"\n },\n {\n \"code\": null,\n \"e\": 14342,\n \"s\": 14245,\n \"text\": \"Step 10 − The following two lines are all we need to configure the services for the application.\"\n },\n {\n \"code\": null,\n \"e\": 14442,\n \"s\": 14342,\n \"text\": \"services.AddIdentity() \\n .AddEntityFrameworkStores();\\n\"\n },\n {\n \"code\": null,\n \"e\": 14662,\n \"s\": 14442,\n \"text\": \"Step 11 − We also need to add the middleware. The location of where we insert the middleware is important because if we insert the middleware too late in the pipeline, it will never have the chance to process a request.\"\n },\n {\n \"code\": null,\n \"e\": 14881,\n \"s\": 14662,\n \"text\": \"And if we require authorization checks inside our MVC controllers, we need to have the Identity middleware inserted before the MVC framework to make sure that cookies and also the 401 errors are processed successfully.\"\n },\n {\n \"code\": null,\n \"e\": 15265,\n \"s\": 14881,\n \"text\": \"public void Configure(IApplicationBuilder app) { \\n app.UseIISPlatformHandler(); \\n \\n app.UseDeveloperExceptionPage(); \\n app.UseRuntimeInfoPage(); \\n \\n app.UseFileServer(); \\n \\n app.UseIdentity(); \\n app.UseMvc(ConfigureRoute); \\n \\n app.Run(async (context) => { \\n var msg = Configuration[\\\"message\\\"]; \\n await context.Response.WriteAsync(msg); \\n }); \\n} \"\n },\n {\n \"code\": null,\n \"e\": 15434,\n \"s\": 15265,\n \"text\": \"Step 12 − The location where we insert the middleware is where we will add the Identity middleware. The following is the complete implementation of the Startup.cs file.\"\n },\n {\n \"code\": null,\n \"e\": 17708,\n \"s\": 15434,\n \"text\": \"using Microsoft.AspNet.Builder; \\nusing Microsoft.AspNet.Hosting; \\nusing Microsoft.AspNet.Http;\\n\\nusing Microsoft.Extensions.DependencyInjection; \\nusing Microsoft.Extensions.Configuration; \\n\\nusing FirstAppDemo.Services; \\nusing Microsoft.AspNet.Routing; \\nusing System; \\n\\nusing FirstAppDemo.Entities; \\nusing Microsoft.Data.Entity; \\n\\nusing FirstAppDemo.Models; \\nusing Microsoft.AspNet.Identity.EntityFramework; \\n\\nnamespace FirstAppDemo { \\n public class Startup { \\n public Startup() { \\n var builder = new ConfigurationBuilder() \\n .AddJsonFile(\\\"AppSettings.json\\\"); \\n Configuration = builder.Build(); \\n } \\n public IConfiguration Configuration { get; set; } \\n \\n // This method gets called by the runtime.\\n // Use this method to add services to the container. \\n // For more information on how to configure your application, \\n // visit http://go.microsoft.com/fwlink/?LinkID = 398940 \\n public void ConfigureServices(IServiceCollection services) { \\n services.AddMvc(); \\n services.AddEntityFramework() \\n .AddSqlServer() \\n .AddDbContext(option => \\n option.UseSqlServer(Configuration[\\\"database:connection\\\"])); \\n \\n services.AddIdentity() \\n .AddEntityFrameworkStores(); \\n }\\n // This method gets called by the runtime. \\n // Use this method to configure the HTTP request pipeline. \\n public void Configure(IApplicationBuilder app) { \\n app.UseIISPlatformHandler(); \\n app.UseDeveloperExceptionPage(); \\n app.UseRuntimeInfoPage(); \\n app.UseFileServer(); \\n app.UseIdentity(); \\n app.UseMvc(ConfigureRoute); \\n \\n app.Run(async (context) => { \\n var msg = Configuration[\\\"message\\\"]; \\n await context.Response.WriteAsync(msg); \\n }); \\n } \\n private void ConfigureRoute(IRouteBuilder routeBuilder) { \\n //Home/Index \\n routeBuilder.MapRoute(\\\"Default\\\", \\\"{controller=Home}/{action=Index}/{id?}\\\"); \\n } \\n // Entry point for the application. \\n public static void Main(string[] args) => WebApplication.Run(args); \\n } \\n}\"\n }\n]"}}},{"rowIdx":407,"cells":{"title":{"kind":"string","value":"How to validate if input in input field has ASCII characters using express-validator ?"},"text":{"kind":"string","value":"24 Dec, 2021\nIn HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only Ascii characters are allowed i.e. there is not allowed any Non-ASCII characters (Ex: ñ). We can also validate these input fields to accept only ASCII characters using express-validator middleware.\nCommand to install express-validator:\nnpm install express-validator\nSteps to use express-validator to implement the logic:\nInstall express-validator middleware.\nCreate a validator.js file to code all the validation logic.\nValidate input by validateInputField: check(input field name) and chain on the validation isAscii() with ‘ . ‘\nUse the validation name(validateInputField) in the routes as a middleware as an array of validations.\nDestructure ‘validationResult’ function from express-validator to use it to find any errors.\nIf error occurs redirect to the same page passing the error information.\nIf error list is empty, give access to the user for the subsequent request.\nNote: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql.\nExample: This example illustrates how to validate an input field to accept only ascii characters.\nFilename – index.js\njavascript\nconst express = require('express')const bodyParser = require('body-parser')const {validationResult} = require('express-validator')const repo = require('./repository')const { validateAsciiCharacters } = require('./validator')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML form to submit ascii textapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post( '/register/ascii', [validateAsciiCharacters], async (req, res) => { const errors = validationResult(req) if(!errors.isEmpty()){ return res.send(formTemplet({errors})) } const {submittedBy, ascii} = req.body await repo.create({submittedBy, ascii}) res.send('Ascii Characters registered successfully')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})\nFilename – repository.js: This file contains all the logic to create a local database and interact with it.\njavascript\n// Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // The filename where datas are going to store if(!filename) { throw new Error( 'Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is created // with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll(){ return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs){ const records = await this.getAll() records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created at// runtime and all the information provided// via signup form store in this file in// JSON format.module.exports = new Repository('datastore.json')\nFilename – form.js: This file contains logic to show the form to submit Ascii text.\njavascript\nconst getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' }} module.exports = ({errors}) => { return `

${getError(errors, 'ascii')}

`}\nFilename – validator.js: This file contain all the validation logic(Logic to validate a input field to accept only ascii characters).\njavascript\nconst {check} = require('express-validator')const repo = require('./repository')module.exports = { validateAsciiCharacters : check('ascii') // To delete leading and trailing space .trim() // Validate minimum length of ascii text // Optional for this context .isLength({min:8}) .withMessage('Please submit minimum 8 characters long Ascii text') // Validate input field to accept only ascii chars .isAscii() .withMessage('Must be Ascii characters only') }\nFilename – package.json\npackage.json file\nDatabase:\nDatabase\nOutput:\nAttempt to submit form when Ascii characters input field contains non ascii characters\nResponse when attempt to submit form where Ascii characters input field contains non ascii characters\nAttempt to submit form when Ascii characters input field contains only ascii characters\nResponse when attempt to submit form where Ascii characters input field contains only ascii characters\nDatabase after successful form submission:\nDatabase after successful form submission\nNote: We have used some Bulma classes(CSS framework) in the signup.js file to design the content.\nkk773572498\nExpress.js\nNode.js-Misc\nNode.js\nWeb Technologies\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":"\n24 Dec, 2021"},{"code":null,"e":477,"s":28,"text":"In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only Ascii characters are allowed i.e. there is not allowed any Non-ASCII characters (Ex: ñ). We can also validate these input fields to accept only ASCII characters using express-validator middleware."},{"code":null,"e":515,"s":477,"text":"Command to install express-validator:"},{"code":null,"e":545,"s":515,"text":"npm install express-validator"},{"code":null,"e":600,"s":545,"text":"Steps to use express-validator to implement the logic:"},{"code":null,"e":638,"s":600,"text":"Install express-validator middleware."},{"code":null,"e":699,"s":638,"text":"Create a validator.js file to code all the validation logic."},{"code":null,"e":810,"s":699,"text":"Validate input by validateInputField: check(input field name) and chain on the validation isAscii() with ‘ . ‘"},{"code":null,"e":912,"s":810,"text":"Use the validation name(validateInputField) in the routes as a middleware as an array of validations."},{"code":null,"e":1005,"s":912,"text":"Destructure ‘validationResult’ function from express-validator to use it to find any errors."},{"code":null,"e":1078,"s":1005,"text":"If error occurs redirect to the same page passing the error information."},{"code":null,"e":1154,"s":1078,"text":"If error list is empty, give access to the user for the subsequent request."},{"code":null,"e":1320,"s":1154,"text":"Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql."},{"code":null,"e":1418,"s":1320,"text":"Example: This example illustrates how to validate an input field to accept only ascii characters."},{"code":null,"e":1438,"s":1418,"text":"Filename – index.js"},{"code":null,"e":1449,"s":1438,"text":"javascript"},{"code":"const express = require('express')const bodyParser = require('body-parser')const {validationResult} = require('express-validator')const repo = require('./repository')const { validateAsciiCharacters } = require('./validator')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML form to submit ascii textapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post( '/register/ascii', [validateAsciiCharacters], async (req, res) => { const errors = validationResult(req) if(!errors.isEmpty()){ return res.send(formTemplet({errors})) } const {submittedBy, ascii} = req.body await repo.create({submittedBy, ascii}) res.send('Ascii Characters registered successfully')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})","e":2454,"s":1449,"text":null},{"code":null,"e":2562,"s":2454,"text":"Filename – repository.js: This file contains all the logic to create a local database and interact with it."},{"code":null,"e":2573,"s":2562,"text":"javascript"},{"code":"// Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // The filename where datas are going to store if(!filename) { throw new Error( 'Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is created // with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll(){ return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs){ const records = await this.getAll() records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created at// runtime and all the information provided// via signup form store in this file in// JSON format.module.exports = new Repository('datastore.json')","e":3614,"s":2573,"text":null},{"code":null,"e":3698,"s":3614,"text":"Filename – form.js: This file contains logic to show the form to submit Ascii text."},{"code":null,"e":3709,"s":3698,"text":"javascript"},{"code":"const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' }} module.exports = ({errors}) => { return `

${getError(errors, 'ascii')}

`}","e":5512,"s":3709,"text":null},{"code":null,"e":5646,"s":5512,"text":"Filename – validator.js: This file contain all the validation logic(Logic to validate a input field to accept only ascii characters)."},{"code":null,"e":5657,"s":5646,"text":"javascript"},{"code":"const {check} = require('express-validator')const repo = require('./repository')module.exports = { validateAsciiCharacters : check('ascii') // To delete leading and trailing space .trim() // Validate minimum length of ascii text // Optional for this context .isLength({min:8}) .withMessage('Please submit minimum 8 characters long Ascii text') // Validate input field to accept only ascii chars .isAscii() .withMessage('Must be Ascii characters only') }","e":6145,"s":5657,"text":null},{"code":null,"e":6169,"s":6145,"text":"Filename – package.json"},{"code":null,"e":6187,"s":6169,"text":"package.json file"},{"code":null,"e":6197,"s":6187,"text":"Database:"},{"code":null,"e":6206,"s":6197,"text":"Database"},{"code":null,"e":6214,"s":6206,"text":"Output:"},{"code":null,"e":6301,"s":6214,"text":"Attempt to submit form when Ascii characters input field contains non ascii characters"},{"code":null,"e":6403,"s":6301,"text":"Response when attempt to submit form where Ascii characters input field contains non ascii characters"},{"code":null,"e":6491,"s":6403,"text":"Attempt to submit form when Ascii characters input field contains only ascii characters"},{"code":null,"e":6594,"s":6491,"text":"Response when attempt to submit form where Ascii characters input field contains only ascii characters"},{"code":null,"e":6637,"s":6594,"text":"Database after successful form submission:"},{"code":null,"e":6679,"s":6637,"text":"Database after successful form submission"},{"code":null,"e":6777,"s":6679,"text":"Note: We have used some Bulma classes(CSS framework) in the signup.js file to design the content."},{"code":null,"e":6789,"s":6777,"text":"kk773572498"},{"code":null,"e":6800,"s":6789,"text":"Express.js"},{"code":null,"e":6813,"s":6800,"text":"Node.js-Misc"},{"code":null,"e":6821,"s":6813,"text":"Node.js"},{"code":null,"e":6838,"s":6821,"text":"Web Technologies"}],"string":"[\n {\n \"code\": null,\n \"e\": 28,\n \"s\": 0,\n \"text\": \"\\n24 Dec, 2021\"\n },\n {\n \"code\": null,\n \"e\": 477,\n \"s\": 28,\n \"text\": \"In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only Ascii characters are allowed i.e. there is not allowed any Non-ASCII characters (Ex: ñ). We can also validate these input fields to accept only ASCII characters using express-validator middleware.\"\n },\n {\n \"code\": null,\n \"e\": 515,\n \"s\": 477,\n \"text\": \"Command to install express-validator:\"\n },\n {\n \"code\": null,\n \"e\": 545,\n \"s\": 515,\n \"text\": \"npm install express-validator\"\n },\n {\n \"code\": null,\n \"e\": 600,\n \"s\": 545,\n \"text\": \"Steps to use express-validator to implement the logic:\"\n },\n {\n \"code\": null,\n \"e\": 638,\n \"s\": 600,\n \"text\": \"Install express-validator middleware.\"\n },\n {\n \"code\": null,\n \"e\": 699,\n \"s\": 638,\n \"text\": \"Create a validator.js file to code all the validation logic.\"\n },\n {\n \"code\": null,\n \"e\": 810,\n \"s\": 699,\n \"text\": \"Validate input by validateInputField: check(input field name) and chain on the validation isAscii() with ‘ . ‘\"\n },\n {\n \"code\": null,\n \"e\": 912,\n \"s\": 810,\n \"text\": \"Use the validation name(validateInputField) in the routes as a middleware as an array of validations.\"\n },\n {\n \"code\": null,\n \"e\": 1005,\n \"s\": 912,\n \"text\": \"Destructure ‘validationResult’ function from express-validator to use it to find any errors.\"\n },\n {\n \"code\": null,\n \"e\": 1078,\n \"s\": 1005,\n \"text\": \"If error occurs redirect to the same page passing the error information.\"\n },\n {\n \"code\": null,\n \"e\": 1154,\n \"s\": 1078,\n \"text\": \"If error list is empty, give access to the user for the subsequent request.\"\n },\n {\n \"code\": null,\n \"e\": 1320,\n \"s\": 1154,\n \"text\": \"Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql.\"\n },\n {\n \"code\": null,\n \"e\": 1418,\n \"s\": 1320,\n \"text\": \"Example: This example illustrates how to validate an input field to accept only ascii characters.\"\n },\n {\n \"code\": null,\n \"e\": 1438,\n \"s\": 1418,\n \"text\": \"Filename – index.js\"\n },\n {\n \"code\": null,\n \"e\": 1449,\n \"s\": 1438,\n \"text\": \"javascript\"\n },\n {\n \"code\": \"const express = require('express')const bodyParser = require('body-parser')const {validationResult} = require('express-validator')const repo = require('./repository')const { validateAsciiCharacters } = require('./validator')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML form to submit ascii textapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post( '/register/ascii', [validateAsciiCharacters], async (req, res) => { const errors = validationResult(req) if(!errors.isEmpty()){ return res.send(formTemplet({errors})) } const {submittedBy, ascii} = req.body await repo.create({submittedBy, ascii}) res.send('Ascii Characters registered successfully')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})\",\n \"e\": 2454,\n \"s\": 1449,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 2562,\n \"s\": 2454,\n \"text\": \"Filename – repository.js: This file contains all the logic to create a local database and interact with it.\"\n },\n {\n \"code\": null,\n \"e\": 2573,\n \"s\": 2562,\n \"text\": \"javascript\"\n },\n {\n \"code\": \"// Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // The filename where datas are going to store if(!filename) { throw new Error( 'Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is created // with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll(){ return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs){ const records = await this.getAll() records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created at// runtime and all the information provided// via signup form store in this file in// JSON format.module.exports = new Repository('datastore.json')\",\n \"e\": 3614,\n \"s\": 2573,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 3698,\n \"s\": 3614,\n \"text\": \"Filename – form.js: This file contains logic to show the form to submit Ascii text.\"\n },\n {\n \"code\": null,\n \"e\": 3709,\n \"s\": 3698,\n \"text\": \"javascript\"\n },\n {\n \"code\": \"const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' }} module.exports = ({errors}) => { return `

${getError(errors, 'ascii')}

`}\",\n \"e\": 5512,\n \"s\": 3709,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 5646,\n \"s\": 5512,\n \"text\": \"Filename – validator.js: This file contain all the validation logic(Logic to validate a input field to accept only ascii characters).\"\n },\n {\n \"code\": null,\n \"e\": 5657,\n \"s\": 5646,\n \"text\": \"javascript\"\n },\n {\n \"code\": \"const {check} = require('express-validator')const repo = require('./repository')module.exports = { validateAsciiCharacters : check('ascii') // To delete leading and trailing space .trim() // Validate minimum length of ascii text // Optional for this context .isLength({min:8}) .withMessage('Please submit minimum 8 characters long Ascii text') // Validate input field to accept only ascii chars .isAscii() .withMessage('Must be Ascii characters only') }\",\n \"e\": 6145,\n \"s\": 5657,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 6169,\n \"s\": 6145,\n \"text\": \"Filename – package.json\"\n },\n {\n \"code\": null,\n \"e\": 6187,\n \"s\": 6169,\n \"text\": \"package.json file\"\n },\n {\n \"code\": null,\n \"e\": 6197,\n \"s\": 6187,\n \"text\": \"Database:\"\n },\n {\n \"code\": null,\n \"e\": 6206,\n \"s\": 6197,\n \"text\": \"Database\"\n },\n {\n \"code\": null,\n \"e\": 6214,\n \"s\": 6206,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 6301,\n \"s\": 6214,\n \"text\": \"Attempt to submit form when Ascii characters input field contains non ascii characters\"\n },\n {\n \"code\": null,\n \"e\": 6403,\n \"s\": 6301,\n \"text\": \"Response when attempt to submit form where Ascii characters input field contains non ascii characters\"\n },\n {\n \"code\": null,\n \"e\": 6491,\n \"s\": 6403,\n \"text\": \"Attempt to submit form when Ascii characters input field contains only ascii characters\"\n },\n {\n \"code\": null,\n \"e\": 6594,\n \"s\": 6491,\n \"text\": \"Response when attempt to submit form where Ascii characters input field contains only ascii characters\"\n },\n {\n \"code\": null,\n \"e\": 6637,\n \"s\": 6594,\n \"text\": \"Database after successful form submission:\"\n },\n {\n \"code\": null,\n \"e\": 6679,\n \"s\": 6637,\n \"text\": \"Database after successful form submission\"\n },\n {\n \"code\": null,\n \"e\": 6777,\n \"s\": 6679,\n \"text\": \"Note: We have used some Bulma classes(CSS framework) in the signup.js file to design the content.\"\n },\n {\n \"code\": null,\n \"e\": 6789,\n \"s\": 6777,\n \"text\": \"kk773572498\"\n },\n {\n \"code\": null,\n \"e\": 6800,\n \"s\": 6789,\n \"text\": \"Express.js\"\n },\n {\n \"code\": null,\n \"e\": 6813,\n \"s\": 6800,\n \"text\": \"Node.js-Misc\"\n },\n {\n \"code\": null,\n \"e\": 6821,\n \"s\": 6813,\n \"text\": \"Node.js\"\n },\n {\n \"code\": null,\n \"e\": 6838,\n \"s\": 6821,\n \"text\": \"Web Technologies\"\n }\n]"}}},{"rowIdx":408,"cells":{"title":{"kind":"string","value":"Creating a one-dimensional NumPy array"},"text":{"kind":"string","value":"02 Sep, 2020\nOne dimensional array contains elements only in one dimension. In other words, the shape of the NumPy array should contain only one value in the tuple. Let us see how to create 1 dimensional NumPy arrays.\nMethod 1: First make a list then pass it in numpy.array()\nPython3\n# importing the moduleimport numpy as np # creating the listlist = [100, 200, 300, 400] # creating 1-d arrayn = np.array(list)print(n)\nOutput:\n[100 200 300 400]\nMethod 2: fromiter() is useful for creating non-numeric sequence type array however it can create any type of array. Here we will convert a string into a NumPy array of characters.\nPython3\n# imporint gthe moduleimport numpy as np # creating the stringstr = \"geeksforgeeks\" # creating 1-d arrayx = np.fromiter(str, dtype = 'U2')print(x)\nOutput:\n['g' 'e' 'e' 'k' 's' 'f' 'o' 'r' 'g' 'e' 'e' 'k' 's']\nMethod 3: arange() returns evenly spaced values within a given interval.\nPython3\n# importing the moduleimport numpy as np # creating 1-d arrayx = np.arange(3, 10, 2)print(x)\nOutput:\n[3 5 7 9]\nMethod 4: linspace() creates evenly space numerical elements between two given limits.\nPython3\n# importing the moduleimport numpy as np # creating 1-d arrayx = np.linspace(3, 10, 3)print(x)\nOutput:\n[ 3. 6.5 10. ]\nPython numpy-arrayCreation\nPython-numpy\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\nIntroduction To PYTHON\nHow to drop one or multiple columns in Pandas Dataframe\nPython | os.path.join() method\nCheck if element exists in list in Python\nHow To Convert Python Dictionary To JSON?\nPython | Get unique values from a list\nPython | datetime.timedelta() function"},"parsed":{"kind":"list like","value":[{"code":null,"e":28,"s":0,"text":"\n02 Sep, 2020"},{"code":null,"e":233,"s":28,"text":"One dimensional array contains elements only in one dimension. In other words, the shape of the NumPy array should contain only one value in the tuple. Let us see how to create 1 dimensional NumPy arrays."},{"code":null,"e":291,"s":233,"text":"Method 1: First make a list then pass it in numpy.array()"},{"code":null,"e":299,"s":291,"text":"Python3"},{"code":"# importing the moduleimport numpy as np # creating the listlist = [100, 200, 300, 400] # creating 1-d arrayn = np.array(list)print(n)","e":436,"s":299,"text":null},{"code":null,"e":444,"s":436,"text":"Output:"},{"code":null,"e":462,"s":444,"text":"[100 200 300 400]"},{"code":null,"e":643,"s":462,"text":"Method 2: fromiter() is useful for creating non-numeric sequence type array however it can create any type of array. Here we will convert a string into a NumPy array of characters."},{"code":null,"e":651,"s":643,"text":"Python3"},{"code":"# imporint gthe moduleimport numpy as np # creating the stringstr = \"geeksforgeeks\" # creating 1-d arrayx = np.fromiter(str, dtype = 'U2')print(x)","e":800,"s":651,"text":null},{"code":null,"e":808,"s":800,"text":"Output:"},{"code":null,"e":862,"s":808,"text":"['g' 'e' 'e' 'k' 's' 'f' 'o' 'r' 'g' 'e' 'e' 'k' 's']"},{"code":null,"e":935,"s":862,"text":"Method 3: arange() returns evenly spaced values within a given interval."},{"code":null,"e":943,"s":935,"text":"Python3"},{"code":"# importing the moduleimport numpy as np # creating 1-d arrayx = np.arange(3, 10, 2)print(x)","e":1037,"s":943,"text":null},{"code":null,"e":1045,"s":1037,"text":"Output:"},{"code":null,"e":1055,"s":1045,"text":"[3 5 7 9]"},{"code":null,"e":1142,"s":1055,"text":"Method 4: linspace() creates evenly space numerical elements between two given limits."},{"code":null,"e":1150,"s":1142,"text":"Python3"},{"code":"# importing the moduleimport numpy as np # creating 1-d arrayx = np.linspace(3, 10, 3)print(x)","e":1246,"s":1150,"text":null},{"code":null,"e":1254,"s":1246,"text":"Output:"},{"code":null,"e":1271,"s":1254,"text":"[ 3. 6.5 10. ]"},{"code":null,"e":1298,"s":1271,"text":"Python numpy-arrayCreation"},{"code":null,"e":1311,"s":1298,"text":"Python-numpy"},{"code":null,"e":1318,"s":1311,"text":"Python"},{"code":null,"e":1416,"s":1318,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":1448,"s":1416,"text":"How to Install PIP on Windows ?"},{"code":null,"e":1475,"s":1448,"text":"Python Classes and Objects"},{"code":null,"e":1496,"s":1475,"text":"Python OOPs Concepts"},{"code":null,"e":1519,"s":1496,"text":"Introduction To PYTHON"},{"code":null,"e":1575,"s":1519,"text":"How to drop one or multiple columns in Pandas Dataframe"},{"code":null,"e":1606,"s":1575,"text":"Python | os.path.join() method"},{"code":null,"e":1648,"s":1606,"text":"Check if element exists in list in Python"},{"code":null,"e":1690,"s":1648,"text":"How To Convert Python Dictionary To JSON?"},{"code":null,"e":1729,"s":1690,"text":"Python | Get unique values from a list"}],"string":"[\n {\n \"code\": null,\n \"e\": 28,\n \"s\": 0,\n \"text\": \"\\n02 Sep, 2020\"\n },\n {\n \"code\": null,\n \"e\": 233,\n \"s\": 28,\n \"text\": \"One dimensional array contains elements only in one dimension. In other words, the shape of the NumPy array should contain only one value in the tuple. Let us see how to create 1 dimensional NumPy arrays.\"\n },\n {\n \"code\": null,\n \"e\": 291,\n \"s\": 233,\n \"text\": \"Method 1: First make a list then pass it in numpy.array()\"\n },\n {\n \"code\": null,\n \"e\": 299,\n \"s\": 291,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"# importing the moduleimport numpy as np # creating the listlist = [100, 200, 300, 400] # creating 1-d arrayn = np.array(list)print(n)\",\n \"e\": 436,\n \"s\": 299,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 444,\n \"s\": 436,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 462,\n \"s\": 444,\n \"text\": \"[100 200 300 400]\"\n },\n {\n \"code\": null,\n \"e\": 643,\n \"s\": 462,\n \"text\": \"Method 2: fromiter() is useful for creating non-numeric sequence type array however it can create any type of array. Here we will convert a string into a NumPy array of characters.\"\n },\n {\n \"code\": null,\n \"e\": 651,\n \"s\": 643,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"# imporint gthe moduleimport numpy as np # creating the stringstr = \\\"geeksforgeeks\\\" # creating 1-d arrayx = np.fromiter(str, dtype = 'U2')print(x)\",\n \"e\": 800,\n \"s\": 651,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 808,\n \"s\": 800,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 862,\n \"s\": 808,\n \"text\": \"['g' 'e' 'e' 'k' 's' 'f' 'o' 'r' 'g' 'e' 'e' 'k' 's']\"\n },\n {\n \"code\": null,\n \"e\": 935,\n \"s\": 862,\n \"text\": \"Method 3: arange() returns evenly spaced values within a given interval.\"\n },\n {\n \"code\": null,\n \"e\": 943,\n \"s\": 935,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"# importing the moduleimport numpy as np # creating 1-d arrayx = np.arange(3, 10, 2)print(x)\",\n \"e\": 1037,\n \"s\": 943,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 1045,\n \"s\": 1037,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 1055,\n \"s\": 1045,\n \"text\": \"[3 5 7 9]\"\n },\n {\n \"code\": null,\n \"e\": 1142,\n \"s\": 1055,\n \"text\": \"Method 4: linspace() creates evenly space numerical elements between two given limits.\"\n },\n {\n \"code\": null,\n \"e\": 1150,\n \"s\": 1142,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"# importing the moduleimport numpy as np # creating 1-d arrayx = np.linspace(3, 10, 3)print(x)\",\n \"e\": 1246,\n \"s\": 1150,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 1254,\n \"s\": 1246,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 1271,\n \"s\": 1254,\n \"text\": \"[ 3. 6.5 10. ]\"\n },\n {\n \"code\": null,\n \"e\": 1298,\n \"s\": 1271,\n \"text\": \"Python numpy-arrayCreation\"\n },\n {\n \"code\": null,\n \"e\": 1311,\n \"s\": 1298,\n \"text\": \"Python-numpy\"\n },\n {\n \"code\": null,\n \"e\": 1318,\n \"s\": 1311,\n \"text\": \"Python\"\n },\n {\n \"code\": null,\n \"e\": 1416,\n \"s\": 1318,\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\": 1448,\n \"s\": 1416,\n \"text\": \"How to Install PIP on Windows ?\"\n },\n {\n \"code\": null,\n \"e\": 1475,\n \"s\": 1448,\n \"text\": \"Python Classes and Objects\"\n },\n {\n \"code\": null,\n \"e\": 1496,\n \"s\": 1475,\n \"text\": \"Python OOPs Concepts\"\n },\n {\n \"code\": null,\n \"e\": 1519,\n \"s\": 1496,\n \"text\": \"Introduction To PYTHON\"\n },\n {\n \"code\": null,\n \"e\": 1575,\n \"s\": 1519,\n \"text\": \"How to drop one or multiple columns in Pandas Dataframe\"\n },\n {\n \"code\": null,\n \"e\": 1606,\n \"s\": 1575,\n \"text\": \"Python | os.path.join() method\"\n },\n {\n \"code\": null,\n \"e\": 1648,\n \"s\": 1606,\n \"text\": \"Check if element exists in list in Python\"\n },\n {\n \"code\": null,\n \"e\": 1690,\n \"s\": 1648,\n \"text\": \"How To Convert Python Dictionary To JSON?\"\n },\n {\n \"code\": null,\n \"e\": 1729,\n \"s\": 1690,\n \"text\": \"Python | Get unique values from a list\"\n }\n]"}}},{"rowIdx":409,"cells":{"title":{"kind":"string","value":"Find sum of even factors of a number"},"text":{"kind":"string","value":"23 Jun, 2022\nGiven a number n, the task is to find the even factor sum of a number.Examples: \nInput : 30\nOutput : 48\nEven dividers sum 2 + 6 + 10 + 30 = 48\n\nInput : 18\nOutput : 26\nEven dividers sum 2 + 6 + 18 = 26\n \nPrerequisite : Sum of factorsAs discussed in above mentioned previous post, sum of factors of a number isLet p1, p2, ... pk be prime factors of n. Let a1, a2, .. ak be highest powers of p1, p2, .. pk respectively that divide n, i.e., we can write n as n = (p1a1)*(p2a2)* ... (pkak). \nSum of divisors = (1 + p1 + p12 ... p1a1) * \n (1 + p2 + p22 ... p2a2) *\n ...........................\n (1 + pk + pk2 ... pkak) \nIf number is odd, then there are no even factors, so we simply return 0.If number is even, we use above formula. We only need to ignore 20. All other terms multiply to produce even factor sum. For example, consider n = 18. It can be written as 2132 and sun of all factors is (20 + 21)*(30 + 31 + 32). if we remove 20 then we get the Sum of even factors (2)*(1+3+32) = 26.To remove odd number in even factor, we ignore then 20 which is 1. After this step, we only get even factors. Note that 2 is the only even prime. Below is the implementation of the above approach. \nC++\nJava\nPython3\nC#\nPHP\nJavascript\n// Formula based CPP program to find sum of all// divisors of n.#include using namespace std; // Returns sum of all factors of n.int sumofFactors(int n){ // If n is odd, then there are no even factors. if (n % 2 != 0) return 0; // Traversing through all prime factors. int res = 1; for (int i = 2; i <= sqrt(n); i++) { // While i divides n, print i and divide n int count = 0, curr_sum = 1, curr_term = 1; while (n % i == 0) { count++; n = n / i; // here we remove the 2^0 that is 1. All // other factors if (i == 2 && count == 1) curr_sum = 0; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle the case when n // is a prime number. if (n >= 2) res *= (1 + n); return res;} // Driver codeint main(){ int n = 18; cout << sumofFactors(n); return 0;}\n// Formula based Java program to // find sum of all divisors of n.import java.util.*;import java.lang.*; public class GfG{ // Returns sum of all factors of n. public static int sumofFactors(int n) { // If n is odd, then there // are no even factors. if (n % 2 != 0) return 0; // Traversing through all prime // factors. int res = 1; for (int i = 2; i <= Math.sqrt(n); i++) { int count = 0, curr_sum = 1; int curr_term = 1; // While i divides n, print i and // divide n while (n % i == 0) { count++; n = n / i; // here we remove the 2^0 that // is 1. All other factors if (i == 2 && count == 1) curr_sum = 0; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle the // case when n is a prime number. if (n >= 2) res *= (1 + n); return res; } // Driver function public static void main(String argc[]){ int n = 18; System.out.println(sumofFactors(n)); } } /* This code is contributed by Sagar Shukla */\n# Formula based Python3# program to find sum# of alldivisors of n.import math # Returns sum of all# factors of n.def sumofFactors(n) : # If n is odd, then # there are no even # factors. if (n % 2 != 0) : return 0 # Traversing through # all prime factors. res = 1 for i in range(2, (int)(math.sqrt(n)) + 1) : # While i divides n # print i and divide n count = 0 curr_sum = 1 curr_term = 1 while (n % i == 0) : count= count + 1 n = n // i # here we remove the # 2^0 that is 1. All # other factors if (i == 2 and count == 1) : curr_sum = 0 curr_term = curr_term * i curr_sum = curr_sum + curr_term res = res * curr_sum # This condition is to # handle the case when # n is a prime number. if (n >= 2) : res = res * (1 + n) return res # Driver coden = 18print(sumofFactors(n)) # This code is contributed by Nikita Tiwari.\n// Formula based C# program to// find sum of all divisors of n.using System; public class GfG { // Returns sum of all factors of n. public static int sumofFactors(int n) { // If n is odd, then there // are no even factors. if (n % 2 != 0) return 0; // Traversing through all prime factors. int res = 1; for (int i = 2; i <= Math.Sqrt(n); i++) { int count = 0, curr_sum = 1; int curr_term = 1; // While i divides n, print i // and divide n while (n % i == 0) { count++; n = n / i; // here we remove the 2^0 that // is 1. All other factors if (i == 2 && count == 1) curr_sum = 0; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle the // case when n is a prime number. if (n >= 2) res *= (1 + n); return res; } // Driver Code public static void Main() { int n = 18; Console.WriteLine(sumofFactors(n)); } } // This code is contributed by vt_m\n= 2) $res *= (1 + $n); return $res;} // Driver code $n = 18; echo sumofFactors($n); // This code is contributed by mits?>\n\nOutput: \n26\nTime Complexity: O(√n log n) Auxiliary Space: O(1)\nPlease suggest if someone has a better solution which is more efficient in terms of space and time.This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above \nMithun Kumar\nsusmitakundugoaldanga\nvinayedula\ncodewithshinchan\nnumber-theory\nprime-factor\nMathematical\nnumber-theory\nMathematical\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nProgram for Fibonacci numbers\nSet in C++ Standard Template Library (STL)\nWrite a program to print all permutations of a given string\nC++ Data Types\nMerge two sorted arrays\nCoin Change | DP-7\nOperators in C / C++\nPrime Numbers\nProgram to find GCD or HCF of two numbers\nFind minimum number of coins that make a given value"},"parsed":{"kind":"list like","value":[{"code":null,"e":54,"s":26,"text":"\n23 Jun, 2022"},{"code":null,"e":136,"s":54,"text":"Given a number n, the task is to find the even factor sum of a number.Examples: "},{"code":null,"e":256,"s":136,"text":"Input : 30\nOutput : 48\nEven dividers sum 2 + 6 + 10 + 30 = 48\n\nInput : 18\nOutput : 26\nEven dividers sum 2 + 6 + 18 = 26"},{"code":null,"e":542,"s":258,"text":"Prerequisite : Sum of factorsAs discussed in above mentioned previous post, sum of factors of a number isLet p1, p2, ... pk be prime factors of n. Let a1, a2, .. ak be highest powers of p1, p2, .. pk respectively that divide n, i.e., we can write n as n = (p1a1)*(p2a2)* ... (pkak). "},{"code":null,"e":720,"s":542,"text":"Sum of divisors = (1 + p1 + p12 ... p1a1) * \n (1 + p2 + p22 ... p2a2) *\n ...........................\n (1 + pk + pk2 ... pkak) "},{"code":null,"e":1290,"s":720,"text":"If number is odd, then there are no even factors, so we simply return 0.If number is even, we use above formula. We only need to ignore 20. All other terms multiply to produce even factor sum. For example, consider n = 18. It can be written as 2132 and sun of all factors is (20 + 21)*(30 + 31 + 32). if we remove 20 then we get the Sum of even factors (2)*(1+3+32) = 26.To remove odd number in even factor, we ignore then 20 which is 1. After this step, we only get even factors. Note that 2 is the only even prime. Below is the implementation of the above approach. "},{"code":null,"e":1294,"s":1290,"text":"C++"},{"code":null,"e":1299,"s":1294,"text":"Java"},{"code":null,"e":1307,"s":1299,"text":"Python3"},{"code":null,"e":1310,"s":1307,"text":"C#"},{"code":null,"e":1314,"s":1310,"text":"PHP"},{"code":null,"e":1325,"s":1314,"text":"Javascript"},{"code":"// Formula based CPP program to find sum of all// divisors of n.#include using namespace std; // Returns sum of all factors of n.int sumofFactors(int n){ // If n is odd, then there are no even factors. if (n % 2 != 0) return 0; // Traversing through all prime factors. int res = 1; for (int i = 2; i <= sqrt(n); i++) { // While i divides n, print i and divide n int count = 0, curr_sum = 1, curr_term = 1; while (n % i == 0) { count++; n = n / i; // here we remove the 2^0 that is 1. All // other factors if (i == 2 && count == 1) curr_sum = 0; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle the case when n // is a prime number. if (n >= 2) res *= (1 + n); return res;} // Driver codeint main(){ int n = 18; cout << sumofFactors(n); return 0;}","e":2317,"s":1325,"text":null},{"code":"// Formula based Java program to // find sum of all divisors of n.import java.util.*;import java.lang.*; public class GfG{ // Returns sum of all factors of n. public static int sumofFactors(int n) { // If n is odd, then there // are no even factors. if (n % 2 != 0) return 0; // Traversing through all prime // factors. int res = 1; for (int i = 2; i <= Math.sqrt(n); i++) { int count = 0, curr_sum = 1; int curr_term = 1; // While i divides n, print i and // divide n while (n % i == 0) { count++; n = n / i; // here we remove the 2^0 that // is 1. All other factors if (i == 2 && count == 1) curr_sum = 0; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle the // case when n is a prime number. if (n >= 2) res *= (1 + n); return res; } // Driver function public static void main(String argc[]){ int n = 18; System.out.println(sumofFactors(n)); } } /* This code is contributed by Sagar Shukla */","e":3650,"s":2317,"text":null},{"code":"# Formula based Python3# program to find sum# of alldivisors of n.import math # Returns sum of all# factors of n.def sumofFactors(n) : # If n is odd, then # there are no even # factors. if (n % 2 != 0) : return 0 # Traversing through # all prime factors. res = 1 for i in range(2, (int)(math.sqrt(n)) + 1) : # While i divides n # print i and divide n count = 0 curr_sum = 1 curr_term = 1 while (n % i == 0) : count= count + 1 n = n // i # here we remove the # 2^0 that is 1. All # other factors if (i == 2 and count == 1) : curr_sum = 0 curr_term = curr_term * i curr_sum = curr_sum + curr_term res = res * curr_sum # This condition is to # handle the case when # n is a prime number. if (n >= 2) : res = res * (1 + n) return res # Driver coden = 18print(sumofFactors(n)) # This code is contributed by Nikita Tiwari.","e":4718,"s":3650,"text":null},{"code":"// Formula based C# program to// find sum of all divisors of n.using System; public class GfG { // Returns sum of all factors of n. public static int sumofFactors(int n) { // If n is odd, then there // are no even factors. if (n % 2 != 0) return 0; // Traversing through all prime factors. int res = 1; for (int i = 2; i <= Math.Sqrt(n); i++) { int count = 0, curr_sum = 1; int curr_term = 1; // While i divides n, print i // and divide n while (n % i == 0) { count++; n = n / i; // here we remove the 2^0 that // is 1. All other factors if (i == 2 && count == 1) curr_sum = 0; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle the // case when n is a prime number. if (n >= 2) res *= (1 + n); return res; } // Driver Code public static void Main() { int n = 18; Console.WriteLine(sumofFactors(n)); } } // This code is contributed by vt_m","e":5985,"s":4718,"text":null},{"code":"= 2) $res *= (1 + $n); return $res;} // Driver code $n = 18; echo sumofFactors($n); // This code is contributed by mits?>","e":7016,"s":5985,"text":null},{"code":"","e":8252,"s":7016,"text":null},{"code":null,"e":8262,"s":8252,"text":"Output: "},{"code":null,"e":8265,"s":8262,"text":"26"},{"code":null,"e":8316,"s":8265,"text":"Time Complexity: O(√n log n) Auxiliary Space: O(1)"},{"code":null,"e":8584,"s":8316,"text":"Please suggest if someone has a better solution which is more efficient in terms of space and time.This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "},{"code":null,"e":8597,"s":8584,"text":"Mithun Kumar"},{"code":null,"e":8619,"s":8597,"text":"susmitakundugoaldanga"},{"code":null,"e":8630,"s":8619,"text":"vinayedula"},{"code":null,"e":8647,"s":8630,"text":"codewithshinchan"},{"code":null,"e":8661,"s":8647,"text":"number-theory"},{"code":null,"e":8674,"s":8661,"text":"prime-factor"},{"code":null,"e":8687,"s":8674,"text":"Mathematical"},{"code":null,"e":8701,"s":8687,"text":"number-theory"},{"code":null,"e":8714,"s":8701,"text":"Mathematical"},{"code":null,"e":8812,"s":8714,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":8842,"s":8812,"text":"Program for Fibonacci numbers"},{"code":null,"e":8885,"s":8842,"text":"Set in C++ Standard Template Library (STL)"},{"code":null,"e":8945,"s":8885,"text":"Write a program to print all permutations of a given string"},{"code":null,"e":8960,"s":8945,"text":"C++ Data Types"},{"code":null,"e":8984,"s":8960,"text":"Merge two sorted arrays"},{"code":null,"e":9003,"s":8984,"text":"Coin Change | DP-7"},{"code":null,"e":9024,"s":9003,"text":"Operators in C / C++"},{"code":null,"e":9038,"s":9024,"text":"Prime Numbers"},{"code":null,"e":9080,"s":9038,"text":"Program to find GCD or HCF of two numbers"}],"string":"[\n {\n \"code\": null,\n \"e\": 54,\n \"s\": 26,\n \"text\": \"\\n23 Jun, 2022\"\n },\n {\n \"code\": null,\n \"e\": 136,\n \"s\": 54,\n \"text\": \"Given a number n, the task is to find the even factor sum of a number.Examples: \"\n },\n {\n \"code\": null,\n \"e\": 256,\n \"s\": 136,\n \"text\": \"Input : 30\\nOutput : 48\\nEven dividers sum 2 + 6 + 10 + 30 = 48\\n\\nInput : 18\\nOutput : 26\\nEven dividers sum 2 + 6 + 18 = 26\"\n },\n {\n \"code\": null,\n \"e\": 542,\n \"s\": 258,\n \"text\": \"Prerequisite : Sum of factorsAs discussed in above mentioned previous post, sum of factors of a number isLet p1, p2, ... pk be prime factors of n. Let a1, a2, .. ak be highest powers of p1, p2, .. pk respectively that divide n, i.e., we can write n as n = (p1a1)*(p2a2)* ... (pkak). \"\n },\n {\n \"code\": null,\n \"e\": 720,\n \"s\": 542,\n \"text\": \"Sum of divisors = (1 + p1 + p12 ... p1a1) * \\n (1 + p2 + p22 ... p2a2) *\\n ...........................\\n (1 + pk + pk2 ... pkak) \"\n },\n {\n \"code\": null,\n \"e\": 1290,\n \"s\": 720,\n \"text\": \"If number is odd, then there are no even factors, so we simply return 0.If number is even, we use above formula. We only need to ignore 20. All other terms multiply to produce even factor sum. For example, consider n = 18. It can be written as 2132 and sun of all factors is (20 + 21)*(30 + 31 + 32). if we remove 20 then we get the Sum of even factors (2)*(1+3+32) = 26.To remove odd number in even factor, we ignore then 20 which is 1. After this step, we only get even factors. Note that 2 is the only even prime. Below is the implementation of the above approach. \"\n },\n {\n \"code\": null,\n \"e\": 1294,\n \"s\": 1290,\n \"text\": \"C++\"\n },\n {\n \"code\": null,\n \"e\": 1299,\n \"s\": 1294,\n \"text\": \"Java\"\n },\n {\n \"code\": null,\n \"e\": 1307,\n \"s\": 1299,\n \"text\": \"Python3\"\n },\n {\n \"code\": null,\n \"e\": 1310,\n \"s\": 1307,\n \"text\": \"C#\"\n },\n {\n \"code\": null,\n \"e\": 1314,\n \"s\": 1310,\n \"text\": \"PHP\"\n },\n {\n \"code\": null,\n \"e\": 1325,\n \"s\": 1314,\n \"text\": \"Javascript\"\n },\n {\n \"code\": \"// Formula based CPP program to find sum of all// divisors of n.#include using namespace std; // Returns sum of all factors of n.int sumofFactors(int n){ // If n is odd, then there are no even factors. if (n % 2 != 0) return 0; // Traversing through all prime factors. int res = 1; for (int i = 2; i <= sqrt(n); i++) { // While i divides n, print i and divide n int count = 0, curr_sum = 1, curr_term = 1; while (n % i == 0) { count++; n = n / i; // here we remove the 2^0 that is 1. All // other factors if (i == 2 && count == 1) curr_sum = 0; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle the case when n // is a prime number. if (n >= 2) res *= (1 + n); return res;} // Driver codeint main(){ int n = 18; cout << sumofFactors(n); return 0;}\",\n \"e\": 2317,\n \"s\": 1325,\n \"text\": null\n },\n {\n \"code\": \"// Formula based Java program to // find sum of all divisors of n.import java.util.*;import java.lang.*; public class GfG{ // Returns sum of all factors of n. public static int sumofFactors(int n) { // If n is odd, then there // are no even factors. if (n % 2 != 0) return 0; // Traversing through all prime // factors. int res = 1; for (int i = 2; i <= Math.sqrt(n); i++) { int count = 0, curr_sum = 1; int curr_term = 1; // While i divides n, print i and // divide n while (n % i == 0) { count++; n = n / i; // here we remove the 2^0 that // is 1. All other factors if (i == 2 && count == 1) curr_sum = 0; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle the // case when n is a prime number. if (n >= 2) res *= (1 + n); return res; } // Driver function public static void main(String argc[]){ int n = 18; System.out.println(sumofFactors(n)); } } /* This code is contributed by Sagar Shukla */\",\n \"e\": 3650,\n \"s\": 2317,\n \"text\": null\n },\n {\n \"code\": \"# Formula based Python3# program to find sum# of alldivisors of n.import math # Returns sum of all# factors of n.def sumofFactors(n) : # If n is odd, then # there are no even # factors. if (n % 2 != 0) : return 0 # Traversing through # all prime factors. res = 1 for i in range(2, (int)(math.sqrt(n)) + 1) : # While i divides n # print i and divide n count = 0 curr_sum = 1 curr_term = 1 while (n % i == 0) : count= count + 1 n = n // i # here we remove the # 2^0 that is 1. All # other factors if (i == 2 and count == 1) : curr_sum = 0 curr_term = curr_term * i curr_sum = curr_sum + curr_term res = res * curr_sum # This condition is to # handle the case when # n is a prime number. if (n >= 2) : res = res * (1 + n) return res # Driver coden = 18print(sumofFactors(n)) # This code is contributed by Nikita Tiwari.\",\n \"e\": 4718,\n \"s\": 3650,\n \"text\": null\n },\n {\n \"code\": \"// Formula based C# program to// find sum of all divisors of n.using System; public class GfG { // Returns sum of all factors of n. public static int sumofFactors(int n) { // If n is odd, then there // are no even factors. if (n % 2 != 0) return 0; // Traversing through all prime factors. int res = 1; for (int i = 2; i <= Math.Sqrt(n); i++) { int count = 0, curr_sum = 1; int curr_term = 1; // While i divides n, print i // and divide n while (n % i == 0) { count++; n = n / i; // here we remove the 2^0 that // is 1. All other factors if (i == 2 && count == 1) curr_sum = 0; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle the // case when n is a prime number. if (n >= 2) res *= (1 + n); return res; } // Driver Code public static void Main() { int n = 18; Console.WriteLine(sumofFactors(n)); } } // This code is contributed by vt_m\",\n \"e\": 5985,\n \"s\": 4718,\n \"text\": null\n },\n {\n \"code\": \"= 2) $res *= (1 + $n); return $res;} // Driver code $n = 18; echo sumofFactors($n); // This code is contributed by mits?>\",\n \"e\": 7016,\n \"s\": 5985,\n \"text\": null\n },\n {\n \"code\": \"\",\n \"e\": 8252,\n \"s\": 7016,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 8262,\n \"s\": 8252,\n \"text\": \"Output: \"\n },\n {\n \"code\": null,\n \"e\": 8265,\n \"s\": 8262,\n \"text\": \"26\"\n },\n {\n \"code\": null,\n \"e\": 8316,\n \"s\": 8265,\n \"text\": \"Time Complexity: O(√n log n) Auxiliary Space: O(1)\"\n },\n {\n \"code\": null,\n \"e\": 8584,\n \"s\": 8316,\n \"text\": \"Please suggest if someone has a better solution which is more efficient in terms of space and time.This article is contributed by Aarti_Rathi. 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\": 8597,\n \"s\": 8584,\n \"text\": \"Mithun Kumar\"\n },\n {\n \"code\": null,\n \"e\": 8619,\n \"s\": 8597,\n \"text\": \"susmitakundugoaldanga\"\n },\n {\n \"code\": null,\n \"e\": 8630,\n \"s\": 8619,\n \"text\": \"vinayedula\"\n },\n {\n \"code\": null,\n \"e\": 8647,\n \"s\": 8630,\n \"text\": \"codewithshinchan\"\n },\n {\n \"code\": null,\n \"e\": 8661,\n \"s\": 8647,\n \"text\": \"number-theory\"\n },\n {\n \"code\": null,\n \"e\": 8674,\n \"s\": 8661,\n \"text\": \"prime-factor\"\n },\n {\n \"code\": null,\n \"e\": 8687,\n \"s\": 8674,\n \"text\": \"Mathematical\"\n },\n {\n \"code\": null,\n \"e\": 8701,\n \"s\": 8687,\n \"text\": \"number-theory\"\n },\n {\n \"code\": null,\n \"e\": 8714,\n \"s\": 8701,\n \"text\": \"Mathematical\"\n },\n {\n \"code\": null,\n \"e\": 8812,\n \"s\": 8714,\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\": 8842,\n \"s\": 8812,\n \"text\": \"Program for Fibonacci numbers\"\n },\n {\n \"code\": null,\n \"e\": 8885,\n \"s\": 8842,\n \"text\": \"Set in C++ Standard Template Library (STL)\"\n },\n {\n \"code\": null,\n \"e\": 8945,\n \"s\": 8885,\n \"text\": \"Write a program to print all permutations of a given string\"\n },\n {\n \"code\": null,\n \"e\": 8960,\n \"s\": 8945,\n \"text\": \"C++ Data Types\"\n },\n {\n \"code\": null,\n \"e\": 8984,\n \"s\": 8960,\n \"text\": \"Merge two sorted arrays\"\n },\n {\n \"code\": null,\n \"e\": 9003,\n \"s\": 8984,\n \"text\": \"Coin Change | DP-7\"\n },\n {\n \"code\": null,\n \"e\": 9024,\n \"s\": 9003,\n \"text\": \"Operators in C / C++\"\n },\n {\n \"code\": null,\n \"e\": 9038,\n \"s\": 9024,\n \"text\": \"Prime Numbers\"\n },\n {\n \"code\": null,\n \"e\": 9080,\n \"s\": 9038,\n \"text\": \"Program to find GCD or HCF of two numbers\"\n }\n]"}}},{"rowIdx":410,"cells":{"title":{"kind":"string","value":"Users in Linux System Administration"},"text":{"kind":"string","value":"05 Jan, 2019\nUsers are accounts that can be used to login into a system. Each user is identified by a unique identification number or UID by the system. All the information of users in a system are stored in /etc/passwd file. The hashed passwords for users are stored in /etc/shadow file.\nUsers can be divided into two categories on the basis of the level of access:\nSuperuser/root/administrator : Access to all the files on the system.Normal users : Limited access.\nSuperuser/root/administrator : Access to all the files on the system.\nNormal users : Limited access.\nWhen a new user is created, by default system takes following actions:\nAssigns UID to the user.\nCreates a home directory /home/.\nSets the default shell of the user to be /bin/sh.\nCreates a private user group, named after the username itself.\nContents of /etc/skel are copied to the home directory of the new user.\n.bashrc, .bash_profile and .bash_logout are copied to the home directory of new user.These files provide environment variables for this user’s session.\nThis file is readable by any user but only root as read and write permissions for it. This file consists of the following colon separated information about users in a system:\nUsername fieldPassword fieldAn `x` in this field denotes that the encrypted password is stored in the /etc/shadow file.The user ID number (UID)User’s group ID number (GID)Additional information field such as the full name of the user or comment (GECOS)Absolute path of user’s home directoryLogin shell of the user\nUsername field\nPassword fieldAn `x` in this field denotes that the encrypted password is stored in the /etc/shadow file.\nAn `x` in this field denotes that the encrypted password is stored in the /etc/shadow file.\nThe user ID number (UID)\nUser’s group ID number (GID)\nAdditional information field such as the full name of the user or comment (GECOS)\nAbsolute path of user’s home directory\nLogin shell of the user\nSyntax:\n[username]:[password]:[UID]:[GID]:[GECOS]:[home_dir]:[shell_path]\n\nExample:\nThis file is readable and writable by only by root user. This file consists of the following colon separated information about password of users in a system:\nUser name fieldPassword fieldContains an encrypted password.A blank entry, {:: }, indicates that a password is not required to login into that user’s account.An asterisk, {:*:}, indicates the account has been disabled.Last Password ChangeThis field denotes the number of days since the date of last password change counted since UNIX time (1-Jan-1970).The minimum number of days after which the user can change his password.Password validityDenotes the number of days after which the password will expire.Warning periodDenotes the number of days before the password expiry date, from which the user will start receiving warning notification for password change.Account validityDenotes the number of days after which the account will be disabled, once the password is expired.Account disabilityThis field denotes the number of days since which the account had been disabled counted from UNIX time (1-Jan-1970).\nUser name field\nPassword field\nContains an encrypted password.A blank entry, {:: }, indicates that a password is not required to login into that user’s account.An asterisk, {:*:}, indicates the account has been disabled.\nA blank entry, {:: }, indicates that a password is not required to login into that user’s account.\nAn asterisk, {:*:}, indicates the account has been disabled.\nLast Password ChangeThis field denotes the number of days since the date of last password change counted since UNIX time (1-Jan-1970).\nThis field denotes the number of days since the date of last password change counted since UNIX time (1-Jan-1970).\nThe minimum number of days after which the user can change his password.\nPassword validityDenotes the number of days after which the password will expire.\nDenotes the number of days after which the password will expire.\nWarning periodDenotes the number of days before the password expiry date, from which the user will start receiving warning notification for password change.\nDenotes the number of days before the password expiry date, from which the user will start receiving warning notification for password change.\nAccount validityDenotes the number of days after which the account will be disabled, once the password is expired.\nDenotes the number of days after which the account will be disabled, once the password is expired.\nAccount disabilityThis field denotes the number of days since which the account had been disabled counted from UNIX time (1-Jan-1970).\nThis field denotes the number of days since which the account had been disabled counted from UNIX time (1-Jan-1970).\nSyntax:\n[username]:[enc_pwd]:[last_pwd_change]:[pwd_validity]:[warn_date]:[acc_validity]:[acc_disablity]\n\nExample:\nlinux-command\nLinux-Unix\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},"parsed":{"kind":"list like","value":[{"code":null,"e":53,"s":25,"text":"\n05 Jan, 2019"},{"code":null,"e":329,"s":53,"text":"Users are accounts that can be used to login into a system. Each user is identified by a unique identification number or UID by the system. All the information of users in a system are stored in /etc/passwd file. The hashed passwords for users are stored in /etc/shadow file."},{"code":null,"e":407,"s":329,"text":"Users can be divided into two categories on the basis of the level of access:"},{"code":null,"e":507,"s":407,"text":"Superuser/root/administrator : Access to all the files on the system.Normal users : Limited access."},{"code":null,"e":577,"s":507,"text":"Superuser/root/administrator : Access to all the files on the system."},{"code":null,"e":608,"s":577,"text":"Normal users : Limited access."},{"code":null,"e":679,"s":608,"text":"When a new user is created, by default system takes following actions:"},{"code":null,"e":704,"s":679,"text":"Assigns UID to the user."},{"code":null,"e":737,"s":704,"text":"Creates a home directory /home/."},{"code":null,"e":787,"s":737,"text":"Sets the default shell of the user to be /bin/sh."},{"code":null,"e":850,"s":787,"text":"Creates a private user group, named after the username itself."},{"code":null,"e":922,"s":850,"text":"Contents of /etc/skel are copied to the home directory of the new user."},{"code":null,"e":1074,"s":922,"text":".bashrc, .bash_profile and .bash_logout are copied to the home directory of new user.These files provide environment variables for this user’s session."},{"code":null,"e":1249,"s":1074,"text":"This file is readable by any user but only root as read and write permissions for it. This file consists of the following colon separated information about users in a system:"},{"code":null,"e":1563,"s":1249,"text":"Username fieldPassword fieldAn `x` in this field denotes that the encrypted password is stored in the /etc/shadow file.The user ID number (UID)User’s group ID number (GID)Additional information field such as the full name of the user or comment (GECOS)Absolute path of user’s home directoryLogin shell of the user"},{"code":null,"e":1578,"s":1563,"text":"Username field"},{"code":null,"e":1684,"s":1578,"text":"Password fieldAn `x` in this field denotes that the encrypted password is stored in the /etc/shadow file."},{"code":null,"e":1776,"s":1684,"text":"An `x` in this field denotes that the encrypted password is stored in the /etc/shadow file."},{"code":null,"e":1801,"s":1776,"text":"The user ID number (UID)"},{"code":null,"e":1830,"s":1801,"text":"User’s group ID number (GID)"},{"code":null,"e":1912,"s":1830,"text":"Additional information field such as the full name of the user or comment (GECOS)"},{"code":null,"e":1951,"s":1912,"text":"Absolute path of user’s home directory"},{"code":null,"e":1975,"s":1951,"text":"Login shell of the user"},{"code":null,"e":1983,"s":1975,"text":"Syntax:"},{"code":null,"e":2050,"s":1983,"text":"[username]:[password]:[UID]:[GID]:[GECOS]:[home_dir]:[shell_path]\n"},{"code":null,"e":2059,"s":2050,"text":"Example:"},{"code":null,"e":2217,"s":2059,"text":"This file is readable and writable by only by root user. This file consists of the following colon separated information about password of users in a system:"},{"code":null,"e":3127,"s":2217,"text":"User name fieldPassword fieldContains an encrypted password.A blank entry, {:: }, indicates that a password is not required to login into that user’s account.An asterisk, {:*:}, indicates the account has been disabled.Last Password ChangeThis field denotes the number of days since the date of last password change counted since UNIX time (1-Jan-1970).The minimum number of days after which the user can change his password.Password validityDenotes the number of days after which the password will expire.Warning periodDenotes the number of days before the password expiry date, from which the user will start receiving warning notification for password change.Account validityDenotes the number of days after which the account will be disabled, once the password is expired.Account disabilityThis field denotes the number of days since which the account had been disabled counted from UNIX time (1-Jan-1970)."},{"code":null,"e":3143,"s":3127,"text":"User name field"},{"code":null,"e":3158,"s":3143,"text":"Password field"},{"code":null,"e":3348,"s":3158,"text":"Contains an encrypted password.A blank entry, {:: }, indicates that a password is not required to login into that user’s account.An asterisk, {:*:}, indicates the account has been disabled."},{"code":null,"e":3447,"s":3348,"text":"A blank entry, {:: }, indicates that a password is not required to login into that user’s account."},{"code":null,"e":3508,"s":3447,"text":"An asterisk, {:*:}, indicates the account has been disabled."},{"code":null,"e":3643,"s":3508,"text":"Last Password ChangeThis field denotes the number of days since the date of last password change counted since UNIX time (1-Jan-1970)."},{"code":null,"e":3758,"s":3643,"text":"This field denotes the number of days since the date of last password change counted since UNIX time (1-Jan-1970)."},{"code":null,"e":3831,"s":3758,"text":"The minimum number of days after which the user can change his password."},{"code":null,"e":3913,"s":3831,"text":"Password validityDenotes the number of days after which the password will expire."},{"code":null,"e":3978,"s":3913,"text":"Denotes the number of days after which the password will expire."},{"code":null,"e":4135,"s":3978,"text":"Warning periodDenotes the number of days before the password expiry date, from which the user will start receiving warning notification for password change."},{"code":null,"e":4278,"s":4135,"text":"Denotes the number of days before the password expiry date, from which the user will start receiving warning notification for password change."},{"code":null,"e":4393,"s":4278,"text":"Account validityDenotes the number of days after which the account will be disabled, once the password is expired."},{"code":null,"e":4492,"s":4393,"text":"Denotes the number of days after which the account will be disabled, once the password is expired."},{"code":null,"e":4627,"s":4492,"text":"Account disabilityThis field denotes the number of days since which the account had been disabled counted from UNIX time (1-Jan-1970)."},{"code":null,"e":4744,"s":4627,"text":"This field denotes the number of days since which the account had been disabled counted from UNIX time (1-Jan-1970)."},{"code":null,"e":4752,"s":4744,"text":"Syntax:"},{"code":null,"e":4850,"s":4752,"text":"[username]:[enc_pwd]:[last_pwd_change]:[pwd_validity]:[warn_date]:[acc_validity]:[acc_disablity]\n"},{"code":null,"e":4859,"s":4850,"text":"Example:"},{"code":null,"e":4873,"s":4859,"text":"linux-command"},{"code":null,"e":4884,"s":4873,"text":"Linux-Unix"}],"string":"[\n {\n \"code\": null,\n \"e\": 53,\n \"s\": 25,\n \"text\": \"\\n05 Jan, 2019\"\n },\n {\n \"code\": null,\n \"e\": 329,\n \"s\": 53,\n \"text\": \"Users are accounts that can be used to login into a system. Each user is identified by a unique identification number or UID by the system. All the information of users in a system are stored in /etc/passwd file. The hashed passwords for users are stored in /etc/shadow file.\"\n },\n {\n \"code\": null,\n \"e\": 407,\n \"s\": 329,\n \"text\": \"Users can be divided into two categories on the basis of the level of access:\"\n },\n {\n \"code\": null,\n \"e\": 507,\n \"s\": 407,\n \"text\": \"Superuser/root/administrator : Access to all the files on the system.Normal users : Limited access.\"\n },\n {\n \"code\": null,\n \"e\": 577,\n \"s\": 507,\n \"text\": \"Superuser/root/administrator : Access to all the files on the system.\"\n },\n {\n \"code\": null,\n \"e\": 608,\n \"s\": 577,\n \"text\": \"Normal users : Limited access.\"\n },\n {\n \"code\": null,\n \"e\": 679,\n \"s\": 608,\n \"text\": \"When a new user is created, by default system takes following actions:\"\n },\n {\n \"code\": null,\n \"e\": 704,\n \"s\": 679,\n \"text\": \"Assigns UID to the user.\"\n },\n {\n \"code\": null,\n \"e\": 737,\n \"s\": 704,\n \"text\": \"Creates a home directory /home/.\"\n },\n {\n \"code\": null,\n \"e\": 787,\n \"s\": 737,\n \"text\": \"Sets the default shell of the user to be /bin/sh.\"\n },\n {\n \"code\": null,\n \"e\": 850,\n \"s\": 787,\n \"text\": \"Creates a private user group, named after the username itself.\"\n },\n {\n \"code\": null,\n \"e\": 922,\n \"s\": 850,\n \"text\": \"Contents of /etc/skel are copied to the home directory of the new user.\"\n },\n {\n \"code\": null,\n \"e\": 1074,\n \"s\": 922,\n \"text\": \".bashrc, .bash_profile and .bash_logout are copied to the home directory of new user.These files provide environment variables for this user’s session.\"\n },\n {\n \"code\": null,\n \"e\": 1249,\n \"s\": 1074,\n \"text\": \"This file is readable by any user but only root as read and write permissions for it. This file consists of the following colon separated information about users in a system:\"\n },\n {\n \"code\": null,\n \"e\": 1563,\n \"s\": 1249,\n \"text\": \"Username fieldPassword fieldAn `x` in this field denotes that the encrypted password is stored in the /etc/shadow file.The user ID number (UID)User’s group ID number (GID)Additional information field such as the full name of the user or comment (GECOS)Absolute path of user’s home directoryLogin shell of the user\"\n },\n {\n \"code\": null,\n \"e\": 1578,\n \"s\": 1563,\n \"text\": \"Username field\"\n },\n {\n \"code\": null,\n \"e\": 1684,\n \"s\": 1578,\n \"text\": \"Password fieldAn `x` in this field denotes that the encrypted password is stored in the /etc/shadow file.\"\n },\n {\n \"code\": null,\n \"e\": 1776,\n \"s\": 1684,\n \"text\": \"An `x` in this field denotes that the encrypted password is stored in the /etc/shadow file.\"\n },\n {\n \"code\": null,\n \"e\": 1801,\n \"s\": 1776,\n \"text\": \"The user ID number (UID)\"\n },\n {\n \"code\": null,\n \"e\": 1830,\n \"s\": 1801,\n \"text\": \"User’s group ID number (GID)\"\n },\n {\n \"code\": null,\n \"e\": 1912,\n \"s\": 1830,\n \"text\": \"Additional information field such as the full name of the user or comment (GECOS)\"\n },\n {\n \"code\": null,\n \"e\": 1951,\n \"s\": 1912,\n \"text\": \"Absolute path of user’s home directory\"\n },\n {\n \"code\": null,\n \"e\": 1975,\n \"s\": 1951,\n \"text\": \"Login shell of the user\"\n },\n {\n \"code\": null,\n \"e\": 1983,\n \"s\": 1975,\n \"text\": \"Syntax:\"\n },\n {\n \"code\": null,\n \"e\": 2050,\n \"s\": 1983,\n \"text\": \"[username]:[password]:[UID]:[GID]:[GECOS]:[home_dir]:[shell_path]\\n\"\n },\n {\n \"code\": null,\n \"e\": 2059,\n \"s\": 2050,\n \"text\": \"Example:\"\n },\n {\n \"code\": null,\n \"e\": 2217,\n \"s\": 2059,\n \"text\": \"This file is readable and writable by only by root user. This file consists of the following colon separated information about password of users in a system:\"\n },\n {\n \"code\": null,\n \"e\": 3127,\n \"s\": 2217,\n \"text\": \"User name fieldPassword fieldContains an encrypted password.A blank entry, {:: }, indicates that a password is not required to login into that user’s account.An asterisk, {:*:}, indicates the account has been disabled.Last Password ChangeThis field denotes the number of days since the date of last password change counted since UNIX time (1-Jan-1970).The minimum number of days after which the user can change his password.Password validityDenotes the number of days after which the password will expire.Warning periodDenotes the number of days before the password expiry date, from which the user will start receiving warning notification for password change.Account validityDenotes the number of days after which the account will be disabled, once the password is expired.Account disabilityThis field denotes the number of days since which the account had been disabled counted from UNIX time (1-Jan-1970).\"\n },\n {\n \"code\": null,\n \"e\": 3143,\n \"s\": 3127,\n \"text\": \"User name field\"\n },\n {\n \"code\": null,\n \"e\": 3158,\n \"s\": 3143,\n \"text\": \"Password field\"\n },\n {\n \"code\": null,\n \"e\": 3348,\n \"s\": 3158,\n \"text\": \"Contains an encrypted password.A blank entry, {:: }, indicates that a password is not required to login into that user’s account.An asterisk, {:*:}, indicates the account has been disabled.\"\n },\n {\n \"code\": null,\n \"e\": 3447,\n \"s\": 3348,\n \"text\": \"A blank entry, {:: }, indicates that a password is not required to login into that user’s account.\"\n },\n {\n \"code\": null,\n \"e\": 3508,\n \"s\": 3447,\n \"text\": \"An asterisk, {:*:}, indicates the account has been disabled.\"\n },\n {\n \"code\": null,\n \"e\": 3643,\n \"s\": 3508,\n \"text\": \"Last Password ChangeThis field denotes the number of days since the date of last password change counted since UNIX time (1-Jan-1970).\"\n },\n {\n \"code\": null,\n \"e\": 3758,\n \"s\": 3643,\n \"text\": \"This field denotes the number of days since the date of last password change counted since UNIX time (1-Jan-1970).\"\n },\n {\n \"code\": null,\n \"e\": 3831,\n \"s\": 3758,\n \"text\": \"The minimum number of days after which the user can change his password.\"\n },\n {\n \"code\": null,\n \"e\": 3913,\n \"s\": 3831,\n \"text\": \"Password validityDenotes the number of days after which the password will expire.\"\n },\n {\n \"code\": null,\n \"e\": 3978,\n \"s\": 3913,\n \"text\": \"Denotes the number of days after which the password will expire.\"\n },\n {\n \"code\": null,\n \"e\": 4135,\n \"s\": 3978,\n \"text\": \"Warning periodDenotes the number of days before the password expiry date, from which the user will start receiving warning notification for password change.\"\n },\n {\n \"code\": null,\n \"e\": 4278,\n \"s\": 4135,\n \"text\": \"Denotes the number of days before the password expiry date, from which the user will start receiving warning notification for password change.\"\n },\n {\n \"code\": null,\n \"e\": 4393,\n \"s\": 4278,\n \"text\": \"Account validityDenotes the number of days after which the account will be disabled, once the password is expired.\"\n },\n {\n \"code\": null,\n \"e\": 4492,\n \"s\": 4393,\n \"text\": \"Denotes the number of days after which the account will be disabled, once the password is expired.\"\n },\n {\n \"code\": null,\n \"e\": 4627,\n \"s\": 4492,\n \"text\": \"Account disabilityThis field denotes the number of days since which the account had been disabled counted from UNIX time (1-Jan-1970).\"\n },\n {\n \"code\": null,\n \"e\": 4744,\n \"s\": 4627,\n \"text\": \"This field denotes the number of days since which the account had been disabled counted from UNIX time (1-Jan-1970).\"\n },\n {\n \"code\": null,\n \"e\": 4752,\n \"s\": 4744,\n \"text\": \"Syntax:\"\n },\n {\n \"code\": null,\n \"e\": 4850,\n \"s\": 4752,\n \"text\": \"[username]:[enc_pwd]:[last_pwd_change]:[pwd_validity]:[warn_date]:[acc_validity]:[acc_disablity]\\n\"\n },\n {\n \"code\": null,\n \"e\": 4859,\n \"s\": 4850,\n \"text\": \"Example:\"\n },\n {\n \"code\": null,\n \"e\": 4873,\n \"s\": 4859,\n \"text\": \"linux-command\"\n },\n {\n \"code\": null,\n \"e\": 4884,\n \"s\": 4873,\n \"text\": \"Linux-Unix\"\n }\n]"}}},{"rowIdx":411,"cells":{"title":{"kind":"string","value":"MySQL Select Statement DISTINCT for Multiple Columns?"},"text":{"kind":"string","value":"To understand the MySQL select statement DISTINCT for multiple columns, let us see an example and create a table. The query to create a table is as follows\nmysql> create table selectDistinctDemo\n -> (\n -> InstructorId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> StudentId int,\n -> TechnicalSubject varchar(100)\n -> );\nQuery OK, 0 rows affected (0.50 sec)\nInsert some records in the table using insert command. The query is as follows\nmysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(121,'Java');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(121,'MongoDB');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(121,'MySQL');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(298,'Python');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(298,'SQL Server');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(397,'C#');\nQuery OK, 1 row affected (0.13 sec)\nDisplay all records from the table using a select statement. The query is as follows\nmysql> select *from selectDistinctDemo;\nThe following is the output\n+--------------+-----------+------------------+\n| InstructorId | StudentId | TechnicalSubject |\n+--------------+-----------+------------------+\n| 1 | 121 | Java |\n| 2 | 121 | MongoDB |\n| 3 | 121 | MySQL |\n| 4 | 298 | Python |\n| 5 | 298 | SQL Server |\n| 6 | 397 | C# |\n+--------------+-----------+------------------+\n6 rows in set (0.00 sec)\nHere is the query to use select statement DISTINCT for multiple columns\nmysql> select InstructorId,StudentId,TechnicalSubject from selectDistinctDemo\n-> where InstructorId IN\n -> (\n -> select max(InstructorId) from selectDistinctDemo\n -> group by StudentId\n -> )\n-> order by InstructorId desc;\nThe following is the output\n+--------------+-----------+------------------+\n| InstructorId | StudentId | TechnicalSubject |\n+--------------+-----------+------------------+\n| 6 | 397 | C# |\n| 5 | 298 | SQL Server |\n| 3 | 121 | MySQL |\n+--------------+-----------+------------------+\n3 rows in set (0.10 sec)"},"parsed":{"kind":"list like","value":[{"code":null,"e":1218,"s":1062,"text":"To understand the MySQL select statement DISTINCT for multiple columns, let us see an example and create a table. The query to create a table is as follows"},{"code":null,"e":1428,"s":1218,"text":"mysql> create table selectDistinctDemo\n -> (\n -> InstructorId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> StudentId int,\n -> TechnicalSubject varchar(100)\n -> );\nQuery OK, 0 rows affected (0.50 sec)"},{"code":null,"e":1507,"s":1428,"text":"Insert some records in the table using insert command. The query is as follows"},{"code":null,"e":2249,"s":1507,"text":"mysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(121,'Java');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(121,'MongoDB');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(121,'MySQL');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(298,'Python');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(298,'SQL Server');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(397,'C#');\nQuery OK, 1 row affected (0.13 sec)"},{"code":null,"e":2334,"s":2249,"text":"Display all records from the table using a select statement. The query is as follows"},{"code":null,"e":2374,"s":2334,"text":"mysql> select *from selectDistinctDemo;"},{"code":null,"e":2402,"s":2374,"text":"The following is the output"},{"code":null,"e":2907,"s":2402,"text":"+--------------+-----------+------------------+\n| InstructorId | StudentId | TechnicalSubject |\n+--------------+-----------+------------------+\n| 1 | 121 | Java |\n| 2 | 121 | MongoDB |\n| 3 | 121 | MySQL |\n| 4 | 298 | Python |\n| 5 | 298 | SQL Server |\n| 6 | 397 | C# |\n+--------------+-----------+------------------+\n6 rows in set (0.00 sec)"},{"code":null,"e":2979,"s":2907,"text":"Here is the query to use select statement DISTINCT for multiple columns"},{"code":null,"e":3209,"s":2979,"text":"mysql> select InstructorId,StudentId,TechnicalSubject from selectDistinctDemo\n-> where InstructorId IN\n -> (\n -> select max(InstructorId) from selectDistinctDemo\n -> group by StudentId\n -> )\n-> order by InstructorId desc;"},{"code":null,"e":3237,"s":3209,"text":"The following is the output"},{"code":null,"e":3598,"s":3237,"text":"+--------------+-----------+------------------+\n| InstructorId | StudentId | TechnicalSubject |\n+--------------+-----------+------------------+\n| 6 | 397 | C# |\n| 5 | 298 | SQL Server |\n| 3 | 121 | MySQL |\n+--------------+-----------+------------------+\n3 rows in set (0.10 sec)"}],"string":"[\n {\n \"code\": null,\n \"e\": 1218,\n \"s\": 1062,\n \"text\": \"To understand the MySQL select statement DISTINCT for multiple columns, let us see an example and create a table. The query to create a table is as follows\"\n },\n {\n \"code\": null,\n \"e\": 1428,\n \"s\": 1218,\n \"text\": \"mysql> create table selectDistinctDemo\\n -> (\\n -> InstructorId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\\n -> StudentId int,\\n -> TechnicalSubject varchar(100)\\n -> );\\nQuery OK, 0 rows affected (0.50 sec)\"\n },\n {\n \"code\": null,\n \"e\": 1507,\n \"s\": 1428,\n \"text\": \"Insert some records in the table using insert command. The query is as follows\"\n },\n {\n \"code\": null,\n \"e\": 2249,\n \"s\": 1507,\n \"text\": \"mysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(121,'Java');\\nQuery OK, 1 row affected (0.15 sec)\\nmysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(121,'MongoDB');\\nQuery OK, 1 row affected (0.16 sec)\\nmysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(121,'MySQL');\\nQuery OK, 1 row affected (0.15 sec)\\nmysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(298,'Python');\\nQuery OK, 1 row affected (0.11 sec)\\nmysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(298,'SQL Server');\\nQuery OK, 1 row affected (0.15 sec)\\nmysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(397,'C#');\\nQuery OK, 1 row affected (0.13 sec)\"\n },\n {\n \"code\": null,\n \"e\": 2334,\n \"s\": 2249,\n \"text\": \"Display all records from the table using a select statement. The query is as follows\"\n },\n {\n \"code\": null,\n \"e\": 2374,\n \"s\": 2334,\n \"text\": \"mysql> select *from selectDistinctDemo;\"\n },\n {\n \"code\": null,\n \"e\": 2402,\n \"s\": 2374,\n \"text\": \"The following is the output\"\n },\n {\n \"code\": null,\n \"e\": 2907,\n \"s\": 2402,\n \"text\": \"+--------------+-----------+------------------+\\n| InstructorId | StudentId | TechnicalSubject |\\n+--------------+-----------+------------------+\\n| 1 | 121 | Java |\\n| 2 | 121 | MongoDB |\\n| 3 | 121 | MySQL |\\n| 4 | 298 | Python |\\n| 5 | 298 | SQL Server |\\n| 6 | 397 | C# |\\n+--------------+-----------+------------------+\\n6 rows in set (0.00 sec)\"\n },\n {\n \"code\": null,\n \"e\": 2979,\n \"s\": 2907,\n \"text\": \"Here is the query to use select statement DISTINCT for multiple columns\"\n },\n {\n \"code\": null,\n \"e\": 3209,\n \"s\": 2979,\n \"text\": \"mysql> select InstructorId,StudentId,TechnicalSubject from selectDistinctDemo\\n-> where InstructorId IN\\n -> (\\n -> select max(InstructorId) from selectDistinctDemo\\n -> group by StudentId\\n -> )\\n-> order by InstructorId desc;\"\n },\n {\n \"code\": null,\n \"e\": 3237,\n \"s\": 3209,\n \"text\": \"The following is the output\"\n },\n {\n \"code\": null,\n \"e\": 3598,\n \"s\": 3237,\n \"text\": \"+--------------+-----------+------------------+\\n| InstructorId | StudentId | TechnicalSubject |\\n+--------------+-----------+------------------+\\n| 6 | 397 | C# |\\n| 5 | 298 | SQL Server |\\n| 3 | 121 | MySQL |\\n+--------------+-----------+------------------+\\n3 rows in set (0.10 sec)\"\n }\n]"}}},{"rowIdx":412,"cells":{"title":{"kind":"string","value":"3 Super Simple Projects to Learn Natural Language Processing using Python | by Eric Kleppen | Towards Data Science"},"text":{"kind":"string","value":"Working in Data Science and having a background in Technical Writing, I was drawn to the field of Natural Language Processing (NLP). Machines understanding language fascinates me, and I often ponder which algorithms Aristotle would have used to build a rhetorical analysis machine if he had the chance. If you’re new to Data Science, getting into NLP can seem complicated, especially since there have been so many recent advancements in the field. It is hard to know where to start.\nThese three super simple projects will give you an introduction to concepts and techniques used in Natural Language Processing.\nWord CloudSentiment AnalysisSpam Detection\nThe data used for these projects is the spam email data set, and it can be found with all of the code in my GitHub:\ngithub.com\nWhile a computer can actually be quite good at finding patterns and summarizing documents, it must transform words into numbers before making sense of them. This transformation is needed because machines “learn” thanks to mathematics, and math doesn’t work very well on words. Before transforming the words into numbers, they are often cleaned of things like special characters and punctuation, and modified into forms that make them more uniform and interpretable.\nCleaning the words is often called preprocessing, and that is the focus of project 1: Word Cloud.\nStart by importing the dependencies and the data. The data is stored as a comma separated values (csv) file, so I will use pandas’ read_csv() function to open it into a DataFrame.\nimport pandas as pdimport sqlite3import regex as reimport matplotlib.pyplot as pltfrom wordcloud import WordCloud#create dataframe from csvdf = pd.read_csv('emails.csv')df.head()\nBefore anything, it is best to do a quick analysis of the data to eliminate duplicate rows and establish some baseline counts. I use pandas drop_duplicates to drop the duplicate rows.\nprint(\"spam count: \" +str(len(df.loc[df.spam==1])))print(\"not spam count: \" +str(len(df.loc[df.spam==0])))print(df.shape)df['spam'] = df['spam'].astype(int)df = df.drop_duplicates()df = df.reset_index(inplace = False)[['text','spam']]print(df.shape)\nWord clouds are a useful way to visualize text data because they make understanding word frequencies easier. Words that appear more frequently within the email text appear larger in the cloud. Word Clouds make it easy to identify “key words.”\nNotice in the word cloud image, all the text is lower case. There are no punctuation marks or special characters. That’s because the text has been cleaned to make it easier to analyze. Using regular expressions, it is easy to clean the text using a loop:\nclean_desc = []for w in range(len(df.text)): desc = df['text'][w].lower() #remove punctuation desc = re.sub('[^a-zA-Z]', ' ', desc) #remove tags desc=re.sub(\"&lt;/?.*?&gt;\",\" &lt;&gt; \",desc) #remove digits and special chars desc=re.sub(\"(\\\\d|\\\\W)+\",\" \",desc) clean_desc.append(desc)#assign the cleaned descriptions to the data framedf['text'] = clean_desc df.head(3)\nNotice I create an empty list clean_desc, then use a for loop to go through the text line by line, setting it to lower case, removing punctuation and special chars, and appending it to the list. Then I replace the text column with the data in the clean_desc list.\nStop words are the most common words like “the” and “of.” Removing them from the email text allows the more relevant frequent words to stand out. Removing stop words is a common technique! Some Python libraries like NLTK come pre-loaded with a list of stop words, but it is easy to create one from scratch.\nstop_words = ['is','you','your','and', 'the', 'to', 'from', 'or', 'I', 'for', 'do', 'get', 'not', 'here', 'in', 'im', 'have', 'on', 're', 'new', 'subject']\nNotice I include a few email related words like “re” and “subject.” It is up to the analyst to determine what words should be included or excluded. Sometimes it is beneficial to include all words!\nConveniently there is a Python library for creating word clouds. It can be installed using pip.\npip install wordcloud\nWhen constructing the word cloud, it is possible to set several parameters like height and width, stop words, and max words. It is even possible to shape it instead of displaying the default rectangle.\nwordcloud = WordCloud(width = 800, height = 800, background_color = 'black', stopwords = stop_words, max_words = 1000 , min_font_size = 20).generate(str(df1['text']))#plot the word cloudfig = plt.figure(figsize = (8,8), facecolor = None)plt.imshow(wordcloud)plt.axis('off')plt.show()\nThe word cloud can be saved and displayed using matplotlib and .show(). This is the result of all records, regardless of it being spam.\nPush the exercise further by splitting the data frame and making two word clouds to help analyze the difference between key words used in spam email and not spam email.\nThis is a binary classification problem since an email can either be spam (1) or not spam (0). I want to build a machine learneing model that can identify whether or not an email is spam. I am going to use the Python library Scikit-Learn to explore tokenization, vectorization, and statistical classification algorithms.\nImport the Scikit-Learn functionality we need to transform and model the data. I will use CountVectorizer, train_test_split, ensemble models, and a couple metrics.\nfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.model_selection import train_test_splitfrom sklearn import ensemble from sklearn.metrics import classification_report, accuracy_score\nIn project 1, the text was cleaned. When you look at a word cloud, notice it is primarily single words. The larger the word, the higher its frequency. To prevent the word cloud from outputting sentences, the text goes through a processes called tokenization. It is the process of breaking down a sentence into the individual words. The individual words are called tokens.\nUsing SciKit-Learn’s CountVectorizer(), it is easy to transform the body of text into a sparse matrix of numbers that the computer can pass to machine learning algorithms. To simplify the concept of count vectorization, imagine you have two sentences:\nThe dog is whiteThe cat is black\nConverting the sentences to a vector space model would transform them in such a way that looks at the words in all sentences, and then represents the words in the sentence with a number.\nThe dog cat is white blackThe dog is white = [1,1,0,1,1,0]The cat is black = [1,0,1,1,0,1]\nWe can show this using code as well. I’ll add a third sentence to show that it counts the tokens.\n#list of sentencestext = [\"the dog is white\", \"the cat is black\", \"the cat and the dog are friends\"]#instantiate the classcv = CountVectorizer()#tokenize and build vocabcv.fit(text)print(cv.vocabulary_)#transform the textvector = cv.transform(text)print(vector.toarray())\nNotice in the last vector, you can see a 2 since the word “the” appears twice. The CountVectorizer is counting the tokens and allowing me to construct the sparse matrix containing the transformed words to numbers.\nBecause the model doesn’t take word placement into account, and instead mixes the words up as if they were tiles in a scrabble game, this is called the bag of words method. I am going to create the sparse matrix, then split the data using sk-learn train_test_split().\ntext_vec = CountVectorizer().fit_transform(df['text'])X_train, X_test, y_train, y_test = train_test_split(text_vec, df['spam'], test_size = 0.45, random_state = 42, shuffle = True)\nNotice I set the sparse matrix text_vec to X and the df[‘spam’] column to Y. I shuffle and take a test size of 45%.\nI highly recommend experimenting with several classifiers and determine which one works best for this scenario. In this example, I am using the GradientBoostingClassifier() model from the Scikit-Learn Ensemble collection.\nclassifier = ensemble.GradientBoostingClassifier( n_estimators = 100, #how many decision trees to build learning_rate = 0.5, #learning rate max_depth = 6)\nEach algorithm will have its own set of parameters you can tweak. That is called hyper-parameter tuning. Go through the documentation to learn more about each of the parameters used in the models.\nFinally, we fit the data, call predict and generate the classification report. Using classification_report(), it is easy to build a text report showing the main classification metrics.\nclassifier.fit(X_train, y_train)predictions = classifier.predict(X_test)print(classification_report(y_test, predictions))\nNotice our model achieved 97% accuracy. Push the exercise further by tweaking the hyper-parameters, exploring different classifiers, and trying different vectorizers!\nSentiment Analysis is also a classification problem of sorts. The text is essentially going to reflect a positive, neutral, or negative sentiment. That is referred to as the polarity of the text. It is also possible to gauge and account for the subjectivity of the text! There are a ton of great resources that cover the theory behind sentiment analysis.\nInstead of building another model, this project uses a simple, out of box tool to analyze sentiment called TextBlob. I’ll use TextBlob to add sentiment columns to the DataFrame so it can be analyzed.\nBuilt on top of NLTK and pattern, the TextBlob library for Python 2 and 3 tries to simplify several text processing tasks. It provides tools for classification, part-of-speech tagging, noun phrase extraction, sentiment analysis and more. Install it using pip and check out the installation guide.\npip install -U textblobpython -m textblob.download_corpora\nUsing the sentiment property, TextBlob returns a named tuple of the form Sentiment(polarity, subjectivity). Polarity is a float in the range [-1.0, 1.0] where -1 is the most negative and 1 is the most positive. Subjectivity is a float in the range [0.0, 1.0] where 0.0 is very objective and 1.0 is very subjective.\nblob = TextBlob(\"This is a good example of a TextBlob\")print(blob)blob.sentiment#Sentiment(polarity=0.7, subjectivity=0.6000000000000001)\nUsing list comprehensions, it is easy to load the text column as a TextBlob, and then create two new columns to store the Polarity and Subjectivity.\n#load the descriptions into textblobemail_blob = [TextBlob(text) for text in df['text']]#add the sentiment metrics to the dataframedf['tb_Pol'] = [b.sentiment.polarity for b in email_blob]df['tb_Subj'] = [b.sentiment.subjectivity for b in email_blob]#show dataframedf.head(3)\nTextBlob makes it super simple to generate a baseline sentiment score for polarity and subjectivity. To push this exerciser further, see if you can add these new features to the spam detection model to increase the accuracy!\nEven though Natural Language Processing can seem like an intimidating topic, the foundational pieces are not that hard to grasp. There are plenty of libraries that make it easy to begin exploring data science and NLP. Completing these three projects:\nWord CloudSpam DetectionSentiment Analysis\nYou explore concrete examples of applying preprocessing, tokenization, vectorization, and feature engineering on text data.\nIf you’re interested in learning more about data science or programming, check out my other articles!\ntowardsdatascience.com\nIf you enjoyed this, follow me on Medium for more\nGet FULL ACCESS and help support my content by subscribing\nLet’s connect on LinkedIn\nAnalyze Data using Python? Check out my website\n— Eric Kleppen"},"parsed":{"kind":"list like","value":[{"code":null,"e":655,"s":172,"text":"Working in Data Science and having a background in Technical Writing, I was drawn to the field of Natural Language Processing (NLP). Machines understanding language fascinates me, and I often ponder which algorithms Aristotle would have used to build a rhetorical analysis machine if he had the chance. If you’re new to Data Science, getting into NLP can seem complicated, especially since there have been so many recent advancements in the field. It is hard to know where to start."},{"code":null,"e":783,"s":655,"text":"These three super simple projects will give you an introduction to concepts and techniques used in Natural Language Processing."},{"code":null,"e":826,"s":783,"text":"Word CloudSentiment AnalysisSpam Detection"},{"code":null,"e":942,"s":826,"text":"The data used for these projects is the spam email data set, and it can be found with all of the code in my GitHub:"},{"code":null,"e":953,"s":942,"text":"github.com"},{"code":null,"e":1419,"s":953,"text":"While a computer can actually be quite good at finding patterns and summarizing documents, it must transform words into numbers before making sense of them. This transformation is needed because machines “learn” thanks to mathematics, and math doesn’t work very well on words. Before transforming the words into numbers, they are often cleaned of things like special characters and punctuation, and modified into forms that make them more uniform and interpretable."},{"code":null,"e":1517,"s":1419,"text":"Cleaning the words is often called preprocessing, and that is the focus of project 1: Word Cloud."},{"code":null,"e":1697,"s":1517,"text":"Start by importing the dependencies and the data. The data is stored as a comma separated values (csv) file, so I will use pandas’ read_csv() function to open it into a DataFrame."},{"code":null,"e":1876,"s":1697,"text":"import pandas as pdimport sqlite3import regex as reimport matplotlib.pyplot as pltfrom wordcloud import WordCloud#create dataframe from csvdf = pd.read_csv('emails.csv')df.head()"},{"code":null,"e":2060,"s":1876,"text":"Before anything, it is best to do a quick analysis of the data to eliminate duplicate rows and establish some baseline counts. I use pandas drop_duplicates to drop the duplicate rows."},{"code":null,"e":2310,"s":2060,"text":"print(\"spam count: \" +str(len(df.loc[df.spam==1])))print(\"not spam count: \" +str(len(df.loc[df.spam==0])))print(df.shape)df['spam'] = df['spam'].astype(int)df = df.drop_duplicates()df = df.reset_index(inplace = False)[['text','spam']]print(df.shape)"},{"code":null,"e":2553,"s":2310,"text":"Word clouds are a useful way to visualize text data because they make understanding word frequencies easier. Words that appear more frequently within the email text appear larger in the cloud. Word Clouds make it easy to identify “key words.”"},{"code":null,"e":2808,"s":2553,"text":"Notice in the word cloud image, all the text is lower case. There are no punctuation marks or special characters. That’s because the text has been cleaned to make it easier to analyze. Using regular expressions, it is easy to clean the text using a loop:"},{"code":null,"e":3223,"s":2808,"text":"clean_desc = []for w in range(len(df.text)): desc = df['text'][w].lower() #remove punctuation desc = re.sub('[^a-zA-Z]', ' ', desc) #remove tags desc=re.sub(\"&lt;/?.*?&gt;\",\" &lt;&gt; \",desc) #remove digits and special chars desc=re.sub(\"(\\\\d|\\\\W)+\",\" \",desc) clean_desc.append(desc)#assign the cleaned descriptions to the data framedf['text'] = clean_desc df.head(3)"},{"code":null,"e":3487,"s":3223,"text":"Notice I create an empty list clean_desc, then use a for loop to go through the text line by line, setting it to lower case, removing punctuation and special chars, and appending it to the list. Then I replace the text column with the data in the clean_desc list."},{"code":null,"e":3794,"s":3487,"text":"Stop words are the most common words like “the” and “of.” Removing them from the email text allows the more relevant frequent words to stand out. Removing stop words is a common technique! Some Python libraries like NLTK come pre-loaded with a list of stop words, but it is easy to create one from scratch."},{"code":null,"e":3950,"s":3794,"text":"stop_words = ['is','you','your','and', 'the', 'to', 'from', 'or', 'I', 'for', 'do', 'get', 'not', 'here', 'in', 'im', 'have', 'on', 're', 'new', 'subject']"},{"code":null,"e":4147,"s":3950,"text":"Notice I include a few email related words like “re” and “subject.” It is up to the analyst to determine what words should be included or excluded. Sometimes it is beneficial to include all words!"},{"code":null,"e":4243,"s":4147,"text":"Conveniently there is a Python library for creating word clouds. It can be installed using pip."},{"code":null,"e":4265,"s":4243,"text":"pip install wordcloud"},{"code":null,"e":4467,"s":4265,"text":"When constructing the word cloud, it is possible to set several parameters like height and width, stop words, and max words. It is even possible to shape it instead of displaying the default rectangle."},{"code":null,"e":4772,"s":4467,"text":"wordcloud = WordCloud(width = 800, height = 800, background_color = 'black', stopwords = stop_words, max_words = 1000 , min_font_size = 20).generate(str(df1['text']))#plot the word cloudfig = plt.figure(figsize = (8,8), facecolor = None)plt.imshow(wordcloud)plt.axis('off')plt.show()"},{"code":null,"e":4908,"s":4772,"text":"The word cloud can be saved and displayed using matplotlib and .show(). This is the result of all records, regardless of it being spam."},{"code":null,"e":5077,"s":4908,"text":"Push the exercise further by splitting the data frame and making two word clouds to help analyze the difference between key words used in spam email and not spam email."},{"code":null,"e":5398,"s":5077,"text":"This is a binary classification problem since an email can either be spam (1) or not spam (0). I want to build a machine learneing model that can identify whether or not an email is spam. I am going to use the Python library Scikit-Learn to explore tokenization, vectorization, and statistical classification algorithms."},{"code":null,"e":5562,"s":5398,"text":"Import the Scikit-Learn functionality we need to transform and model the data. I will use CountVectorizer, train_test_split, ensemble models, and a couple metrics."},{"code":null,"e":5768,"s":5562,"text":"from sklearn.feature_extraction.text import CountVectorizerfrom sklearn.model_selection import train_test_splitfrom sklearn import ensemble from sklearn.metrics import classification_report, accuracy_score"},{"code":null,"e":6140,"s":5768,"text":"In project 1, the text was cleaned. When you look at a word cloud, notice it is primarily single words. The larger the word, the higher its frequency. To prevent the word cloud from outputting sentences, the text goes through a processes called tokenization. It is the process of breaking down a sentence into the individual words. The individual words are called tokens."},{"code":null,"e":6392,"s":6140,"text":"Using SciKit-Learn’s CountVectorizer(), it is easy to transform the body of text into a sparse matrix of numbers that the computer can pass to machine learning algorithms. To simplify the concept of count vectorization, imagine you have two sentences:"},{"code":null,"e":6425,"s":6392,"text":"The dog is whiteThe cat is black"},{"code":null,"e":6612,"s":6425,"text":"Converting the sentences to a vector space model would transform them in such a way that looks at the words in all sentences, and then represents the words in the sentence with a number."},{"code":null,"e":6703,"s":6612,"text":"The dog cat is white blackThe dog is white = [1,1,0,1,1,0]The cat is black = [1,0,1,1,0,1]"},{"code":null,"e":6801,"s":6703,"text":"We can show this using code as well. I’ll add a third sentence to show that it counts the tokens."},{"code":null,"e":7073,"s":6801,"text":"#list of sentencestext = [\"the dog is white\", \"the cat is black\", \"the cat and the dog are friends\"]#instantiate the classcv = CountVectorizer()#tokenize and build vocabcv.fit(text)print(cv.vocabulary_)#transform the textvector = cv.transform(text)print(vector.toarray())"},{"code":null,"e":7287,"s":7073,"text":"Notice in the last vector, you can see a 2 since the word “the” appears twice. The CountVectorizer is counting the tokens and allowing me to construct the sparse matrix containing the transformed words to numbers."},{"code":null,"e":7555,"s":7287,"text":"Because the model doesn’t take word placement into account, and instead mixes the words up as if they were tiles in a scrabble game, this is called the bag of words method. I am going to create the sparse matrix, then split the data using sk-learn train_test_split()."},{"code":null,"e":7736,"s":7555,"text":"text_vec = CountVectorizer().fit_transform(df['text'])X_train, X_test, y_train, y_test = train_test_split(text_vec, df['spam'], test_size = 0.45, random_state = 42, shuffle = True)"},{"code":null,"e":7852,"s":7736,"text":"Notice I set the sparse matrix text_vec to X and the df[‘spam’] column to Y. I shuffle and take a test size of 45%."},{"code":null,"e":8074,"s":7852,"text":"I highly recommend experimenting with several classifiers and determine which one works best for this scenario. In this example, I am using the GradientBoostingClassifier() model from the Scikit-Learn Ensemble collection."},{"code":null,"e":8238,"s":8074,"text":"classifier = ensemble.GradientBoostingClassifier( n_estimators = 100, #how many decision trees to build learning_rate = 0.5, #learning rate max_depth = 6)"},{"code":null,"e":8435,"s":8238,"text":"Each algorithm will have its own set of parameters you can tweak. That is called hyper-parameter tuning. Go through the documentation to learn more about each of the parameters used in the models."},{"code":null,"e":8620,"s":8435,"text":"Finally, we fit the data, call predict and generate the classification report. Using classification_report(), it is easy to build a text report showing the main classification metrics."},{"code":null,"e":8742,"s":8620,"text":"classifier.fit(X_train, y_train)predictions = classifier.predict(X_test)print(classification_report(y_test, predictions))"},{"code":null,"e":8909,"s":8742,"text":"Notice our model achieved 97% accuracy. Push the exercise further by tweaking the hyper-parameters, exploring different classifiers, and trying different vectorizers!"},{"code":null,"e":9264,"s":8909,"text":"Sentiment Analysis is also a classification problem of sorts. The text is essentially going to reflect a positive, neutral, or negative sentiment. That is referred to as the polarity of the text. It is also possible to gauge and account for the subjectivity of the text! There are a ton of great resources that cover the theory behind sentiment analysis."},{"code":null,"e":9464,"s":9264,"text":"Instead of building another model, this project uses a simple, out of box tool to analyze sentiment called TextBlob. I’ll use TextBlob to add sentiment columns to the DataFrame so it can be analyzed."},{"code":null,"e":9761,"s":9464,"text":"Built on top of NLTK and pattern, the TextBlob library for Python 2 and 3 tries to simplify several text processing tasks. It provides tools for classification, part-of-speech tagging, noun phrase extraction, sentiment analysis and more. Install it using pip and check out the installation guide."},{"code":null,"e":9820,"s":9761,"text":"pip install -U textblobpython -m textblob.download_corpora"},{"code":null,"e":10135,"s":9820,"text":"Using the sentiment property, TextBlob returns a named tuple of the form Sentiment(polarity, subjectivity). Polarity is a float in the range [-1.0, 1.0] where -1 is the most negative and 1 is the most positive. Subjectivity is a float in the range [0.0, 1.0] where 0.0 is very objective and 1.0 is very subjective."},{"code":null,"e":10273,"s":10135,"text":"blob = TextBlob(\"This is a good example of a TextBlob\")print(blob)blob.sentiment#Sentiment(polarity=0.7, subjectivity=0.6000000000000001)"},{"code":null,"e":10422,"s":10273,"text":"Using list comprehensions, it is easy to load the text column as a TextBlob, and then create two new columns to store the Polarity and Subjectivity."},{"code":null,"e":10698,"s":10422,"text":"#load the descriptions into textblobemail_blob = [TextBlob(text) for text in df['text']]#add the sentiment metrics to the dataframedf['tb_Pol'] = [b.sentiment.polarity for b in email_blob]df['tb_Subj'] = [b.sentiment.subjectivity for b in email_blob]#show dataframedf.head(3)"},{"code":null,"e":10923,"s":10698,"text":"TextBlob makes it super simple to generate a baseline sentiment score for polarity and subjectivity. To push this exerciser further, see if you can add these new features to the spam detection model to increase the accuracy!"},{"code":null,"e":11174,"s":10923,"text":"Even though Natural Language Processing can seem like an intimidating topic, the foundational pieces are not that hard to grasp. There are plenty of libraries that make it easy to begin exploring data science and NLP. Completing these three projects:"},{"code":null,"e":11217,"s":11174,"text":"Word CloudSpam DetectionSentiment Analysis"},{"code":null,"e":11341,"s":11217,"text":"You explore concrete examples of applying preprocessing, tokenization, vectorization, and feature engineering on text data."},{"code":null,"e":11443,"s":11341,"text":"If you’re interested in learning more about data science or programming, check out my other articles!"},{"code":null,"e":11466,"s":11443,"text":"towardsdatascience.com"},{"code":null,"e":11516,"s":11466,"text":"If you enjoyed this, follow me on Medium for more"},{"code":null,"e":11575,"s":11516,"text":"Get FULL ACCESS and help support my content by subscribing"},{"code":null,"e":11601,"s":11575,"text":"Let’s connect on LinkedIn"},{"code":null,"e":11649,"s":11601,"text":"Analyze Data using Python? Check out my website"}],"string":"[\n {\n \"code\": null,\n \"e\": 655,\n \"s\": 172,\n \"text\": \"Working in Data Science and having a background in Technical Writing, I was drawn to the field of Natural Language Processing (NLP). Machines understanding language fascinates me, and I often ponder which algorithms Aristotle would have used to build a rhetorical analysis machine if he had the chance. If you’re new to Data Science, getting into NLP can seem complicated, especially since there have been so many recent advancements in the field. It is hard to know where to start.\"\n },\n {\n \"code\": null,\n \"e\": 783,\n \"s\": 655,\n \"text\": \"These three super simple projects will give you an introduction to concepts and techniques used in Natural Language Processing.\"\n },\n {\n \"code\": null,\n \"e\": 826,\n \"s\": 783,\n \"text\": \"Word CloudSentiment AnalysisSpam Detection\"\n },\n {\n \"code\": null,\n \"e\": 942,\n \"s\": 826,\n \"text\": \"The data used for these projects is the spam email data set, and it can be found with all of the code in my GitHub:\"\n },\n {\n \"code\": null,\n \"e\": 953,\n \"s\": 942,\n \"text\": \"github.com\"\n },\n {\n \"code\": null,\n \"e\": 1419,\n \"s\": 953,\n \"text\": \"While a computer can actually be quite good at finding patterns and summarizing documents, it must transform words into numbers before making sense of them. This transformation is needed because machines “learn” thanks to mathematics, and math doesn’t work very well on words. Before transforming the words into numbers, they are often cleaned of things like special characters and punctuation, and modified into forms that make them more uniform and interpretable.\"\n },\n {\n \"code\": null,\n \"e\": 1517,\n \"s\": 1419,\n \"text\": \"Cleaning the words is often called preprocessing, and that is the focus of project 1: Word Cloud.\"\n },\n {\n \"code\": null,\n \"e\": 1697,\n \"s\": 1517,\n \"text\": \"Start by importing the dependencies and the data. The data is stored as a comma separated values (csv) file, so I will use pandas’ read_csv() function to open it into a DataFrame.\"\n },\n {\n \"code\": null,\n \"e\": 1876,\n \"s\": 1697,\n \"text\": \"import pandas as pdimport sqlite3import regex as reimport matplotlib.pyplot as pltfrom wordcloud import WordCloud#create dataframe from csvdf = pd.read_csv('emails.csv')df.head()\"\n },\n {\n \"code\": null,\n \"e\": 2060,\n \"s\": 1876,\n \"text\": \"Before anything, it is best to do a quick analysis of the data to eliminate duplicate rows and establish some baseline counts. I use pandas drop_duplicates to drop the duplicate rows.\"\n },\n {\n \"code\": null,\n \"e\": 2310,\n \"s\": 2060,\n \"text\": \"print(\\\"spam count: \\\" +str(len(df.loc[df.spam==1])))print(\\\"not spam count: \\\" +str(len(df.loc[df.spam==0])))print(df.shape)df['spam'] = df['spam'].astype(int)df = df.drop_duplicates()df = df.reset_index(inplace = False)[['text','spam']]print(df.shape)\"\n },\n {\n \"code\": null,\n \"e\": 2553,\n \"s\": 2310,\n \"text\": \"Word clouds are a useful way to visualize text data because they make understanding word frequencies easier. Words that appear more frequently within the email text appear larger in the cloud. Word Clouds make it easy to identify “key words.”\"\n },\n {\n \"code\": null,\n \"e\": 2808,\n \"s\": 2553,\n \"text\": \"Notice in the word cloud image, all the text is lower case. There are no punctuation marks or special characters. That’s because the text has been cleaned to make it easier to analyze. Using regular expressions, it is easy to clean the text using a loop:\"\n },\n {\n \"code\": null,\n \"e\": 3223,\n \"s\": 2808,\n \"text\": \"clean_desc = []for w in range(len(df.text)): desc = df['text'][w].lower() #remove punctuation desc = re.sub('[^a-zA-Z]', ' ', desc) #remove tags desc=re.sub(\\\"&lt;/?.*?&gt;\\\",\\\" &lt;&gt; \\\",desc) #remove digits and special chars desc=re.sub(\\\"(\\\\\\\\d|\\\\\\\\W)+\\\",\\\" \\\",desc) clean_desc.append(desc)#assign the cleaned descriptions to the data framedf['text'] = clean_desc df.head(3)\"\n },\n {\n \"code\": null,\n \"e\": 3487,\n \"s\": 3223,\n \"text\": \"Notice I create an empty list clean_desc, then use a for loop to go through the text line by line, setting it to lower case, removing punctuation and special chars, and appending it to the list. Then I replace the text column with the data in the clean_desc list.\"\n },\n {\n \"code\": null,\n \"e\": 3794,\n \"s\": 3487,\n \"text\": \"Stop words are the most common words like “the” and “of.” Removing them from the email text allows the more relevant frequent words to stand out. Removing stop words is a common technique! Some Python libraries like NLTK come pre-loaded with a list of stop words, but it is easy to create one from scratch.\"\n },\n {\n \"code\": null,\n \"e\": 3950,\n \"s\": 3794,\n \"text\": \"stop_words = ['is','you','your','and', 'the', 'to', 'from', 'or', 'I', 'for', 'do', 'get', 'not', 'here', 'in', 'im', 'have', 'on', 're', 'new', 'subject']\"\n },\n {\n \"code\": null,\n \"e\": 4147,\n \"s\": 3950,\n \"text\": \"Notice I include a few email related words like “re” and “subject.” It is up to the analyst to determine what words should be included or excluded. Sometimes it is beneficial to include all words!\"\n },\n {\n \"code\": null,\n \"e\": 4243,\n \"s\": 4147,\n \"text\": \"Conveniently there is a Python library for creating word clouds. It can be installed using pip.\"\n },\n {\n \"code\": null,\n \"e\": 4265,\n \"s\": 4243,\n \"text\": \"pip install wordcloud\"\n },\n {\n \"code\": null,\n \"e\": 4467,\n \"s\": 4265,\n \"text\": \"When constructing the word cloud, it is possible to set several parameters like height and width, stop words, and max words. It is even possible to shape it instead of displaying the default rectangle.\"\n },\n {\n \"code\": null,\n \"e\": 4772,\n \"s\": 4467,\n \"text\": \"wordcloud = WordCloud(width = 800, height = 800, background_color = 'black', stopwords = stop_words, max_words = 1000 , min_font_size = 20).generate(str(df1['text']))#plot the word cloudfig = plt.figure(figsize = (8,8), facecolor = None)plt.imshow(wordcloud)plt.axis('off')plt.show()\"\n },\n {\n \"code\": null,\n \"e\": 4908,\n \"s\": 4772,\n \"text\": \"The word cloud can be saved and displayed using matplotlib and .show(). This is the result of all records, regardless of it being spam.\"\n },\n {\n \"code\": null,\n \"e\": 5077,\n \"s\": 4908,\n \"text\": \"Push the exercise further by splitting the data frame and making two word clouds to help analyze the difference between key words used in spam email and not spam email.\"\n },\n {\n \"code\": null,\n \"e\": 5398,\n \"s\": 5077,\n \"text\": \"This is a binary classification problem since an email can either be spam (1) or not spam (0). I want to build a machine learneing model that can identify whether or not an email is spam. I am going to use the Python library Scikit-Learn to explore tokenization, vectorization, and statistical classification algorithms.\"\n },\n {\n \"code\": null,\n \"e\": 5562,\n \"s\": 5398,\n \"text\": \"Import the Scikit-Learn functionality we need to transform and model the data. I will use CountVectorizer, train_test_split, ensemble models, and a couple metrics.\"\n },\n {\n \"code\": null,\n \"e\": 5768,\n \"s\": 5562,\n \"text\": \"from sklearn.feature_extraction.text import CountVectorizerfrom sklearn.model_selection import train_test_splitfrom sklearn import ensemble from sklearn.metrics import classification_report, accuracy_score\"\n },\n {\n \"code\": null,\n \"e\": 6140,\n \"s\": 5768,\n \"text\": \"In project 1, the text was cleaned. When you look at a word cloud, notice it is primarily single words. The larger the word, the higher its frequency. To prevent the word cloud from outputting sentences, the text goes through a processes called tokenization. It is the process of breaking down a sentence into the individual words. The individual words are called tokens.\"\n },\n {\n \"code\": null,\n \"e\": 6392,\n \"s\": 6140,\n \"text\": \"Using SciKit-Learn’s CountVectorizer(), it is easy to transform the body of text into a sparse matrix of numbers that the computer can pass to machine learning algorithms. To simplify the concept of count vectorization, imagine you have two sentences:\"\n },\n {\n \"code\": null,\n \"e\": 6425,\n \"s\": 6392,\n \"text\": \"The dog is whiteThe cat is black\"\n },\n {\n \"code\": null,\n \"e\": 6612,\n \"s\": 6425,\n \"text\": \"Converting the sentences to a vector space model would transform them in such a way that looks at the words in all sentences, and then represents the words in the sentence with a number.\"\n },\n {\n \"code\": null,\n \"e\": 6703,\n \"s\": 6612,\n \"text\": \"The dog cat is white blackThe dog is white = [1,1,0,1,1,0]The cat is black = [1,0,1,1,0,1]\"\n },\n {\n \"code\": null,\n \"e\": 6801,\n \"s\": 6703,\n \"text\": \"We can show this using code as well. I’ll add a third sentence to show that it counts the tokens.\"\n },\n {\n \"code\": null,\n \"e\": 7073,\n \"s\": 6801,\n \"text\": \"#list of sentencestext = [\\\"the dog is white\\\", \\\"the cat is black\\\", \\\"the cat and the dog are friends\\\"]#instantiate the classcv = CountVectorizer()#tokenize and build vocabcv.fit(text)print(cv.vocabulary_)#transform the textvector = cv.transform(text)print(vector.toarray())\"\n },\n {\n \"code\": null,\n \"e\": 7287,\n \"s\": 7073,\n \"text\": \"Notice in the last vector, you can see a 2 since the word “the” appears twice. The CountVectorizer is counting the tokens and allowing me to construct the sparse matrix containing the transformed words to numbers.\"\n },\n {\n \"code\": null,\n \"e\": 7555,\n \"s\": 7287,\n \"text\": \"Because the model doesn’t take word placement into account, and instead mixes the words up as if they were tiles in a scrabble game, this is called the bag of words method. I am going to create the sparse matrix, then split the data using sk-learn train_test_split().\"\n },\n {\n \"code\": null,\n \"e\": 7736,\n \"s\": 7555,\n \"text\": \"text_vec = CountVectorizer().fit_transform(df['text'])X_train, X_test, y_train, y_test = train_test_split(text_vec, df['spam'], test_size = 0.45, random_state = 42, shuffle = True)\"\n },\n {\n \"code\": null,\n \"e\": 7852,\n \"s\": 7736,\n \"text\": \"Notice I set the sparse matrix text_vec to X and the df[‘spam’] column to Y. I shuffle and take a test size of 45%.\"\n },\n {\n \"code\": null,\n \"e\": 8074,\n \"s\": 7852,\n \"text\": \"I highly recommend experimenting with several classifiers and determine which one works best for this scenario. In this example, I am using the GradientBoostingClassifier() model from the Scikit-Learn Ensemble collection.\"\n },\n {\n \"code\": null,\n \"e\": 8238,\n \"s\": 8074,\n \"text\": \"classifier = ensemble.GradientBoostingClassifier( n_estimators = 100, #how many decision trees to build learning_rate = 0.5, #learning rate max_depth = 6)\"\n },\n {\n \"code\": null,\n \"e\": 8435,\n \"s\": 8238,\n \"text\": \"Each algorithm will have its own set of parameters you can tweak. That is called hyper-parameter tuning. Go through the documentation to learn more about each of the parameters used in the models.\"\n },\n {\n \"code\": null,\n \"e\": 8620,\n \"s\": 8435,\n \"text\": \"Finally, we fit the data, call predict and generate the classification report. Using classification_report(), it is easy to build a text report showing the main classification metrics.\"\n },\n {\n \"code\": null,\n \"e\": 8742,\n \"s\": 8620,\n \"text\": \"classifier.fit(X_train, y_train)predictions = classifier.predict(X_test)print(classification_report(y_test, predictions))\"\n },\n {\n \"code\": null,\n \"e\": 8909,\n \"s\": 8742,\n \"text\": \"Notice our model achieved 97% accuracy. Push the exercise further by tweaking the hyper-parameters, exploring different classifiers, and trying different vectorizers!\"\n },\n {\n \"code\": null,\n \"e\": 9264,\n \"s\": 8909,\n \"text\": \"Sentiment Analysis is also a classification problem of sorts. The text is essentially going to reflect a positive, neutral, or negative sentiment. That is referred to as the polarity of the text. It is also possible to gauge and account for the subjectivity of the text! There are a ton of great resources that cover the theory behind sentiment analysis.\"\n },\n {\n \"code\": null,\n \"e\": 9464,\n \"s\": 9264,\n \"text\": \"Instead of building another model, this project uses a simple, out of box tool to analyze sentiment called TextBlob. I’ll use TextBlob to add sentiment columns to the DataFrame so it can be analyzed.\"\n },\n {\n \"code\": null,\n \"e\": 9761,\n \"s\": 9464,\n \"text\": \"Built on top of NLTK and pattern, the TextBlob library for Python 2 and 3 tries to simplify several text processing tasks. It provides tools for classification, part-of-speech tagging, noun phrase extraction, sentiment analysis and more. Install it using pip and check out the installation guide.\"\n },\n {\n \"code\": null,\n \"e\": 9820,\n \"s\": 9761,\n \"text\": \"pip install -U textblobpython -m textblob.download_corpora\"\n },\n {\n \"code\": null,\n \"e\": 10135,\n \"s\": 9820,\n \"text\": \"Using the sentiment property, TextBlob returns a named tuple of the form Sentiment(polarity, subjectivity). Polarity is a float in the range [-1.0, 1.0] where -1 is the most negative and 1 is the most positive. Subjectivity is a float in the range [0.0, 1.0] where 0.0 is very objective and 1.0 is very subjective.\"\n },\n {\n \"code\": null,\n \"e\": 10273,\n \"s\": 10135,\n \"text\": \"blob = TextBlob(\\\"This is a good example of a TextBlob\\\")print(blob)blob.sentiment#Sentiment(polarity=0.7, subjectivity=0.6000000000000001)\"\n },\n {\n \"code\": null,\n \"e\": 10422,\n \"s\": 10273,\n \"text\": \"Using list comprehensions, it is easy to load the text column as a TextBlob, and then create two new columns to store the Polarity and Subjectivity.\"\n },\n {\n \"code\": null,\n \"e\": 10698,\n \"s\": 10422,\n \"text\": \"#load the descriptions into textblobemail_blob = [TextBlob(text) for text in df['text']]#add the sentiment metrics to the dataframedf['tb_Pol'] = [b.sentiment.polarity for b in email_blob]df['tb_Subj'] = [b.sentiment.subjectivity for b in email_blob]#show dataframedf.head(3)\"\n },\n {\n \"code\": null,\n \"e\": 10923,\n \"s\": 10698,\n \"text\": \"TextBlob makes it super simple to generate a baseline sentiment score for polarity and subjectivity. To push this exerciser further, see if you can add these new features to the spam detection model to increase the accuracy!\"\n },\n {\n \"code\": null,\n \"e\": 11174,\n \"s\": 10923,\n \"text\": \"Even though Natural Language Processing can seem like an intimidating topic, the foundational pieces are not that hard to grasp. There are plenty of libraries that make it easy to begin exploring data science and NLP. Completing these three projects:\"\n },\n {\n \"code\": null,\n \"e\": 11217,\n \"s\": 11174,\n \"text\": \"Word CloudSpam DetectionSentiment Analysis\"\n },\n {\n \"code\": null,\n \"e\": 11341,\n \"s\": 11217,\n \"text\": \"You explore concrete examples of applying preprocessing, tokenization, vectorization, and feature engineering on text data.\"\n },\n {\n \"code\": null,\n \"e\": 11443,\n \"s\": 11341,\n \"text\": \"If you’re interested in learning more about data science or programming, check out my other articles!\"\n },\n {\n \"code\": null,\n \"e\": 11466,\n \"s\": 11443,\n \"text\": \"towardsdatascience.com\"\n },\n {\n \"code\": null,\n \"e\": 11516,\n \"s\": 11466,\n \"text\": \"If you enjoyed this, follow me on Medium for more\"\n },\n {\n \"code\": null,\n \"e\": 11575,\n \"s\": 11516,\n \"text\": \"Get FULL ACCESS and help support my content by subscribing\"\n },\n {\n \"code\": null,\n \"e\": 11601,\n \"s\": 11575,\n \"text\": \"Let’s connect on LinkedIn\"\n },\n {\n \"code\": null,\n \"e\": 11649,\n \"s\": 11601,\n \"text\": \"Analyze Data using Python? Check out my website\"\n }\n]"}}},{"rowIdx":413,"cells":{"title":{"kind":"string","value":"How to get Source Code of any website ? - GeeksforGeeks"},"text":{"kind":"string","value":"11 Sep, 2021\nA Website is defined as a collection of web pages. A website can be designed using HTML, CSS, Bootstrap, etc. HTML language decides what will appear on the webpage and CSS language depicts how it will appear. In other words, HTML place elements on the webpage, and CSS styles it. Bootstrap is pre-compiled CSS. Suppose we see a website eg. geeksforgeeks.org, and we want its source code then there are two ways to get it:\nUsing Inspect Element (Ctrl + Shift + I )\nUsing View Page Source ( Ctrl + U )\nLet’s understand both methods one by one.\n1. Using Inspect Element \nBelow is the step-by-step implementation.\n \nStep 1: Visit your desired website eg geeksforgeeks.org.\nStep 2: Click on Inspect.\nStep 3: You will get code on right-hand side.\nShort Cut Key: \n(Ctrl + Shift + I )\n \n2. Using Page Source:\nStep 1: Visit your desired website eg geeksforgeeks.org.\nStep 2: Right click on website and click on “View Page Source”.\nStep 3: You will get source code as following. \nShortcut Key\nCTRL + U\nBlogathon-2021\nBlogathon\nWeb Technologies\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nHow to Import JSON Data into SQL Server?\nHow to Create a Table With Multiple Foreign Keys in SQL?\nHow to Install Tkinter in Windows?\nSQL Query to Convert Datetime to Date\nSQL Query to Create Table With a Primary Key\nRoadmap to Become a Web Developer in 2022\nInstallation of Node.js on Linux\nHow to fetch data from an API in ReactJS ?\nHow to insert spaces/tabs in text using HTML/CSS?\nTop 10 Projects For Beginners To Practice HTML and CSS Skills"},"parsed":{"kind":"list like","value":[{"code":null,"e":24814,"s":24786,"text":"\n11 Sep, 2021"},{"code":null,"e":25236,"s":24814,"text":"A Website is defined as a collection of web pages. A website can be designed using HTML, CSS, Bootstrap, etc. HTML language decides what will appear on the webpage and CSS language depicts how it will appear. In other words, HTML place elements on the webpage, and CSS styles it. Bootstrap is pre-compiled CSS. Suppose we see a website eg. geeksforgeeks.org, and we want its source code then there are two ways to get it:"},{"code":null,"e":25278,"s":25236,"text":"Using Inspect Element (Ctrl + Shift + I )"},{"code":null,"e":25314,"s":25278,"text":"Using View Page Source ( Ctrl + U )"},{"code":null,"e":25356,"s":25314,"text":"Let’s understand both methods one by one."},{"code":null,"e":25382,"s":25356,"text":"1. Using Inspect Element "},{"code":null,"e":25424,"s":25382,"text":"Below is the step-by-step implementation."},{"code":null,"e":25483,"s":25426,"text":"Step 1: Visit your desired website eg geeksforgeeks.org."},{"code":null,"e":25509,"s":25483,"text":"Step 2: Click on Inspect."},{"code":null,"e":25555,"s":25509,"text":"Step 3: You will get code on right-hand side."},{"code":null,"e":25571,"s":25555,"text":"Short Cut Key: "},{"code":null,"e":25591,"s":25571,"text":"(Ctrl + Shift + I )"},{"code":null,"e":25615,"s":25593,"text":"2. Using Page Source:"},{"code":null,"e":25672,"s":25615,"text":"Step 1: Visit your desired website eg geeksforgeeks.org."},{"code":null,"e":25736,"s":25672,"text":"Step 2: Right click on website and click on “View Page Source”."},{"code":null,"e":25784,"s":25736,"text":"Step 3: You will get source code as following. "},{"code":null,"e":25797,"s":25784,"text":"Shortcut Key"},{"code":null,"e":25806,"s":25797,"text":"CTRL + U"},{"code":null,"e":25821,"s":25806,"text":"Blogathon-2021"},{"code":null,"e":25831,"s":25821,"text":"Blogathon"},{"code":null,"e":25848,"s":25831,"text":"Web Technologies"},{"code":null,"e":25946,"s":25848,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":25987,"s":25946,"text":"How to Import JSON Data into SQL Server?"},{"code":null,"e":26044,"s":25987,"text":"How to Create a Table With Multiple Foreign Keys in SQL?"},{"code":null,"e":26079,"s":26044,"text":"How to Install Tkinter in Windows?"},{"code":null,"e":26117,"s":26079,"text":"SQL Query to Convert Datetime to Date"},{"code":null,"e":26162,"s":26117,"text":"SQL Query to Create Table With a Primary Key"},{"code":null,"e":26204,"s":26162,"text":"Roadmap to Become a Web Developer in 2022"},{"code":null,"e":26237,"s":26204,"text":"Installation of Node.js on Linux"},{"code":null,"e":26280,"s":26237,"text":"How to fetch data from an API in ReactJS ?"},{"code":null,"e":26330,"s":26280,"text":"How to insert spaces/tabs in text using HTML/CSS?"}],"string":"[\n {\n \"code\": null,\n \"e\": 24814,\n \"s\": 24786,\n \"text\": \"\\n11 Sep, 2021\"\n },\n {\n \"code\": null,\n \"e\": 25236,\n \"s\": 24814,\n \"text\": \"A Website is defined as a collection of web pages. A website can be designed using HTML, CSS, Bootstrap, etc. HTML language decides what will appear on the webpage and CSS language depicts how it will appear. In other words, HTML place elements on the webpage, and CSS styles it. Bootstrap is pre-compiled CSS. Suppose we see a website eg. geeksforgeeks.org, and we want its source code then there are two ways to get it:\"\n },\n {\n \"code\": null,\n \"e\": 25278,\n \"s\": 25236,\n \"text\": \"Using Inspect Element (Ctrl + Shift + I )\"\n },\n {\n \"code\": null,\n \"e\": 25314,\n \"s\": 25278,\n \"text\": \"Using View Page Source ( Ctrl + U )\"\n },\n {\n \"code\": null,\n \"e\": 25356,\n \"s\": 25314,\n \"text\": \"Let’s understand both methods one by one.\"\n },\n {\n \"code\": null,\n \"e\": 25382,\n \"s\": 25356,\n \"text\": \"1. Using Inspect Element \"\n },\n {\n \"code\": null,\n \"e\": 25424,\n \"s\": 25382,\n \"text\": \"Below is the step-by-step implementation.\"\n },\n {\n \"code\": null,\n \"e\": 25483,\n \"s\": 25426,\n \"text\": \"Step 1: Visit your desired website eg geeksforgeeks.org.\"\n },\n {\n \"code\": null,\n \"e\": 25509,\n \"s\": 25483,\n \"text\": \"Step 2: Click on Inspect.\"\n },\n {\n \"code\": null,\n \"e\": 25555,\n \"s\": 25509,\n \"text\": \"Step 3: You will get code on right-hand side.\"\n },\n {\n \"code\": null,\n \"e\": 25571,\n \"s\": 25555,\n \"text\": \"Short Cut Key: \"\n },\n {\n \"code\": null,\n \"e\": 25591,\n \"s\": 25571,\n \"text\": \"(Ctrl + Shift + I )\"\n },\n {\n \"code\": null,\n \"e\": 25615,\n \"s\": 25593,\n \"text\": \"2. Using Page Source:\"\n },\n {\n \"code\": null,\n \"e\": 25672,\n \"s\": 25615,\n \"text\": \"Step 1: Visit your desired website eg geeksforgeeks.org.\"\n },\n {\n \"code\": null,\n \"e\": 25736,\n \"s\": 25672,\n \"text\": \"Step 2: Right click on website and click on “View Page Source”.\"\n },\n {\n \"code\": null,\n \"e\": 25784,\n \"s\": 25736,\n \"text\": \"Step 3: You will get source code as following. \"\n },\n {\n \"code\": null,\n \"e\": 25797,\n \"s\": 25784,\n \"text\": \"Shortcut Key\"\n },\n {\n \"code\": null,\n \"e\": 25806,\n \"s\": 25797,\n \"text\": \"CTRL + U\"\n },\n {\n \"code\": null,\n \"e\": 25821,\n \"s\": 25806,\n \"text\": \"Blogathon-2021\"\n },\n {\n \"code\": null,\n \"e\": 25831,\n \"s\": 25821,\n \"text\": \"Blogathon\"\n },\n {\n \"code\": null,\n \"e\": 25848,\n \"s\": 25831,\n \"text\": \"Web Technologies\"\n },\n {\n \"code\": null,\n \"e\": 25946,\n \"s\": 25848,\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\": 25987,\n \"s\": 25946,\n \"text\": \"How to Import JSON Data into SQL Server?\"\n },\n {\n \"code\": null,\n \"e\": 26044,\n \"s\": 25987,\n \"text\": \"How to Create a Table With Multiple Foreign Keys in SQL?\"\n },\n {\n \"code\": null,\n \"e\": 26079,\n \"s\": 26044,\n \"text\": \"How to Install Tkinter in Windows?\"\n },\n {\n \"code\": null,\n \"e\": 26117,\n \"s\": 26079,\n \"text\": \"SQL Query to Convert Datetime to Date\"\n },\n {\n \"code\": null,\n \"e\": 26162,\n \"s\": 26117,\n \"text\": \"SQL Query to Create Table With a Primary Key\"\n },\n {\n \"code\": null,\n \"e\": 26204,\n \"s\": 26162,\n \"text\": \"Roadmap to Become a Web Developer in 2022\"\n },\n {\n \"code\": null,\n \"e\": 26237,\n \"s\": 26204,\n \"text\": \"Installation of Node.js on Linux\"\n },\n {\n \"code\": null,\n \"e\": 26280,\n \"s\": 26237,\n \"text\": \"How to fetch data from an API in ReactJS ?\"\n },\n {\n \"code\": null,\n \"e\": 26330,\n \"s\": 26280,\n \"text\": \"How to insert spaces/tabs in text using HTML/CSS?\"\n }\n]"}}},{"rowIdx":414,"cells":{"title":{"kind":"string","value":"Get unique values from a list in Python"},"text":{"kind":"string","value":"A list in python is a number of items placed with in [] which may or may not have same data types. It can also contain duplicates. In this article we will see how to extract only the unique values from a list.\nIn this approach we will first create a new empty list and then keep appending elements to this new list only if it is not already present in this new list. A for loop is used along with not in condition. It checks for the existence of the incoming element and it is appended only if it is not already present.\n Live Demo\ndef catch_unique(list_in):\n # intilize an empty list\n unq_list = []\n\n # Check for elements\n for x in list_in:\n # check if exists in unq_list\n if x not in unq_list:\n unq_list.append(x)\n # print list\n for x in unq_list:\n print(x)\n\nAlist = ['Mon', 'Tue', 'Mon', 'wed', 40, 40]\nprint(\"Unique values from the list is\")\ncatch_unique(Alist)\nRunning the above code gives us the following result −\nUnique values from the list is\nMon\nTue\nwed\n40\nA set only contains unique values. In this approach we convert the list to a set and then convert the set back to a list which holds all the unique elements.\n Live Demo\nAlist = ['Mon', 'Tue', 'Mon', 'wed', 40, 40]\nA_set = set(Alist)\nNew_List=list(A_set)\nprint(\"Unique values from the list is\")\nprint(New_List)\nRunning the above code gives us the following result −\nUnique values from the list is\n[40, 'Tue', 'wed', 'Mon']\nThe numpy library has a function named unique which does the straight job of taking the list as input and giving the unique elements as a new list.\n Live Demo\nimport numpy as np\n\nAlist = ['Mon', 'Tue', 'Mon', 'wed', 40, 40]\nprint(\"The unique values from list is: \")\nprint(np.unique(Alist))\nRunning the above code gives us the following result −\nThe unique values from list is:\n['40' 'Mon' 'Tue' 'wed']"},"parsed":{"kind":"list like","value":[{"code":null,"e":1272,"s":1062,"text":"A list in python is a number of items placed with in [] which may or may not have same data types. It can also contain duplicates. In this article we will see how to extract only the unique values from a list."},{"code":null,"e":1583,"s":1272,"text":"In this approach we will first create a new empty list and then keep appending elements to this new list only if it is not already present in this new list. A for loop is used along with not in condition. It checks for the existence of the incoming element and it is appended only if it is not already present."},{"code":null,"e":1594,"s":1583,"text":" Live Demo"},{"code":null,"e":1969,"s":1594,"text":"def catch_unique(list_in):\n # intilize an empty list\n unq_list = []\n\n # Check for elements\n for x in list_in:\n # check if exists in unq_list\n if x not in unq_list:\n unq_list.append(x)\n # print list\n for x in unq_list:\n print(x)\n\nAlist = ['Mon', 'Tue', 'Mon', 'wed', 40, 40]\nprint(\"Unique values from the list is\")\ncatch_unique(Alist)"},{"code":null,"e":2024,"s":1969,"text":"Running the above code gives us the following result −"},{"code":null,"e":2070,"s":2024,"text":"Unique values from the list is\nMon\nTue\nwed\n40"},{"code":null,"e":2228,"s":2070,"text":"A set only contains unique values. In this approach we convert the list to a set and then convert the set back to a list which holds all the unique elements."},{"code":null,"e":2239,"s":2228,"text":" Live Demo"},{"code":null,"e":2380,"s":2239,"text":"Alist = ['Mon', 'Tue', 'Mon', 'wed', 40, 40]\nA_set = set(Alist)\nNew_List=list(A_set)\nprint(\"Unique values from the list is\")\nprint(New_List)"},{"code":null,"e":2435,"s":2380,"text":"Running the above code gives us the following result −"},{"code":null,"e":2492,"s":2435,"text":"Unique values from the list is\n[40, 'Tue', 'wed', 'Mon']"},{"code":null,"e":2640,"s":2492,"text":"The numpy library has a function named unique which does the straight job of taking the list as input and giving the unique elements as a new list."},{"code":null,"e":2651,"s":2640,"text":" Live Demo"},{"code":null,"e":2782,"s":2651,"text":"import numpy as np\n\nAlist = ['Mon', 'Tue', 'Mon', 'wed', 40, 40]\nprint(\"The unique values from list is: \")\nprint(np.unique(Alist))"},{"code":null,"e":2837,"s":2782,"text":"Running the above code gives us the following result −"},{"code":null,"e":2894,"s":2837,"text":"The unique values from list is:\n['40' 'Mon' 'Tue' 'wed']"}],"string":"[\n {\n \"code\": null,\n \"e\": 1272,\n \"s\": 1062,\n \"text\": \"A list in python is a number of items placed with in [] which may or may not have same data types. It can also contain duplicates. In this article we will see how to extract only the unique values from a list.\"\n },\n {\n \"code\": null,\n \"e\": 1583,\n \"s\": 1272,\n \"text\": \"In this approach we will first create a new empty list and then keep appending elements to this new list only if it is not already present in this new list. A for loop is used along with not in condition. It checks for the existence of the incoming element and it is appended only if it is not already present.\"\n },\n {\n \"code\": null,\n \"e\": 1594,\n \"s\": 1583,\n \"text\": \" Live Demo\"\n },\n {\n \"code\": null,\n \"e\": 1969,\n \"s\": 1594,\n \"text\": \"def catch_unique(list_in):\\n # intilize an empty list\\n unq_list = []\\n\\n # Check for elements\\n for x in list_in:\\n # check if exists in unq_list\\n if x not in unq_list:\\n unq_list.append(x)\\n # print list\\n for x in unq_list:\\n print(x)\\n\\nAlist = ['Mon', 'Tue', 'Mon', 'wed', 40, 40]\\nprint(\\\"Unique values from the list is\\\")\\ncatch_unique(Alist)\"\n },\n {\n \"code\": null,\n \"e\": 2024,\n \"s\": 1969,\n \"text\": \"Running the above code gives us the following result −\"\n },\n {\n \"code\": null,\n \"e\": 2070,\n \"s\": 2024,\n \"text\": \"Unique values from the list is\\nMon\\nTue\\nwed\\n40\"\n },\n {\n \"code\": null,\n \"e\": 2228,\n \"s\": 2070,\n \"text\": \"A set only contains unique values. In this approach we convert the list to a set and then convert the set back to a list which holds all the unique elements.\"\n },\n {\n \"code\": null,\n \"e\": 2239,\n \"s\": 2228,\n \"text\": \" Live Demo\"\n },\n {\n \"code\": null,\n \"e\": 2380,\n \"s\": 2239,\n \"text\": \"Alist = ['Mon', 'Tue', 'Mon', 'wed', 40, 40]\\nA_set = set(Alist)\\nNew_List=list(A_set)\\nprint(\\\"Unique values from the list is\\\")\\nprint(New_List)\"\n },\n {\n \"code\": null,\n \"e\": 2435,\n \"s\": 2380,\n \"text\": \"Running the above code gives us the following result −\"\n },\n {\n \"code\": null,\n \"e\": 2492,\n \"s\": 2435,\n \"text\": \"Unique values from the list is\\n[40, 'Tue', 'wed', 'Mon']\"\n },\n {\n \"code\": null,\n \"e\": 2640,\n \"s\": 2492,\n \"text\": \"The numpy library has a function named unique which does the straight job of taking the list as input and giving the unique elements as a new list.\"\n },\n {\n \"code\": null,\n \"e\": 2651,\n \"s\": 2640,\n \"text\": \" Live Demo\"\n },\n {\n \"code\": null,\n \"e\": 2782,\n \"s\": 2651,\n \"text\": \"import numpy as np\\n\\nAlist = ['Mon', 'Tue', 'Mon', 'wed', 40, 40]\\nprint(\\\"The unique values from list is: \\\")\\nprint(np.unique(Alist))\"\n },\n {\n \"code\": null,\n \"e\": 2837,\n \"s\": 2782,\n \"text\": \"Running the above code gives us the following result −\"\n },\n {\n \"code\": null,\n \"e\": 2894,\n \"s\": 2837,\n \"text\": \"The unique values from list is:\\n['40' 'Mon' 'Tue' 'wed']\"\n }\n]"}}},{"rowIdx":415,"cells":{"title":{"kind":"string","value":"How to raise an error within MySQL?"},"text":{"kind":"string","value":"MySQL has introduced signals similar to an exception in other languages. Let us first see the syntax of signal.\nSIGNAL SQLSTATE ' PredefinedValueforSignalError' \nSET MESSAGE_TEXT = 'AnyMessageInformation';\n\nAbove, we have set our own error message text as well.\nWe will apply the above query to get an error message with the help of signals.\nmysql > SIGNAL SQLSTATE '42927' SET MESSAGE_TEXT = 'Error Generated';\nThe following is the output of the above query.\nERROR 1644 (42927): Error Generated\n\nIn the above output, ‘42927’ is a SQLSTATE and ‘Error Generated’ is an error message, which we added."},"parsed":{"kind":"list like","value":[{"code":null,"e":1174,"s":1062,"text":"MySQL has introduced signals similar to an exception in other languages. Let us first see the syntax of signal."},{"code":null,"e":1269,"s":1174,"text":"SIGNAL SQLSTATE ' PredefinedValueforSignalError' \nSET MESSAGE_TEXT = 'AnyMessageInformation';\n"},{"code":null,"e":1324,"s":1269,"text":"Above, we have set our own error message text as well."},{"code":null,"e":1404,"s":1324,"text":"We will apply the above query to get an error message with the help of signals."},{"code":null,"e":1474,"s":1404,"text":"mysql > SIGNAL SQLSTATE '42927' SET MESSAGE_TEXT = 'Error Generated';"},{"code":null,"e":1522,"s":1474,"text":"The following is the output of the above query."},{"code":null,"e":1559,"s":1522,"text":"ERROR 1644 (42927): Error Generated\n"},{"code":null,"e":1661,"s":1559,"text":"In the above output, ‘42927’ is a SQLSTATE and ‘Error Generated’ is an error message, which we added."}],"string":"[\n {\n \"code\": null,\n \"e\": 1174,\n \"s\": 1062,\n \"text\": \"MySQL has introduced signals similar to an exception in other languages. Let us first see the syntax of signal.\"\n },\n {\n \"code\": null,\n \"e\": 1269,\n \"s\": 1174,\n \"text\": \"SIGNAL SQLSTATE ' PredefinedValueforSignalError' \\nSET MESSAGE_TEXT = 'AnyMessageInformation';\\n\"\n },\n {\n \"code\": null,\n \"e\": 1324,\n \"s\": 1269,\n \"text\": \"Above, we have set our own error message text as well.\"\n },\n {\n \"code\": null,\n \"e\": 1404,\n \"s\": 1324,\n \"text\": \"We will apply the above query to get an error message with the help of signals.\"\n },\n {\n \"code\": null,\n \"e\": 1474,\n \"s\": 1404,\n \"text\": \"mysql > SIGNAL SQLSTATE '42927' SET MESSAGE_TEXT = 'Error Generated';\"\n },\n {\n \"code\": null,\n \"e\": 1522,\n \"s\": 1474,\n \"text\": \"The following is the output of the above query.\"\n },\n {\n \"code\": null,\n \"e\": 1559,\n \"s\": 1522,\n \"text\": \"ERROR 1644 (42927): Error Generated\\n\"\n },\n {\n \"code\": null,\n \"e\": 1661,\n \"s\": 1559,\n \"text\": \"In the above output, ‘42927’ is a SQLSTATE and ‘Error Generated’ is an error message, which we added.\"\n }\n]"}}},{"rowIdx":416,"cells":{"title":{"kind":"string","value":"Social Media Sentiment Analysis using Machine Learning : Part — II | by Deepak Das | Towards Data Science"},"text":{"kind":"string","value":"Hello everyone, so let’s start right where we left off in Part — I.\nIn this post we will discuss how we can extract features from our textual dataset by using Bag-of-Words and TF-IDF. Then we will see how we can apply Machine Learning models using these features to predict whether a tweet falls into the Positive: ‘0’ or Negative: ‘1’ sentiment.\nNote : In case you haven’t read the Part — I of this series do give it a read to get a better understanding of Part — II.\nmedium.com\nSo, let’s start shall we ?\nBag of Words is a method to extract features from text documents. These features can be used for training machine learning algorithms. It creates a vocabulary of all the unique words occurring in all the documents in the training set.\nConsider a corpus (a collection of texts) called C of D documents {d1,d2.....dD} and N unique tokens extracted out of the corpus C. The N tokens (words) will form a list, and the size of the bag-of-words matrix M will be given by D X N. Each row in the matrix M contains the frequency of tokens in document D(i).\nFor example, if you have 2 documents-\nD1: He is a lazy boy. She is also lazy.\nD2: Smith is a lazy person.\nFirst, it creates a vocabulary using unique words from all the documents.\n[‘He’ , ’She’ , ’lazy’ , ‘boy’ , ‘Smith’ , ’person’]\nAs we can see in the above list we don’t consider “is” , “a” , “also” in this set because they don’t convey the necessary information required for the model.\nHere, D=2, N=6\nThe matrix M of size 2 X 6 will be represented as:\nThe above table depicts the training features containing term frequencies of each word in each document. This is called bag-of-words approach since the number of occurrence and not sequence or order of words matters in this approach.\nSo,let’s apply this word embedding technique to our available dataset.\nWe have a package called CountVectorizer to perform this task.\nOUTPUT :-\nTF-IDF stands for Term Frequency-Inverse Document Frequency, and the TF-IDF weight is a weight often used in information retrieval and text mining. This weight is a statistical measure used to evaluate how important a word is to a document in a collection or corpus. The importance increases proportionally to the number of times a word appears in the document but is offset by the frequency of the word in the corpus.\nTypically, the TF-IDF weight is composed by two terms:\nThe first computes the normalized Term Frequency (TF), aka. the number of times a word appears in a document, divided by the total number of words in that document.\nExample :-\nConsider a document containing 100 words wherein the word cat appears 3 times.\nThe Term Frequency (TF) for cat is then (3 / 100) = 0.03\nThe second term is the Inverse Document Frequency (IDF), computed as the logarithm of the number of the documents in the corpus divided by the number of documents where the specific term appears.\nExample :-\nAssume we have 10 million documents and the word cat appears in one thousand of these.\nThen, the Inverse Document Frequency (IDF) is calculated as\nlog(10,000,000 / 1,000) = 4.\nFormula for finding the TF-IDF weight :-\nFrom the above examples the Term Frequency is 0.03 and Inverse Document Frequency is 4.\nThus, the TF-IDF weight is the product of these quantities : 0.03 * 4 = 0.12.\nCODE :-\nLet us apply this technique to our dataset using Python.\nWe have a package available for this in Scikit-Learn known as TfidfVectorizer.\nOUTPUT :-\nThese are the Word Embedding techniques which we have used on our dataset for feature extraction.\nLet’s move on to the next step.\nSplitting of our dataset into training and validation set.\nFrom the above two techniques that is Bag-of-Words and TF-IDF we have extracted features from the tweets present in our dataset.\nNow, we have one dataset with features from the Bag-of-Words model and another dataset with features from TF-IDF model.\nFirst task is to split the dataset into training and validation set so that we can train and test our model before applying it to predict for unseen and unlabeled test data.\nUsing the features from Bag-of-Words for training set\ntrain_bow = bow[:31962]train_bow.todense()\nOUTPUT :-\nUsing features from TF-IDF for training set\ntrain_tfidf_matrix = tfidf_matrix[:31962]train_tfidf_matrix.todense()\nOUTPUT :-\nSplitting the data into training and validation set\nfrom sklearn.model_selection import train_test_split\nBag-of-Words Features\nx_train_bow, x_valid_bow, y_train_bow, y_valid_bow = train_test_split(train_bow,train['label'],test_size=0.3,random_state=2)\nTF-IDF features\nx_train_tfidf, x_valid_tfidf, y_train_tfidf, y_valid_tfidf = train_test_split(train_tfidf_matrix,train['label'],test_size=0.3,random_state=17)\nWe are done with splitting our dataset into train and validation set.\nWant to know more about the Bag-of-Words and TF-IDF models used for feature extraction. Do give a read to the following blog post for an in depth discussion.\ntowardsdatascience.com\nFinally , we are here for the most awaited part of this series that is applying Machine Learning Models on our dataset.\nThe underlying problem we are going to solve comes under the Supervised Machine Learning category. So, let us have a brief discussion about this topic before moving on to apply different Machine Learning models on our dataset.\nThe majority of practical machine learning uses supervised learning.\nSupervised learning is where you have input variables (x) and an output variable (Y) and you use an algorithm to learn the mapping function from the input to the output.\nThe goal is to approximate the mapping function so well that when you have new input data (x) that you can predict the output variables (Y) for that data.\nIt is called supervised learning because the process of an algorithm learning from the training dataset can be thought of as a teacher supervising the learning process. We know the correct answers, the algorithm iteratively makes predictions on the training data and is corrected by the teacher. Learning stops when the algorithm achieves an acceptable level of performance.\nSupervised learning problems can be further grouped into regression and classification problems.\nClassification: A classification problem is when the output variable is a category, such as “red” or “blue” or “disease” and “no disease” or in our case “Positive” or “Negative”\nRegression: A regression problem is when the output variable is a real value, such as “dollars” or “weight”.\nOur problem comes under the classification category because we have to classify our results into either Positive or Negative class.\nThere is another category of Machine Learning algorithm called Unsupervised Machine Learning where you have an input data but no corresponding output variables. The goal for unsupervised learning is to model the underlying structure or distribution in the data in order to learn more about the data. But that is of no concern for us for this problem statement.\nSo from the above splitting of dataset we see that we will use features from the Bag-of-Words and TF-IDF for our Machine Learning Models.\nWe generally use different models to see which best fits our dataset and then we use that model for predicting results on the test data.\nHere we will use 3 different models\nLogistic Regression\nXGBoost\nDecision Trees\nand then we will compare their performance and choose the best possible model with the best possible feature extraction technique for predicting results on our test data.\nWe will use F1 Score throughout to asses our model’s performance instead of accuracy. You will get to know why at the end of this article.\nCODE :-\nfrom sklearn.metrics import f1_score\nNow, let’s move on to applying different models on our dataset from the features extracted by using Bag-of-Words and TF-IDF.\nThe first model we are going to use is Logistic Regression.\nfrom sklearn.linear_model import LogisticRegressionLog_Reg = LogisticRegression(random_state=0,solver='lbfgs')\nFitting the Logistic Regression Model.\nLog_Reg.fit(x_train_bow,y_train_bow)\nPredicting the probabilities.\nprediction_bow = Log_Reg.predict_proba(x_valid_bow)prediction_bow\nOUTPUT :-\nIf you are confused about the above output , read this stack overflow answer and you will have a clear idea about it.\nstackoverflow.com\nThe output basically provides us with the probabilities of the tweet falling into either of the classes that is Negative or Positive.\nCalculating the F1 score\nFitting the Logistic Regression Model.\nLog_Reg.fit(x_train_tfidf,y_train_tfidf)\nPredicting the probabilities.\nprediction_tfidf = Log_Reg.predict_proba(x_valid_tfidf)prediction_tfidf\nOUTPUT :-\nCalculating the F1 Score\nNote : In the nested list the element[0][0] is for label : 0 or Positive tweets and element [0][1] is for label : 1 or Negative Tweets.\nFor an in depth analysis of Logistic Regression do read the following article.\nmachinelearningmastery.com\nThe next model we use is XGBoost.\nfrom xgboost import XGBClassifier\nmodel_bow = XGBClassifier(random_state=22,learning_rate=0.9)\nFitting the XGBoost Model\nmodel_bow.fit(x_train_bow, y_train_bow)\nPredicting the probabilities.\nxgb = model_bow.predict_proba(x_valid_bow)xgb\nCalculating the F1 Score\nOUTPUT :-\nmodel_tfidf = XGBClassifier(random_state=29,learning_rate=0.7)\nFitting the XGBoost model\nmodel_tfidf.fit(x_train_tfidf, y_train_tfidf)\nPredicting the probabilities.\nxgb_tfidf=model_tfidf.predict_proba(x_valid_tfidf)xgb_tfidf\nCalculating the F1 Score\nOUTPUT :-\nFor a more in depth analysis of the XGBoost model read the following article.\nmachinelearningmastery.com\nThe last model we use is Decision Trees.\nfrom sklearn.tree import DecisionTreeClassifierdct = DecisionTreeClassifier(criterion='entropy', random_state=1)\nFitting the Decision Tree model.\ndct.fit(x_train_bow,y_train_bow)\nPredicting the probabilities.\ndct_bow = dct.predict_proba(x_valid_bow)dct_bow\nCalculating the F1 Score\nFitting the Decision Tree model\ndct.fit(x_train_tfidf,y_train_tfidf)\nPredicting the probabilities.\ndct_tfidf = dct.predict_proba(x_valid_tfidf)dct_tfidf\nCalculating the F1 Score\nFor a more in depth analysis of Decision Trees model do give a read to the following article.\ntowardsdatascience.com\nNow, let us compare the different models we have applied on our dataset with different word embedding techniques.\nComparison Graph\nComparison Graph\nAs we can see the best possible model from both Bag-of-Words and TF-IDF is Logistic Regression.\nNow, let us compare the score of the Logistic Regression model with both the feature extraction techniques that is Bag-of-Words and TF-IDF.\nComparison Graph\nFrom the above comparison graph we can clearly see that the best possible F1 Score is obtained by the Logistic Regression Model using TF-IDF features.\nCode :-\nres = pd.read_csv('result.csv')res\nFrom the above output we can see that our Logistic Regression model with TF-IDF features predicts whether a tweets falls into the category of Positive — label : 0 or Negative — label : 1 sentiment.\nBag-of-Words\nTF-IDF\nLogistic Regression\nXGBoost\nDecision Trees\nF1 Score\nSo, finally we have reached the end of our journey. We completed the tasks which were required to predict the sentiment of a particular tweet using Machine Learning.\nThe questions that arises are “What is F1 Score ?” and “Why F1 Score instead of accuracy ?”.\nSo, before we proceed you need to have a basic idea about the terminologies like Confusion Matrix and its contents for example.\nSo, refer to this article for a basic understanding of the terminologies associated with Confusion Matrix.\ntowardsdatascience.com\nOK , let us answer the above queries.\nLet us generate a countplot for our training dataset labels i.e. ‘0’ or ‘1’ .\nsns.countplot(train_original['label'])sns.despine()\nFrom the above countplot generated above we see how imbalanced our dataset is.We can see that the values with Positive — label : 0 sentiments are quite high in number as compared to the values with Negative — label : 1 sentiments.\nSo when we keep Accuracy as our evaluation metric there may be cases where we may encounter high number of false positives. So that is why we use F1 Score as our evaluation metric instead of Accuracy.\nTo know about F1 Score we first have to know about Precision and Recall.\nPrecision means the percentage of your results which are relevant.\nRecall refers to the percentage of total relevant results correctly classified by your algorithm.\nWe always face a trade-off situation between Precision and Recall i.e. High Precision gives low Recall and vice versa.\nIn most problems, you could either give a higher priority to maximising precision, or recall, depending upon the problem you are trying to solve. But in general, there is a simpler metric which takes into account both precision and recall, and therefore, you can aim to maximise this number to make your model better. This metric is known as F1-score, which is simply the harmonic mean of Precision and Recall.\nSo this metric seems much more easier and convenient to work with, as you only have to maximise one score, rather than balancing two separate scores.\nFinally, we have reached the end of the two part series of this article. I hope after this post you get a basic understanding of how you can start off with text processing and apply Machine Learning models to text data and extract information out of it.\nAfter this we can try to deploy our Machine Learning Models over a website using the available web frameworks such as Flask ,FastAPI etc. to production. But that’s a story for another blog post.\nYou can reach me at :\nLinkedIn : https://www.linkedin.com/in/deepak-das-profile/\nGitHub : https://github.com/dD2405"},"parsed":{"kind":"list like","value":[{"code":null,"e":240,"s":172,"text":"Hello everyone, so let’s start right where we left off in Part — I."},{"code":null,"e":519,"s":240,"text":"In this post we will discuss how we can extract features from our textual dataset by using Bag-of-Words and TF-IDF. Then we will see how we can apply Machine Learning models using these features to predict whether a tweet falls into the Positive: ‘0’ or Negative: ‘1’ sentiment."},{"code":null,"e":641,"s":519,"text":"Note : In case you haven’t read the Part — I of this series do give it a read to get a better understanding of Part — II."},{"code":null,"e":652,"s":641,"text":"medium.com"},{"code":null,"e":679,"s":652,"text":"So, let’s start shall we ?"},{"code":null,"e":914,"s":679,"text":"Bag of Words is a method to extract features from text documents. These features can be used for training machine learning algorithms. It creates a vocabulary of all the unique words occurring in all the documents in the training set."},{"code":null,"e":1227,"s":914,"text":"Consider a corpus (a collection of texts) called C of D documents {d1,d2.....dD} and N unique tokens extracted out of the corpus C. The N tokens (words) will form a list, and the size of the bag-of-words matrix M will be given by D X N. Each row in the matrix M contains the frequency of tokens in document D(i)."},{"code":null,"e":1265,"s":1227,"text":"For example, if you have 2 documents-"},{"code":null,"e":1305,"s":1265,"text":"D1: He is a lazy boy. She is also lazy."},{"code":null,"e":1333,"s":1305,"text":"D2: Smith is a lazy person."},{"code":null,"e":1407,"s":1333,"text":"First, it creates a vocabulary using unique words from all the documents."},{"code":null,"e":1460,"s":1407,"text":"[‘He’ , ’She’ , ’lazy’ , ‘boy’ , ‘Smith’ , ’person’]"},{"code":null,"e":1618,"s":1460,"text":"As we can see in the above list we don’t consider “is” , “a” , “also” in this set because they don’t convey the necessary information required for the model."},{"code":null,"e":1633,"s":1618,"text":"Here, D=2, N=6"},{"code":null,"e":1684,"s":1633,"text":"The matrix M of size 2 X 6 will be represented as:"},{"code":null,"e":1918,"s":1684,"text":"The above table depicts the training features containing term frequencies of each word in each document. This is called bag-of-words approach since the number of occurrence and not sequence or order of words matters in this approach."},{"code":null,"e":1989,"s":1918,"text":"So,let’s apply this word embedding technique to our available dataset."},{"code":null,"e":2052,"s":1989,"text":"We have a package called CountVectorizer to perform this task."},{"code":null,"e":2062,"s":2052,"text":"OUTPUT :-"},{"code":null,"e":2481,"s":2062,"text":"TF-IDF stands for Term Frequency-Inverse Document Frequency, and the TF-IDF weight is a weight often used in information retrieval and text mining. This weight is a statistical measure used to evaluate how important a word is to a document in a collection or corpus. The importance increases proportionally to the number of times a word appears in the document but is offset by the frequency of the word in the corpus."},{"code":null,"e":2536,"s":2481,"text":"Typically, the TF-IDF weight is composed by two terms:"},{"code":null,"e":2701,"s":2536,"text":"The first computes the normalized Term Frequency (TF), aka. the number of times a word appears in a document, divided by the total number of words in that document."},{"code":null,"e":2712,"s":2701,"text":"Example :-"},{"code":null,"e":2791,"s":2712,"text":"Consider a document containing 100 words wherein the word cat appears 3 times."},{"code":null,"e":2848,"s":2791,"text":"The Term Frequency (TF) for cat is then (3 / 100) = 0.03"},{"code":null,"e":3044,"s":2848,"text":"The second term is the Inverse Document Frequency (IDF), computed as the logarithm of the number of the documents in the corpus divided by the number of documents where the specific term appears."},{"code":null,"e":3055,"s":3044,"text":"Example :-"},{"code":null,"e":3142,"s":3055,"text":"Assume we have 10 million documents and the word cat appears in one thousand of these."},{"code":null,"e":3202,"s":3142,"text":"Then, the Inverse Document Frequency (IDF) is calculated as"},{"code":null,"e":3231,"s":3202,"text":"log(10,000,000 / 1,000) = 4."},{"code":null,"e":3272,"s":3231,"text":"Formula for finding the TF-IDF weight :-"},{"code":null,"e":3360,"s":3272,"text":"From the above examples the Term Frequency is 0.03 and Inverse Document Frequency is 4."},{"code":null,"e":3438,"s":3360,"text":"Thus, the TF-IDF weight is the product of these quantities : 0.03 * 4 = 0.12."},{"code":null,"e":3446,"s":3438,"text":"CODE :-"},{"code":null,"e":3503,"s":3446,"text":"Let us apply this technique to our dataset using Python."},{"code":null,"e":3582,"s":3503,"text":"We have a package available for this in Scikit-Learn known as TfidfVectorizer."},{"code":null,"e":3592,"s":3582,"text":"OUTPUT :-"},{"code":null,"e":3690,"s":3592,"text":"These are the Word Embedding techniques which we have used on our dataset for feature extraction."},{"code":null,"e":3722,"s":3690,"text":"Let’s move on to the next step."},{"code":null,"e":3781,"s":3722,"text":"Splitting of our dataset into training and validation set."},{"code":null,"e":3910,"s":3781,"text":"From the above two techniques that is Bag-of-Words and TF-IDF we have extracted features from the tweets present in our dataset."},{"code":null,"e":4030,"s":3910,"text":"Now, we have one dataset with features from the Bag-of-Words model and another dataset with features from TF-IDF model."},{"code":null,"e":4204,"s":4030,"text":"First task is to split the dataset into training and validation set so that we can train and test our model before applying it to predict for unseen and unlabeled test data."},{"code":null,"e":4258,"s":4204,"text":"Using the features from Bag-of-Words for training set"},{"code":null,"e":4301,"s":4258,"text":"train_bow = bow[:31962]train_bow.todense()"},{"code":null,"e":4311,"s":4301,"text":"OUTPUT :-"},{"code":null,"e":4355,"s":4311,"text":"Using features from TF-IDF for training set"},{"code":null,"e":4425,"s":4355,"text":"train_tfidf_matrix = tfidf_matrix[:31962]train_tfidf_matrix.todense()"},{"code":null,"e":4435,"s":4425,"text":"OUTPUT :-"},{"code":null,"e":4487,"s":4435,"text":"Splitting the data into training and validation set"},{"code":null,"e":4540,"s":4487,"text":"from sklearn.model_selection import train_test_split"},{"code":null,"e":4562,"s":4540,"text":"Bag-of-Words Features"},{"code":null,"e":4687,"s":4562,"text":"x_train_bow, x_valid_bow, y_train_bow, y_valid_bow = train_test_split(train_bow,train['label'],test_size=0.3,random_state=2)"},{"code":null,"e":4703,"s":4687,"text":"TF-IDF features"},{"code":null,"e":4846,"s":4703,"text":"x_train_tfidf, x_valid_tfidf, y_train_tfidf, y_valid_tfidf = train_test_split(train_tfidf_matrix,train['label'],test_size=0.3,random_state=17)"},{"code":null,"e":4916,"s":4846,"text":"We are done with splitting our dataset into train and validation set."},{"code":null,"e":5074,"s":4916,"text":"Want to know more about the Bag-of-Words and TF-IDF models used for feature extraction. Do give a read to the following blog post for an in depth discussion."},{"code":null,"e":5097,"s":5074,"text":"towardsdatascience.com"},{"code":null,"e":5217,"s":5097,"text":"Finally , we are here for the most awaited part of this series that is applying Machine Learning Models on our dataset."},{"code":null,"e":5444,"s":5217,"text":"The underlying problem we are going to solve comes under the Supervised Machine Learning category. So, let us have a brief discussion about this topic before moving on to apply different Machine Learning models on our dataset."},{"code":null,"e":5513,"s":5444,"text":"The majority of practical machine learning uses supervised learning."},{"code":null,"e":5683,"s":5513,"text":"Supervised learning is where you have input variables (x) and an output variable (Y) and you use an algorithm to learn the mapping function from the input to the output."},{"code":null,"e":5838,"s":5683,"text":"The goal is to approximate the mapping function so well that when you have new input data (x) that you can predict the output variables (Y) for that data."},{"code":null,"e":6213,"s":5838,"text":"It is called supervised learning because the process of an algorithm learning from the training dataset can be thought of as a teacher supervising the learning process. We know the correct answers, the algorithm iteratively makes predictions on the training data and is corrected by the teacher. Learning stops when the algorithm achieves an acceptable level of performance."},{"code":null,"e":6310,"s":6213,"text":"Supervised learning problems can be further grouped into regression and classification problems."},{"code":null,"e":6488,"s":6310,"text":"Classification: A classification problem is when the output variable is a category, such as “red” or “blue” or “disease” and “no disease” or in our case “Positive” or “Negative”"},{"code":null,"e":6597,"s":6488,"text":"Regression: A regression problem is when the output variable is a real value, such as “dollars” or “weight”."},{"code":null,"e":6729,"s":6597,"text":"Our problem comes under the classification category because we have to classify our results into either Positive or Negative class."},{"code":null,"e":7090,"s":6729,"text":"There is another category of Machine Learning algorithm called Unsupervised Machine Learning where you have an input data but no corresponding output variables. The goal for unsupervised learning is to model the underlying structure or distribution in the data in order to learn more about the data. But that is of no concern for us for this problem statement."},{"code":null,"e":7228,"s":7090,"text":"So from the above splitting of dataset we see that we will use features from the Bag-of-Words and TF-IDF for our Machine Learning Models."},{"code":null,"e":7365,"s":7228,"text":"We generally use different models to see which best fits our dataset and then we use that model for predicting results on the test data."},{"code":null,"e":7401,"s":7365,"text":"Here we will use 3 different models"},{"code":null,"e":7421,"s":7401,"text":"Logistic Regression"},{"code":null,"e":7429,"s":7421,"text":"XGBoost"},{"code":null,"e":7444,"s":7429,"text":"Decision Trees"},{"code":null,"e":7615,"s":7444,"text":"and then we will compare their performance and choose the best possible model with the best possible feature extraction technique for predicting results on our test data."},{"code":null,"e":7754,"s":7615,"text":"We will use F1 Score throughout to asses our model’s performance instead of accuracy. You will get to know why at the end of this article."},{"code":null,"e":7762,"s":7754,"text":"CODE :-"},{"code":null,"e":7799,"s":7762,"text":"from sklearn.metrics import f1_score"},{"code":null,"e":7924,"s":7799,"text":"Now, let’s move on to applying different models on our dataset from the features extracted by using Bag-of-Words and TF-IDF."},{"code":null,"e":7984,"s":7924,"text":"The first model we are going to use is Logistic Regression."},{"code":null,"e":8095,"s":7984,"text":"from sklearn.linear_model import LogisticRegressionLog_Reg = LogisticRegression(random_state=0,solver='lbfgs')"},{"code":null,"e":8134,"s":8095,"text":"Fitting the Logistic Regression Model."},{"code":null,"e":8171,"s":8134,"text":"Log_Reg.fit(x_train_bow,y_train_bow)"},{"code":null,"e":8201,"s":8171,"text":"Predicting the probabilities."},{"code":null,"e":8267,"s":8201,"text":"prediction_bow = Log_Reg.predict_proba(x_valid_bow)prediction_bow"},{"code":null,"e":8277,"s":8267,"text":"OUTPUT :-"},{"code":null,"e":8395,"s":8277,"text":"If you are confused about the above output , read this stack overflow answer and you will have a clear idea about it."},{"code":null,"e":8413,"s":8395,"text":"stackoverflow.com"},{"code":null,"e":8547,"s":8413,"text":"The output basically provides us with the probabilities of the tweet falling into either of the classes that is Negative or Positive."},{"code":null,"e":8572,"s":8547,"text":"Calculating the F1 score"},{"code":null,"e":8611,"s":8572,"text":"Fitting the Logistic Regression Model."},{"code":null,"e":8652,"s":8611,"text":"Log_Reg.fit(x_train_tfidf,y_train_tfidf)"},{"code":null,"e":8682,"s":8652,"text":"Predicting the probabilities."},{"code":null,"e":8754,"s":8682,"text":"prediction_tfidf = Log_Reg.predict_proba(x_valid_tfidf)prediction_tfidf"},{"code":null,"e":8764,"s":8754,"text":"OUTPUT :-"},{"code":null,"e":8789,"s":8764,"text":"Calculating the F1 Score"},{"code":null,"e":8925,"s":8789,"text":"Note : In the nested list the element[0][0] is for label : 0 or Positive tweets and element [0][1] is for label : 1 or Negative Tweets."},{"code":null,"e":9004,"s":8925,"text":"For an in depth analysis of Logistic Regression do read the following article."},{"code":null,"e":9031,"s":9004,"text":"machinelearningmastery.com"},{"code":null,"e":9065,"s":9031,"text":"The next model we use is XGBoost."},{"code":null,"e":9099,"s":9065,"text":"from xgboost import XGBClassifier"},{"code":null,"e":9160,"s":9099,"text":"model_bow = XGBClassifier(random_state=22,learning_rate=0.9)"},{"code":null,"e":9186,"s":9160,"text":"Fitting the XGBoost Model"},{"code":null,"e":9226,"s":9186,"text":"model_bow.fit(x_train_bow, y_train_bow)"},{"code":null,"e":9256,"s":9226,"text":"Predicting the probabilities."},{"code":null,"e":9302,"s":9256,"text":"xgb = model_bow.predict_proba(x_valid_bow)xgb"},{"code":null,"e":9327,"s":9302,"text":"Calculating the F1 Score"},{"code":null,"e":9337,"s":9327,"text":"OUTPUT :-"},{"code":null,"e":9400,"s":9337,"text":"model_tfidf = XGBClassifier(random_state=29,learning_rate=0.7)"},{"code":null,"e":9426,"s":9400,"text":"Fitting the XGBoost model"},{"code":null,"e":9472,"s":9426,"text":"model_tfidf.fit(x_train_tfidf, y_train_tfidf)"},{"code":null,"e":9502,"s":9472,"text":"Predicting the probabilities."},{"code":null,"e":9562,"s":9502,"text":"xgb_tfidf=model_tfidf.predict_proba(x_valid_tfidf)xgb_tfidf"},{"code":null,"e":9587,"s":9562,"text":"Calculating the F1 Score"},{"code":null,"e":9597,"s":9587,"text":"OUTPUT :-"},{"code":null,"e":9675,"s":9597,"text":"For a more in depth analysis of the XGBoost model read the following article."},{"code":null,"e":9702,"s":9675,"text":"machinelearningmastery.com"},{"code":null,"e":9743,"s":9702,"text":"The last model we use is Decision Trees."},{"code":null,"e":9856,"s":9743,"text":"from sklearn.tree import DecisionTreeClassifierdct = DecisionTreeClassifier(criterion='entropy', random_state=1)"},{"code":null,"e":9889,"s":9856,"text":"Fitting the Decision Tree model."},{"code":null,"e":9922,"s":9889,"text":"dct.fit(x_train_bow,y_train_bow)"},{"code":null,"e":9952,"s":9922,"text":"Predicting the probabilities."},{"code":null,"e":10000,"s":9952,"text":"dct_bow = dct.predict_proba(x_valid_bow)dct_bow"},{"code":null,"e":10025,"s":10000,"text":"Calculating the F1 Score"},{"code":null,"e":10057,"s":10025,"text":"Fitting the Decision Tree model"},{"code":null,"e":10094,"s":10057,"text":"dct.fit(x_train_tfidf,y_train_tfidf)"},{"code":null,"e":10124,"s":10094,"text":"Predicting the probabilities."},{"code":null,"e":10178,"s":10124,"text":"dct_tfidf = dct.predict_proba(x_valid_tfidf)dct_tfidf"},{"code":null,"e":10203,"s":10178,"text":"Calculating the F1 Score"},{"code":null,"e":10297,"s":10203,"text":"For a more in depth analysis of Decision Trees model do give a read to the following article."},{"code":null,"e":10320,"s":10297,"text":"towardsdatascience.com"},{"code":null,"e":10434,"s":10320,"text":"Now, let us compare the different models we have applied on our dataset with different word embedding techniques."},{"code":null,"e":10451,"s":10434,"text":"Comparison Graph"},{"code":null,"e":10468,"s":10451,"text":"Comparison Graph"},{"code":null,"e":10564,"s":10468,"text":"As we can see the best possible model from both Bag-of-Words and TF-IDF is Logistic Regression."},{"code":null,"e":10704,"s":10564,"text":"Now, let us compare the score of the Logistic Regression model with both the feature extraction techniques that is Bag-of-Words and TF-IDF."},{"code":null,"e":10721,"s":10704,"text":"Comparison Graph"},{"code":null,"e":10872,"s":10721,"text":"From the above comparison graph we can clearly see that the best possible F1 Score is obtained by the Logistic Regression Model using TF-IDF features."},{"code":null,"e":10880,"s":10872,"text":"Code :-"},{"code":null,"e":10915,"s":10880,"text":"res = pd.read_csv('result.csv')res"},{"code":null,"e":11113,"s":10915,"text":"From the above output we can see that our Logistic Regression model with TF-IDF features predicts whether a tweets falls into the category of Positive — label : 0 or Negative — label : 1 sentiment."},{"code":null,"e":11126,"s":11113,"text":"Bag-of-Words"},{"code":null,"e":11133,"s":11126,"text":"TF-IDF"},{"code":null,"e":11153,"s":11133,"text":"Logistic Regression"},{"code":null,"e":11161,"s":11153,"text":"XGBoost"},{"code":null,"e":11176,"s":11161,"text":"Decision Trees"},{"code":null,"e":11185,"s":11176,"text":"F1 Score"},{"code":null,"e":11351,"s":11185,"text":"So, finally we have reached the end of our journey. We completed the tasks which were required to predict the sentiment of a particular tweet using Machine Learning."},{"code":null,"e":11444,"s":11351,"text":"The questions that arises are “What is F1 Score ?” and “Why F1 Score instead of accuracy ?”."},{"code":null,"e":11572,"s":11444,"text":"So, before we proceed you need to have a basic idea about the terminologies like Confusion Matrix and its contents for example."},{"code":null,"e":11679,"s":11572,"text":"So, refer to this article for a basic understanding of the terminologies associated with Confusion Matrix."},{"code":null,"e":11702,"s":11679,"text":"towardsdatascience.com"},{"code":null,"e":11740,"s":11702,"text":"OK , let us answer the above queries."},{"code":null,"e":11818,"s":11740,"text":"Let us generate a countplot for our training dataset labels i.e. ‘0’ or ‘1’ ."},{"code":null,"e":11870,"s":11818,"text":"sns.countplot(train_original['label'])sns.despine()"},{"code":null,"e":12101,"s":11870,"text":"From the above countplot generated above we see how imbalanced our dataset is.We can see that the values with Positive — label : 0 sentiments are quite high in number as compared to the values with Negative — label : 1 sentiments."},{"code":null,"e":12302,"s":12101,"text":"So when we keep Accuracy as our evaluation metric there may be cases where we may encounter high number of false positives. So that is why we use F1 Score as our evaluation metric instead of Accuracy."},{"code":null,"e":12375,"s":12302,"text":"To know about F1 Score we first have to know about Precision and Recall."},{"code":null,"e":12442,"s":12375,"text":"Precision means the percentage of your results which are relevant."},{"code":null,"e":12540,"s":12442,"text":"Recall refers to the percentage of total relevant results correctly classified by your algorithm."},{"code":null,"e":12659,"s":12540,"text":"We always face a trade-off situation between Precision and Recall i.e. High Precision gives low Recall and vice versa."},{"code":null,"e":13070,"s":12659,"text":"In most problems, you could either give a higher priority to maximising precision, or recall, depending upon the problem you are trying to solve. But in general, there is a simpler metric which takes into account both precision and recall, and therefore, you can aim to maximise this number to make your model better. This metric is known as F1-score, which is simply the harmonic mean of Precision and Recall."},{"code":null,"e":13220,"s":13070,"text":"So this metric seems much more easier and convenient to work with, as you only have to maximise one score, rather than balancing two separate scores."},{"code":null,"e":13474,"s":13220,"text":"Finally, we have reached the end of the two part series of this article. I hope after this post you get a basic understanding of how you can start off with text processing and apply Machine Learning models to text data and extract information out of it."},{"code":null,"e":13669,"s":13474,"text":"After this we can try to deploy our Machine Learning Models over a website using the available web frameworks such as Flask ,FastAPI etc. to production. But that’s a story for another blog post."},{"code":null,"e":13691,"s":13669,"text":"You can reach me at :"},{"code":null,"e":13750,"s":13691,"text":"LinkedIn : https://www.linkedin.com/in/deepak-das-profile/"}],"string":"[\n {\n \"code\": null,\n \"e\": 240,\n \"s\": 172,\n \"text\": \"Hello everyone, so let’s start right where we left off in Part — I.\"\n },\n {\n \"code\": null,\n \"e\": 519,\n \"s\": 240,\n \"text\": \"In this post we will discuss how we can extract features from our textual dataset by using Bag-of-Words and TF-IDF. Then we will see how we can apply Machine Learning models using these features to predict whether a tweet falls into the Positive: ‘0’ or Negative: ‘1’ sentiment.\"\n },\n {\n \"code\": null,\n \"e\": 641,\n \"s\": 519,\n \"text\": \"Note : In case you haven’t read the Part — I of this series do give it a read to get a better understanding of Part — II.\"\n },\n {\n \"code\": null,\n \"e\": 652,\n \"s\": 641,\n \"text\": \"medium.com\"\n },\n {\n \"code\": null,\n \"e\": 679,\n \"s\": 652,\n \"text\": \"So, let’s start shall we ?\"\n },\n {\n \"code\": null,\n \"e\": 914,\n \"s\": 679,\n \"text\": \"Bag of Words is a method to extract features from text documents. These features can be used for training machine learning algorithms. It creates a vocabulary of all the unique words occurring in all the documents in the training set.\"\n },\n {\n \"code\": null,\n \"e\": 1227,\n \"s\": 914,\n \"text\": \"Consider a corpus (a collection of texts) called C of D documents {d1,d2.....dD} and N unique tokens extracted out of the corpus C. The N tokens (words) will form a list, and the size of the bag-of-words matrix M will be given by D X N. Each row in the matrix M contains the frequency of tokens in document D(i).\"\n },\n {\n \"code\": null,\n \"e\": 1265,\n \"s\": 1227,\n \"text\": \"For example, if you have 2 documents-\"\n },\n {\n \"code\": null,\n \"e\": 1305,\n \"s\": 1265,\n \"text\": \"D1: He is a lazy boy. She is also lazy.\"\n },\n {\n \"code\": null,\n \"e\": 1333,\n \"s\": 1305,\n \"text\": \"D2: Smith is a lazy person.\"\n },\n {\n \"code\": null,\n \"e\": 1407,\n \"s\": 1333,\n \"text\": \"First, it creates a vocabulary using unique words from all the documents.\"\n },\n {\n \"code\": null,\n \"e\": 1460,\n \"s\": 1407,\n \"text\": \"[‘He’ , ’She’ , ’lazy’ , ‘boy’ , ‘Smith’ , ’person’]\"\n },\n {\n \"code\": null,\n \"e\": 1618,\n \"s\": 1460,\n \"text\": \"As we can see in the above list we don’t consider “is” , “a” , “also” in this set because they don’t convey the necessary information required for the model.\"\n },\n {\n \"code\": null,\n \"e\": 1633,\n \"s\": 1618,\n \"text\": \"Here, D=2, N=6\"\n },\n {\n \"code\": null,\n \"e\": 1684,\n \"s\": 1633,\n \"text\": \"The matrix M of size 2 X 6 will be represented as:\"\n },\n {\n \"code\": null,\n \"e\": 1918,\n \"s\": 1684,\n \"text\": \"The above table depicts the training features containing term frequencies of each word in each document. This is called bag-of-words approach since the number of occurrence and not sequence or order of words matters in this approach.\"\n },\n {\n \"code\": null,\n \"e\": 1989,\n \"s\": 1918,\n \"text\": \"So,let’s apply this word embedding technique to our available dataset.\"\n },\n {\n \"code\": null,\n \"e\": 2052,\n \"s\": 1989,\n \"text\": \"We have a package called CountVectorizer to perform this task.\"\n },\n {\n \"code\": null,\n \"e\": 2062,\n \"s\": 2052,\n \"text\": \"OUTPUT :-\"\n },\n {\n \"code\": null,\n \"e\": 2481,\n \"s\": 2062,\n \"text\": \"TF-IDF stands for Term Frequency-Inverse Document Frequency, and the TF-IDF weight is a weight often used in information retrieval and text mining. This weight is a statistical measure used to evaluate how important a word is to a document in a collection or corpus. The importance increases proportionally to the number of times a word appears in the document but is offset by the frequency of the word in the corpus.\"\n },\n {\n \"code\": null,\n \"e\": 2536,\n \"s\": 2481,\n \"text\": \"Typically, the TF-IDF weight is composed by two terms:\"\n },\n {\n \"code\": null,\n \"e\": 2701,\n \"s\": 2536,\n \"text\": \"The first computes the normalized Term Frequency (TF), aka. the number of times a word appears in a document, divided by the total number of words in that document.\"\n },\n {\n \"code\": null,\n \"e\": 2712,\n \"s\": 2701,\n \"text\": \"Example :-\"\n },\n {\n \"code\": null,\n \"e\": 2791,\n \"s\": 2712,\n \"text\": \"Consider a document containing 100 words wherein the word cat appears 3 times.\"\n },\n {\n \"code\": null,\n \"e\": 2848,\n \"s\": 2791,\n \"text\": \"The Term Frequency (TF) for cat is then (3 / 100) = 0.03\"\n },\n {\n \"code\": null,\n \"e\": 3044,\n \"s\": 2848,\n \"text\": \"The second term is the Inverse Document Frequency (IDF), computed as the logarithm of the number of the documents in the corpus divided by the number of documents where the specific term appears.\"\n },\n {\n \"code\": null,\n \"e\": 3055,\n \"s\": 3044,\n \"text\": \"Example :-\"\n },\n {\n \"code\": null,\n \"e\": 3142,\n \"s\": 3055,\n \"text\": \"Assume we have 10 million documents and the word cat appears in one thousand of these.\"\n },\n {\n \"code\": null,\n \"e\": 3202,\n \"s\": 3142,\n \"text\": \"Then, the Inverse Document Frequency (IDF) is calculated as\"\n },\n {\n \"code\": null,\n \"e\": 3231,\n \"s\": 3202,\n \"text\": \"log(10,000,000 / 1,000) = 4.\"\n },\n {\n \"code\": null,\n \"e\": 3272,\n \"s\": 3231,\n \"text\": \"Formula for finding the TF-IDF weight :-\"\n },\n {\n \"code\": null,\n \"e\": 3360,\n \"s\": 3272,\n \"text\": \"From the above examples the Term Frequency is 0.03 and Inverse Document Frequency is 4.\"\n },\n {\n \"code\": null,\n \"e\": 3438,\n \"s\": 3360,\n \"text\": \"Thus, the TF-IDF weight is the product of these quantities : 0.03 * 4 = 0.12.\"\n },\n {\n \"code\": null,\n \"e\": 3446,\n \"s\": 3438,\n \"text\": \"CODE :-\"\n },\n {\n \"code\": null,\n \"e\": 3503,\n \"s\": 3446,\n \"text\": \"Let us apply this technique to our dataset using Python.\"\n },\n {\n \"code\": null,\n \"e\": 3582,\n \"s\": 3503,\n \"text\": \"We have a package available for this in Scikit-Learn known as TfidfVectorizer.\"\n },\n {\n \"code\": null,\n \"e\": 3592,\n \"s\": 3582,\n \"text\": \"OUTPUT :-\"\n },\n {\n \"code\": null,\n \"e\": 3690,\n \"s\": 3592,\n \"text\": \"These are the Word Embedding techniques which we have used on our dataset for feature extraction.\"\n },\n {\n \"code\": null,\n \"e\": 3722,\n \"s\": 3690,\n \"text\": \"Let’s move on to the next step.\"\n },\n {\n \"code\": null,\n \"e\": 3781,\n \"s\": 3722,\n \"text\": \"Splitting of our dataset into training and validation set.\"\n },\n {\n \"code\": null,\n \"e\": 3910,\n \"s\": 3781,\n \"text\": \"From the above two techniques that is Bag-of-Words and TF-IDF we have extracted features from the tweets present in our dataset.\"\n },\n {\n \"code\": null,\n \"e\": 4030,\n \"s\": 3910,\n \"text\": \"Now, we have one dataset with features from the Bag-of-Words model and another dataset with features from TF-IDF model.\"\n },\n {\n \"code\": null,\n \"e\": 4204,\n \"s\": 4030,\n \"text\": \"First task is to split the dataset into training and validation set so that we can train and test our model before applying it to predict for unseen and unlabeled test data.\"\n },\n {\n \"code\": null,\n \"e\": 4258,\n \"s\": 4204,\n \"text\": \"Using the features from Bag-of-Words for training set\"\n },\n {\n \"code\": null,\n \"e\": 4301,\n \"s\": 4258,\n \"text\": \"train_bow = bow[:31962]train_bow.todense()\"\n },\n {\n \"code\": null,\n \"e\": 4311,\n \"s\": 4301,\n \"text\": \"OUTPUT :-\"\n },\n {\n \"code\": null,\n \"e\": 4355,\n \"s\": 4311,\n \"text\": \"Using features from TF-IDF for training set\"\n },\n {\n \"code\": null,\n \"e\": 4425,\n \"s\": 4355,\n \"text\": \"train_tfidf_matrix = tfidf_matrix[:31962]train_tfidf_matrix.todense()\"\n },\n {\n \"code\": null,\n \"e\": 4435,\n \"s\": 4425,\n \"text\": \"OUTPUT :-\"\n },\n {\n \"code\": null,\n \"e\": 4487,\n \"s\": 4435,\n \"text\": \"Splitting the data into training and validation set\"\n },\n {\n \"code\": null,\n \"e\": 4540,\n \"s\": 4487,\n \"text\": \"from sklearn.model_selection import train_test_split\"\n },\n {\n \"code\": null,\n \"e\": 4562,\n \"s\": 4540,\n \"text\": \"Bag-of-Words Features\"\n },\n {\n \"code\": null,\n \"e\": 4687,\n \"s\": 4562,\n \"text\": \"x_train_bow, x_valid_bow, y_train_bow, y_valid_bow = train_test_split(train_bow,train['label'],test_size=0.3,random_state=2)\"\n },\n {\n \"code\": null,\n \"e\": 4703,\n \"s\": 4687,\n \"text\": \"TF-IDF features\"\n },\n {\n \"code\": null,\n \"e\": 4846,\n \"s\": 4703,\n \"text\": \"x_train_tfidf, x_valid_tfidf, y_train_tfidf, y_valid_tfidf = train_test_split(train_tfidf_matrix,train['label'],test_size=0.3,random_state=17)\"\n },\n {\n \"code\": null,\n \"e\": 4916,\n \"s\": 4846,\n \"text\": \"We are done with splitting our dataset into train and validation set.\"\n },\n {\n \"code\": null,\n \"e\": 5074,\n \"s\": 4916,\n \"text\": \"Want to know more about the Bag-of-Words and TF-IDF models used for feature extraction. Do give a read to the following blog post for an in depth discussion.\"\n },\n {\n \"code\": null,\n \"e\": 5097,\n \"s\": 5074,\n \"text\": \"towardsdatascience.com\"\n },\n {\n \"code\": null,\n \"e\": 5217,\n \"s\": 5097,\n \"text\": \"Finally , we are here for the most awaited part of this series that is applying Machine Learning Models on our dataset.\"\n },\n {\n \"code\": null,\n \"e\": 5444,\n \"s\": 5217,\n \"text\": \"The underlying problem we are going to solve comes under the Supervised Machine Learning category. So, let us have a brief discussion about this topic before moving on to apply different Machine Learning models on our dataset.\"\n },\n {\n \"code\": null,\n \"e\": 5513,\n \"s\": 5444,\n \"text\": \"The majority of practical machine learning uses supervised learning.\"\n },\n {\n \"code\": null,\n \"e\": 5683,\n \"s\": 5513,\n \"text\": \"Supervised learning is where you have input variables (x) and an output variable (Y) and you use an algorithm to learn the mapping function from the input to the output.\"\n },\n {\n \"code\": null,\n \"e\": 5838,\n \"s\": 5683,\n \"text\": \"The goal is to approximate the mapping function so well that when you have new input data (x) that you can predict the output variables (Y) for that data.\"\n },\n {\n \"code\": null,\n \"e\": 6213,\n \"s\": 5838,\n \"text\": \"It is called supervised learning because the process of an algorithm learning from the training dataset can be thought of as a teacher supervising the learning process. We know the correct answers, the algorithm iteratively makes predictions on the training data and is corrected by the teacher. Learning stops when the algorithm achieves an acceptable level of performance.\"\n },\n {\n \"code\": null,\n \"e\": 6310,\n \"s\": 6213,\n \"text\": \"Supervised learning problems can be further grouped into regression and classification problems.\"\n },\n {\n \"code\": null,\n \"e\": 6488,\n \"s\": 6310,\n \"text\": \"Classification: A classification problem is when the output variable is a category, such as “red” or “blue” or “disease” and “no disease” or in our case “Positive” or “Negative”\"\n },\n {\n \"code\": null,\n \"e\": 6597,\n \"s\": 6488,\n \"text\": \"Regression: A regression problem is when the output variable is a real value, such as “dollars” or “weight”.\"\n },\n {\n \"code\": null,\n \"e\": 6729,\n \"s\": 6597,\n \"text\": \"Our problem comes under the classification category because we have to classify our results into either Positive or Negative class.\"\n },\n {\n \"code\": null,\n \"e\": 7090,\n \"s\": 6729,\n \"text\": \"There is another category of Machine Learning algorithm called Unsupervised Machine Learning where you have an input data but no corresponding output variables. The goal for unsupervised learning is to model the underlying structure or distribution in the data in order to learn more about the data. But that is of no concern for us for this problem statement.\"\n },\n {\n \"code\": null,\n \"e\": 7228,\n \"s\": 7090,\n \"text\": \"So from the above splitting of dataset we see that we will use features from the Bag-of-Words and TF-IDF for our Machine Learning Models.\"\n },\n {\n \"code\": null,\n \"e\": 7365,\n \"s\": 7228,\n \"text\": \"We generally use different models to see which best fits our dataset and then we use that model for predicting results on the test data.\"\n },\n {\n \"code\": null,\n \"e\": 7401,\n \"s\": 7365,\n \"text\": \"Here we will use 3 different models\"\n },\n {\n \"code\": null,\n \"e\": 7421,\n \"s\": 7401,\n \"text\": \"Logistic Regression\"\n },\n {\n \"code\": null,\n \"e\": 7429,\n \"s\": 7421,\n \"text\": \"XGBoost\"\n },\n {\n \"code\": null,\n \"e\": 7444,\n \"s\": 7429,\n \"text\": \"Decision Trees\"\n },\n {\n \"code\": null,\n \"e\": 7615,\n \"s\": 7444,\n \"text\": \"and then we will compare their performance and choose the best possible model with the best possible feature extraction technique for predicting results on our test data.\"\n },\n {\n \"code\": null,\n \"e\": 7754,\n \"s\": 7615,\n \"text\": \"We will use F1 Score throughout to asses our model’s performance instead of accuracy. You will get to know why at the end of this article.\"\n },\n {\n \"code\": null,\n \"e\": 7762,\n \"s\": 7754,\n \"text\": \"CODE :-\"\n },\n {\n \"code\": null,\n \"e\": 7799,\n \"s\": 7762,\n \"text\": \"from sklearn.metrics import f1_score\"\n },\n {\n \"code\": null,\n \"e\": 7924,\n \"s\": 7799,\n \"text\": \"Now, let’s move on to applying different models on our dataset from the features extracted by using Bag-of-Words and TF-IDF.\"\n },\n {\n \"code\": null,\n \"e\": 7984,\n \"s\": 7924,\n \"text\": \"The first model we are going to use is Logistic Regression.\"\n },\n {\n \"code\": null,\n \"e\": 8095,\n \"s\": 7984,\n \"text\": \"from sklearn.linear_model import LogisticRegressionLog_Reg = LogisticRegression(random_state=0,solver='lbfgs')\"\n },\n {\n \"code\": null,\n \"e\": 8134,\n \"s\": 8095,\n \"text\": \"Fitting the Logistic Regression Model.\"\n },\n {\n \"code\": null,\n \"e\": 8171,\n \"s\": 8134,\n \"text\": \"Log_Reg.fit(x_train_bow,y_train_bow)\"\n },\n {\n \"code\": null,\n \"e\": 8201,\n \"s\": 8171,\n \"text\": \"Predicting the probabilities.\"\n },\n {\n \"code\": null,\n \"e\": 8267,\n \"s\": 8201,\n \"text\": \"prediction_bow = Log_Reg.predict_proba(x_valid_bow)prediction_bow\"\n },\n {\n \"code\": null,\n \"e\": 8277,\n \"s\": 8267,\n \"text\": \"OUTPUT :-\"\n },\n {\n \"code\": null,\n \"e\": 8395,\n \"s\": 8277,\n \"text\": \"If you are confused about the above output , read this stack overflow answer and you will have a clear idea about it.\"\n },\n {\n \"code\": null,\n \"e\": 8413,\n \"s\": 8395,\n \"text\": \"stackoverflow.com\"\n },\n {\n \"code\": null,\n \"e\": 8547,\n \"s\": 8413,\n \"text\": \"The output basically provides us with the probabilities of the tweet falling into either of the classes that is Negative or Positive.\"\n },\n {\n \"code\": null,\n \"e\": 8572,\n \"s\": 8547,\n \"text\": \"Calculating the F1 score\"\n },\n {\n \"code\": null,\n \"e\": 8611,\n \"s\": 8572,\n \"text\": \"Fitting the Logistic Regression Model.\"\n },\n {\n \"code\": null,\n \"e\": 8652,\n \"s\": 8611,\n \"text\": \"Log_Reg.fit(x_train_tfidf,y_train_tfidf)\"\n },\n {\n \"code\": null,\n \"e\": 8682,\n \"s\": 8652,\n \"text\": \"Predicting the probabilities.\"\n },\n {\n \"code\": null,\n \"e\": 8754,\n \"s\": 8682,\n \"text\": \"prediction_tfidf = Log_Reg.predict_proba(x_valid_tfidf)prediction_tfidf\"\n },\n {\n \"code\": null,\n \"e\": 8764,\n \"s\": 8754,\n \"text\": \"OUTPUT :-\"\n },\n {\n \"code\": null,\n \"e\": 8789,\n \"s\": 8764,\n \"text\": \"Calculating the F1 Score\"\n },\n {\n \"code\": null,\n \"e\": 8925,\n \"s\": 8789,\n \"text\": \"Note : In the nested list the element[0][0] is for label : 0 or Positive tweets and element [0][1] is for label : 1 or Negative Tweets.\"\n },\n {\n \"code\": null,\n \"e\": 9004,\n \"s\": 8925,\n \"text\": \"For an in depth analysis of Logistic Regression do read the following article.\"\n },\n {\n \"code\": null,\n \"e\": 9031,\n \"s\": 9004,\n \"text\": \"machinelearningmastery.com\"\n },\n {\n \"code\": null,\n \"e\": 9065,\n \"s\": 9031,\n \"text\": \"The next model we use is XGBoost.\"\n },\n {\n \"code\": null,\n \"e\": 9099,\n \"s\": 9065,\n \"text\": \"from xgboost import XGBClassifier\"\n },\n {\n \"code\": null,\n \"e\": 9160,\n \"s\": 9099,\n \"text\": \"model_bow = XGBClassifier(random_state=22,learning_rate=0.9)\"\n },\n {\n \"code\": null,\n \"e\": 9186,\n \"s\": 9160,\n \"text\": \"Fitting the XGBoost Model\"\n },\n {\n \"code\": null,\n \"e\": 9226,\n \"s\": 9186,\n \"text\": \"model_bow.fit(x_train_bow, y_train_bow)\"\n },\n {\n \"code\": null,\n \"e\": 9256,\n \"s\": 9226,\n \"text\": \"Predicting the probabilities.\"\n },\n {\n \"code\": null,\n \"e\": 9302,\n \"s\": 9256,\n \"text\": \"xgb = model_bow.predict_proba(x_valid_bow)xgb\"\n },\n {\n \"code\": null,\n \"e\": 9327,\n \"s\": 9302,\n \"text\": \"Calculating the F1 Score\"\n },\n {\n \"code\": null,\n \"e\": 9337,\n \"s\": 9327,\n \"text\": \"OUTPUT :-\"\n },\n {\n \"code\": null,\n \"e\": 9400,\n \"s\": 9337,\n \"text\": \"model_tfidf = XGBClassifier(random_state=29,learning_rate=0.7)\"\n },\n {\n \"code\": null,\n \"e\": 9426,\n \"s\": 9400,\n \"text\": \"Fitting the XGBoost model\"\n },\n {\n \"code\": null,\n \"e\": 9472,\n \"s\": 9426,\n \"text\": \"model_tfidf.fit(x_train_tfidf, y_train_tfidf)\"\n },\n {\n \"code\": null,\n \"e\": 9502,\n \"s\": 9472,\n \"text\": \"Predicting the probabilities.\"\n },\n {\n \"code\": null,\n \"e\": 9562,\n \"s\": 9502,\n \"text\": \"xgb_tfidf=model_tfidf.predict_proba(x_valid_tfidf)xgb_tfidf\"\n },\n {\n \"code\": null,\n \"e\": 9587,\n \"s\": 9562,\n \"text\": \"Calculating the F1 Score\"\n },\n {\n \"code\": null,\n \"e\": 9597,\n \"s\": 9587,\n \"text\": \"OUTPUT :-\"\n },\n {\n \"code\": null,\n \"e\": 9675,\n \"s\": 9597,\n \"text\": \"For a more in depth analysis of the XGBoost model read the following article.\"\n },\n {\n \"code\": null,\n \"e\": 9702,\n \"s\": 9675,\n \"text\": \"machinelearningmastery.com\"\n },\n {\n \"code\": null,\n \"e\": 9743,\n \"s\": 9702,\n \"text\": \"The last model we use is Decision Trees.\"\n },\n {\n \"code\": null,\n \"e\": 9856,\n \"s\": 9743,\n \"text\": \"from sklearn.tree import DecisionTreeClassifierdct = DecisionTreeClassifier(criterion='entropy', random_state=1)\"\n },\n {\n \"code\": null,\n \"e\": 9889,\n \"s\": 9856,\n \"text\": \"Fitting the Decision Tree model.\"\n },\n {\n \"code\": null,\n \"e\": 9922,\n \"s\": 9889,\n \"text\": \"dct.fit(x_train_bow,y_train_bow)\"\n },\n {\n \"code\": null,\n \"e\": 9952,\n \"s\": 9922,\n \"text\": \"Predicting the probabilities.\"\n },\n {\n \"code\": null,\n \"e\": 10000,\n \"s\": 9952,\n \"text\": \"dct_bow = dct.predict_proba(x_valid_bow)dct_bow\"\n },\n {\n \"code\": null,\n \"e\": 10025,\n \"s\": 10000,\n \"text\": \"Calculating the F1 Score\"\n },\n {\n \"code\": null,\n \"e\": 10057,\n \"s\": 10025,\n \"text\": \"Fitting the Decision Tree model\"\n },\n {\n \"code\": null,\n \"e\": 10094,\n \"s\": 10057,\n \"text\": \"dct.fit(x_train_tfidf,y_train_tfidf)\"\n },\n {\n \"code\": null,\n \"e\": 10124,\n \"s\": 10094,\n \"text\": \"Predicting the probabilities.\"\n },\n {\n \"code\": null,\n \"e\": 10178,\n \"s\": 10124,\n \"text\": \"dct_tfidf = dct.predict_proba(x_valid_tfidf)dct_tfidf\"\n },\n {\n \"code\": null,\n \"e\": 10203,\n \"s\": 10178,\n \"text\": \"Calculating the F1 Score\"\n },\n {\n \"code\": null,\n \"e\": 10297,\n \"s\": 10203,\n \"text\": \"For a more in depth analysis of Decision Trees model do give a read to the following article.\"\n },\n {\n \"code\": null,\n \"e\": 10320,\n \"s\": 10297,\n \"text\": \"towardsdatascience.com\"\n },\n {\n \"code\": null,\n \"e\": 10434,\n \"s\": 10320,\n \"text\": \"Now, let us compare the different models we have applied on our dataset with different word embedding techniques.\"\n },\n {\n \"code\": null,\n \"e\": 10451,\n \"s\": 10434,\n \"text\": \"Comparison Graph\"\n },\n {\n \"code\": null,\n \"e\": 10468,\n \"s\": 10451,\n \"text\": \"Comparison Graph\"\n },\n {\n \"code\": null,\n \"e\": 10564,\n \"s\": 10468,\n \"text\": \"As we can see the best possible model from both Bag-of-Words and TF-IDF is Logistic Regression.\"\n },\n {\n \"code\": null,\n \"e\": 10704,\n \"s\": 10564,\n \"text\": \"Now, let us compare the score of the Logistic Regression model with both the feature extraction techniques that is Bag-of-Words and TF-IDF.\"\n },\n {\n \"code\": null,\n \"e\": 10721,\n \"s\": 10704,\n \"text\": \"Comparison Graph\"\n },\n {\n \"code\": null,\n \"e\": 10872,\n \"s\": 10721,\n \"text\": \"From the above comparison graph we can clearly see that the best possible F1 Score is obtained by the Logistic Regression Model using TF-IDF features.\"\n },\n {\n \"code\": null,\n \"e\": 10880,\n \"s\": 10872,\n \"text\": \"Code :-\"\n },\n {\n \"code\": null,\n \"e\": 10915,\n \"s\": 10880,\n \"text\": \"res = pd.read_csv('result.csv')res\"\n },\n {\n \"code\": null,\n \"e\": 11113,\n \"s\": 10915,\n \"text\": \"From the above output we can see that our Logistic Regression model with TF-IDF features predicts whether a tweets falls into the category of Positive — label : 0 or Negative — label : 1 sentiment.\"\n },\n {\n \"code\": null,\n \"e\": 11126,\n \"s\": 11113,\n \"text\": \"Bag-of-Words\"\n },\n {\n \"code\": null,\n \"e\": 11133,\n \"s\": 11126,\n \"text\": \"TF-IDF\"\n },\n {\n \"code\": null,\n \"e\": 11153,\n \"s\": 11133,\n \"text\": \"Logistic Regression\"\n },\n {\n \"code\": null,\n \"e\": 11161,\n \"s\": 11153,\n \"text\": \"XGBoost\"\n },\n {\n \"code\": null,\n \"e\": 11176,\n \"s\": 11161,\n \"text\": \"Decision Trees\"\n },\n {\n \"code\": null,\n \"e\": 11185,\n \"s\": 11176,\n \"text\": \"F1 Score\"\n },\n {\n \"code\": null,\n \"e\": 11351,\n \"s\": 11185,\n \"text\": \"So, finally we have reached the end of our journey. We completed the tasks which were required to predict the sentiment of a particular tweet using Machine Learning.\"\n },\n {\n \"code\": null,\n \"e\": 11444,\n \"s\": 11351,\n \"text\": \"The questions that arises are “What is F1 Score ?” and “Why F1 Score instead of accuracy ?”.\"\n },\n {\n \"code\": null,\n \"e\": 11572,\n \"s\": 11444,\n \"text\": \"So, before we proceed you need to have a basic idea about the terminologies like Confusion Matrix and its contents for example.\"\n },\n {\n \"code\": null,\n \"e\": 11679,\n \"s\": 11572,\n \"text\": \"So, refer to this article for a basic understanding of the terminologies associated with Confusion Matrix.\"\n },\n {\n \"code\": null,\n \"e\": 11702,\n \"s\": 11679,\n \"text\": \"towardsdatascience.com\"\n },\n {\n \"code\": null,\n \"e\": 11740,\n \"s\": 11702,\n \"text\": \"OK , let us answer the above queries.\"\n },\n {\n \"code\": null,\n \"e\": 11818,\n \"s\": 11740,\n \"text\": \"Let us generate a countplot for our training dataset labels i.e. ‘0’ or ‘1’ .\"\n },\n {\n \"code\": null,\n \"e\": 11870,\n \"s\": 11818,\n \"text\": \"sns.countplot(train_original['label'])sns.despine()\"\n },\n {\n \"code\": null,\n \"e\": 12101,\n \"s\": 11870,\n \"text\": \"From the above countplot generated above we see how imbalanced our dataset is.We can see that the values with Positive — label : 0 sentiments are quite high in number as compared to the values with Negative — label : 1 sentiments.\"\n },\n {\n \"code\": null,\n \"e\": 12302,\n \"s\": 12101,\n \"text\": \"So when we keep Accuracy as our evaluation metric there may be cases where we may encounter high number of false positives. So that is why we use F1 Score as our evaluation metric instead of Accuracy.\"\n },\n {\n \"code\": null,\n \"e\": 12375,\n \"s\": 12302,\n \"text\": \"To know about F1 Score we first have to know about Precision and Recall.\"\n },\n {\n \"code\": null,\n \"e\": 12442,\n \"s\": 12375,\n \"text\": \"Precision means the percentage of your results which are relevant.\"\n },\n {\n \"code\": null,\n \"e\": 12540,\n \"s\": 12442,\n \"text\": \"Recall refers to the percentage of total relevant results correctly classified by your algorithm.\"\n },\n {\n \"code\": null,\n \"e\": 12659,\n \"s\": 12540,\n \"text\": \"We always face a trade-off situation between Precision and Recall i.e. High Precision gives low Recall and vice versa.\"\n },\n {\n \"code\": null,\n \"e\": 13070,\n \"s\": 12659,\n \"text\": \"In most problems, you could either give a higher priority to maximising precision, or recall, depending upon the problem you are trying to solve. But in general, there is a simpler metric which takes into account both precision and recall, and therefore, you can aim to maximise this number to make your model better. This metric is known as F1-score, which is simply the harmonic mean of Precision and Recall.\"\n },\n {\n \"code\": null,\n \"e\": 13220,\n \"s\": 13070,\n \"text\": \"So this metric seems much more easier and convenient to work with, as you only have to maximise one score, rather than balancing two separate scores.\"\n },\n {\n \"code\": null,\n \"e\": 13474,\n \"s\": 13220,\n \"text\": \"Finally, we have reached the end of the two part series of this article. I hope after this post you get a basic understanding of how you can start off with text processing and apply Machine Learning models to text data and extract information out of it.\"\n },\n {\n \"code\": null,\n \"e\": 13669,\n \"s\": 13474,\n \"text\": \"After this we can try to deploy our Machine Learning Models over a website using the available web frameworks such as Flask ,FastAPI etc. to production. But that’s a story for another blog post.\"\n },\n {\n \"code\": null,\n \"e\": 13691,\n \"s\": 13669,\n \"text\": \"You can reach me at :\"\n },\n {\n \"code\": null,\n \"e\": 13750,\n \"s\": 13691,\n \"text\": \"LinkedIn : https://www.linkedin.com/in/deepak-das-profile/\"\n }\n]"}}},{"rowIdx":417,"cells":{"title":{"kind":"string","value":"How to write and render LaTeX math formulas on Medium | by Shuyi Yang | Towards Data Science"},"text":{"kind":"string","value":"Every day, many practitioners share technical tutorials and findings by creating contents on Medium. However, posting articles with math formulas (eg. equations written in LaTeX) is a struggle since it is not supported on Medium. The most common solution to this limitation is transforming your formulas in images and add them to the article. You can take a screenshot to a rendered PDF file or use an online LaTeX editor like CodeCogs.\nThe image containing the formula attached to this article will be visualized as:\nThis is the most simple strategy to add math formulas when posting on Medium, but it is not flexible and it doesn’t work for inline equations.\nA similar approach consists in creating Jupyter Notebook Markdown with math formulas and upload the notebook to GitHub Gist.\nThen, just copy the Share link on Medium and the result is:\nThis is a math formula rendered in Jupyter Notebook:\nHonestly, it is not very fancy.\nAnother way to add LaTeX formulas on Medium is using TeX to Unicode Chrome Addon to convert LaTeX code to Unicode. Once installed the addon, just select the LaTeX code you want to convert, for example\n\\alpha : \\mathbb{R} \\to \\mathbb{R}\npress Alt+W (you can change the shortcut in configuration) and you should get the unicode version of the equation:\nα : R → R\nThis method doesn’t rely on images or embedded objects, it can work inline but it is also limited in characters and layout conversion. For example, the instance above\n(\\cos x + \\sin x)^2 = \\underbrace{\\cos^2 x + \\sin^2 x}_{1} + \\overbrace{2 \\sin x \\cos x}^{\\sin 2x}\nis converted in\n(\\cos x + \\sin x)2 = \\underbrace{\\cos2 x + \\sin2 x}1 + \\overbrace{2 \\sin x \\cos x}^{\\sin 2x}\nNot very useful when the formula is a little complex.\nThe last method to render mathematics formulas on Medium requires the installation of a Chome addon both on creator’s and reader’s browser. The addon is called Math Anywhere and it should render every MathML/LaTeX formulas on any page, also outside Medium. During the editing, you just need to put your formulas in appropriate delimiters like dollar symbols (the addon should be turned off) and during the reading, once activated the addon, the equations will be converted.\nThe formula\nshould be rendered correctly:\n(cosx+sinx)2=cos2x+sin2x+2sinxcosx(cos⁡x+sin⁡x)2=cos2⁡x+sin2⁡x+2sin⁡xcos⁡x(\\cos x + \\sin x)^2=\\cos^2 x + \\sin^2 x+2 \\sin x \\cos x\nand also inline formulas like α:R→Rα:R→R\\alpha: \\mathbb{R} \\to \\mathbb{R} should work. The drawback of this approach is that the reader is required to install the addon (only the first time). Of course, we can insert a kind reminder at the beginning of the post like this:\nThis post contains LaTeX formulas. To render them correctly, install Math Anywhere addon and activate it.\nDo you know any other method to add math formulas on Medium? Let me know in comments!\nHow to write mathematics on MediumHow to use math formula on Medium posting\nContacts: LinkedIn | Twitter"},"parsed":{"kind":"list like","value":[{"code":null,"e":609,"s":172,"text":"Every day, many practitioners share technical tutorials and findings by creating contents on Medium. However, posting articles with math formulas (eg. equations written in LaTeX) is a struggle since it is not supported on Medium. The most common solution to this limitation is transforming your formulas in images and add them to the article. You can take a screenshot to a rendered PDF file or use an online LaTeX editor like CodeCogs."},{"code":null,"e":690,"s":609,"text":"The image containing the formula attached to this article will be visualized as:"},{"code":null,"e":833,"s":690,"text":"This is the most simple strategy to add math formulas when posting on Medium, but it is not flexible and it doesn’t work for inline equations."},{"code":null,"e":958,"s":833,"text":"A similar approach consists in creating Jupyter Notebook Markdown with math formulas and upload the notebook to GitHub Gist."},{"code":null,"e":1018,"s":958,"text":"Then, just copy the Share link on Medium and the result is:"},{"code":null,"e":1071,"s":1018,"text":"This is a math formula rendered in Jupyter Notebook:"},{"code":null,"e":1103,"s":1071,"text":"Honestly, it is not very fancy."},{"code":null,"e":1304,"s":1103,"text":"Another way to add LaTeX formulas on Medium is using TeX to Unicode Chrome Addon to convert LaTeX code to Unicode. Once installed the addon, just select the LaTeX code you want to convert, for example"},{"code":null,"e":1339,"s":1304,"text":"\\alpha : \\mathbb{R} \\to \\mathbb{R}"},{"code":null,"e":1454,"s":1339,"text":"press Alt+W (you can change the shortcut in configuration) and you should get the unicode version of the equation:"},{"code":null,"e":1464,"s":1454,"text":"α : R → R"},{"code":null,"e":1631,"s":1464,"text":"This method doesn’t rely on images or embedded objects, it can work inline but it is also limited in characters and layout conversion. For example, the instance above"},{"code":null,"e":1736,"s":1631,"text":"(\\cos x + \\sin x)^2 = \\underbrace{\\cos^2 x + \\sin^2 x}_{1} + \\overbrace{2 \\sin x \\cos x}^{\\sin 2x}"},{"code":null,"e":1752,"s":1736,"text":"is converted in"},{"code":null,"e":1851,"s":1752,"text":"(\\cos x + \\sin x)2 = \\underbrace{\\cos2 x + \\sin2 x}1 + \\overbrace{2 \\sin x \\cos x}^{\\sin 2x}"},{"code":null,"e":1905,"s":1851,"text":"Not very useful when the formula is a little complex."},{"code":null,"e":2379,"s":1905,"text":"The last method to render mathematics formulas on Medium requires the installation of a Chome addon both on creator’s and reader’s browser. The addon is called Math Anywhere and it should render every MathML/LaTeX formulas on any page, also outside Medium. During the editing, you just need to put your formulas in appropriate delimiters like dollar symbols (the addon should be turned off) and during the reading, once activated the addon, the equations will be converted."},{"code":null,"e":2391,"s":2379,"text":"The formula"},{"code":null,"e":2421,"s":2391,"text":"should be rendered correctly:"},{"code":null,"e":2551,"s":2421,"text":"(cosx+sinx)2=cos2x+sin2x+2sinxcosx(cos⁡x+sin⁡x)2=cos2⁡x+sin2⁡x+2sin⁡xcos⁡x(\\cos x + \\sin x)^2=\\cos^2 x + \\sin^2 x+2 \\sin x \\cos x"},{"code":null,"e":2824,"s":2551,"text":"and also inline formulas like α:R→Rα:R→R\\alpha: \\mathbb{R} \\to \\mathbb{R} should work. The drawback of this approach is that the reader is required to install the addon (only the first time). Of course, we can insert a kind reminder at the beginning of the post like this:"},{"code":null,"e":2930,"s":2824,"text":"This post contains LaTeX formulas. To render them correctly, install Math Anywhere addon and activate it."},{"code":null,"e":3016,"s":2930,"text":"Do you know any other method to add math formulas on Medium? Let me know in comments!"},{"code":null,"e":3092,"s":3016,"text":"How to write mathematics on MediumHow to use math formula on Medium posting"}],"string":"[\n {\n \"code\": null,\n \"e\": 609,\n \"s\": 172,\n \"text\": \"Every day, many practitioners share technical tutorials and findings by creating contents on Medium. However, posting articles with math formulas (eg. equations written in LaTeX) is a struggle since it is not supported on Medium. The most common solution to this limitation is transforming your formulas in images and add them to the article. You can take a screenshot to a rendered PDF file or use an online LaTeX editor like CodeCogs.\"\n },\n {\n \"code\": null,\n \"e\": 690,\n \"s\": 609,\n \"text\": \"The image containing the formula attached to this article will be visualized as:\"\n },\n {\n \"code\": null,\n \"e\": 833,\n \"s\": 690,\n \"text\": \"This is the most simple strategy to add math formulas when posting on Medium, but it is not flexible and it doesn’t work for inline equations.\"\n },\n {\n \"code\": null,\n \"e\": 958,\n \"s\": 833,\n \"text\": \"A similar approach consists in creating Jupyter Notebook Markdown with math formulas and upload the notebook to GitHub Gist.\"\n },\n {\n \"code\": null,\n \"e\": 1018,\n \"s\": 958,\n \"text\": \"Then, just copy the Share link on Medium and the result is:\"\n },\n {\n \"code\": null,\n \"e\": 1071,\n \"s\": 1018,\n \"text\": \"This is a math formula rendered in Jupyter Notebook:\"\n },\n {\n \"code\": null,\n \"e\": 1103,\n \"s\": 1071,\n \"text\": \"Honestly, it is not very fancy.\"\n },\n {\n \"code\": null,\n \"e\": 1304,\n \"s\": 1103,\n \"text\": \"Another way to add LaTeX formulas on Medium is using TeX to Unicode Chrome Addon to convert LaTeX code to Unicode. Once installed the addon, just select the LaTeX code you want to convert, for example\"\n },\n {\n \"code\": null,\n \"e\": 1339,\n \"s\": 1304,\n \"text\": \"\\\\alpha : \\\\mathbb{R} \\\\to \\\\mathbb{R}\"\n },\n {\n \"code\": null,\n \"e\": 1454,\n \"s\": 1339,\n \"text\": \"press Alt+W (you can change the shortcut in configuration) and you should get the unicode version of the equation:\"\n },\n {\n \"code\": null,\n \"e\": 1464,\n \"s\": 1454,\n \"text\": \"α : R → R\"\n },\n {\n \"code\": null,\n \"e\": 1631,\n \"s\": 1464,\n \"text\": \"This method doesn’t rely on images or embedded objects, it can work inline but it is also limited in characters and layout conversion. For example, the instance above\"\n },\n {\n \"code\": null,\n \"e\": 1736,\n \"s\": 1631,\n \"text\": \"(\\\\cos x + \\\\sin x)^2 = \\\\underbrace{\\\\cos^2 x + \\\\sin^2 x}_{1} + \\\\overbrace{2 \\\\sin x \\\\cos x}^{\\\\sin 2x}\"\n },\n {\n \"code\": null,\n \"e\": 1752,\n \"s\": 1736,\n \"text\": \"is converted in\"\n },\n {\n \"code\": null,\n \"e\": 1851,\n \"s\": 1752,\n \"text\": \"(\\\\cos x + \\\\sin x)2 = \\\\underbrace{\\\\cos2 x + \\\\sin2 x}1 + \\\\overbrace{2 \\\\sin x \\\\cos x}^{\\\\sin 2x}\"\n },\n {\n \"code\": null,\n \"e\": 1905,\n \"s\": 1851,\n \"text\": \"Not very useful when the formula is a little complex.\"\n },\n {\n \"code\": null,\n \"e\": 2379,\n \"s\": 1905,\n \"text\": \"The last method to render mathematics formulas on Medium requires the installation of a Chome addon both on creator’s and reader’s browser. The addon is called Math Anywhere and it should render every MathML/LaTeX formulas on any page, also outside Medium. During the editing, you just need to put your formulas in appropriate delimiters like dollar symbols (the addon should be turned off) and during the reading, once activated the addon, the equations will be converted.\"\n },\n {\n \"code\": null,\n \"e\": 2391,\n \"s\": 2379,\n \"text\": \"The formula\"\n },\n {\n \"code\": null,\n \"e\": 2421,\n \"s\": 2391,\n \"text\": \"should be rendered correctly:\"\n },\n {\n \"code\": null,\n \"e\": 2551,\n \"s\": 2421,\n \"text\": \"(cosx+sinx)2=cos2x+sin2x+2sinxcosx(cos⁡x+sin⁡x)2=cos2⁡x+sin2⁡x+2sin⁡xcos⁡x(\\\\cos x + \\\\sin x)^2=\\\\cos^2 x + \\\\sin^2 x+2 \\\\sin x \\\\cos x\"\n },\n {\n \"code\": null,\n \"e\": 2824,\n \"s\": 2551,\n \"text\": \"and also inline formulas like α:R→Rα:R→R\\\\alpha: \\\\mathbb{R} \\\\to \\\\mathbb{R} should work. The drawback of this approach is that the reader is required to install the addon (only the first time). Of course, we can insert a kind reminder at the beginning of the post like this:\"\n },\n {\n \"code\": null,\n \"e\": 2930,\n \"s\": 2824,\n \"text\": \"This post contains LaTeX formulas. To render them correctly, install Math Anywhere addon and activate it.\"\n },\n {\n \"code\": null,\n \"e\": 3016,\n \"s\": 2930,\n \"text\": \"Do you know any other method to add math formulas on Medium? Let me know in comments!\"\n },\n {\n \"code\": null,\n \"e\": 3092,\n \"s\": 3016,\n \"text\": \"How to write mathematics on MediumHow to use math formula on Medium posting\"\n }\n]"}}},{"rowIdx":418,"cells":{"title":{"kind":"string","value":"Async and Await in Dart Programming"},"text":{"kind":"string","value":"Async and Await keywords are used to provide a declarative way to define the asynchronous function and use their results.\nThe async keyword is used when we want to declare a function as asynchronous and the await keyword is used only on asynchronous functions.\nvoid main() async { .. }\nIf the function has a declared return type, then update the type of the Future to the return type.\nFuture main() async { .. }\nAnd finally, we make use of await keyword when we want to wait for the asynchronous function to finish.\nawait someAsynchronousFunction()\nLet's consider an example where we are declaring the main function with the help of the async keyword and then wait for an asynchronous result using the await keyword.\nFuture printDelayedMessage() {\n return Future.delayed(Duration(seconds: 4), () => print('Delayed Output.'));\n}\nvoid main() async {\nawait printDelayedMessage(); // will block the output until the asynchronous result\nprint('First output ...');\n}\nDelayed Output.\nFirst output ...\nLet's consider one more complete example where we make use of both the async and await keyword.\nConsider the example shown below −\nvoid main() async {\n var userEmailFuture = getUserEmail();\n // register callback\n await userEmailFuture.then((userEmail) => print(userEmail));\n print('Hello');\n}\n// method which computes a future\nFuture getUserEmail() {\n // simulate a long network call\n return Future.delayed(Duration(seconds: 4), () => \"mukul@tutorialspoint.com\");\n}\nmukul@tutorialspoint.com\nHello"},"parsed":{"kind":"list like","value":[{"code":null,"e":1184,"s":1062,"text":"Async and Await keywords are used to provide a declarative way to define the asynchronous function and use their results."},{"code":null,"e":1323,"s":1184,"text":"The async keyword is used when we want to declare a function as asynchronous and the await keyword is used only on asynchronous functions."},{"code":null,"e":1348,"s":1323,"text":"void main() async { .. }"},{"code":null,"e":1450,"s":1348,"text":"If the function has a declared return type, then update the type of the Future to the return type."},{"code":null,"e":1483,"s":1450,"text":"Future main() async { .. }"},{"code":null,"e":1587,"s":1483,"text":"And finally, we make use of await keyword when we want to wait for the asynchronous function to finish."},{"code":null,"e":1620,"s":1587,"text":"await someAsynchronousFunction()"},{"code":null,"e":1788,"s":1620,"text":"Let's consider an example where we are declaring the main function with the help of the async keyword and then wait for an asynchronous result using the await keyword."},{"code":null,"e":2040,"s":1788,"text":"Future printDelayedMessage() {\n return Future.delayed(Duration(seconds: 4), () => print('Delayed Output.'));\n}\nvoid main() async {\nawait printDelayedMessage(); // will block the output until the asynchronous result\nprint('First output ...');\n}"},{"code":null,"e":2073,"s":2040,"text":"Delayed Output.\nFirst output ..."},{"code":null,"e":2169,"s":2073,"text":"Let's consider one more complete example where we make use of both the async and await keyword."},{"code":null,"e":2204,"s":2169,"text":"Consider the example shown below −"},{"code":null,"e":2559,"s":2204,"text":"void main() async {\n var userEmailFuture = getUserEmail();\n // register callback\n await userEmailFuture.then((userEmail) => print(userEmail));\n print('Hello');\n}\n// method which computes a future\nFuture getUserEmail() {\n // simulate a long network call\n return Future.delayed(Duration(seconds: 4), () => \"mukul@tutorialspoint.com\");\n}"},{"code":null,"e":2590,"s":2559,"text":"mukul@tutorialspoint.com\nHello"}],"string":"[\n {\n \"code\": null,\n \"e\": 1184,\n \"s\": 1062,\n \"text\": \"Async and Await keywords are used to provide a declarative way to define the asynchronous function and use their results.\"\n },\n {\n \"code\": null,\n \"e\": 1323,\n \"s\": 1184,\n \"text\": \"The async keyword is used when we want to declare a function as asynchronous and the await keyword is used only on asynchronous functions.\"\n },\n {\n \"code\": null,\n \"e\": 1348,\n \"s\": 1323,\n \"text\": \"void main() async { .. }\"\n },\n {\n \"code\": null,\n \"e\": 1450,\n \"s\": 1348,\n \"text\": \"If the function has a declared return type, then update the type of the Future to the return type.\"\n },\n {\n \"code\": null,\n \"e\": 1483,\n \"s\": 1450,\n \"text\": \"Future main() async { .. }\"\n },\n {\n \"code\": null,\n \"e\": 1587,\n \"s\": 1483,\n \"text\": \"And finally, we make use of await keyword when we want to wait for the asynchronous function to finish.\"\n },\n {\n \"code\": null,\n \"e\": 1620,\n \"s\": 1587,\n \"text\": \"await someAsynchronousFunction()\"\n },\n {\n \"code\": null,\n \"e\": 1788,\n \"s\": 1620,\n \"text\": \"Let's consider an example where we are declaring the main function with the help of the async keyword and then wait for an asynchronous result using the await keyword.\"\n },\n {\n \"code\": null,\n \"e\": 2040,\n \"s\": 1788,\n \"text\": \"Future printDelayedMessage() {\\n return Future.delayed(Duration(seconds: 4), () => print('Delayed Output.'));\\n}\\nvoid main() async {\\nawait printDelayedMessage(); // will block the output until the asynchronous result\\nprint('First output ...');\\n}\"\n },\n {\n \"code\": null,\n \"e\": 2073,\n \"s\": 2040,\n \"text\": \"Delayed Output.\\nFirst output ...\"\n },\n {\n \"code\": null,\n \"e\": 2169,\n \"s\": 2073,\n \"text\": \"Let's consider one more complete example where we make use of both the async and await keyword.\"\n },\n {\n \"code\": null,\n \"e\": 2204,\n \"s\": 2169,\n \"text\": \"Consider the example shown below −\"\n },\n {\n \"code\": null,\n \"e\": 2559,\n \"s\": 2204,\n \"text\": \"void main() async {\\n var userEmailFuture = getUserEmail();\\n // register callback\\n await userEmailFuture.then((userEmail) => print(userEmail));\\n print('Hello');\\n}\\n// method which computes a future\\nFuture getUserEmail() {\\n // simulate a long network call\\n return Future.delayed(Duration(seconds: 4), () => \\\"mukul@tutorialspoint.com\\\");\\n}\"\n },\n {\n \"code\": null,\n \"e\": 2590,\n \"s\": 2559,\n \"text\": \"mukul@tutorialspoint.com\\nHello\"\n }\n]"}}},{"rowIdx":419,"cells":{"title":{"kind":"string","value":"Python - Filter tuple with all same elements - GeeksforGeeks"},"text":{"kind":"string","value":"07 Oct, 2021\nGiven List of tuples, filter tuples that have same values.\nInput : test_list = [(5, 6, 5, 5), (6, 6, 6), (9, 10)] Output : [(6, 6, 6)] Explanation : 1 tuple with same elements.\nInput : test_list = [(5, 6, 5, 5), (6, 5, 6), (9, 10)] Output : [] Explanation : No tuple with same elements. \nMethod #1 : Using list comprehension + set() + len()\nIn this, we check for length of set converted tuple to be 1, if that checks out, tuple is added to result, else, omitted.\nPython3\n# Python3 code to demonstrate working of# Filter similar elements Tuples# Using list comprehension + set() + len() # initializing listtest_list = [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)] # printing original listprint(\"The original list is : \" + str(test_list)) # length is computed using len()res = [sub for sub in test_list if len(set(sub)) == 1] # printing resultsprint(\"Filtered Tuples : \" + str(res))\nThe original list is : [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)]\nFiltered Tuples : [(6, 6, 6), (1, 1)]\nMethod #2 : Using filter() + lambda + set() + len()\nIn this, we perform task of filtering using filter(), and single element logic is checked in lambda function using set() and len().\nPython3\n# Python3 code to demonstrate working of# Filter similar elements Tuples# Using filter() + lambda + set() + len() # initializing listtest_list = [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)] # printing original listprint(\"The original list is : \" + str(test_list)) # end result converted to list object# filter extracts req. tuplesres = list(filter(lambda sub : len(set(sub)) == 1, test_list)) # printing resultsprint(\"Filtered Tuples : \" + str(res))\nThe original list is : [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)]\nFiltered Tuples : [(6, 6, 6), (1, 1)]\nabhishek0719kadiyan\nPython list-programs\nPython\nPython Programs\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nComments\nOld Comments\nPython Dictionary\nEnumerate() in Python\nRead a file line by line in Python\nDefaultdict in Python\nDifferent ways to create Pandas Dataframe\nDefaultdict in Python\nPython program to convert a list to string\nPython | Get dictionary keys as a list\nPython | Split string into list of characters\nPython | Convert a list to dictionary"},"parsed":{"kind":"list like","value":[{"code":null,"e":24119,"s":24091,"text":"\n07 Oct, 2021"},{"code":null,"e":24178,"s":24119,"text":"Given List of tuples, filter tuples that have same values."},{"code":null,"e":24296,"s":24178,"text":"Input : test_list = [(5, 6, 5, 5), (6, 6, 6), (9, 10)] Output : [(6, 6, 6)] Explanation : 1 tuple with same elements."},{"code":null,"e":24407,"s":24296,"text":"Input : test_list = [(5, 6, 5, 5), (6, 5, 6), (9, 10)] Output : [] Explanation : No tuple with same elements. "},{"code":null,"e":24460,"s":24407,"text":"Method #1 : Using list comprehension + set() + len()"},{"code":null,"e":24582,"s":24460,"text":"In this, we check for length of set converted tuple to be 1, if that checks out, tuple is added to result, else, omitted."},{"code":null,"e":24590,"s":24582,"text":"Python3"},{"code":"# Python3 code to demonstrate working of# Filter similar elements Tuples# Using list comprehension + set() + len() # initializing listtest_list = [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)] # printing original listprint(\"The original list is : \" + str(test_list)) # length is computed using len()res = [sub for sub in test_list if len(set(sub)) == 1] # printing resultsprint(\"Filtered Tuples : \" + str(res))","e":25005,"s":24590,"text":null},{"code":null,"e":25109,"s":25005,"text":"The original list is : [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)]\nFiltered Tuples : [(6, 6, 6), (1, 1)]"},{"code":null,"e":25161,"s":25109,"text":"Method #2 : Using filter() + lambda + set() + len()"},{"code":null,"e":25293,"s":25161,"text":"In this, we perform task of filtering using filter(), and single element logic is checked in lambda function using set() and len()."},{"code":null,"e":25301,"s":25293,"text":"Python3"},{"code":"# Python3 code to demonstrate working of# Filter similar elements Tuples# Using filter() + lambda + set() + len() # initializing listtest_list = [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)] # printing original listprint(\"The original list is : \" + str(test_list)) # end result converted to list object# filter extracts req. tuplesres = list(filter(lambda sub : len(set(sub)) == 1, test_list)) # printing resultsprint(\"Filtered Tuples : \" + str(res))","e":25757,"s":25301,"text":null},{"code":null,"e":25861,"s":25757,"text":"The original list is : [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)]\nFiltered Tuples : [(6, 6, 6), (1, 1)]"},{"code":null,"e":25881,"s":25861,"text":"abhishek0719kadiyan"},{"code":null,"e":25902,"s":25881,"text":"Python list-programs"},{"code":null,"e":25909,"s":25902,"text":"Python"},{"code":null,"e":25925,"s":25909,"text":"Python Programs"},{"code":null,"e":26023,"s":25925,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":26032,"s":26023,"text":"Comments"},{"code":null,"e":26045,"s":26032,"text":"Old Comments"},{"code":null,"e":26063,"s":26045,"text":"Python Dictionary"},{"code":null,"e":26085,"s":26063,"text":"Enumerate() in Python"},{"code":null,"e":26120,"s":26085,"text":"Read a file line by line in Python"},{"code":null,"e":26142,"s":26120,"text":"Defaultdict in Python"},{"code":null,"e":26184,"s":26142,"text":"Different ways to create Pandas Dataframe"},{"code":null,"e":26206,"s":26184,"text":"Defaultdict in Python"},{"code":null,"e":26249,"s":26206,"text":"Python program to convert a list to string"},{"code":null,"e":26288,"s":26249,"text":"Python | Get dictionary keys as a list"},{"code":null,"e":26334,"s":26288,"text":"Python | Split string into list of characters"}],"string":"[\n {\n \"code\": null,\n \"e\": 24119,\n \"s\": 24091,\n \"text\": \"\\n07 Oct, 2021\"\n },\n {\n \"code\": null,\n \"e\": 24178,\n \"s\": 24119,\n \"text\": \"Given List of tuples, filter tuples that have same values.\"\n },\n {\n \"code\": null,\n \"e\": 24296,\n \"s\": 24178,\n \"text\": \"Input : test_list = [(5, 6, 5, 5), (6, 6, 6), (9, 10)] Output : [(6, 6, 6)] Explanation : 1 tuple with same elements.\"\n },\n {\n \"code\": null,\n \"e\": 24407,\n \"s\": 24296,\n \"text\": \"Input : test_list = [(5, 6, 5, 5), (6, 5, 6), (9, 10)] Output : [] Explanation : No tuple with same elements. \"\n },\n {\n \"code\": null,\n \"e\": 24460,\n \"s\": 24407,\n \"text\": \"Method #1 : Using list comprehension + set() + len()\"\n },\n {\n \"code\": null,\n \"e\": 24582,\n \"s\": 24460,\n \"text\": \"In this, we check for length of set converted tuple to be 1, if that checks out, tuple is added to result, else, omitted.\"\n },\n {\n \"code\": null,\n \"e\": 24590,\n \"s\": 24582,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"# Python3 code to demonstrate working of# Filter similar elements Tuples# Using list comprehension + set() + len() # initializing listtest_list = [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)] # printing original listprint(\\\"The original list is : \\\" + str(test_list)) # length is computed using len()res = [sub for sub in test_list if len(set(sub)) == 1] # printing resultsprint(\\\"Filtered Tuples : \\\" + str(res))\",\n \"e\": 25005,\n \"s\": 24590,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 25109,\n \"s\": 25005,\n \"text\": \"The original list is : [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)]\\nFiltered Tuples : [(6, 6, 6), (1, 1)]\"\n },\n {\n \"code\": null,\n \"e\": 25161,\n \"s\": 25109,\n \"text\": \"Method #2 : Using filter() + lambda + set() + len()\"\n },\n {\n \"code\": null,\n \"e\": 25293,\n \"s\": 25161,\n \"text\": \"In this, we perform task of filtering using filter(), and single element logic is checked in lambda function using set() and len().\"\n },\n {\n \"code\": null,\n \"e\": 25301,\n \"s\": 25293,\n \"text\": \"Python3\"\n },\n {\n \"code\": \"# Python3 code to demonstrate working of# Filter similar elements Tuples# Using filter() + lambda + set() + len() # initializing listtest_list = [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)] # printing original listprint(\\\"The original list is : \\\" + str(test_list)) # end result converted to list object# filter extracts req. tuplesres = list(filter(lambda sub : len(set(sub)) == 1, test_list)) # printing resultsprint(\\\"Filtered Tuples : \\\" + str(res))\",\n \"e\": 25757,\n \"s\": 25301,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 25861,\n \"s\": 25757,\n \"text\": \"The original list is : [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)]\\nFiltered Tuples : [(6, 6, 6), (1, 1)]\"\n },\n {\n \"code\": null,\n \"e\": 25881,\n \"s\": 25861,\n \"text\": \"abhishek0719kadiyan\"\n },\n {\n \"code\": null,\n \"e\": 25902,\n \"s\": 25881,\n \"text\": \"Python list-programs\"\n },\n {\n \"code\": null,\n \"e\": 25909,\n \"s\": 25902,\n \"text\": \"Python\"\n },\n {\n \"code\": null,\n \"e\": 25925,\n \"s\": 25909,\n \"text\": \"Python Programs\"\n },\n {\n \"code\": null,\n \"e\": 26023,\n \"s\": 25925,\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\": 26032,\n \"s\": 26023,\n \"text\": \"Comments\"\n },\n {\n \"code\": null,\n \"e\": 26045,\n \"s\": 26032,\n \"text\": \"Old Comments\"\n },\n {\n \"code\": null,\n \"e\": 26063,\n \"s\": 26045,\n \"text\": \"Python Dictionary\"\n },\n {\n \"code\": null,\n \"e\": 26085,\n \"s\": 26063,\n \"text\": \"Enumerate() in Python\"\n },\n {\n \"code\": null,\n \"e\": 26120,\n \"s\": 26085,\n \"text\": \"Read a file line by line in Python\"\n },\n {\n \"code\": null,\n \"e\": 26142,\n \"s\": 26120,\n \"text\": \"Defaultdict in Python\"\n },\n {\n \"code\": null,\n \"e\": 26184,\n \"s\": 26142,\n \"text\": \"Different ways to create Pandas Dataframe\"\n },\n {\n \"code\": null,\n \"e\": 26206,\n \"s\": 26184,\n \"text\": \"Defaultdict in Python\"\n },\n {\n \"code\": null,\n \"e\": 26249,\n \"s\": 26206,\n \"text\": \"Python program to convert a list to string\"\n },\n {\n \"code\": null,\n \"e\": 26288,\n \"s\": 26249,\n \"text\": \"Python | Get dictionary keys as a list\"\n },\n {\n \"code\": null,\n \"e\": 26334,\n \"s\": 26288,\n \"text\": \"Python | Split string into list of characters\"\n }\n]"}}},{"rowIdx":420,"cells":{"title":{"kind":"string","value":"Animate border-color property with CSS"},"text":{"kind":"string","value":"To implement animation on the border-color property with CSS, you can try to run the following code\nLive Demo\n\n\n \n \n \n \n

Performing Animation for color of border

\n
\n \n"},"parsed":{"kind":"list like","value":[{"code":null,"e":1162,"s":1062,"text":"To implement animation on the border-color property with CSS, you can try to run the following code"},{"code":null,"e":1172,"s":1162,"text":"Live Demo"},{"code":null,"e":1726,"s":1172,"text":"\n\n \n \n \n \n

Performing Animation for color of border

\n
\n \n"}],"string":"[\n {\n \"code\": null,\n \"e\": 1162,\n \"s\": 1062,\n \"text\": \"To implement animation on the border-color property with CSS, you can try to run the following code\"\n },\n {\n \"code\": null,\n \"e\": 1172,\n \"s\": 1162,\n \"text\": \"Live Demo\"\n },\n {\n \"code\": null,\n \"e\": 1726,\n \"s\": 1172,\n \"text\": \"\\n\\n \\n \\n \\n \\n

Performing Animation for color of border

\\n
\\n \\n\"\n }\n]"}}},{"rowIdx":421,"cells":{"title":{"kind":"string","value":"AbstractList remove() Method in Java with Examples - GeeksforGeeks"},"text":{"kind":"string","value":"26 Nov, 2018\nThe remove(int index) method of java.util.AbstractList class is used to remove an element from an abstract list from a specific position or index.\nSyntax:\nAbstractList.remove(int index)\nParameters: The parameter index is of integer data type and specifies the position of the element to be removed from the AbstractList.\nReturn Value: This method returns the element that has just been removed from the list.\nBelow programs illustrate the AbstractList.remove(int index) method:\nProgram 1:\n// Java code to illustrate remove() method import java.util.*;import java.util.LinkedList; public class AbstractListDemo { public static void main(String args[]) { // Creating an empty AbstractList AbstractList list = new LinkedList(); // Using add() method to add elements in the list list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); list.add(\"10\"); list.add(\"20\"); // Output the list System.out.println(\"AbstractList: \" + list); // Remove the head using remove() list.remove(3); // Print the final list System.out.println(\"Final AbstractList: \" + list); }}\nAbstractList: [Geeks, for, Geeks, 10, 20]\nFinal AbstractList: [Geeks, for, Geeks, 20]\n\nProgram 2:\n// Java code to illustrate remove() when position of// element is passed as parameter import java.util.*;import java.util.LinkedList; public class AbstractListDemo { public static void main(String args[]) { // Creating an empty AbstractList AbstractList list = new LinkedList(); // Use add() method to add elements in the list list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); list.add(\"10\"); list.add(\"20\"); // Output the list System.out.println(\"AbstractList:\" + list); // Remove the head using remove() list.remove(0); // Print the final list System.out.println(\"Final AbstractList:\" + list); }}\nAbstractList:[Geeks, for, Geeks, 10, 20]\nFinal AbstractList:[for, Geeks, 10, 20]\n\nJava - util package\nJava-AbstractList\nJava-Collections\nJava-Functions\nJava\nJava\nJava-Collections\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nComments\nOld Comments\nArrays in Java\nSplit() String method in Java with examples\nFor-each loop in Java\nReverse a string in Java\nArrays.sort() in Java with examples\nObject Oriented Programming (OOPs) Concept in Java\nHashMap in Java with Examples\nHow to iterate any Map in Java\nInterfaces in Java\nInitialize an ArrayList in Java"},"parsed":{"kind":"list like","value":[{"code":null,"e":23299,"s":23271,"text":"\n26 Nov, 2018"},{"code":null,"e":23446,"s":23299,"text":"The remove(int index) method of java.util.AbstractList class is used to remove an element from an abstract list from a specific position or index."},{"code":null,"e":23454,"s":23446,"text":"Syntax:"},{"code":null,"e":23485,"s":23454,"text":"AbstractList.remove(int index)"},{"code":null,"e":23620,"s":23485,"text":"Parameters: The parameter index is of integer data type and specifies the position of the element to be removed from the AbstractList."},{"code":null,"e":23708,"s":23620,"text":"Return Value: This method returns the element that has just been removed from the list."},{"code":null,"e":23777,"s":23708,"text":"Below programs illustrate the AbstractList.remove(int index) method:"},{"code":null,"e":23788,"s":23777,"text":"Program 1:"},{"code":"// Java code to illustrate remove() method import java.util.*;import java.util.LinkedList; public class AbstractListDemo { public static void main(String args[]) { // Creating an empty AbstractList AbstractList list = new LinkedList(); // Using add() method to add elements in the list list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); list.add(\"10\"); list.add(\"20\"); // Output the list System.out.println(\"AbstractList: \" + list); // Remove the head using remove() list.remove(3); // Print the final list System.out.println(\"Final AbstractList: \" + list); }}","e":24499,"s":23788,"text":null},{"code":null,"e":24586,"s":24499,"text":"AbstractList: [Geeks, for, Geeks, 10, 20]\nFinal AbstractList: [Geeks, for, Geeks, 20]\n"},{"code":null,"e":24597,"s":24586,"text":"Program 2:"},{"code":"// Java code to illustrate remove() when position of// element is passed as parameter import java.util.*;import java.util.LinkedList; public class AbstractListDemo { public static void main(String args[]) { // Creating an empty AbstractList AbstractList list = new LinkedList(); // Use add() method to add elements in the list list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); list.add(\"10\"); list.add(\"20\"); // Output the list System.out.println(\"AbstractList:\" + list); // Remove the head using remove() list.remove(0); // Print the final list System.out.println(\"Final AbstractList:\" + list); }}","e":25336,"s":24597,"text":null},{"code":null,"e":25418,"s":25336,"text":"AbstractList:[Geeks, for, Geeks, 10, 20]\nFinal AbstractList:[for, Geeks, 10, 20]\n"},{"code":null,"e":25438,"s":25418,"text":"Java - util package"},{"code":null,"e":25456,"s":25438,"text":"Java-AbstractList"},{"code":null,"e":25473,"s":25456,"text":"Java-Collections"},{"code":null,"e":25488,"s":25473,"text":"Java-Functions"},{"code":null,"e":25493,"s":25488,"text":"Java"},{"code":null,"e":25498,"s":25493,"text":"Java"},{"code":null,"e":25515,"s":25498,"text":"Java-Collections"},{"code":null,"e":25613,"s":25515,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":25622,"s":25613,"text":"Comments"},{"code":null,"e":25635,"s":25622,"text":"Old Comments"},{"code":null,"e":25650,"s":25635,"text":"Arrays in Java"},{"code":null,"e":25694,"s":25650,"text":"Split() String method in Java with examples"},{"code":null,"e":25716,"s":25694,"text":"For-each loop in Java"},{"code":null,"e":25741,"s":25716,"text":"Reverse a string in Java"},{"code":null,"e":25777,"s":25741,"text":"Arrays.sort() in Java with examples"},{"code":null,"e":25828,"s":25777,"text":"Object Oriented Programming (OOPs) Concept in Java"},{"code":null,"e":25858,"s":25828,"text":"HashMap in Java with Examples"},{"code":null,"e":25889,"s":25858,"text":"How to iterate any Map in Java"},{"code":null,"e":25908,"s":25889,"text":"Interfaces in Java"}],"string":"[\n {\n \"code\": null,\n \"e\": 23299,\n \"s\": 23271,\n \"text\": \"\\n26 Nov, 2018\"\n },\n {\n \"code\": null,\n \"e\": 23446,\n \"s\": 23299,\n \"text\": \"The remove(int index) method of java.util.AbstractList class is used to remove an element from an abstract list from a specific position or index.\"\n },\n {\n \"code\": null,\n \"e\": 23454,\n \"s\": 23446,\n \"text\": \"Syntax:\"\n },\n {\n \"code\": null,\n \"e\": 23485,\n \"s\": 23454,\n \"text\": \"AbstractList.remove(int index)\"\n },\n {\n \"code\": null,\n \"e\": 23620,\n \"s\": 23485,\n \"text\": \"Parameters: The parameter index is of integer data type and specifies the position of the element to be removed from the AbstractList.\"\n },\n {\n \"code\": null,\n \"e\": 23708,\n \"s\": 23620,\n \"text\": \"Return Value: This method returns the element that has just been removed from the list.\"\n },\n {\n \"code\": null,\n \"e\": 23777,\n \"s\": 23708,\n \"text\": \"Below programs illustrate the AbstractList.remove(int index) method:\"\n },\n {\n \"code\": null,\n \"e\": 23788,\n \"s\": 23777,\n \"text\": \"Program 1:\"\n },\n {\n \"code\": \"// Java code to illustrate remove() method import java.util.*;import java.util.LinkedList; public class AbstractListDemo { public static void main(String args[]) { // Creating an empty AbstractList AbstractList list = new LinkedList(); // Using add() method to add elements in the list list.add(\\\"Geeks\\\"); list.add(\\\"for\\\"); list.add(\\\"Geeks\\\"); list.add(\\\"10\\\"); list.add(\\\"20\\\"); // Output the list System.out.println(\\\"AbstractList: \\\" + list); // Remove the head using remove() list.remove(3); // Print the final list System.out.println(\\\"Final AbstractList: \\\" + list); }}\",\n \"e\": 24499,\n \"s\": 23788,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 24586,\n \"s\": 24499,\n \"text\": \"AbstractList: [Geeks, for, Geeks, 10, 20]\\nFinal AbstractList: [Geeks, for, Geeks, 20]\\n\"\n },\n {\n \"code\": null,\n \"e\": 24597,\n \"s\": 24586,\n \"text\": \"Program 2:\"\n },\n {\n \"code\": \"// Java code to illustrate remove() when position of// element is passed as parameter import java.util.*;import java.util.LinkedList; public class AbstractListDemo { public static void main(String args[]) { // Creating an empty AbstractList AbstractList list = new LinkedList(); // Use add() method to add elements in the list list.add(\\\"Geeks\\\"); list.add(\\\"for\\\"); list.add(\\\"Geeks\\\"); list.add(\\\"10\\\"); list.add(\\\"20\\\"); // Output the list System.out.println(\\\"AbstractList:\\\" + list); // Remove the head using remove() list.remove(0); // Print the final list System.out.println(\\\"Final AbstractList:\\\" + list); }}\",\n \"e\": 25336,\n \"s\": 24597,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 25418,\n \"s\": 25336,\n \"text\": \"AbstractList:[Geeks, for, Geeks, 10, 20]\\nFinal AbstractList:[for, Geeks, 10, 20]\\n\"\n },\n {\n \"code\": null,\n \"e\": 25438,\n \"s\": 25418,\n \"text\": \"Java - util package\"\n },\n {\n \"code\": null,\n \"e\": 25456,\n \"s\": 25438,\n \"text\": \"Java-AbstractList\"\n },\n {\n \"code\": null,\n \"e\": 25473,\n \"s\": 25456,\n \"text\": \"Java-Collections\"\n },\n {\n \"code\": null,\n \"e\": 25488,\n \"s\": 25473,\n \"text\": \"Java-Functions\"\n },\n {\n \"code\": null,\n \"e\": 25493,\n \"s\": 25488,\n \"text\": \"Java\"\n },\n {\n \"code\": null,\n \"e\": 25498,\n \"s\": 25493,\n \"text\": \"Java\"\n },\n {\n \"code\": null,\n \"e\": 25515,\n \"s\": 25498,\n \"text\": \"Java-Collections\"\n },\n {\n \"code\": null,\n \"e\": 25613,\n \"s\": 25515,\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\": 25622,\n \"s\": 25613,\n \"text\": \"Comments\"\n },\n {\n \"code\": null,\n \"e\": 25635,\n \"s\": 25622,\n \"text\": \"Old Comments\"\n },\n {\n \"code\": null,\n \"e\": 25650,\n \"s\": 25635,\n \"text\": \"Arrays in Java\"\n },\n {\n \"code\": null,\n \"e\": 25694,\n \"s\": 25650,\n \"text\": \"Split() String method in Java with examples\"\n },\n {\n \"code\": null,\n \"e\": 25716,\n \"s\": 25694,\n \"text\": \"For-each loop in Java\"\n },\n {\n \"code\": null,\n \"e\": 25741,\n \"s\": 25716,\n \"text\": \"Reverse a string in Java\"\n },\n {\n \"code\": null,\n \"e\": 25777,\n \"s\": 25741,\n \"text\": \"Arrays.sort() in Java with examples\"\n },\n {\n \"code\": null,\n \"e\": 25828,\n \"s\": 25777,\n \"text\": \"Object Oriented Programming (OOPs) Concept in Java\"\n },\n {\n \"code\": null,\n \"e\": 25858,\n \"s\": 25828,\n \"text\": \"HashMap in Java with Examples\"\n },\n {\n \"code\": null,\n \"e\": 25889,\n \"s\": 25858,\n \"text\": \"How to iterate any Map in Java\"\n },\n {\n \"code\": null,\n \"e\": 25908,\n \"s\": 25889,\n \"text\": \"Interfaces in Java\"\n }\n]"}}},{"rowIdx":422,"cells":{"title":{"kind":"string","value":"How to define the breaks for a histogram using ggplot2 in R?"},"text":{"kind":"string","value":"To manually define the breaks for a histogram using ggplot2, we can use breaks argument in the geom_histogram function. While creating the number of breaks we must be careful about the starting point and the difference between values for breaks. This will define the number of bars for histogram so it should be taken seriously and should be according to the distribution of the data.\nConsider the below data frame −\n Live Demo\nx<-rnorm(5000,525,30.24)\ndf<-data.frame(x)\nhead(df,20)\n x\n1 524.0964\n2 490.5952\n3 518.6243\n4 544.0018\n5 480.8306\n6 461.2975\n7 464.0870\n8 516.5240\n9 517.3936\n10 506.0277\n11 480.3274\n12 505.6415\n13 440.9464\n14 532.0064\n15 482.7700\n16 517.3608\n17 536.5500\n18 518.7121\n19 598.5776\n20 506.3834\nLoading ggplot2 package and creating a histogram of x −\nlibrary(ggplot2)\nggplot(df,aes(x))+geom_histogram(bins=30)\nCreating histogram of x with manually defined breaks −\nggplot(df,aes(x))+geom_histogram(bins=30,breaks=c(400,420,440,460,480,500,520,540,560))"},"parsed":{"kind":"list like","value":[{"code":null,"e":1447,"s":1062,"text":"To manually define the breaks for a histogram using ggplot2, we can use breaks argument in the geom_histogram function. While creating the number of breaks we must be careful about the starting point and the difference between values for breaks. This will define the number of bars for histogram so it should be taken seriously and should be according to the distribution of the data."},{"code":null,"e":1479,"s":1447,"text":"Consider the below data frame −"},{"code":null,"e":1490,"s":1479,"text":" Live Demo"},{"code":null,"e":1545,"s":1490,"text":"x<-rnorm(5000,525,30.24)\ndf<-data.frame(x)\nhead(df,20)"},{"code":null,"e":1791,"s":1545,"text":" x\n1 524.0964\n2 490.5952\n3 518.6243\n4 544.0018\n5 480.8306\n6 461.2975\n7 464.0870\n8 516.5240\n9 517.3936\n10 506.0277\n11 480.3274\n12 505.6415\n13 440.9464\n14 532.0064\n15 482.7700\n16 517.3608\n17 536.5500\n18 518.7121\n19 598.5776\n20 506.3834"},{"code":null,"e":1847,"s":1791,"text":"Loading ggplot2 package and creating a histogram of x −"},{"code":null,"e":1906,"s":1847,"text":"library(ggplot2)\nggplot(df,aes(x))+geom_histogram(bins=30)"},{"code":null,"e":1961,"s":1906,"text":"Creating histogram of x with manually defined breaks −"},{"code":null,"e":2049,"s":1961,"text":"ggplot(df,aes(x))+geom_histogram(bins=30,breaks=c(400,420,440,460,480,500,520,540,560))"}],"string":"[\n {\n \"code\": null,\n \"e\": 1447,\n \"s\": 1062,\n \"text\": \"To manually define the breaks for a histogram using ggplot2, we can use breaks argument in the geom_histogram function. While creating the number of breaks we must be careful about the starting point and the difference between values for breaks. This will define the number of bars for histogram so it should be taken seriously and should be according to the distribution of the data.\"\n },\n {\n \"code\": null,\n \"e\": 1479,\n \"s\": 1447,\n \"text\": \"Consider the below data frame −\"\n },\n {\n \"code\": null,\n \"e\": 1490,\n \"s\": 1479,\n \"text\": \" Live Demo\"\n },\n {\n \"code\": null,\n \"e\": 1545,\n \"s\": 1490,\n \"text\": \"x<-rnorm(5000,525,30.24)\\ndf<-data.frame(x)\\nhead(df,20)\"\n },\n {\n \"code\": null,\n \"e\": 1791,\n \"s\": 1545,\n \"text\": \" x\\n1 524.0964\\n2 490.5952\\n3 518.6243\\n4 544.0018\\n5 480.8306\\n6 461.2975\\n7 464.0870\\n8 516.5240\\n9 517.3936\\n10 506.0277\\n11 480.3274\\n12 505.6415\\n13 440.9464\\n14 532.0064\\n15 482.7700\\n16 517.3608\\n17 536.5500\\n18 518.7121\\n19 598.5776\\n20 506.3834\"\n },\n {\n \"code\": null,\n \"e\": 1847,\n \"s\": 1791,\n \"text\": \"Loading ggplot2 package and creating a histogram of x −\"\n },\n {\n \"code\": null,\n \"e\": 1906,\n \"s\": 1847,\n \"text\": \"library(ggplot2)\\nggplot(df,aes(x))+geom_histogram(bins=30)\"\n },\n {\n \"code\": null,\n \"e\": 1961,\n \"s\": 1906,\n \"text\": \"Creating histogram of x with manually defined breaks −\"\n },\n {\n \"code\": null,\n \"e\": 2049,\n \"s\": 1961,\n \"text\": \"ggplot(df,aes(x))+geom_histogram(bins=30,breaks=c(400,420,440,460,480,500,520,540,560))\"\n }\n]"}}},{"rowIdx":423,"cells":{"title":{"kind":"string","value":".NET Core API for the Angular Tour of Heroes App — Introduction | by Richard Peterson | Towards Data Science"},"text":{"kind":"string","value":"This article assumes that you have already built the Angular official tutorial — Tour of Heroes app. If you have not built this, you should check the Angular docs, or download from here. Everything else will be taken care of in this series of articles!\nIn this series, we will embark on a magical exploration of .NET Core, Angular, Docker, Azure, and Azure SQL Server.\nWe will become familiar with several technologies, such as Docker containers, C#, JavaScript, SQL, and the Azure Command Line Interface.\nThe end result of these articles will be an Angular front end with a .NET Core API that talks to an Azure SQL server, all hosted on Azure.\nThis article — environment setup and explanation of MVC.Local Docker setup of a Microsoft SQL Server (mssql).Build the .NET API.Deploying your API to Azure.Deploy your Angular app to Azure.\nThis article — environment setup and explanation of MVC.\nLocal Docker setup of a Microsoft SQL Server (mssql).\nBuild the .NET API.\nDeploying your API to Azure.\nDeploy your Angular app to Azure.\nVisual Studio Code (it’s the free one)Angular CLI (should already be setup from the Tour Of Heroes Tutorial).NET Core — This API will use version 3.0.2Postman — for testing the APIDocker — for a local dev database, and for containerizing our apps\nVisual Studio Code (it’s the free one)\nAngular CLI (should already be setup from the Tour Of Heroes Tutorial)\n.NET Core — This API will use version 3.0.2\nPostman — for testing the API\nDocker — for a local dev database, and for containerizing our apps\nFollow along using my GitHub repo.\nFirst, launch your Tour of Heroes Angular app by running ng serve --open from the root directory of your app. You should see the app running on port 4200.\nWhen you built the original app, it had a built-in web server that mimicked an actual server. We will be replacing this artificial server with a web API written in C# using the .NET framework. Let’s shutdown the app and get to work on the API.\nMake sure the .NET Core CLI is installed by running dotnet --version. The .NET Core CLI has lots of templates from which to choose. Check these option flags with dotnet new -h. Do you see the Template for ASP.NET Core Web API? Its Short Name is webapi. Create your API from the command line by running:\ndotnet new webapi -n Heroes.API\nYou should get a result of Restore succeeded. Move into the new directory by typing cd Heroes.API. Check ls to see the folders and files that have been created, and launch VS Code in this directory by typing (with a period)code . .\nLet’s also make sure the API launches by running dotnet run. In a web browser, navigate to https://localhost:5001/weatherforecast and accept the unsafe destination to view sample output returned by your API in JSON format. This is great because is gives you an idea of how .NET Core APIs work by using a Model and a Controller. We will create our own Model and Controller, and also add a database Context.\nMVC is a web development philosophy that recommends the separation of pieces of an app into logical components. This allows you to build each piece separately and confirm it works, and then connect your pieces for a finished whole. This article from FreeCodeCamp.org does an excellent job of explaining how MVC is like ordering a drink from a bar. The drink menu is the View, and you make requests to the bartender (Controller), who makes drinks based on ingredients and instructions (Model), and returns your finished drink to the bar (View).\nIn the context of our app, this means:\nVIEW: The Angular app will receive input, make requests, and display data.CONTROLLER: C# class that accepts incoming requests, deciphers the route of the request, and uses a specified Model to interact with the database based on the route it receives.MODEL: C# class that defines the data being passed to or retrieved from the database. This will mean defining things like id is an integer, name is a string, so that C# can pass these values in a way that SQL can interpret. Database context is important to the Model\nVIEW: The Angular app will receive input, make requests, and display data.\nCONTROLLER: C# class that accepts incoming requests, deciphers the route of the request, and uses a specified Model to interact with the database based on the route it receives.\nMODEL: C# class that defines the data being passed to or retrieved from the database. This will mean defining things like id is an integer, name is a string, so that C# can pass these values in a way that SQL can interpret. Database context is important to the Model\nMicrosoft has published great tutorials on .NET Core, and I highly recommend checking out:\nTutorial: Create a web API with ASP.NET Core.Create a web app with ASP.NET Core MVC\nTutorial: Create a web API with ASP.NET Core.\nCreate a web app with ASP.NET Core MVC\nAt this point, you should have 2 resources:\nA working Angular Tour of Heroes App.A generic .NET Core API.\nA working Angular Tour of Heroes App.\nA generic .NET Core API.\nWe need to create a database that can handle requests from our API Controller. We will eventually move to a hosted Azure SQL database, but for now, let’s launch a local Docker container of a Microsoft SQL Server. This container is a lightweight version of SQL Server that we can easily spin up for development.\nHead on over to Build a MSSQL Docker Container to setup the database!\nBuild your .NET API from scratch, with a little help from the aspnet-codegenerator. The app will handle API requests to these routes:\nGET: api/Heroes — this method will return all the heroes in the databaseGET: api/Heroes/5 — this method will return a specific hero from the database. In this case, it will return the hero with an Id of 5.PUT: api/Heroes/5 — this method will update a specific hero’s information.POST: api/Heroes — this method will post a new hero to the database.DELETE: api/Heroes/5 — this method will delete a specific hero from the database.\nGET: api/Heroes — this method will return all the heroes in the database\nGET: api/Heroes/5 — this method will return a specific hero from the database. In this case, it will return the hero with an Id of 5.\nPUT: api/Heroes/5 — this method will update a specific hero’s information.\nPOST: api/Heroes — this method will post a new hero to the database.\nDELETE: api/Heroes/5 — this method will delete a specific hero from the database.\nAt the end of this article, you will have a working local version of the Angular app, .NET API, and database.\nFinally, you will create an Azure SQL server and deploy your .NET API to an Azure remote git repo, and serve with a web app.\nThen you will deploy your angular app to Azure as a Docker container web app.\nThank you for reading!"},"parsed":{"kind":"list like","value":[{"code":null,"e":425,"s":172,"text":"This article assumes that you have already built the Angular official tutorial — Tour of Heroes app. If you have not built this, you should check the Angular docs, or download from here. Everything else will be taken care of in this series of articles!"},{"code":null,"e":541,"s":425,"text":"In this series, we will embark on a magical exploration of .NET Core, Angular, Docker, Azure, and Azure SQL Server."},{"code":null,"e":678,"s":541,"text":"We will become familiar with several technologies, such as Docker containers, C#, JavaScript, SQL, and the Azure Command Line Interface."},{"code":null,"e":817,"s":678,"text":"The end result of these articles will be an Angular front end with a .NET Core API that talks to an Azure SQL server, all hosted on Azure."},{"code":null,"e":1007,"s":817,"text":"This article — environment setup and explanation of MVC.Local Docker setup of a Microsoft SQL Server (mssql).Build the .NET API.Deploying your API to Azure.Deploy your Angular app to Azure."},{"code":null,"e":1064,"s":1007,"text":"This article — environment setup and explanation of MVC."},{"code":null,"e":1118,"s":1064,"text":"Local Docker setup of a Microsoft SQL Server (mssql)."},{"code":null,"e":1138,"s":1118,"text":"Build the .NET API."},{"code":null,"e":1167,"s":1138,"text":"Deploying your API to Azure."},{"code":null,"e":1201,"s":1167,"text":"Deploy your Angular app to Azure."},{"code":null,"e":1448,"s":1201,"text":"Visual Studio Code (it’s the free one)Angular CLI (should already be setup from the Tour Of Heroes Tutorial).NET Core — This API will use version 3.0.2Postman — for testing the APIDocker — for a local dev database, and for containerizing our apps"},{"code":null,"e":1487,"s":1448,"text":"Visual Studio Code (it’s the free one)"},{"code":null,"e":1558,"s":1487,"text":"Angular CLI (should already be setup from the Tour Of Heroes Tutorial)"},{"code":null,"e":1602,"s":1558,"text":".NET Core — This API will use version 3.0.2"},{"code":null,"e":1632,"s":1602,"text":"Postman — for testing the API"},{"code":null,"e":1699,"s":1632,"text":"Docker — for a local dev database, and for containerizing our apps"},{"code":null,"e":1734,"s":1699,"text":"Follow along using my GitHub repo."},{"code":null,"e":1889,"s":1734,"text":"First, launch your Tour of Heroes Angular app by running ng serve --open from the root directory of your app. You should see the app running on port 4200."},{"code":null,"e":2133,"s":1889,"text":"When you built the original app, it had a built-in web server that mimicked an actual server. We will be replacing this artificial server with a web API written in C# using the .NET framework. Let’s shutdown the app and get to work on the API."},{"code":null,"e":2436,"s":2133,"text":"Make sure the .NET Core CLI is installed by running dotnet --version. The .NET Core CLI has lots of templates from which to choose. Check these option flags with dotnet new -h. Do you see the Template for ASP.NET Core Web API? Its Short Name is webapi. Create your API from the command line by running:"},{"code":null,"e":2468,"s":2436,"text":"dotnet new webapi -n Heroes.API"},{"code":null,"e":2700,"s":2468,"text":"You should get a result of Restore succeeded. Move into the new directory by typing cd Heroes.API. Check ls to see the folders and files that have been created, and launch VS Code in this directory by typing (with a period)code . ."},{"code":null,"e":3106,"s":2700,"text":"Let’s also make sure the API launches by running dotnet run. In a web browser, navigate to https://localhost:5001/weatherforecast and accept the unsafe destination to view sample output returned by your API in JSON format. This is great because is gives you an idea of how .NET Core APIs work by using a Model and a Controller. We will create our own Model and Controller, and also add a database Context."},{"code":null,"e":3650,"s":3106,"text":"MVC is a web development philosophy that recommends the separation of pieces of an app into logical components. This allows you to build each piece separately and confirm it works, and then connect your pieces for a finished whole. This article from FreeCodeCamp.org does an excellent job of explaining how MVC is like ordering a drink from a bar. The drink menu is the View, and you make requests to the bartender (Controller), who makes drinks based on ingredients and instructions (Model), and returns your finished drink to the bar (View)."},{"code":null,"e":3689,"s":3650,"text":"In the context of our app, this means:"},{"code":null,"e":4207,"s":3689,"text":"VIEW: The Angular app will receive input, make requests, and display data.CONTROLLER: C# class that accepts incoming requests, deciphers the route of the request, and uses a specified Model to interact with the database based on the route it receives.MODEL: C# class that defines the data being passed to or retrieved from the database. This will mean defining things like id is an integer, name is a string, so that C# can pass these values in a way that SQL can interpret. Database context is important to the Model"},{"code":null,"e":4282,"s":4207,"text":"VIEW: The Angular app will receive input, make requests, and display data."},{"code":null,"e":4460,"s":4282,"text":"CONTROLLER: C# class that accepts incoming requests, deciphers the route of the request, and uses a specified Model to interact with the database based on the route it receives."},{"code":null,"e":4727,"s":4460,"text":"MODEL: C# class that defines the data being passed to or retrieved from the database. This will mean defining things like id is an integer, name is a string, so that C# can pass these values in a way that SQL can interpret. Database context is important to the Model"},{"code":null,"e":4818,"s":4727,"text":"Microsoft has published great tutorials on .NET Core, and I highly recommend checking out:"},{"code":null,"e":4902,"s":4818,"text":"Tutorial: Create a web API with ASP.NET Core.Create a web app with ASP.NET Core MVC"},{"code":null,"e":4948,"s":4902,"text":"Tutorial: Create a web API with ASP.NET Core."},{"code":null,"e":4987,"s":4948,"text":"Create a web app with ASP.NET Core MVC"},{"code":null,"e":5031,"s":4987,"text":"At this point, you should have 2 resources:"},{"code":null,"e":5093,"s":5031,"text":"A working Angular Tour of Heroes App.A generic .NET Core API."},{"code":null,"e":5131,"s":5093,"text":"A working Angular Tour of Heroes App."},{"code":null,"e":5156,"s":5131,"text":"A generic .NET Core API."},{"code":null,"e":5467,"s":5156,"text":"We need to create a database that can handle requests from our API Controller. We will eventually move to a hosted Azure SQL database, but for now, let’s launch a local Docker container of a Microsoft SQL Server. This container is a lightweight version of SQL Server that we can easily spin up for development."},{"code":null,"e":5537,"s":5467,"text":"Head on over to Build a MSSQL Docker Container to setup the database!"},{"code":null,"e":5671,"s":5537,"text":"Build your .NET API from scratch, with a little help from the aspnet-codegenerator. The app will handle API requests to these routes:"},{"code":null,"e":6100,"s":5671,"text":"GET: api/Heroes — this method will return all the heroes in the databaseGET: api/Heroes/5 — this method will return a specific hero from the database. In this case, it will return the hero with an Id of 5.PUT: api/Heroes/5 — this method will update a specific hero’s information.POST: api/Heroes — this method will post a new hero to the database.DELETE: api/Heroes/5 — this method will delete a specific hero from the database."},{"code":null,"e":6173,"s":6100,"text":"GET: api/Heroes — this method will return all the heroes in the database"},{"code":null,"e":6307,"s":6173,"text":"GET: api/Heroes/5 — this method will return a specific hero from the database. In this case, it will return the hero with an Id of 5."},{"code":null,"e":6382,"s":6307,"text":"PUT: api/Heroes/5 — this method will update a specific hero’s information."},{"code":null,"e":6451,"s":6382,"text":"POST: api/Heroes — this method will post a new hero to the database."},{"code":null,"e":6533,"s":6451,"text":"DELETE: api/Heroes/5 — this method will delete a specific hero from the database."},{"code":null,"e":6643,"s":6533,"text":"At the end of this article, you will have a working local version of the Angular app, .NET API, and database."},{"code":null,"e":6768,"s":6643,"text":"Finally, you will create an Azure SQL server and deploy your .NET API to an Azure remote git repo, and serve with a web app."},{"code":null,"e":6846,"s":6768,"text":"Then you will deploy your angular app to Azure as a Docker container web app."}],"string":"[\n {\n \"code\": null,\n \"e\": 425,\n \"s\": 172,\n \"text\": \"This article assumes that you have already built the Angular official tutorial — Tour of Heroes app. If you have not built this, you should check the Angular docs, or download from here. Everything else will be taken care of in this series of articles!\"\n },\n {\n \"code\": null,\n \"e\": 541,\n \"s\": 425,\n \"text\": \"In this series, we will embark on a magical exploration of .NET Core, Angular, Docker, Azure, and Azure SQL Server.\"\n },\n {\n \"code\": null,\n \"e\": 678,\n \"s\": 541,\n \"text\": \"We will become familiar with several technologies, such as Docker containers, C#, JavaScript, SQL, and the Azure Command Line Interface.\"\n },\n {\n \"code\": null,\n \"e\": 817,\n \"s\": 678,\n \"text\": \"The end result of these articles will be an Angular front end with a .NET Core API that talks to an Azure SQL server, all hosted on Azure.\"\n },\n {\n \"code\": null,\n \"e\": 1007,\n \"s\": 817,\n \"text\": \"This article — environment setup and explanation of MVC.Local Docker setup of a Microsoft SQL Server (mssql).Build the .NET API.Deploying your API to Azure.Deploy your Angular app to Azure.\"\n },\n {\n \"code\": null,\n \"e\": 1064,\n \"s\": 1007,\n \"text\": \"This article — environment setup and explanation of MVC.\"\n },\n {\n \"code\": null,\n \"e\": 1118,\n \"s\": 1064,\n \"text\": \"Local Docker setup of a Microsoft SQL Server (mssql).\"\n },\n {\n \"code\": null,\n \"e\": 1138,\n \"s\": 1118,\n \"text\": \"Build the .NET API.\"\n },\n {\n \"code\": null,\n \"e\": 1167,\n \"s\": 1138,\n \"text\": \"Deploying your API to Azure.\"\n },\n {\n \"code\": null,\n \"e\": 1201,\n \"s\": 1167,\n \"text\": \"Deploy your Angular app to Azure.\"\n },\n {\n \"code\": null,\n \"e\": 1448,\n \"s\": 1201,\n \"text\": \"Visual Studio Code (it’s the free one)Angular CLI (should already be setup from the Tour Of Heroes Tutorial).NET Core — This API will use version 3.0.2Postman — for testing the APIDocker — for a local dev database, and for containerizing our apps\"\n },\n {\n \"code\": null,\n \"e\": 1487,\n \"s\": 1448,\n \"text\": \"Visual Studio Code (it’s the free one)\"\n },\n {\n \"code\": null,\n \"e\": 1558,\n \"s\": 1487,\n \"text\": \"Angular CLI (should already be setup from the Tour Of Heroes Tutorial)\"\n },\n {\n \"code\": null,\n \"e\": 1602,\n \"s\": 1558,\n \"text\": \".NET Core — This API will use version 3.0.2\"\n },\n {\n \"code\": null,\n \"e\": 1632,\n \"s\": 1602,\n \"text\": \"Postman — for testing the API\"\n },\n {\n \"code\": null,\n \"e\": 1699,\n \"s\": 1632,\n \"text\": \"Docker — for a local dev database, and for containerizing our apps\"\n },\n {\n \"code\": null,\n \"e\": 1734,\n \"s\": 1699,\n \"text\": \"Follow along using my GitHub repo.\"\n },\n {\n \"code\": null,\n \"e\": 1889,\n \"s\": 1734,\n \"text\": \"First, launch your Tour of Heroes Angular app by running ng serve --open from the root directory of your app. You should see the app running on port 4200.\"\n },\n {\n \"code\": null,\n \"e\": 2133,\n \"s\": 1889,\n \"text\": \"When you built the original app, it had a built-in web server that mimicked an actual server. We will be replacing this artificial server with a web API written in C# using the .NET framework. Let’s shutdown the app and get to work on the API.\"\n },\n {\n \"code\": null,\n \"e\": 2436,\n \"s\": 2133,\n \"text\": \"Make sure the .NET Core CLI is installed by running dotnet --version. The .NET Core CLI has lots of templates from which to choose. Check these option flags with dotnet new -h. Do you see the Template for ASP.NET Core Web API? Its Short Name is webapi. Create your API from the command line by running:\"\n },\n {\n \"code\": null,\n \"e\": 2468,\n \"s\": 2436,\n \"text\": \"dotnet new webapi -n Heroes.API\"\n },\n {\n \"code\": null,\n \"e\": 2700,\n \"s\": 2468,\n \"text\": \"You should get a result of Restore succeeded. Move into the new directory by typing cd Heroes.API. Check ls to see the folders and files that have been created, and launch VS Code in this directory by typing (with a period)code . .\"\n },\n {\n \"code\": null,\n \"e\": 3106,\n \"s\": 2700,\n \"text\": \"Let’s also make sure the API launches by running dotnet run. In a web browser, navigate to https://localhost:5001/weatherforecast and accept the unsafe destination to view sample output returned by your API in JSON format. This is great because is gives you an idea of how .NET Core APIs work by using a Model and a Controller. We will create our own Model and Controller, and also add a database Context.\"\n },\n {\n \"code\": null,\n \"e\": 3650,\n \"s\": 3106,\n \"text\": \"MVC is a web development philosophy that recommends the separation of pieces of an app into logical components. This allows you to build each piece separately and confirm it works, and then connect your pieces for a finished whole. This article from FreeCodeCamp.org does an excellent job of explaining how MVC is like ordering a drink from a bar. The drink menu is the View, and you make requests to the bartender (Controller), who makes drinks based on ingredients and instructions (Model), and returns your finished drink to the bar (View).\"\n },\n {\n \"code\": null,\n \"e\": 3689,\n \"s\": 3650,\n \"text\": \"In the context of our app, this means:\"\n },\n {\n \"code\": null,\n \"e\": 4207,\n \"s\": 3689,\n \"text\": \"VIEW: The Angular app will receive input, make requests, and display data.CONTROLLER: C# class that accepts incoming requests, deciphers the route of the request, and uses a specified Model to interact with the database based on the route it receives.MODEL: C# class that defines the data being passed to or retrieved from the database. This will mean defining things like id is an integer, name is a string, so that C# can pass these values in a way that SQL can interpret. Database context is important to the Model\"\n },\n {\n \"code\": null,\n \"e\": 4282,\n \"s\": 4207,\n \"text\": \"VIEW: The Angular app will receive input, make requests, and display data.\"\n },\n {\n \"code\": null,\n \"e\": 4460,\n \"s\": 4282,\n \"text\": \"CONTROLLER: C# class that accepts incoming requests, deciphers the route of the request, and uses a specified Model to interact with the database based on the route it receives.\"\n },\n {\n \"code\": null,\n \"e\": 4727,\n \"s\": 4460,\n \"text\": \"MODEL: C# class that defines the data being passed to or retrieved from the database. This will mean defining things like id is an integer, name is a string, so that C# can pass these values in a way that SQL can interpret. Database context is important to the Model\"\n },\n {\n \"code\": null,\n \"e\": 4818,\n \"s\": 4727,\n \"text\": \"Microsoft has published great tutorials on .NET Core, and I highly recommend checking out:\"\n },\n {\n \"code\": null,\n \"e\": 4902,\n \"s\": 4818,\n \"text\": \"Tutorial: Create a web API with ASP.NET Core.Create a web app with ASP.NET Core MVC\"\n },\n {\n \"code\": null,\n \"e\": 4948,\n \"s\": 4902,\n \"text\": \"Tutorial: Create a web API with ASP.NET Core.\"\n },\n {\n \"code\": null,\n \"e\": 4987,\n \"s\": 4948,\n \"text\": \"Create a web app with ASP.NET Core MVC\"\n },\n {\n \"code\": null,\n \"e\": 5031,\n \"s\": 4987,\n \"text\": \"At this point, you should have 2 resources:\"\n },\n {\n \"code\": null,\n \"e\": 5093,\n \"s\": 5031,\n \"text\": \"A working Angular Tour of Heroes App.A generic .NET Core API.\"\n },\n {\n \"code\": null,\n \"e\": 5131,\n \"s\": 5093,\n \"text\": \"A working Angular Tour of Heroes App.\"\n },\n {\n \"code\": null,\n \"e\": 5156,\n \"s\": 5131,\n \"text\": \"A generic .NET Core API.\"\n },\n {\n \"code\": null,\n \"e\": 5467,\n \"s\": 5156,\n \"text\": \"We need to create a database that can handle requests from our API Controller. We will eventually move to a hosted Azure SQL database, but for now, let’s launch a local Docker container of a Microsoft SQL Server. This container is a lightweight version of SQL Server that we can easily spin up for development.\"\n },\n {\n \"code\": null,\n \"e\": 5537,\n \"s\": 5467,\n \"text\": \"Head on over to Build a MSSQL Docker Container to setup the database!\"\n },\n {\n \"code\": null,\n \"e\": 5671,\n \"s\": 5537,\n \"text\": \"Build your .NET API from scratch, with a little help from the aspnet-codegenerator. The app will handle API requests to these routes:\"\n },\n {\n \"code\": null,\n \"e\": 6100,\n \"s\": 5671,\n \"text\": \"GET: api/Heroes — this method will return all the heroes in the databaseGET: api/Heroes/5 — this method will return a specific hero from the database. In this case, it will return the hero with an Id of 5.PUT: api/Heroes/5 — this method will update a specific hero’s information.POST: api/Heroes — this method will post a new hero to the database.DELETE: api/Heroes/5 — this method will delete a specific hero from the database.\"\n },\n {\n \"code\": null,\n \"e\": 6173,\n \"s\": 6100,\n \"text\": \"GET: api/Heroes — this method will return all the heroes in the database\"\n },\n {\n \"code\": null,\n \"e\": 6307,\n \"s\": 6173,\n \"text\": \"GET: api/Heroes/5 — this method will return a specific hero from the database. In this case, it will return the hero with an Id of 5.\"\n },\n {\n \"code\": null,\n \"e\": 6382,\n \"s\": 6307,\n \"text\": \"PUT: api/Heroes/5 — this method will update a specific hero’s information.\"\n },\n {\n \"code\": null,\n \"e\": 6451,\n \"s\": 6382,\n \"text\": \"POST: api/Heroes — this method will post a new hero to the database.\"\n },\n {\n \"code\": null,\n \"e\": 6533,\n \"s\": 6451,\n \"text\": \"DELETE: api/Heroes/5 — this method will delete a specific hero from the database.\"\n },\n {\n \"code\": null,\n \"e\": 6643,\n \"s\": 6533,\n \"text\": \"At the end of this article, you will have a working local version of the Angular app, .NET API, and database.\"\n },\n {\n \"code\": null,\n \"e\": 6768,\n \"s\": 6643,\n \"text\": \"Finally, you will create an Azure SQL server and deploy your .NET API to an Azure remote git repo, and serve with a web app.\"\n },\n {\n \"code\": null,\n \"e\": 6846,\n \"s\": 6768,\n \"text\": \"Then you will deploy your angular app to Azure as a Docker container web app.\"\n }\n]"}}},{"rowIdx":424,"cells":{"title":{"kind":"string","value":"Go - The Switch Statement"},"text":{"kind":"string","value":"A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.\nIn Go programming, switch statements are of two types −\nExpression Switch − In expression switch, a case contains expressions, which is compared against the value of the switch expression.\nExpression Switch − In expression switch, a case contains expressions, which is compared against the value of the switch expression.\nType Switch − In type switch, a case contain type which is compared against the type of a specially annotated switch expression.\nType Switch − In type switch, a case contain type which is compared against the type of a specially annotated switch expression.\nThe syntax for expression switch statement in Go programming language is as follows −\nswitch(boolean-expression or integral type){\n case boolean-expression or integral type :\n statement(s); \n case boolean-expression or integral type :\n statement(s); \n \n /* you can have any number of case statements */\n default : /* Optional */\n statement(s);\n}\n\nThe following rules apply to a switch statement −\nThe expression used in a switch statement must have an integral or boolean expression, or be of a class type in which the class has a single conversion function to an integral or boolean value. If the expression is not passed then the default value is true.\nThe expression used in a switch statement must have an integral or boolean expression, or be of a class type in which the class has a single conversion function to an integral or boolean value. If the expression is not passed then the default value is true.\nYou can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.\nYou can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.\nThe constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.\nThe constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.\nWhen the variable being switched on is equal to a case, the statements following that case will execute. No break is needed in the case statement.\nWhen the variable being switched on is equal to a case, the statements following that case will execute. No break is needed in the case statement.\nA switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.\nA switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n /* local variable definition */\n var grade string = \"B\"\n var marks int = 90\n\n switch marks {\n case 90: grade = \"A\"\n case 80: grade = \"B\"\n case 50,60,70 : grade = \"C\"\n default: grade = \"D\" \n }\n switch {\n case grade == \"A\" :\n fmt.Printf(\"Excellent!\\n\" ) \n case grade == \"B\", grade == \"C\" :\n fmt.Printf(\"Well done\\n\" ) \n case grade == \"D\" :\n fmt.Printf(\"You passed\\n\" ) \n case grade == \"F\":\n fmt.Printf(\"Better try again\\n\" )\n default:\n fmt.Printf(\"Invalid grade\\n\" );\n }\n fmt.Printf(\"Your grade is %s\\n\", grade ); \n}\nWhen the above code is compiled and executed, it produces the following result −\nExcellent!\nYour grade is A\n\nThe syntax for a type switch statement in Go programming is as follows −\nswitch x.(type){\n case type:\n statement(s); \n case type:\n statement(s); \n /* you can have any number of case statements */\n default: /* Optional */\n statement(s);\n}\n\nThe following rules apply to a switch statement −\nThe expression used in a switch statement must have an variable of interface{} type.\nThe expression used in a switch statement must have an variable of interface{} type.\nYou can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.\nYou can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.\nThe type for a case must be the same data type as the variable in the switch, and it must be a valid data type.\nThe type for a case must be the same data type as the variable in the switch, and it must be a valid data type.\nWhen the variable being switched on is equal to a case, the statements following that case will execute. No break is needed in the case statement.\nWhen the variable being switched on is equal to a case, the statements following that case will execute. No break is needed in the case statement.\nA switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.\nA switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n var x interface{}\n \n switch i := x.(type) {\n case nil:\t \n fmt.Printf(\"type of x :%T\",i) \n case int:\t \n fmt.Printf(\"x is int\") \n case float64:\n fmt.Printf(\"x is float64\") \n case func(int) float64:\n fmt.Printf(\"x is func(int)\") \n case bool, string:\n fmt.Printf(\"x is bool or string\") \n default:\n fmt.Printf(\"don't know the type\") \n } \n}\nWhen the above code is compiled and executed, it produces the following result −\ntype of x :\n\n\n 64 Lectures \n 6.5 hours \n\n Ridhi Arora\n\n 20 Lectures \n 2.5 hours \n\n Asif Hussain\n\n 22 Lectures \n 4 hours \n\n Dilip Padmanabhan\n\n 48 Lectures \n 6 hours \n\n Arnab Chakraborty\n\n 7 Lectures \n 1 hours \n\n Aditya Kulkarni\n\n 44 Lectures \n 3 hours \n\n Arnab Chakraborty\n Print\n Add Notes\n Bookmark this page"},"parsed":{"kind":"list like","value":[{"code":null,"e":2123,"s":1937,"text":"A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case."},{"code":null,"e":2179,"s":2123,"text":"In Go programming, switch statements are of two types −"},{"code":null,"e":2312,"s":2179,"text":"Expression Switch − In expression switch, a case contains expressions, which is compared against the value of the switch expression."},{"code":null,"e":2445,"s":2312,"text":"Expression Switch − In expression switch, a case contains expressions, which is compared against the value of the switch expression."},{"code":null,"e":2574,"s":2445,"text":"Type Switch − In type switch, a case contain type which is compared against the type of a specially annotated switch expression."},{"code":null,"e":2703,"s":2574,"text":"Type Switch − In type switch, a case contain type which is compared against the type of a specially annotated switch expression."},{"code":null,"e":2789,"s":2703,"text":"The syntax for expression switch statement in Go programming language is as follows −"},{"code":null,"e":3080,"s":2789,"text":"switch(boolean-expression or integral type){\n case boolean-expression or integral type :\n statement(s); \n case boolean-expression or integral type :\n statement(s); \n \n /* you can have any number of case statements */\n default : /* Optional */\n statement(s);\n}\n"},{"code":null,"e":3130,"s":3080,"text":"The following rules apply to a switch statement −"},{"code":null,"e":3388,"s":3130,"text":"The expression used in a switch statement must have an integral or boolean expression, or be of a class type in which the class has a single conversion function to an integral or boolean value. If the expression is not passed then the default value is true."},{"code":null,"e":3646,"s":3388,"text":"The expression used in a switch statement must have an integral or boolean expression, or be of a class type in which the class has a single conversion function to an integral or boolean value. If the expression is not passed then the default value is true."},{"code":null,"e":3772,"s":3646,"text":"You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon."},{"code":null,"e":3898,"s":3772,"text":"You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon."},{"code":null,"e":4031,"s":3898,"text":"The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal."},{"code":null,"e":4164,"s":4031,"text":"The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal."},{"code":null,"e":4311,"s":4164,"text":"When the variable being switched on is equal to a case, the statements following that case will execute. No break is needed in the case statement."},{"code":null,"e":4458,"s":4311,"text":"When the variable being switched on is equal to a case, the statements following that case will execute. No break is needed in the case statement."},{"code":null,"e":4679,"s":4458,"text":"A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case."},{"code":null,"e":4900,"s":4679,"text":"A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case."},{"code":null,"e":5580,"s":4900,"text":"package main\n\nimport \"fmt\"\n\nfunc main() {\n /* local variable definition */\n var grade string = \"B\"\n var marks int = 90\n\n switch marks {\n case 90: grade = \"A\"\n case 80: grade = \"B\"\n case 50,60,70 : grade = \"C\"\n default: grade = \"D\" \n }\n switch {\n case grade == \"A\" :\n fmt.Printf(\"Excellent!\\n\" ) \n case grade == \"B\", grade == \"C\" :\n fmt.Printf(\"Well done\\n\" ) \n case grade == \"D\" :\n fmt.Printf(\"You passed\\n\" ) \n case grade == \"F\":\n fmt.Printf(\"Better try again\\n\" )\n default:\n fmt.Printf(\"Invalid grade\\n\" );\n }\n fmt.Printf(\"Your grade is %s\\n\", grade ); \n}"},{"code":null,"e":5661,"s":5580,"text":"When the above code is compiled and executed, it produces the following result −"},{"code":null,"e":5690,"s":5661,"text":"Excellent!\nYour grade is A\n"},{"code":null,"e":5763,"s":5690,"text":"The syntax for a type switch statement in Go programming is as follows −"},{"code":null,"e":5957,"s":5763,"text":"switch x.(type){\n case type:\n statement(s); \n case type:\n statement(s); \n /* you can have any number of case statements */\n default: /* Optional */\n statement(s);\n}\n"},{"code":null,"e":6007,"s":5957,"text":"The following rules apply to a switch statement −"},{"code":null,"e":6092,"s":6007,"text":"The expression used in a switch statement must have an variable of interface{} type."},{"code":null,"e":6177,"s":6092,"text":"The expression used in a switch statement must have an variable of interface{} type."},{"code":null,"e":6303,"s":6177,"text":"You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon."},{"code":null,"e":6429,"s":6303,"text":"You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon."},{"code":null,"e":6541,"s":6429,"text":"The type for a case must be the same data type as the variable in the switch, and it must be a valid data type."},{"code":null,"e":6653,"s":6541,"text":"The type for a case must be the same data type as the variable in the switch, and it must be a valid data type."},{"code":null,"e":6800,"s":6653,"text":"When the variable being switched on is equal to a case, the statements following that case will execute. No break is needed in the case statement."},{"code":null,"e":6947,"s":6800,"text":"When the variable being switched on is equal to a case, the statements following that case will execute. No break is needed in the case statement."},{"code":null,"e":7168,"s":6947,"text":"A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case."},{"code":null,"e":7389,"s":7168,"text":"A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case."},{"code":null,"e":7937,"s":7389,"text":"package main\n\nimport \"fmt\"\n\nfunc main() {\n var x interface{}\n \n switch i := x.(type) {\n case nil:\t \n fmt.Printf(\"type of x :%T\",i) \n case int:\t \n fmt.Printf(\"x is int\") \n case float64:\n fmt.Printf(\"x is float64\") \n case func(int) float64:\n fmt.Printf(\"x is func(int)\") \n case bool, string:\n fmt.Printf(\"x is bool or string\") \n default:\n fmt.Printf(\"don't know the type\") \n } \n}"},{"code":null,"e":8018,"s":7937,"text":"When the above code is compiled and executed, it produces the following result −"},{"code":null,"e":8036,"s":8018,"text":"type of x :\n"},{"code":null,"e":8071,"s":8036,"text":"\n 64 Lectures \n 6.5 hours \n"},{"code":null,"e":8084,"s":8071,"text":" Ridhi Arora"},{"code":null,"e":8119,"s":8084,"text":"\n 20 Lectures \n 2.5 hours \n"},{"code":null,"e":8133,"s":8119,"text":" Asif Hussain"},{"code":null,"e":8166,"s":8133,"text":"\n 22 Lectures \n 4 hours \n"},{"code":null,"e":8185,"s":8166,"text":" Dilip Padmanabhan"},{"code":null,"e":8218,"s":8185,"text":"\n 48 Lectures \n 6 hours \n"},{"code":null,"e":8237,"s":8218,"text":" Arnab Chakraborty"},{"code":null,"e":8269,"s":8237,"text":"\n 7 Lectures \n 1 hours \n"},{"code":null,"e":8286,"s":8269,"text":" Aditya Kulkarni"},{"code":null,"e":8319,"s":8286,"text":"\n 44 Lectures \n 3 hours \n"},{"code":null,"e":8338,"s":8319,"text":" Arnab Chakraborty"},{"code":null,"e":8345,"s":8338,"text":" Print"},{"code":null,"e":8356,"s":8345,"text":" Add Notes"}],"string":"[\n {\n \"code\": null,\n \"e\": 2123,\n \"s\": 1937,\n \"text\": \"A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.\"\n },\n {\n \"code\": null,\n \"e\": 2179,\n \"s\": 2123,\n \"text\": \"In Go programming, switch statements are of two types −\"\n },\n {\n \"code\": null,\n \"e\": 2312,\n \"s\": 2179,\n \"text\": \"Expression Switch − In expression switch, a case contains expressions, which is compared against the value of the switch expression.\"\n },\n {\n \"code\": null,\n \"e\": 2445,\n \"s\": 2312,\n \"text\": \"Expression Switch − In expression switch, a case contains expressions, which is compared against the value of the switch expression.\"\n },\n {\n \"code\": null,\n \"e\": 2574,\n \"s\": 2445,\n \"text\": \"Type Switch − In type switch, a case contain type which is compared against the type of a specially annotated switch expression.\"\n },\n {\n \"code\": null,\n \"e\": 2703,\n \"s\": 2574,\n \"text\": \"Type Switch − In type switch, a case contain type which is compared against the type of a specially annotated switch expression.\"\n },\n {\n \"code\": null,\n \"e\": 2789,\n \"s\": 2703,\n \"text\": \"The syntax for expression switch statement in Go programming language is as follows −\"\n },\n {\n \"code\": null,\n \"e\": 3080,\n \"s\": 2789,\n \"text\": \"switch(boolean-expression or integral type){\\n case boolean-expression or integral type :\\n statement(s); \\n case boolean-expression or integral type :\\n statement(s); \\n \\n /* you can have any number of case statements */\\n default : /* Optional */\\n statement(s);\\n}\\n\"\n },\n {\n \"code\": null,\n \"e\": 3130,\n \"s\": 3080,\n \"text\": \"The following rules apply to a switch statement −\"\n },\n {\n \"code\": null,\n \"e\": 3388,\n \"s\": 3130,\n \"text\": \"The expression used in a switch statement must have an integral or boolean expression, or be of a class type in which the class has a single conversion function to an integral or boolean value. If the expression is not passed then the default value is true.\"\n },\n {\n \"code\": null,\n \"e\": 3646,\n \"s\": 3388,\n \"text\": \"The expression used in a switch statement must have an integral or boolean expression, or be of a class type in which the class has a single conversion function to an integral or boolean value. If the expression is not passed then the default value is true.\"\n },\n {\n \"code\": null,\n \"e\": 3772,\n \"s\": 3646,\n \"text\": \"You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.\"\n },\n {\n \"code\": null,\n \"e\": 3898,\n \"s\": 3772,\n \"text\": \"You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.\"\n },\n {\n \"code\": null,\n \"e\": 4031,\n \"s\": 3898,\n \"text\": \"The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.\"\n },\n {\n \"code\": null,\n \"e\": 4164,\n \"s\": 4031,\n \"text\": \"The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.\"\n },\n {\n \"code\": null,\n \"e\": 4311,\n \"s\": 4164,\n \"text\": \"When the variable being switched on is equal to a case, the statements following that case will execute. No break is needed in the case statement.\"\n },\n {\n \"code\": null,\n \"e\": 4458,\n \"s\": 4311,\n \"text\": \"When the variable being switched on is equal to a case, the statements following that case will execute. No break is needed in the case statement.\"\n },\n {\n \"code\": null,\n \"e\": 4679,\n \"s\": 4458,\n \"text\": \"A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.\"\n },\n {\n \"code\": null,\n \"e\": 4900,\n \"s\": 4679,\n \"text\": \"A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.\"\n },\n {\n \"code\": null,\n \"e\": 5580,\n \"s\": 4900,\n \"text\": \"package main\\n\\nimport \\\"fmt\\\"\\n\\nfunc main() {\\n /* local variable definition */\\n var grade string = \\\"B\\\"\\n var marks int = 90\\n\\n switch marks {\\n case 90: grade = \\\"A\\\"\\n case 80: grade = \\\"B\\\"\\n case 50,60,70 : grade = \\\"C\\\"\\n default: grade = \\\"D\\\" \\n }\\n switch {\\n case grade == \\\"A\\\" :\\n fmt.Printf(\\\"Excellent!\\\\n\\\" ) \\n case grade == \\\"B\\\", grade == \\\"C\\\" :\\n fmt.Printf(\\\"Well done\\\\n\\\" ) \\n case grade == \\\"D\\\" :\\n fmt.Printf(\\\"You passed\\\\n\\\" ) \\n case grade == \\\"F\\\":\\n fmt.Printf(\\\"Better try again\\\\n\\\" )\\n default:\\n fmt.Printf(\\\"Invalid grade\\\\n\\\" );\\n }\\n fmt.Printf(\\\"Your grade is %s\\\\n\\\", grade ); \\n}\"\n },\n {\n \"code\": null,\n \"e\": 5661,\n \"s\": 5580,\n \"text\": \"When the above code is compiled and executed, it produces the following result −\"\n },\n {\n \"code\": null,\n \"e\": 5690,\n \"s\": 5661,\n \"text\": \"Excellent!\\nYour grade is A\\n\"\n },\n {\n \"code\": null,\n \"e\": 5763,\n \"s\": 5690,\n \"text\": \"The syntax for a type switch statement in Go programming is as follows −\"\n },\n {\n \"code\": null,\n \"e\": 5957,\n \"s\": 5763,\n \"text\": \"switch x.(type){\\n case type:\\n statement(s); \\n case type:\\n statement(s); \\n /* you can have any number of case statements */\\n default: /* Optional */\\n statement(s);\\n}\\n\"\n },\n {\n \"code\": null,\n \"e\": 6007,\n \"s\": 5957,\n \"text\": \"The following rules apply to a switch statement −\"\n },\n {\n \"code\": null,\n \"e\": 6092,\n \"s\": 6007,\n \"text\": \"The expression used in a switch statement must have an variable of interface{} type.\"\n },\n {\n \"code\": null,\n \"e\": 6177,\n \"s\": 6092,\n \"text\": \"The expression used in a switch statement must have an variable of interface{} type.\"\n },\n {\n \"code\": null,\n \"e\": 6303,\n \"s\": 6177,\n \"text\": \"You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.\"\n },\n {\n \"code\": null,\n \"e\": 6429,\n \"s\": 6303,\n \"text\": \"You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.\"\n },\n {\n \"code\": null,\n \"e\": 6541,\n \"s\": 6429,\n \"text\": \"The type for a case must be the same data type as the variable in the switch, and it must be a valid data type.\"\n },\n {\n \"code\": null,\n \"e\": 6653,\n \"s\": 6541,\n \"text\": \"The type for a case must be the same data type as the variable in the switch, and it must be a valid data type.\"\n },\n {\n \"code\": null,\n \"e\": 6800,\n \"s\": 6653,\n \"text\": \"When the variable being switched on is equal to a case, the statements following that case will execute. No break is needed in the case statement.\"\n },\n {\n \"code\": null,\n \"e\": 6947,\n \"s\": 6800,\n \"text\": \"When the variable being switched on is equal to a case, the statements following that case will execute. No break is needed in the case statement.\"\n },\n {\n \"code\": null,\n \"e\": 7168,\n \"s\": 6947,\n \"text\": \"A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.\"\n },\n {\n \"code\": null,\n \"e\": 7389,\n \"s\": 7168,\n \"text\": \"A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.\"\n },\n {\n \"code\": null,\n \"e\": 7937,\n \"s\": 7389,\n \"text\": \"package main\\n\\nimport \\\"fmt\\\"\\n\\nfunc main() {\\n var x interface{}\\n \\n switch i := x.(type) {\\n case nil:\\t \\n fmt.Printf(\\\"type of x :%T\\\",i) \\n case int:\\t \\n fmt.Printf(\\\"x is int\\\") \\n case float64:\\n fmt.Printf(\\\"x is float64\\\") \\n case func(int) float64:\\n fmt.Printf(\\\"x is func(int)\\\") \\n case bool, string:\\n fmt.Printf(\\\"x is bool or string\\\") \\n default:\\n fmt.Printf(\\\"don't know the type\\\") \\n } \\n}\"\n },\n {\n \"code\": null,\n \"e\": 8018,\n \"s\": 7937,\n \"text\": \"When the above code is compiled and executed, it produces the following result −\"\n },\n {\n \"code\": null,\n \"e\": 8036,\n \"s\": 8018,\n \"text\": \"type of x :\\n\"\n },\n {\n \"code\": null,\n \"e\": 8071,\n \"s\": 8036,\n \"text\": \"\\n 64 Lectures \\n 6.5 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 8084,\n \"s\": 8071,\n \"text\": \" Ridhi Arora\"\n },\n {\n \"code\": null,\n \"e\": 8119,\n \"s\": 8084,\n \"text\": \"\\n 20 Lectures \\n 2.5 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 8133,\n \"s\": 8119,\n \"text\": \" Asif Hussain\"\n },\n {\n \"code\": null,\n \"e\": 8166,\n \"s\": 8133,\n \"text\": \"\\n 22 Lectures \\n 4 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 8185,\n \"s\": 8166,\n \"text\": \" Dilip Padmanabhan\"\n },\n {\n \"code\": null,\n \"e\": 8218,\n \"s\": 8185,\n \"text\": \"\\n 48 Lectures \\n 6 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 8237,\n \"s\": 8218,\n \"text\": \" Arnab Chakraborty\"\n },\n {\n \"code\": null,\n \"e\": 8269,\n \"s\": 8237,\n \"text\": \"\\n 7 Lectures \\n 1 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 8286,\n \"s\": 8269,\n \"text\": \" Aditya Kulkarni\"\n },\n {\n \"code\": null,\n \"e\": 8319,\n \"s\": 8286,\n \"text\": \"\\n 44 Lectures \\n 3 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 8338,\n \"s\": 8319,\n \"text\": \" Arnab Chakraborty\"\n },\n {\n \"code\": null,\n \"e\": 8345,\n \"s\": 8338,\n \"text\": \" Print\"\n },\n {\n \"code\": null,\n \"e\": 8356,\n \"s\": 8345,\n \"text\": \" Add Notes\"\n }\n]"}}},{"rowIdx":425,"cells":{"title":{"kind":"string","value":"MATLAB - GNU Octave Tutorial"},"text":{"kind":"string","value":"GNU Octave is a high-level programming language like MATLAB and it is mostly compatible with MATLAB. It is also used for numerical computations.\nOctave has the following common features with MATLAB −\nmatrices are fundamental data type\nit has built-in support for complex numbers\nit has built-in math functions and libraries\nit supports user-defined functions\nGNU Octave is also freely redistributable software. You may redistribute it and/or modify it under the terms of the GNU General Public License (GPL) as published by the Free Software Foundation.\nMost MATLAB programs run in Octave, but some of the Octave programs may not run in MATLAB because, Octave allows some syntax that MATLAB does not.\nFor example, MATLAB supports single quotes only, but Octave supports both single and double quotes for defining strings. If you are looking for a tutorial on Octave, then kindly go through this tutorial from beginning which covers both MATLAB as well as Octave.\nAlmost all the examples covered in this tutorial are compatible with MATLAB as well as Octave. Let's try following example in MATLAB and Octave which produces same result without any syntax changes −\nThis example creates a 3D surface map for the function g = xe-(x2 + y2). Create a script file and type the following code −\n[x,y] = meshgrid(-2:.2:2);\ng = x .* exp(-x.^2 - y.^2);\nsurf(x, y, g)\nprint -deps graph.eps\nWhen you run the file, MATLAB displays the following 3-D map −\nThough all the core functionality of MATLAB is available in Octave, there are some functionality for example, Differential & Integration Calculus, which does not match exactly in both the languages. This tutorial has tried to give both type of examples where they differed in their syntax.\nConsider following example where MATLAB and Octave make use of different functions to get the area of a curve: f(x) = x2 cos(x) for −4 ≤ x ≤ 9. Following is MATLAB version of the code −\nf = x^2*cos(x);\nezplot(f, [-4,9])\na = int(f, -4, 9)\ndisp('Area: '), disp(double(a));\nWhen you run the file, MATLAB plots the graph −\nThe following result is displayed\na =\n8*cos(4) + 18*cos(9) + 14*sin(4) + 79*sin(9)\n \nArea: \n 0.3326\n\nBut to give area of the same curve in Octave, you will have to make use of symbolic package as follows −\npkg load symbolic\nsymbols\n\nx = sym(\"x\");\nf = inline(\"x^2*cos(x)\");\n\nezplot(f, [-4,9])\nprint -deps graph.eps\n\n[a, ierror, nfneval] = quad(f, -4, 9);\ndisplay('Area: '), disp(double(a));\n\n 30 Lectures \n 4 hours \n\n Nouman Azam\n\n 127 Lectures \n 12 hours \n\n Nouman Azam\n\n 17 Lectures \n 3 hours \n\n Sanjeev\n\n 37 Lectures \n 5 hours \n\n TELCOMA Global\n\n 22 Lectures \n 4 hours \n\n TELCOMA Global\n\n 18 Lectures \n 3 hours \n\n Phinite Academy\n Print\n Add Notes\n Bookmark this page"},"parsed":{"kind":"list like","value":[{"code":null,"e":2286,"s":2141,"text":"GNU Octave is a high-level programming language like MATLAB and it is mostly compatible with MATLAB. It is also used for numerical computations."},{"code":null,"e":2341,"s":2286,"text":"Octave has the following common features with MATLAB −"},{"code":null,"e":2376,"s":2341,"text":"matrices are fundamental data type"},{"code":null,"e":2420,"s":2376,"text":"it has built-in support for complex numbers"},{"code":null,"e":2465,"s":2420,"text":"it has built-in math functions and libraries"},{"code":null,"e":2500,"s":2465,"text":"it supports user-defined functions"},{"code":null,"e":2695,"s":2500,"text":"GNU Octave is also freely redistributable software. You may redistribute it and/or modify it under the terms of the GNU General Public License (GPL) as published by the Free Software Foundation."},{"code":null,"e":2842,"s":2695,"text":"Most MATLAB programs run in Octave, but some of the Octave programs may not run in MATLAB because, Octave allows some syntax that MATLAB does not."},{"code":null,"e":3105,"s":2842,"text":"For example, MATLAB supports single quotes only, but Octave supports both single and double quotes for defining strings. If you are looking for a tutorial on Octave, then kindly go through this tutorial from beginning which covers both MATLAB as well as Octave."},{"code":null,"e":3305,"s":3105,"text":"Almost all the examples covered in this tutorial are compatible with MATLAB as well as Octave. Let's try following example in MATLAB and Octave which produces same result without any syntax changes −"},{"code":null,"e":3429,"s":3305,"text":"This example creates a 3D surface map for the function g = xe-(x2 + y2). Create a script file and type the following code −"},{"code":null,"e":3520,"s":3429,"text":"[x,y] = meshgrid(-2:.2:2);\ng = x .* exp(-x.^2 - y.^2);\nsurf(x, y, g)\nprint -deps graph.eps"},{"code":null,"e":3583,"s":3520,"text":"When you run the file, MATLAB displays the following 3-D map −"},{"code":null,"e":3873,"s":3583,"text":"Though all the core functionality of MATLAB is available in Octave, there are some functionality for example, Differential & Integration Calculus, which does not match exactly in both the languages. This tutorial has tried to give both type of examples where they differed in their syntax."},{"code":null,"e":4059,"s":3873,"text":"Consider following example where MATLAB and Octave make use of different functions to get the area of a curve: f(x) = x2 cos(x) for −4 ≤ x ≤ 9. Following is MATLAB version of the code −"},{"code":null,"e":4144,"s":4059,"text":"f = x^2*cos(x);\nezplot(f, [-4,9])\na = int(f, -4, 9)\ndisp('Area: '), disp(double(a));"},{"code":null,"e":4192,"s":4144,"text":"When you run the file, MATLAB plots the graph −"},{"code":null,"e":4226,"s":4192,"text":"The following result is displayed"},{"code":null,"e":4295,"s":4226,"text":"a =\n8*cos(4) + 18*cos(9) + 14*sin(4) + 79*sin(9)\n \nArea: \n 0.3326\n"},{"code":null,"e":4400,"s":4295,"text":"But to give area of the same curve in Octave, you will have to make use of symbolic package as follows −"},{"code":null,"e":4584,"s":4400,"text":"pkg load symbolic\nsymbols\n\nx = sym(\"x\");\nf = inline(\"x^2*cos(x)\");\n\nezplot(f, [-4,9])\nprint -deps graph.eps\n\n[a, ierror, nfneval] = quad(f, -4, 9);\ndisplay('Area: '), disp(double(a));"},{"code":null,"e":4617,"s":4584,"text":"\n 30 Lectures \n 4 hours \n"},{"code":null,"e":4630,"s":4617,"text":" Nouman Azam"},{"code":null,"e":4665,"s":4630,"text":"\n 127 Lectures \n 12 hours \n"},{"code":null,"e":4678,"s":4665,"text":" Nouman Azam"},{"code":null,"e":4711,"s":4678,"text":"\n 17 Lectures \n 3 hours \n"},{"code":null,"e":4720,"s":4711,"text":" Sanjeev"},{"code":null,"e":4753,"s":4720,"text":"\n 37 Lectures \n 5 hours \n"},{"code":null,"e":4769,"s":4753,"text":" TELCOMA Global"},{"code":null,"e":4802,"s":4769,"text":"\n 22 Lectures \n 4 hours \n"},{"code":null,"e":4818,"s":4802,"text":" TELCOMA Global"},{"code":null,"e":4851,"s":4818,"text":"\n 18 Lectures \n 3 hours \n"},{"code":null,"e":4868,"s":4851,"text":" Phinite Academy"},{"code":null,"e":4875,"s":4868,"text":" Print"},{"code":null,"e":4886,"s":4875,"text":" Add Notes"}],"string":"[\n {\n \"code\": null,\n \"e\": 2286,\n \"s\": 2141,\n \"text\": \"GNU Octave is a high-level programming language like MATLAB and it is mostly compatible with MATLAB. It is also used for numerical computations.\"\n },\n {\n \"code\": null,\n \"e\": 2341,\n \"s\": 2286,\n \"text\": \"Octave has the following common features with MATLAB −\"\n },\n {\n \"code\": null,\n \"e\": 2376,\n \"s\": 2341,\n \"text\": \"matrices are fundamental data type\"\n },\n {\n \"code\": null,\n \"e\": 2420,\n \"s\": 2376,\n \"text\": \"it has built-in support for complex numbers\"\n },\n {\n \"code\": null,\n \"e\": 2465,\n \"s\": 2420,\n \"text\": \"it has built-in math functions and libraries\"\n },\n {\n \"code\": null,\n \"e\": 2500,\n \"s\": 2465,\n \"text\": \"it supports user-defined functions\"\n },\n {\n \"code\": null,\n \"e\": 2695,\n \"s\": 2500,\n \"text\": \"GNU Octave is also freely redistributable software. You may redistribute it and/or modify it under the terms of the GNU General Public License (GPL) as published by the Free Software Foundation.\"\n },\n {\n \"code\": null,\n \"e\": 2842,\n \"s\": 2695,\n \"text\": \"Most MATLAB programs run in Octave, but some of the Octave programs may not run in MATLAB because, Octave allows some syntax that MATLAB does not.\"\n },\n {\n \"code\": null,\n \"e\": 3105,\n \"s\": 2842,\n \"text\": \"For example, MATLAB supports single quotes only, but Octave supports both single and double quotes for defining strings. If you are looking for a tutorial on Octave, then kindly go through this tutorial from beginning which covers both MATLAB as well as Octave.\"\n },\n {\n \"code\": null,\n \"e\": 3305,\n \"s\": 3105,\n \"text\": \"Almost all the examples covered in this tutorial are compatible with MATLAB as well as Octave. Let's try following example in MATLAB and Octave which produces same result without any syntax changes −\"\n },\n {\n \"code\": null,\n \"e\": 3429,\n \"s\": 3305,\n \"text\": \"This example creates a 3D surface map for the function g = xe-(x2 + y2). Create a script file and type the following code −\"\n },\n {\n \"code\": null,\n \"e\": 3520,\n \"s\": 3429,\n \"text\": \"[x,y] = meshgrid(-2:.2:2);\\ng = x .* exp(-x.^2 - y.^2);\\nsurf(x, y, g)\\nprint -deps graph.eps\"\n },\n {\n \"code\": null,\n \"e\": 3583,\n \"s\": 3520,\n \"text\": \"When you run the file, MATLAB displays the following 3-D map −\"\n },\n {\n \"code\": null,\n \"e\": 3873,\n \"s\": 3583,\n \"text\": \"Though all the core functionality of MATLAB is available in Octave, there are some functionality for example, Differential & Integration Calculus, which does not match exactly in both the languages. This tutorial has tried to give both type of examples where they differed in their syntax.\"\n },\n {\n \"code\": null,\n \"e\": 4059,\n \"s\": 3873,\n \"text\": \"Consider following example where MATLAB and Octave make use of different functions to get the area of a curve: f(x) = x2 cos(x) for −4 ≤ x ≤ 9. Following is MATLAB version of the code −\"\n },\n {\n \"code\": null,\n \"e\": 4144,\n \"s\": 4059,\n \"text\": \"f = x^2*cos(x);\\nezplot(f, [-4,9])\\na = int(f, -4, 9)\\ndisp('Area: '), disp(double(a));\"\n },\n {\n \"code\": null,\n \"e\": 4192,\n \"s\": 4144,\n \"text\": \"When you run the file, MATLAB plots the graph −\"\n },\n {\n \"code\": null,\n \"e\": 4226,\n \"s\": 4192,\n \"text\": \"The following result is displayed\"\n },\n {\n \"code\": null,\n \"e\": 4295,\n \"s\": 4226,\n \"text\": \"a =\\n8*cos(4) + 18*cos(9) + 14*sin(4) + 79*sin(9)\\n \\nArea: \\n 0.3326\\n\"\n },\n {\n \"code\": null,\n \"e\": 4400,\n \"s\": 4295,\n \"text\": \"But to give area of the same curve in Octave, you will have to make use of symbolic package as follows −\"\n },\n {\n \"code\": null,\n \"e\": 4584,\n \"s\": 4400,\n \"text\": \"pkg load symbolic\\nsymbols\\n\\nx = sym(\\\"x\\\");\\nf = inline(\\\"x^2*cos(x)\\\");\\n\\nezplot(f, [-4,9])\\nprint -deps graph.eps\\n\\n[a, ierror, nfneval] = quad(f, -4, 9);\\ndisplay('Area: '), disp(double(a));\"\n },\n {\n \"code\": null,\n \"e\": 4617,\n \"s\": 4584,\n \"text\": \"\\n 30 Lectures \\n 4 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 4630,\n \"s\": 4617,\n \"text\": \" Nouman Azam\"\n },\n {\n \"code\": null,\n \"e\": 4665,\n \"s\": 4630,\n \"text\": \"\\n 127 Lectures \\n 12 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 4678,\n \"s\": 4665,\n \"text\": \" Nouman Azam\"\n },\n {\n \"code\": null,\n \"e\": 4711,\n \"s\": 4678,\n \"text\": \"\\n 17 Lectures \\n 3 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 4720,\n \"s\": 4711,\n \"text\": \" Sanjeev\"\n },\n {\n \"code\": null,\n \"e\": 4753,\n \"s\": 4720,\n \"text\": \"\\n 37 Lectures \\n 5 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 4769,\n \"s\": 4753,\n \"text\": \" TELCOMA Global\"\n },\n {\n \"code\": null,\n \"e\": 4802,\n \"s\": 4769,\n \"text\": \"\\n 22 Lectures \\n 4 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 4818,\n \"s\": 4802,\n \"text\": \" TELCOMA Global\"\n },\n {\n \"code\": null,\n \"e\": 4851,\n \"s\": 4818,\n \"text\": \"\\n 18 Lectures \\n 3 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 4868,\n \"s\": 4851,\n \"text\": \" Phinite Academy\"\n },\n {\n \"code\": null,\n \"e\": 4875,\n \"s\": 4868,\n \"text\": \" Print\"\n },\n {\n \"code\": null,\n \"e\": 4886,\n \"s\": 4875,\n \"text\": \" Add Notes\"\n }\n]"}}},{"rowIdx":426,"cells":{"title":{"kind":"string","value":"Bootstrap 5 Modal - GeeksforGeeks"},"text":{"kind":"string","value":"11 Sep, 2020\nBootstrap 5 is the latest major release by Bootstrap in which they have revamped the UI and made various changes. Modals are used to add dialogs to your site for lightboxes, user notifications, or completely custom content. Modals are built with HTML, CSS, and JavaScript. They’re positioned over everything else in the document and remove scroll from the so that modal content scrolls instead.\nSyntax:\n
Contents...
\nExample: This example uses show the working of a modal in Bootstrap 5.\n

GeeksforGeeks

Modal title
GeeksforGeeks
\nOutput before triggering the modal:\nOutput after triggering the modal:\nTooltips: can be added inside the modal. When modals are closed, tooltips within are also automatically dismissed.Example:\n

GeeksforGeeks

Modal title
Tooltips in a modal
Hover over me
\nOutput:\nPopovers: can be added inside the modal. When modals are closed, popovers within are also automatically dismissed.Example:\n

GeeksforGeeks

Modal title
Popover in a modal
Toggle popover
\nOutput:\nUsing Grids: We can utilize the Bootstrap grid system within a modal by nesting .container-fluid within the .modal-body. Then, use the normal grid system classes as you would anywhere else.Example:\n

GeeksforGeeks

Modal title
This is 4 grids
This is 8 grids
This is 12 grids
\nOutput:\nVarying modal content: We can trigger the same modal with different data as given below.Example:\n

GeeksforGeeks

New message
\nOutput without triggering any modal:Output for clicking on Send email to @geeksforgeeks:Output for clicking on Send email to author @gurrrung:\nOptional sizes Default max-width of a Bootstrap modal is 500px. Bootstrap provides the option to customize the size of the Modal by using certain classes as described below:\nmodal-xl\nmodal-lg\nmodal-sm\nmodal-xl: This provides the largest modal size with max-width of 1140px.Example:\n

GeeksforGeeks

Modal title
GeeksforGeeks
\nOutput:\nmodal-lg: This provides the large modal size with max-width of 800px.Example:\n

GeeksforGeeks

Modal title
GeeksforGeeks
\nOutput:\nmodal-sm: This provides the largest modal size with max-width of 300px.Example:\n

GeeksforGeeks

Modal title
GeeksforGeeks
\nOutput:\nBootstrap-Misc\nBootstrap\nWeb Technologies\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nComments\nOld Comments\nHow to change navigation bar color in Bootstrap ?\nForm validation using jQuery\nHow to align navbar items to the right in Bootstrap 4 ?\nHow to pass data into a bootstrap modal?\nHow to Show Images on Click using HTML ?\nTop 10 Front End Developer Skills That You Need in 2022\nInstallation of Node.js on Linux\nTop 10 Projects For Beginners To Practice HTML and CSS Skills\nHow to fetch data from an API in ReactJS ?\nHow to insert spaces/tabs in text using HTML/CSS?"},"parsed":{"kind":"list like","value":[{"code":null,"e":28049,"s":28021,"text":"\n11 Sep, 2020"},{"code":null,"e":28451,"s":28049,"text":"Bootstrap 5 is the latest major release by Bootstrap in which they have revamped the UI and made various changes. Modals are used to add dialogs to your site for lightboxes, user notifications, or completely custom content. Modals are built with HTML, CSS, and JavaScript. They’re positioned over everything else in the document and remove scroll from the so that modal content scrolls instead."},{"code":null,"e":28459,"s":28451,"text":"Syntax:"},{"code":null,"e":28497,"s":28459,"text":"
Contents...
"},{"code":null,"e":28568,"s":28497,"text":"Example: This example uses show the working of a modal in Bootstrap 5."},{"code":"

GeeksforGeeks

Modal title
GeeksforGeeks
","e":31235,"s":28568,"text":null},{"code":null,"e":31271,"s":31235,"text":"Output before triggering the modal:"},{"code":null,"e":31306,"s":31271,"text":"Output after triggering the modal:"},{"code":null,"e":31429,"s":31306,"text":"Tooltips: can be added inside the modal. When modals are closed, tooltips within are also automatically dismissed.Example:"},{"code":"

GeeksforGeeks

Modal title
Tooltips in a modal
Hover over me
","e":34693,"s":31429,"text":null},{"code":null,"e":34701,"s":34693,"text":"Output:"},{"code":null,"e":34824,"s":34701,"text":"Popovers: can be added inside the modal. When modals are closed, popovers within are also automatically dismissed.Example:"},{"code":"

GeeksforGeeks

Modal title
Popover in a modal
Toggle popover
","e":38164,"s":34824,"text":null},{"code":null,"e":38172,"s":38164,"text":"Output:"},{"code":null,"e":38370,"s":38172,"text":"Using Grids: We can utilize the Bootstrap grid system within a modal by nesting .container-fluid within the .modal-body. Then, use the normal grid system classes as you would anywhere else.Example:"},{"code":"

GeeksforGeeks

Modal title
This is 4 grids
This is 8 grids
This is 12 grids
","e":41974,"s":38370,"text":null},{"code":null,"e":41982,"s":41974,"text":"Output:"},{"code":null,"e":42079,"s":41982,"text":"Varying modal content: We can trigger the same modal with different data as given below.Example:"},{"code":"

GeeksforGeeks

New message
","e":46839,"s":42079,"text":null},{"code":null,"e":46982,"s":46839,"text":"Output without triggering any modal:Output for clicking on Send email to @geeksforgeeks:Output for clicking on Send email to author @gurrrung:"},{"code":null,"e":47156,"s":46982,"text":"Optional sizes Default max-width of a Bootstrap modal is 500px. Bootstrap provides the option to customize the size of the Modal by using certain classes as described below:"},{"code":null,"e":47165,"s":47156,"text":"modal-xl"},{"code":null,"e":47174,"s":47165,"text":"modal-lg"},{"code":null,"e":47183,"s":47174,"text":"modal-sm"},{"code":null,"e":47264,"s":47183,"text":"modal-xl: This provides the largest modal size with max-width of 1140px.Example:"},{"code":"

GeeksforGeeks

Modal title
GeeksforGeeks
","e":49943,"s":47264,"text":null},{"code":null,"e":49951,"s":49943,"text":"Output:"},{"code":null,"e":50029,"s":49951,"text":"modal-lg: This provides the large modal size with max-width of 800px.Example:"},{"code":"

GeeksforGeeks

Modal title
GeeksforGeeks
","e":52704,"s":50029,"text":null},{"code":null,"e":52712,"s":52704,"text":"Output:"},{"code":null,"e":52792,"s":52712,"text":"modal-sm: This provides the largest modal size with max-width of 300px.Example:"},{"code":"

GeeksforGeeks

Modal title
GeeksforGeeks
","e":55470,"s":52792,"text":null},{"code":null,"e":55478,"s":55470,"text":"Output:"},{"code":null,"e":55493,"s":55478,"text":"Bootstrap-Misc"},{"code":null,"e":55503,"s":55493,"text":"Bootstrap"},{"code":null,"e":55520,"s":55503,"text":"Web Technologies"},{"code":null,"e":55618,"s":55520,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":55627,"s":55618,"text":"Comments"},{"code":null,"e":55640,"s":55627,"text":"Old Comments"},{"code":null,"e":55690,"s":55640,"text":"How to change navigation bar color in Bootstrap ?"},{"code":null,"e":55719,"s":55690,"text":"Form validation using jQuery"},{"code":null,"e":55775,"s":55719,"text":"How to align navbar items to the right in Bootstrap 4 ?"},{"code":null,"e":55816,"s":55775,"text":"How to pass data into a bootstrap modal?"},{"code":null,"e":55857,"s":55816,"text":"How to Show Images on Click using HTML ?"},{"code":null,"e":55913,"s":55857,"text":"Top 10 Front End Developer Skills That You Need in 2022"},{"code":null,"e":55946,"s":55913,"text":"Installation of Node.js on Linux"},{"code":null,"e":56008,"s":55946,"text":"Top 10 Projects For Beginners To Practice HTML and CSS Skills"},{"code":null,"e":56051,"s":56008,"text":"How to fetch data from an API in ReactJS ?"}],"string":"[\n {\n \"code\": null,\n \"e\": 28049,\n \"s\": 28021,\n \"text\": \"\\n11 Sep, 2020\"\n },\n {\n \"code\": null,\n \"e\": 28451,\n \"s\": 28049,\n \"text\": \"Bootstrap 5 is the latest major release by Bootstrap in which they have revamped the UI and made various changes. Modals are used to add dialogs to your site for lightboxes, user notifications, or completely custom content. Modals are built with HTML, CSS, and JavaScript. They’re positioned over everything else in the document and remove scroll from the so that modal content scrolls instead.\"\n },\n {\n \"code\": null,\n \"e\": 28459,\n \"s\": 28451,\n \"text\": \"Syntax:\"\n },\n {\n \"code\": null,\n \"e\": 28497,\n \"s\": 28459,\n \"text\": \"
Contents...
\"\n },\n {\n \"code\": null,\n \"e\": 28568,\n \"s\": 28497,\n \"text\": \"Example: This example uses show the working of a modal in Bootstrap 5.\"\n },\n {\n \"code\": \"

GeeksforGeeks

Modal title
GeeksforGeeks
\",\n \"e\": 31235,\n \"s\": 28568,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 31271,\n \"s\": 31235,\n \"text\": \"Output before triggering the modal:\"\n },\n {\n \"code\": null,\n \"e\": 31306,\n \"s\": 31271,\n \"text\": \"Output after triggering the modal:\"\n },\n {\n \"code\": null,\n \"e\": 31429,\n \"s\": 31306,\n \"text\": \"Tooltips: can be added inside the modal. When modals are closed, tooltips within are also automatically dismissed.Example:\"\n },\n {\n \"code\": \"

GeeksforGeeks

Modal title
Tooltips in a modal
Hover over me
\",\n \"e\": 34693,\n \"s\": 31429,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 34701,\n \"s\": 34693,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 34824,\n \"s\": 34701,\n \"text\": \"Popovers: can be added inside the modal. When modals are closed, popovers within are also automatically dismissed.Example:\"\n },\n {\n \"code\": \"

GeeksforGeeks

Modal title
Popover in a modal
Toggle popover
\",\n \"e\": 38164,\n \"s\": 34824,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 38172,\n \"s\": 38164,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 38370,\n \"s\": 38172,\n \"text\": \"Using Grids: We can utilize the Bootstrap grid system within a modal by nesting .container-fluid within the .modal-body. Then, use the normal grid system classes as you would anywhere else.Example:\"\n },\n {\n \"code\": \"

GeeksforGeeks

Modal title
This is 4 grids
This is 8 grids
This is 12 grids
\",\n \"e\": 41974,\n \"s\": 38370,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 41982,\n \"s\": 41974,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 42079,\n \"s\": 41982,\n \"text\": \"Varying modal content: We can trigger the same modal with different data as given below.Example:\"\n },\n {\n \"code\": \"

GeeksforGeeks

New message
\",\n \"e\": 46839,\n \"s\": 42079,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 46982,\n \"s\": 46839,\n \"text\": \"Output without triggering any modal:Output for clicking on Send email to @geeksforgeeks:Output for clicking on Send email to author @gurrrung:\"\n },\n {\n \"code\": null,\n \"e\": 47156,\n \"s\": 46982,\n \"text\": \"Optional sizes Default max-width of a Bootstrap modal is 500px. Bootstrap provides the option to customize the size of the Modal by using certain classes as described below:\"\n },\n {\n \"code\": null,\n \"e\": 47165,\n \"s\": 47156,\n \"text\": \"modal-xl\"\n },\n {\n \"code\": null,\n \"e\": 47174,\n \"s\": 47165,\n \"text\": \"modal-lg\"\n },\n {\n \"code\": null,\n \"e\": 47183,\n \"s\": 47174,\n \"text\": \"modal-sm\"\n },\n {\n \"code\": null,\n \"e\": 47264,\n \"s\": 47183,\n \"text\": \"modal-xl: This provides the largest modal size with max-width of 1140px.Example:\"\n },\n {\n \"code\": \"

GeeksforGeeks

Modal title
GeeksforGeeks
\",\n \"e\": 49943,\n \"s\": 47264,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 49951,\n \"s\": 49943,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 50029,\n \"s\": 49951,\n \"text\": \"modal-lg: This provides the large modal size with max-width of 800px.Example:\"\n },\n {\n \"code\": \"

GeeksforGeeks

Modal title
GeeksforGeeks
\",\n \"e\": 52704,\n \"s\": 50029,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 52712,\n \"s\": 52704,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 52792,\n \"s\": 52712,\n \"text\": \"modal-sm: This provides the largest modal size with max-width of 300px.Example:\"\n },\n {\n \"code\": \"

GeeksforGeeks

Modal title
GeeksforGeeks
\",\n \"e\": 55470,\n \"s\": 52792,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 55478,\n \"s\": 55470,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 55493,\n \"s\": 55478,\n \"text\": \"Bootstrap-Misc\"\n },\n {\n \"code\": null,\n \"e\": 55503,\n \"s\": 55493,\n \"text\": \"Bootstrap\"\n },\n {\n \"code\": null,\n \"e\": 55520,\n \"s\": 55503,\n \"text\": \"Web Technologies\"\n },\n {\n \"code\": null,\n \"e\": 55618,\n \"s\": 55520,\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\": 55627,\n \"s\": 55618,\n \"text\": \"Comments\"\n },\n {\n \"code\": null,\n \"e\": 55640,\n \"s\": 55627,\n \"text\": \"Old Comments\"\n },\n {\n \"code\": null,\n \"e\": 55690,\n \"s\": 55640,\n \"text\": \"How to change navigation bar color in Bootstrap ?\"\n },\n {\n \"code\": null,\n \"e\": 55719,\n \"s\": 55690,\n \"text\": \"Form validation using jQuery\"\n },\n {\n \"code\": null,\n \"e\": 55775,\n \"s\": 55719,\n \"text\": \"How to align navbar items to the right in Bootstrap 4 ?\"\n },\n {\n \"code\": null,\n \"e\": 55816,\n \"s\": 55775,\n \"text\": \"How to pass data into a bootstrap modal?\"\n },\n {\n \"code\": null,\n \"e\": 55857,\n \"s\": 55816,\n \"text\": \"How to Show Images on Click using HTML ?\"\n },\n {\n \"code\": null,\n \"e\": 55913,\n \"s\": 55857,\n \"text\": \"Top 10 Front End Developer Skills That You Need in 2022\"\n },\n {\n \"code\": null,\n \"e\": 55946,\n \"s\": 55913,\n \"text\": \"Installation of Node.js on Linux\"\n },\n {\n \"code\": null,\n \"e\": 56008,\n \"s\": 55946,\n \"text\": \"Top 10 Projects For Beginners To Practice HTML and CSS Skills\"\n },\n {\n \"code\": null,\n \"e\": 56051,\n \"s\": 56008,\n \"text\": \"How to fetch data from an API in ReactJS ?\"\n }\n]"}}},{"rowIdx":427,"cells":{"title":{"kind":"string","value":"HTML canvas strokeRect() Method"},"text":{"kind":"string","value":"The strokeRect() method of the HTML canvas is used to create a rectangle on a web page. The element allows you to draw graphics on a web page using JavaScript. Every canvas has two elements that describes the height and width of the canvas i.e. height and width respectively.\nFollowing is the syntax −\ncontext.strokeRect(p,q,width,height);\nAbove,\np − The x-coordinate of the upper-left corner of the rectangle\nq − The y-coordinate of the upper-left corner of the rectangle\nwidth − Width of the rectangle\nheight − Height of the rectangle\nLet us now see an example to implement the strokeStyle property of canvas −\n Live Demo\n\n\n\n\n\n\n"},"parsed":{"kind":"list like","value":[{"code":null,"e":1347,"s":1062,"text":"The strokeRect() method of the HTML canvas is used to create a rectangle on a web page. The element allows you to draw graphics on a web page using JavaScript. Every canvas has two elements that describes the height and width of the canvas i.e. height and width respectively."},{"code":null,"e":1373,"s":1347,"text":"Following is the syntax −"},{"code":null,"e":1411,"s":1373,"text":"context.strokeRect(p,q,width,height);"},{"code":null,"e":1418,"s":1411,"text":"Above,"},{"code":null,"e":1481,"s":1418,"text":"p − The x-coordinate of the upper-left corner of the rectangle"},{"code":null,"e":1544,"s":1481,"text":"q − The y-coordinate of the upper-left corner of the rectangle"},{"code":null,"e":1575,"s":1544,"text":"width − Width of the rectangle"},{"code":null,"e":1608,"s":1575,"text":"height − Height of the rectangle"},{"code":null,"e":1684,"s":1608,"text":"Let us now see an example to implement the strokeStyle property of canvas −"},{"code":null,"e":1695,"s":1684,"text":" Live Demo"},{"code":null,"e":1973,"s":1695,"text":"\n\n\n\n\n\n"}],"string":"[\n {\n \"code\": null,\n \"e\": 1347,\n \"s\": 1062,\n \"text\": \"The strokeRect() method of the HTML canvas is used to create a rectangle on a web page. The element allows you to draw graphics on a web page using JavaScript. Every canvas has two elements that describes the height and width of the canvas i.e. height and width respectively.\"\n },\n {\n \"code\": null,\n \"e\": 1373,\n \"s\": 1347,\n \"text\": \"Following is the syntax −\"\n },\n {\n \"code\": null,\n \"e\": 1411,\n \"s\": 1373,\n \"text\": \"context.strokeRect(p,q,width,height);\"\n },\n {\n \"code\": null,\n \"e\": 1418,\n \"s\": 1411,\n \"text\": \"Above,\"\n },\n {\n \"code\": null,\n \"e\": 1481,\n \"s\": 1418,\n \"text\": \"p − The x-coordinate of the upper-left corner of the rectangle\"\n },\n {\n \"code\": null,\n \"e\": 1544,\n \"s\": 1481,\n \"text\": \"q − The y-coordinate of the upper-left corner of the rectangle\"\n },\n {\n \"code\": null,\n \"e\": 1575,\n \"s\": 1544,\n \"text\": \"width − Width of the rectangle\"\n },\n {\n \"code\": null,\n \"e\": 1608,\n \"s\": 1575,\n \"text\": \"height − Height of the rectangle\"\n },\n {\n \"code\": null,\n \"e\": 1684,\n \"s\": 1608,\n \"text\": \"Let us now see an example to implement the strokeStyle property of canvas −\"\n },\n {\n \"code\": null,\n \"e\": 1695,\n \"s\": 1684,\n \"text\": \" Live Demo\"\n },\n {\n \"code\": null,\n \"e\": 1973,\n \"s\": 1695,\n \"text\": \"\\n\\n\\n\\n\\n\\n\"\n }\n]"}}},{"rowIdx":428,"cells":{"title":{"kind":"string","value":"How to start service using Alarm Manager in android?"},"text":{"kind":"string","value":"This example demonstrates how do I start a service using alarm manager in android.\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 − Add the following code to res/layout/activity_main.xml.\n\n\n \n \n\nStep 3 − Add the following code to src/MainActivity.java\npackage app.com.sample;\nimport android.app.AlarmManager;\nimport android.app.PendingIntent;\nimport android.content.Intent;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.Toast;\nimport java.util.Calendar;\npublic class MainActivity extends AppCompatActivity {\n Button btnStart, btnStop;\n PendingIntent pendingIntent;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n btnStart = findViewById(R.id.btnStartService);\n btnStop = findViewById(R.id.btnStopService);\n btnStart.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Intent myIntent = new Intent(MainActivity.this, MyAlarmService.class);\n pendingIntent = PendingIntent.getService(MainActivity.this, 0, myIntent, 0);\n AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);\n Calendar calendar = Calendar.getInstance();\n calendar.setTimeInMillis(System.currentTimeMillis());\n calendar.add(Calendar.SECOND, 3);\n assert alarmManager != null;\n alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);\n Toast.makeText(MainActivity.this, \"Starting Service Alarm\", Toast.LENGTH_LONG).show();\n }});\n btnStop.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);\n assert alarmManager != null;\n alarmManager.cancel(pendingIntent);\n Toast.makeText(MainActivity.this, \"Service Cancelled\", Toast.LENGTH_LONG).show();\n }\n });\n }\n}\nStep 4 – Create a java class (MyAlarmService.java) and add the following code?\nimport android.app.Service;\nimport android.content.Intent;\nimport android.os.IBinder;\nimport android.support.annotation.Nullable;\nimport android.widget.Toast;\npublic class MyAlarmService extends Service {\n @Override\n public void onCreate() {\n Toast.makeText(this, \"MyAlarmService.onCreate()\", Toast.LENGTH_LONG).show();\n }\n @Nullable\n @Override\n public IBinder onBind(Intent intent) {\n Toast.makeText(this, \"MyAlarmService.onBind()\", Toast.LENGTH_LONG).show();\n return null;\n }\n @Override\n public void onDestroy() {\n super.onDestroy();\n Toast.makeText(this, \"MyAlarmService.onDestroy()\", Toast.LENGTH_LONG).show();\n }\n @Override\n public void onStart(Intent intent, int startId) {\n super.onStart(intent, startId);\n Toast.makeText(this, \"MyAlarmService.onStart()\", Toast.LENGTH_LONG).show();\n }\n @Override\n public boolean onUnbind(Intent intent) {\n Toast.makeText(this, \"MyAlarmService.onUnbind()\", Toast.LENGTH_LONG).show();\n return super.onUnbind(intent);\n }\n}\nStep 5 − Add the following code to androidManifest.xml\n\n\n \n \n \n \n \n \n \n \n \n\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 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 –\nClick here to download the project code."},"parsed":{"kind":"list like","value":[{"code":null,"e":1145,"s":1062,"text":"This example demonstrates how do I start a service using alarm manager in android."},{"code":null,"e":1274,"s":1145,"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":1339,"s":1274,"text":"Step 2 − Add the following code to res/layout/activity_main.xml."},{"code":null,"e":2109,"s":1339,"text":"\n\n \n \n"},{"code":null,"e":2166,"s":2109,"text":"Step 3 − Add the following code to src/MainActivity.java"},{"code":null,"e":4033,"s":2166,"text":"package app.com.sample;\nimport android.app.AlarmManager;\nimport android.app.PendingIntent;\nimport android.content.Intent;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.Toast;\nimport java.util.Calendar;\npublic class MainActivity extends AppCompatActivity {\n Button btnStart, btnStop;\n PendingIntent pendingIntent;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n btnStart = findViewById(R.id.btnStartService);\n btnStop = findViewById(R.id.btnStopService);\n btnStart.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Intent myIntent = new Intent(MainActivity.this, MyAlarmService.class);\n pendingIntent = PendingIntent.getService(MainActivity.this, 0, myIntent, 0);\n AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);\n Calendar calendar = Calendar.getInstance();\n calendar.setTimeInMillis(System.currentTimeMillis());\n calendar.add(Calendar.SECOND, 3);\n assert alarmManager != null;\n alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);\n Toast.makeText(MainActivity.this, \"Starting Service Alarm\", Toast.LENGTH_LONG).show();\n }});\n btnStop.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);\n assert alarmManager != null;\n alarmManager.cancel(pendingIntent);\n Toast.makeText(MainActivity.this, \"Service Cancelled\", Toast.LENGTH_LONG).show();\n }\n });\n }\n}"},{"code":null,"e":4112,"s":4033,"text":"Step 4 – Create a java class (MyAlarmService.java) and add the following code?"},{"code":null,"e":5150,"s":4112,"text":"import android.app.Service;\nimport android.content.Intent;\nimport android.os.IBinder;\nimport android.support.annotation.Nullable;\nimport android.widget.Toast;\npublic class MyAlarmService extends Service {\n @Override\n public void onCreate() {\n Toast.makeText(this, \"MyAlarmService.onCreate()\", Toast.LENGTH_LONG).show();\n }\n @Nullable\n @Override\n public IBinder onBind(Intent intent) {\n Toast.makeText(this, \"MyAlarmService.onBind()\", Toast.LENGTH_LONG).show();\n return null;\n }\n @Override\n public void onDestroy() {\n super.onDestroy();\n Toast.makeText(this, \"MyAlarmService.onDestroy()\", Toast.LENGTH_LONG).show();\n }\n @Override\n public void onStart(Intent intent, int startId) {\n super.onStart(intent, startId);\n Toast.makeText(this, \"MyAlarmService.onStart()\", Toast.LENGTH_LONG).show();\n }\n @Override\n public boolean onUnbind(Intent intent) {\n Toast.makeText(this, \"MyAlarmService.onUnbind()\", Toast.LENGTH_LONG).show();\n return super.onUnbind(intent);\n }\n}"},{"code":null,"e":5205,"s":5150,"text":"Step 5 − Add the following code to androidManifest.xml"},{"code":null,"e":5921,"s":5205,"text":"\n\n \n \n \n \n \n \n \n \n \n"},{"code":null,"e":6268,"s":5921,"text":"Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"},{"code":null,"e":6309,"s":6268,"text":"Click here to download the project code."}],"string":"[\n {\n \"code\": null,\n \"e\": 1145,\n \"s\": 1062,\n \"text\": \"This example demonstrates how do I start a service using alarm manager in android.\"\n },\n {\n \"code\": null,\n \"e\": 1274,\n \"s\": 1145,\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\": 1339,\n \"s\": 1274,\n \"text\": \"Step 2 − Add the following code to res/layout/activity_main.xml.\"\n },\n {\n \"code\": null,\n \"e\": 2109,\n \"s\": 1339,\n \"text\": \"\\n\\n \\n \\n\"\n },\n {\n \"code\": null,\n \"e\": 2166,\n \"s\": 2109,\n \"text\": \"Step 3 − Add the following code to src/MainActivity.java\"\n },\n {\n \"code\": null,\n \"e\": 4033,\n \"s\": 2166,\n \"text\": \"package app.com.sample;\\nimport android.app.AlarmManager;\\nimport android.app.PendingIntent;\\nimport android.content.Intent;\\nimport android.support.v7.app.AppCompatActivity;\\nimport android.os.Bundle;\\nimport android.view.View;\\nimport android.widget.Button;\\nimport android.widget.Toast;\\nimport java.util.Calendar;\\npublic class MainActivity extends AppCompatActivity {\\n Button btnStart, btnStop;\\n PendingIntent pendingIntent;\\n @Override\\n protected void onCreate(Bundle savedInstanceState) {\\n super.onCreate(savedInstanceState);\\n setContentView(R.layout.activity_main);\\n btnStart = findViewById(R.id.btnStartService);\\n btnStop = findViewById(R.id.btnStopService);\\n btnStart.setOnClickListener(new View.OnClickListener() {\\n @Override\\n public void onClick(View v) {\\n Intent myIntent = new Intent(MainActivity.this, MyAlarmService.class);\\n pendingIntent = PendingIntent.getService(MainActivity.this, 0, myIntent, 0);\\n AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);\\n Calendar calendar = Calendar.getInstance();\\n calendar.setTimeInMillis(System.currentTimeMillis());\\n calendar.add(Calendar.SECOND, 3);\\n assert alarmManager != null;\\n alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);\\n Toast.makeText(MainActivity.this, \\\"Starting Service Alarm\\\", Toast.LENGTH_LONG).show();\\n }});\\n btnStop.setOnClickListener(new View.OnClickListener() {\\n @Override\\n public void onClick(View v) {\\n AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);\\n assert alarmManager != null;\\n alarmManager.cancel(pendingIntent);\\n Toast.makeText(MainActivity.this, \\\"Service Cancelled\\\", Toast.LENGTH_LONG).show();\\n }\\n });\\n }\\n}\"\n },\n {\n \"code\": null,\n \"e\": 4112,\n \"s\": 4033,\n \"text\": \"Step 4 – Create a java class (MyAlarmService.java) and add the following code?\"\n },\n {\n \"code\": null,\n \"e\": 5150,\n \"s\": 4112,\n \"text\": \"import android.app.Service;\\nimport android.content.Intent;\\nimport android.os.IBinder;\\nimport android.support.annotation.Nullable;\\nimport android.widget.Toast;\\npublic class MyAlarmService extends Service {\\n @Override\\n public void onCreate() {\\n Toast.makeText(this, \\\"MyAlarmService.onCreate()\\\", Toast.LENGTH_LONG).show();\\n }\\n @Nullable\\n @Override\\n public IBinder onBind(Intent intent) {\\n Toast.makeText(this, \\\"MyAlarmService.onBind()\\\", Toast.LENGTH_LONG).show();\\n return null;\\n }\\n @Override\\n public void onDestroy() {\\n super.onDestroy();\\n Toast.makeText(this, \\\"MyAlarmService.onDestroy()\\\", Toast.LENGTH_LONG).show();\\n }\\n @Override\\n public void onStart(Intent intent, int startId) {\\n super.onStart(intent, startId);\\n Toast.makeText(this, \\\"MyAlarmService.onStart()\\\", Toast.LENGTH_LONG).show();\\n }\\n @Override\\n public boolean onUnbind(Intent intent) {\\n Toast.makeText(this, \\\"MyAlarmService.onUnbind()\\\", Toast.LENGTH_LONG).show();\\n return super.onUnbind(intent);\\n }\\n}\"\n },\n {\n \"code\": null,\n \"e\": 5205,\n \"s\": 5150,\n \"text\": \"Step 5 − Add the following code to androidManifest.xml\"\n },\n {\n \"code\": null,\n \"e\": 5921,\n \"s\": 5205,\n \"text\": \"\\n\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n\"\n },\n {\n \"code\": null,\n \"e\": 6268,\n \"s\": 5921,\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 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\": 6309,\n \"s\": 6268,\n \"text\": \"Click here to download the project code.\"\n }\n]"}}},{"rowIdx":429,"cells":{"title":{"kind":"string","value":"Python Number Systems Example - onlinetutorialspoint"},"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\nAccording to the mathematics we have four types of number systems which are representing the numbers in computer architecture. In this tutorial, we are going to learn how to deal with these number systems in Python Language.\nThe python number system is representing the way of using the below numbers in Language.\nBinary Number System\nOctal Number System\nDecimal Number System\nHexadecimal Number System\nLet’s see one by one, how these are used in the python language.\nIn general, a binary number represents a 0 or 1 in the system.\nThe base or radix of the binary number system is 2.\nThe possible digits that are used in a binary number system are 0 and 1.\nIf we wanted to store a binary number in python variable, that number should sharts with 0b.\nx = 0b1010\n\nprint('Value is : ',x)\n\n\nOutput :\n(Value is : 10)\nNote: we can not give the x=ob1020 since binary numbers contain only 0 and 1. If so we will get an error message like SyntaxError: invalid syntax.\nThe base or radix of the octal number system is 8.\nThe possible digits that are used in the octal number system are 0 to 7.\nTo represent an octal number in Python, the number should start with 0 (python2) or ox (python3).\nx=0123\n\nprint('Value is : '+x)\n\nOutput :\n(Value is : 83)\nNote: we can not give the x=o180 since octal numbers contain from 0 to 7. If so we will get an error message like SyntaxError: invalid token.\nThe base or radix of the decimal number system is 10.\nThe possible digits that are used in the decimal number system are 0 to 9.\nThe default number system followed by python is the decimal number system.\nx=1234\n\nprint('Value is : '+x)\n\nOutput :\n(Value is : 1234)\nNote: we can not give the x=1234p since the decimal numbers contain from 0 to 9. If so we will get an error message like SyntaxError: invalid syntax.\nThe base or radix of the hexadecimal number system is 16.\nThe possible digits that are used in hexadecimal number systems are 0 to 9 and a to f.\nTo represent a hexadecimal number in Python, the number should start with 0x.\nx=0x25\n\nprint('Value is :'+x)\n\nOutput :\n(Value is : 37)\nNumber System Wiki\nPython-Dev Peps\nHappy Learning 🙂\n\nConvert any Number to Python Binary Number\nBinary To Hexadecimal Conversion Java Program\nDecimal To Octal Conversion Java Program\nOctal To Decimal Conversion Java Program\nDecimal To Hex Conversion Java Program\nBinary To Decimal Conversion Java Program\nDecimal To Binary Conversion Java Program\nPython – Find the biggest of 2 given numbers\nFeatures of Python Language\nModes of Python Program\nPython Operators Example\nPython Conditional Statements\nWhat are different Python Data Types\nWhat are the List of Python Keywords\nPython String to int Conversion Example\n\nConvert any Number to Python Binary Number\nBinary To Hexadecimal Conversion Java Program\nDecimal To Octal Conversion Java Program\nOctal To Decimal Conversion Java Program\nDecimal To Hex Conversion Java Program\nBinary To Decimal Conversion Java Program\nDecimal To Binary Conversion Java Program\nPython – Find the biggest of 2 given numbers\nFeatures of Python Language\nModes of Python Program\nPython Operators Example\nPython Conditional Statements\nWhat are different Python Data Types\nWhat are the List of Python Keywords\nPython String to int Conversion Example\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":623,"s":398,"text":"According to the mathematics we have four types of number systems which are representing the numbers in computer architecture. In this tutorial, we are going to learn how to deal with these number systems in Python Language."},{"code":null,"e":712,"s":623,"text":"The python number system is representing the way of using the below numbers in Language."},{"code":null,"e":733,"s":712,"text":"Binary Number System"},{"code":null,"e":753,"s":733,"text":"Octal Number System"},{"code":null,"e":775,"s":753,"text":"Decimal Number System"},{"code":null,"e":801,"s":775,"text":"Hexadecimal Number System"},{"code":null,"e":866,"s":801,"text":"Let’s see one by one, how these are used in the python language."},{"code":null,"e":929,"s":866,"text":"In general, a binary number represents a 0 or 1 in the system."},{"code":null,"e":981,"s":929,"text":"The base or radix of the binary number system is 2."},{"code":null,"e":1054,"s":981,"text":"The possible digits that are used in a binary number system are 0 and 1."},{"code":null,"e":1147,"s":1054,"text":"If we wanted to store a binary number in python variable, that number should sharts with 0b."},{"code":null,"e":1184,"s":1147,"text":"x = 0b1010\n\nprint('Value is : ',x)\n\n"},{"code":null,"e":1193,"s":1184,"text":"Output :"},{"code":null,"e":1209,"s":1193,"text":"(Value is : 10)"},{"code":null,"e":1356,"s":1209,"text":"Note: we can not give the x=ob1020 since binary numbers contain only 0 and 1. If so we will get an error message like SyntaxError: invalid syntax."},{"code":null,"e":1407,"s":1356,"text":"The base or radix of the octal number system is 8."},{"code":null,"e":1480,"s":1407,"text":"The possible digits that are used in the octal number system are 0 to 7."},{"code":null,"e":1578,"s":1480,"text":"To represent an octal number in Python, the number should start with 0 (python2) or ox (python3)."},{"code":null,"e":1610,"s":1578,"text":"x=0123\n\nprint('Value is : '+x)\n"},{"code":null,"e":1619,"s":1610,"text":"Output :"},{"code":null,"e":1635,"s":1619,"text":"(Value is : 83)"},{"code":null,"e":1777,"s":1635,"text":"Note: we can not give the x=o180 since octal numbers contain from 0 to 7. If so we will get an error message like SyntaxError: invalid token."},{"code":null,"e":1831,"s":1777,"text":"The base or radix of the decimal number system is 10."},{"code":null,"e":1906,"s":1831,"text":"The possible digits that are used in the decimal number system are 0 to 9."},{"code":null,"e":1981,"s":1906,"text":"The default number system followed by python is the decimal number system."},{"code":null,"e":2013,"s":1981,"text":"x=1234\n\nprint('Value is : '+x)\n"},{"code":null,"e":2022,"s":2013,"text":"Output :"},{"code":null,"e":2040,"s":2022,"text":"(Value is : 1234)"},{"code":null,"e":2190,"s":2040,"text":"Note: we can not give the x=1234p since the decimal numbers contain from 0 to 9. If so we will get an error message like SyntaxError: invalid syntax."},{"code":null,"e":2248,"s":2190,"text":"The base or radix of the hexadecimal number system is 16."},{"code":null,"e":2336,"s":2248,"text":"The possible digits that are used in hexadecimal number systems are 0 to 9 and a to f."},{"code":null,"e":2414,"s":2336,"text":"To represent a hexadecimal number in Python, the number should start with 0x."},{"code":null,"e":2445,"s":2414,"text":"x=0x25\n\nprint('Value is :'+x)\n"},{"code":null,"e":2454,"s":2445,"text":"Output :"},{"code":null,"e":2470,"s":2454,"text":"(Value is : 37)"},{"code":null,"e":2489,"s":2470,"text":"Number System Wiki"},{"code":null,"e":2505,"s":2489,"text":"Python-Dev Peps"},{"code":null,"e":2522,"s":2505,"text":"Happy Learning 🙂"},{"code":null,"e":3084,"s":2522,"text":"\nConvert any Number to Python Binary Number\nBinary To Hexadecimal Conversion Java Program\nDecimal To Octal Conversion Java Program\nOctal To Decimal Conversion Java Program\nDecimal To Hex Conversion Java Program\nBinary To Decimal Conversion Java Program\nDecimal To Binary Conversion Java Program\nPython – Find the biggest of 2 given numbers\nFeatures of Python Language\nModes of Python Program\nPython Operators Example\nPython Conditional Statements\nWhat are different Python Data Types\nWhat are the List of Python Keywords\nPython String to int Conversion Example\n"},{"code":null,"e":3127,"s":3084,"text":"Convert any Number to Python Binary Number"},{"code":null,"e":3173,"s":3127,"text":"Binary To Hexadecimal Conversion Java Program"},{"code":null,"e":3214,"s":3173,"text":"Decimal To Octal Conversion Java Program"},{"code":null,"e":3255,"s":3214,"text":"Octal To Decimal Conversion Java Program"},{"code":null,"e":3294,"s":3255,"text":"Decimal To Hex Conversion Java Program"},{"code":null,"e":3336,"s":3294,"text":"Binary To Decimal Conversion Java Program"},{"code":null,"e":3378,"s":3336,"text":"Decimal To Binary Conversion Java Program"},{"code":null,"e":3423,"s":3378,"text":"Python – Find the biggest of 2 given numbers"},{"code":null,"e":3451,"s":3423,"text":"Features of Python Language"},{"code":null,"e":3475,"s":3451,"text":"Modes of Python Program"},{"code":null,"e":3500,"s":3475,"text":"Python Operators Example"},{"code":null,"e":3530,"s":3500,"text":"Python Conditional Statements"},{"code":null,"e":3567,"s":3530,"text":"What are different Python Data Types"},{"code":null,"e":3604,"s":3567,"text":"What are the List of Python Keywords"},{"code":null,"e":3644,"s":3604,"text":"Python String to int Conversion Example"},{"code":null,"e":3650,"s":3648,"text":"Δ"},{"code":null,"e":3673,"s":3650,"text":" Python – Introduction"},{"code":null,"e":3692,"s":3673,"text":" Python – Features"},{"code":null,"e":3721,"s":3692,"text":" Python – Install on Windows"},{"code":null,"e":3748,"s":3721,"text":" Python – Modes of Program"},{"code":null,"e":3772,"s":3748,"text":" Python – Number System"},{"code":null,"e":3794,"s":3772,"text":" Python – Identifiers"},{"code":null,"e":3814,"s":3794,"text":" Python – Operators"},{"code":null,"e":3841,"s":3814,"text":" Python – Ternary Operator"},{"code":null,"e":3874,"s":3841,"text":" Python – Command Line Arguments"},{"code":null,"e":3893,"s":3874,"text":" Python – Keywords"},{"code":null,"e":3914,"s":3893,"text":" Python – Data Types"},{"code":null,"e":3943,"s":3914,"text":" Python – Upgrade Python PIP"},{"code":null,"e":3973,"s":3943,"text":" Python – Virtual Environment"},{"code":null,"e":3996,"s":3973,"text":" Pyhton – Type Casting"},{"code":null,"e":4020,"s":3996,"text":" Python – String to Int"},{"code":null,"e":4053,"s":4020,"text":" Python – Conditional Statements"},{"code":null,"e":4076,"s":4053,"text":" Python – if statement"},{"code":null,"e":4105,"s":4076,"text":" Python – *args and **kwargs"},{"code":null,"e":4131,"s":4105,"text":" Python – Date Formatting"},{"code":null,"e":4166,"s":4131,"text":" Python – Read input from keyboard"},{"code":null,"e":4186,"s":4166,"text":" Python – raw_input"},{"code":null,"e":4210,"s":4186,"text":" Python – List In Depth"},{"code":null,"e":4239,"s":4210,"text":" Python – List Comprehension"},{"code":null,"e":4262,"s":4239,"text":" Python – Set in Depth"},{"code":null,"e":4292,"s":4262,"text":" Python – Dictionary in Depth"},{"code":null,"e":4317,"s":4292,"text":" Python – Tuple in Depth"},{"code":null,"e":4347,"s":4317,"text":" Python – Stack Datastructure"},{"code":null,"e":4377,"s":4347,"text":" Python – Classes and Objects"},{"code":null,"e":4400,"s":4377,"text":" Python – Constructors"},{"code":null,"e":4431,"s":4400,"text":" Python – Object Introspection"},{"code":null,"e":4453,"s":4431,"text":" Python – Inheritance"},{"code":null,"e":4474,"s":4453,"text":" Python – Decorators"},{"code":null,"e":4510,"s":4474,"text":" Python – Serialization with Pickle"},{"code":null,"e":4540,"s":4510,"text":" Python – Exceptions Handling"},{"code":null,"e":4574,"s":4540,"text":" Python – User defined Exceptions"},{"code":null,"e":4600,"s":4574,"text":" Python – Multiprocessing"},{"code":null,"e":4638,"s":4600,"text":" Python – Default function parameters"},{"code":null,"e":4666,"s":4638,"text":" Python – Lambdas Functions"},{"code":null,"e":4690,"s":4666,"text":" Python – NumPy Library"},{"code":null,"e":4716,"s":4690,"text":" Python – MySQL Connector"},{"code":null,"e":4748,"s":4716,"text":" Python – MySQL Create Database"},{"code":null,"e":4774,"s":4748,"text":" Python – MySQL Read Data"},{"code":null,"e":4802,"s":4774,"text":" Python – MySQL Insert Data"},{"code":null,"e":4833,"s":4802,"text":" Python – MySQL Update Records"},{"code":null,"e":4864,"s":4833,"text":" Python – MySQL Delete Records"},{"code":null,"e":4897,"s":4864,"text":" Python – String Case Conversion"},{"code":null,"e":4932,"s":4897,"text":" Howto – Find biggest of 2 numbers"},{"code":null,"e":4969,"s":4932,"text":" Howto – Remove duplicates from List"},{"code":null,"e":5007,"s":4969,"text":" Howto – Convert any Number to Binary"},{"code":null,"e":5033,"s":5007,"text":" Howto – Merge two Lists"},{"code":null,"e":5058,"s":5033,"text":" Howto – Merge two dicts"},{"code":null,"e":5098,"s":5058,"text":" Howto – Get Characters Count in a File"},{"code":null,"e":5133,"s":5098,"text":" Howto – Get Words Count in a File"},{"code":null,"e":5168,"s":5133,"text":" Howto – Remove Spaces from String"},{"code":null,"e":5197,"s":5168,"text":" Howto – Read Env variables"},{"code":null,"e":5223,"s":5197,"text":" Howto – Read a text File"},{"code":null,"e":5249,"s":5223,"text":" Howto – Read a JSON File"},{"code":null,"e":5281,"s":5249,"text":" Howto – Read Config.ini files"},{"code":null,"e":5309,"s":5281,"text":" Howto – Iterate Dictionary"},{"code":null,"e":5349,"s":5309,"text":" Howto – Convert List Of Objects to CSV"},{"code":null,"e":5383,"s":5349,"text":" Howto – Merge two dict in Python"},{"code":null,"e":5408,"s":5383,"text":" Howto – create Zip File"},{"code":null,"e":5429,"s":5408,"text":" Howto – Get OS info"},{"code":null,"e":5460,"s":5429,"text":" Howto – Get size of Directory"},{"code":null,"e":5497,"s":5460,"text":" Howto – Check whether a file exists"},{"code":null,"e":5534,"s":5497,"text":" Howto – Remove key from dictionary"},{"code":null,"e":5556,"s":5534,"text":" Howto – Sort Objects"},{"code":null,"e":5594,"s":5556,"text":" Howto – Create or Delete Directories"},{"code":null,"e":5617,"s":5594,"text":" Howto – Read CSV File"},{"code":null,"e":5655,"s":5617,"text":" Howto – Create Python Iterable class"},{"code":null,"e":5686,"s":5655,"text":" Howto – Access for loop index"},{"code":null,"e":5724,"s":5686,"text":" Howto – Clear all elements from List"},{"code":null,"e":5764,"s":5724,"text":" Howto – Remove empty lists from a List"},{"code":null,"e":5811,"s":5764,"text":" Howto – Remove special characters from String"},{"code":null,"e":5843,"s":5811,"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\": 623,\n \"s\": 398,\n \"text\": \"According to the mathematics we have four types of number systems which are representing the numbers in computer architecture. In this tutorial, we are going to learn how to deal with these number systems in Python Language.\"\n },\n {\n \"code\": null,\n \"e\": 712,\n \"s\": 623,\n \"text\": \"The python number system is representing the way of using the below numbers in Language.\"\n },\n {\n \"code\": null,\n \"e\": 733,\n \"s\": 712,\n \"text\": \"Binary Number System\"\n },\n {\n \"code\": null,\n \"e\": 753,\n \"s\": 733,\n \"text\": \"Octal Number System\"\n },\n {\n \"code\": null,\n \"e\": 775,\n \"s\": 753,\n \"text\": \"Decimal Number System\"\n },\n {\n \"code\": null,\n \"e\": 801,\n \"s\": 775,\n \"text\": \"Hexadecimal Number System\"\n },\n {\n \"code\": null,\n \"e\": 866,\n \"s\": 801,\n \"text\": \"Let’s see one by one, how these are used in the python language.\"\n },\n {\n \"code\": null,\n \"e\": 929,\n \"s\": 866,\n \"text\": \"In general, a binary number represents a 0 or 1 in the system.\"\n },\n {\n \"code\": null,\n \"e\": 981,\n \"s\": 929,\n \"text\": \"The base or radix of the binary number system is 2.\"\n },\n {\n \"code\": null,\n \"e\": 1054,\n \"s\": 981,\n \"text\": \"The possible digits that are used in a binary number system are 0 and 1.\"\n },\n {\n \"code\": null,\n \"e\": 1147,\n \"s\": 1054,\n \"text\": \"If we wanted to store a binary number in python variable, that number should sharts with 0b.\"\n },\n {\n \"code\": null,\n \"e\": 1184,\n \"s\": 1147,\n \"text\": \"x = 0b1010\\n\\nprint('Value is : ',x)\\n\\n\"\n },\n {\n \"code\": null,\n \"e\": 1193,\n \"s\": 1184,\n \"text\": \"Output :\"\n },\n {\n \"code\": null,\n \"e\": 1209,\n \"s\": 1193,\n \"text\": \"(Value is : 10)\"\n },\n {\n \"code\": null,\n \"e\": 1356,\n \"s\": 1209,\n \"text\": \"Note: we can not give the x=ob1020 since binary numbers contain only 0 and 1. If so we will get an error message like SyntaxError: invalid syntax.\"\n },\n {\n \"code\": null,\n \"e\": 1407,\n \"s\": 1356,\n \"text\": \"The base or radix of the octal number system is 8.\"\n },\n {\n \"code\": null,\n \"e\": 1480,\n \"s\": 1407,\n \"text\": \"The possible digits that are used in the octal number system are 0 to 7.\"\n },\n {\n \"code\": null,\n \"e\": 1578,\n \"s\": 1480,\n \"text\": \"To represent an octal number in Python, the number should start with 0 (python2) or ox (python3).\"\n },\n {\n \"code\": null,\n \"e\": 1610,\n \"s\": 1578,\n \"text\": \"x=0123\\n\\nprint('Value is : '+x)\\n\"\n },\n {\n \"code\": null,\n \"e\": 1619,\n \"s\": 1610,\n \"text\": \"Output :\"\n },\n {\n \"code\": null,\n \"e\": 1635,\n \"s\": 1619,\n \"text\": \"(Value is : 83)\"\n },\n {\n \"code\": null,\n \"e\": 1777,\n \"s\": 1635,\n \"text\": \"Note: we can not give the x=o180 since octal numbers contain from 0 to 7. If so we will get an error message like SyntaxError: invalid token.\"\n },\n {\n \"code\": null,\n \"e\": 1831,\n \"s\": 1777,\n \"text\": \"The base or radix of the decimal number system is 10.\"\n },\n {\n \"code\": null,\n \"e\": 1906,\n \"s\": 1831,\n \"text\": \"The possible digits that are used in the decimal number system are 0 to 9.\"\n },\n {\n \"code\": null,\n \"e\": 1981,\n \"s\": 1906,\n \"text\": \"The default number system followed by python is the decimal number system.\"\n },\n {\n \"code\": null,\n \"e\": 2013,\n \"s\": 1981,\n \"text\": \"x=1234\\n\\nprint('Value is : '+x)\\n\"\n },\n {\n \"code\": null,\n \"e\": 2022,\n \"s\": 2013,\n \"text\": \"Output :\"\n },\n {\n \"code\": null,\n \"e\": 2040,\n \"s\": 2022,\n \"text\": \"(Value is : 1234)\"\n },\n {\n \"code\": null,\n \"e\": 2190,\n \"s\": 2040,\n \"text\": \"Note: we can not give the x=1234p since the decimal numbers contain from 0 to 9. If so we will get an error message like SyntaxError: invalid syntax.\"\n },\n {\n \"code\": null,\n \"e\": 2248,\n \"s\": 2190,\n \"text\": \"The base or radix of the hexadecimal number system is 16.\"\n },\n {\n \"code\": null,\n \"e\": 2336,\n \"s\": 2248,\n \"text\": \"The possible digits that are used in hexadecimal number systems are 0 to 9 and a to f.\"\n },\n {\n \"code\": null,\n \"e\": 2414,\n \"s\": 2336,\n \"text\": \"To represent a hexadecimal number in Python, the number should start with 0x.\"\n },\n {\n \"code\": null,\n \"e\": 2445,\n \"s\": 2414,\n \"text\": \"x=0x25\\n\\nprint('Value is :'+x)\\n\"\n },\n {\n \"code\": null,\n \"e\": 2454,\n \"s\": 2445,\n \"text\": \"Output :\"\n },\n {\n \"code\": null,\n \"e\": 2470,\n \"s\": 2454,\n \"text\": \"(Value is : 37)\"\n },\n {\n \"code\": null,\n \"e\": 2489,\n \"s\": 2470,\n \"text\": \"Number System Wiki\"\n },\n {\n \"code\": null,\n \"e\": 2505,\n \"s\": 2489,\n \"text\": \"Python-Dev Peps\"\n },\n {\n \"code\": null,\n \"e\": 2522,\n \"s\": 2505,\n \"text\": \"Happy Learning 🙂\"\n },\n {\n \"code\": null,\n \"e\": 3084,\n \"s\": 2522,\n \"text\": \"\\nConvert any Number to Python Binary Number\\nBinary To Hexadecimal Conversion Java Program\\nDecimal To Octal Conversion Java Program\\nOctal To Decimal Conversion Java Program\\nDecimal To Hex Conversion Java Program\\nBinary To Decimal Conversion Java Program\\nDecimal To Binary Conversion Java Program\\nPython – Find the biggest of 2 given numbers\\nFeatures of Python Language\\nModes of Python Program\\nPython Operators Example\\nPython Conditional Statements\\nWhat are different Python Data Types\\nWhat are the List of Python Keywords\\nPython String to int Conversion Example\\n\"\n },\n {\n \"code\": null,\n \"e\": 3127,\n \"s\": 3084,\n \"text\": \"Convert any Number to Python Binary Number\"\n },\n {\n \"code\": null,\n \"e\": 3173,\n \"s\": 3127,\n \"text\": \"Binary To Hexadecimal Conversion Java Program\"\n },\n {\n \"code\": null,\n \"e\": 3214,\n \"s\": 3173,\n \"text\": \"Decimal To Octal Conversion Java Program\"\n },\n {\n \"code\": null,\n \"e\": 3255,\n \"s\": 3214,\n \"text\": \"Octal To Decimal Conversion Java Program\"\n },\n {\n \"code\": null,\n \"e\": 3294,\n \"s\": 3255,\n \"text\": \"Decimal To Hex Conversion Java Program\"\n },\n {\n \"code\": null,\n \"e\": 3336,\n \"s\": 3294,\n \"text\": \"Binary To Decimal Conversion Java Program\"\n },\n {\n \"code\": null,\n \"e\": 3378,\n \"s\": 3336,\n \"text\": \"Decimal To Binary Conversion Java Program\"\n },\n {\n \"code\": null,\n \"e\": 3423,\n \"s\": 3378,\n \"text\": \"Python – Find the biggest of 2 given numbers\"\n },\n {\n \"code\": null,\n \"e\": 3451,\n \"s\": 3423,\n \"text\": \"Features of Python Language\"\n },\n {\n \"code\": null,\n \"e\": 3475,\n \"s\": 3451,\n \"text\": \"Modes of Python Program\"\n },\n {\n \"code\": null,\n \"e\": 3500,\n \"s\": 3475,\n \"text\": \"Python Operators Example\"\n },\n {\n \"code\": null,\n \"e\": 3530,\n \"s\": 3500,\n \"text\": \"Python Conditional Statements\"\n },\n {\n \"code\": null,\n \"e\": 3567,\n \"s\": 3530,\n \"text\": \"What are different Python Data Types\"\n },\n {\n \"code\": null,\n \"e\": 3604,\n \"s\": 3567,\n \"text\": \"What are the List of Python Keywords\"\n },\n {\n \"code\": null,\n \"e\": 3644,\n \"s\": 3604,\n \"text\": \"Python String to int Conversion Example\"\n },\n {\n \"code\": null,\n \"e\": 3650,\n \"s\": 3648,\n \"text\": \"Δ\"\n },\n {\n \"code\": null,\n \"e\": 3673,\n \"s\": 3650,\n \"text\": \" Python – Introduction\"\n },\n {\n \"code\": null,\n \"e\": 3692,\n \"s\": 3673,\n \"text\": \" Python – Features\"\n },\n {\n \"code\": null,\n \"e\": 3721,\n \"s\": 3692,\n \"text\": \" Python – Install on Windows\"\n },\n {\n \"code\": null,\n \"e\": 3748,\n \"s\": 3721,\n \"text\": \" Python – Modes of Program\"\n },\n {\n \"code\": null,\n \"e\": 3772,\n \"s\": 3748,\n \"text\": \" Python – Number System\"\n },\n {\n \"code\": null,\n \"e\": 3794,\n \"s\": 3772,\n \"text\": \" Python – Identifiers\"\n },\n {\n \"code\": null,\n \"e\": 3814,\n \"s\": 3794,\n \"text\": \" Python – Operators\"\n },\n {\n \"code\": null,\n \"e\": 3841,\n \"s\": 3814,\n \"text\": \" Python – Ternary Operator\"\n },\n {\n \"code\": null,\n \"e\": 3874,\n \"s\": 3841,\n \"text\": \" Python – Command Line Arguments\"\n },\n {\n \"code\": null,\n \"e\": 3893,\n \"s\": 3874,\n \"text\": \" Python – Keywords\"\n },\n {\n \"code\": null,\n \"e\": 3914,\n \"s\": 3893,\n \"text\": \" Python – Data Types\"\n },\n {\n \"code\": null,\n \"e\": 3943,\n \"s\": 3914,\n \"text\": \" Python – Upgrade Python PIP\"\n },\n {\n \"code\": null,\n \"e\": 3973,\n \"s\": 3943,\n \"text\": \" Python – Virtual Environment\"\n },\n {\n \"code\": null,\n \"e\": 3996,\n \"s\": 3973,\n \"text\": \" Pyhton – Type Casting\"\n },\n {\n \"code\": null,\n \"e\": 4020,\n \"s\": 3996,\n \"text\": \" Python – String to Int\"\n },\n {\n \"code\": null,\n \"e\": 4053,\n \"s\": 4020,\n \"text\": \" Python – Conditional Statements\"\n },\n {\n \"code\": null,\n \"e\": 4076,\n \"s\": 4053,\n \"text\": \" Python – if statement\"\n },\n {\n \"code\": null,\n \"e\": 4105,\n \"s\": 4076,\n \"text\": \" Python – *args and **kwargs\"\n },\n {\n \"code\": null,\n \"e\": 4131,\n \"s\": 4105,\n \"text\": \" Python – Date Formatting\"\n },\n {\n \"code\": null,\n \"e\": 4166,\n \"s\": 4131,\n \"text\": \" Python – Read input from keyboard\"\n },\n {\n \"code\": null,\n \"e\": 4186,\n \"s\": 4166,\n \"text\": \" Python – raw_input\"\n },\n {\n \"code\": null,\n \"e\": 4210,\n \"s\": 4186,\n \"text\": \" Python – List In Depth\"\n },\n {\n \"code\": null,\n \"e\": 4239,\n \"s\": 4210,\n \"text\": \" Python – List Comprehension\"\n },\n {\n \"code\": null,\n \"e\": 4262,\n \"s\": 4239,\n \"text\": \" Python – Set in Depth\"\n },\n {\n \"code\": null,\n \"e\": 4292,\n \"s\": 4262,\n \"text\": \" Python – Dictionary in Depth\"\n },\n {\n \"code\": null,\n \"e\": 4317,\n \"s\": 4292,\n \"text\": \" Python – Tuple in Depth\"\n },\n {\n \"code\": null,\n \"e\": 4347,\n \"s\": 4317,\n \"text\": \" Python – Stack Datastructure\"\n },\n {\n \"code\": null,\n \"e\": 4377,\n \"s\": 4347,\n \"text\": \" Python – Classes and Objects\"\n },\n {\n \"code\": null,\n \"e\": 4400,\n \"s\": 4377,\n \"text\": \" Python – Constructors\"\n },\n {\n \"code\": null,\n \"e\": 4431,\n \"s\": 4400,\n \"text\": \" Python – Object Introspection\"\n },\n {\n \"code\": null,\n \"e\": 4453,\n \"s\": 4431,\n \"text\": \" Python – Inheritance\"\n },\n {\n \"code\": null,\n \"e\": 4474,\n \"s\": 4453,\n \"text\": \" Python – Decorators\"\n },\n {\n \"code\": null,\n \"e\": 4510,\n \"s\": 4474,\n \"text\": \" Python – Serialization with Pickle\"\n },\n {\n \"code\": null,\n \"e\": 4540,\n \"s\": 4510,\n \"text\": \" Python – Exceptions Handling\"\n },\n {\n \"code\": null,\n \"e\": 4574,\n \"s\": 4540,\n \"text\": \" Python – User defined Exceptions\"\n },\n {\n \"code\": null,\n \"e\": 4600,\n \"s\": 4574,\n \"text\": \" Python – Multiprocessing\"\n },\n {\n \"code\": null,\n \"e\": 4638,\n \"s\": 4600,\n \"text\": \" Python – Default function parameters\"\n },\n {\n \"code\": null,\n \"e\": 4666,\n \"s\": 4638,\n \"text\": \" Python – Lambdas Functions\"\n },\n {\n \"code\": null,\n \"e\": 4690,\n \"s\": 4666,\n \"text\": \" Python – NumPy Library\"\n },\n {\n \"code\": null,\n \"e\": 4716,\n \"s\": 4690,\n \"text\": \" Python – MySQL Connector\"\n },\n {\n \"code\": null,\n \"e\": 4748,\n \"s\": 4716,\n \"text\": \" Python – MySQL Create Database\"\n },\n {\n \"code\": null,\n \"e\": 4774,\n \"s\": 4748,\n \"text\": \" Python – MySQL Read Data\"\n },\n {\n \"code\": null,\n \"e\": 4802,\n \"s\": 4774,\n \"text\": \" Python – MySQL Insert Data\"\n },\n {\n \"code\": null,\n \"e\": 4833,\n \"s\": 4802,\n \"text\": \" Python – MySQL Update Records\"\n },\n {\n \"code\": null,\n \"e\": 4864,\n \"s\": 4833,\n \"text\": \" Python – MySQL Delete Records\"\n },\n {\n \"code\": null,\n \"e\": 4897,\n \"s\": 4864,\n \"text\": \" Python – String Case Conversion\"\n },\n {\n \"code\": null,\n \"e\": 4932,\n \"s\": 4897,\n \"text\": \" Howto – Find biggest of 2 numbers\"\n },\n {\n \"code\": null,\n \"e\": 4969,\n \"s\": 4932,\n \"text\": \" Howto – Remove duplicates from List\"\n },\n {\n \"code\": null,\n \"e\": 5007,\n \"s\": 4969,\n \"text\": \" Howto – Convert any Number to Binary\"\n },\n {\n \"code\": null,\n \"e\": 5033,\n \"s\": 5007,\n \"text\": \" Howto – Merge two Lists\"\n },\n {\n \"code\": null,\n \"e\": 5058,\n \"s\": 5033,\n \"text\": \" Howto – Merge two dicts\"\n },\n {\n \"code\": null,\n \"e\": 5098,\n \"s\": 5058,\n \"text\": \" Howto – Get Characters Count in a File\"\n },\n {\n \"code\": null,\n \"e\": 5133,\n \"s\": 5098,\n \"text\": \" Howto – Get Words Count in a File\"\n },\n {\n \"code\": null,\n \"e\": 5168,\n \"s\": 5133,\n \"text\": \" Howto – Remove Spaces from String\"\n },\n {\n \"code\": null,\n \"e\": 5197,\n \"s\": 5168,\n \"text\": \" Howto – Read Env variables\"\n },\n {\n \"code\": null,\n \"e\": 5223,\n \"s\": 5197,\n \"text\": \" Howto – Read a text File\"\n },\n {\n \"code\": null,\n \"e\": 5249,\n \"s\": 5223,\n \"text\": \" Howto – Read a JSON File\"\n },\n {\n \"code\": null,\n \"e\": 5281,\n \"s\": 5249,\n \"text\": \" Howto – Read Config.ini files\"\n },\n {\n \"code\": null,\n \"e\": 5309,\n \"s\": 5281,\n \"text\": \" Howto – Iterate Dictionary\"\n },\n {\n \"code\": null,\n \"e\": 5349,\n \"s\": 5309,\n \"text\": \" Howto – Convert List Of Objects to CSV\"\n },\n {\n \"code\": null,\n \"e\": 5383,\n \"s\": 5349,\n \"text\": \" Howto – Merge two dict in Python\"\n },\n {\n \"code\": null,\n \"e\": 5408,\n \"s\": 5383,\n \"text\": \" Howto – create Zip File\"\n },\n {\n \"code\": null,\n \"e\": 5429,\n \"s\": 5408,\n \"text\": \" Howto – Get OS info\"\n },\n {\n \"code\": null,\n \"e\": 5460,\n \"s\": 5429,\n \"text\": \" Howto – Get size of Directory\"\n },\n {\n \"code\": null,\n \"e\": 5497,\n \"s\": 5460,\n \"text\": \" Howto – Check whether a file exists\"\n },\n {\n \"code\": null,\n \"e\": 5534,\n \"s\": 5497,\n \"text\": \" Howto – Remove key from dictionary\"\n },\n {\n \"code\": null,\n \"e\": 5556,\n \"s\": 5534,\n \"text\": \" Howto – Sort Objects\"\n },\n {\n \"code\": null,\n \"e\": 5594,\n \"s\": 5556,\n \"text\": \" Howto – Create or Delete Directories\"\n },\n {\n \"code\": null,\n \"e\": 5617,\n \"s\": 5594,\n \"text\": \" Howto – Read CSV File\"\n },\n {\n \"code\": null,\n \"e\": 5655,\n \"s\": 5617,\n \"text\": \" Howto – Create Python Iterable class\"\n },\n {\n \"code\": null,\n \"e\": 5686,\n \"s\": 5655,\n \"text\": \" Howto – Access for loop index\"\n },\n {\n \"code\": null,\n \"e\": 5724,\n \"s\": 5686,\n \"text\": \" Howto – Clear all elements from List\"\n },\n {\n \"code\": null,\n \"e\": 5764,\n \"s\": 5724,\n \"text\": \" Howto – Remove empty lists from a List\"\n },\n {\n \"code\": null,\n \"e\": 5811,\n \"s\": 5764,\n \"text\": \" Howto – Remove special characters from String\"\n },\n {\n \"code\": null,\n \"e\": 5843,\n \"s\": 5811,\n \"text\": \" Howto – Sort dictionary by key\"\n }\n]"}}},{"rowIdx":430,"cells":{"title":{"kind":"string","value":"How to write Java program to add two matrices"},"text":{"kind":"string","value":"To add two matrices −\nCreate an empty matrix\nAt each position in the new matrix, assign the sum of the values in the same position from the given two matrices i.e. if A[i][j] and B[i][j] are the two given matrices then, the value of c[i][j] should be A[i][j] + B[i][j]\nLive Demo\npublic class AddingTwoMatrices{\n public static void main(String args[]){\n int a[][]={{1,2,3},{4,5,6},{7,8,9}};\n int b[][]={{1,1,1},{1,1,1},{1,1,1}};\n int c[][]=new int[3][3];\n\n for(int i = 0;i<3;i++){\n for(int j = 0;j<3;j++){\n c[i][j] = a[i][j]+b[i][j];\n System.out.print(c[i][j]+\" \");\n }\n System.out.println();\n }\n }\n}\n2 3 4\n5 6 7\n8 9 10"},"parsed":{"kind":"list like","value":[{"code":null,"e":1084,"s":1062,"text":"To add two matrices −"},{"code":null,"e":1107,"s":1084,"text":"Create an empty matrix"},{"code":null,"e":1331,"s":1107,"text":"At each position in the new matrix, assign the sum of the values in the same position from the given two matrices i.e. if A[i][j] and B[i][j] are the two given matrices then, the value of c[i][j] should be A[i][j] + B[i][j]"},{"code":null,"e":1341,"s":1331,"text":"Live Demo"},{"code":null,"e":1736,"s":1341,"text":"public class AddingTwoMatrices{\n public static void main(String args[]){\n int a[][]={{1,2,3},{4,5,6},{7,8,9}};\n int b[][]={{1,1,1},{1,1,1},{1,1,1}};\n int c[][]=new int[3][3];\n\n for(int i = 0;i<3;i++){\n for(int j = 0;j<3;j++){\n c[i][j] = a[i][j]+b[i][j];\n System.out.print(c[i][j]+\" \");\n }\n System.out.println();\n }\n }\n}"},{"code":null,"e":1755,"s":1736,"text":"2 3 4\n5 6 7\n8 9 10"}],"string":"[\n {\n \"code\": null,\n \"e\": 1084,\n \"s\": 1062,\n \"text\": \"To add two matrices −\"\n },\n {\n \"code\": null,\n \"e\": 1107,\n \"s\": 1084,\n \"text\": \"Create an empty matrix\"\n },\n {\n \"code\": null,\n \"e\": 1331,\n \"s\": 1107,\n \"text\": \"At each position in the new matrix, assign the sum of the values in the same position from the given two matrices i.e. if A[i][j] and B[i][j] are the two given matrices then, the value of c[i][j] should be A[i][j] + B[i][j]\"\n },\n {\n \"code\": null,\n \"e\": 1341,\n \"s\": 1331,\n \"text\": \"Live Demo\"\n },\n {\n \"code\": null,\n \"e\": 1736,\n \"s\": 1341,\n \"text\": \"public class AddingTwoMatrices{\\n public static void main(String args[]){\\n int a[][]={{1,2,3},{4,5,6},{7,8,9}};\\n int b[][]={{1,1,1},{1,1,1},{1,1,1}};\\n int c[][]=new int[3][3];\\n\\n for(int i = 0;i<3;i++){\\n for(int j = 0;j<3;j++){\\n c[i][j] = a[i][j]+b[i][j];\\n System.out.print(c[i][j]+\\\" \\\");\\n }\\n System.out.println();\\n }\\n }\\n}\"\n },\n {\n \"code\": null,\n \"e\": 1755,\n \"s\": 1736,\n \"text\": \"2 3 4\\n5 6 7\\n8 9 10\"\n }\n]"}}},{"rowIdx":431,"cells":{"title":{"kind":"string","value":"How to implement the Fibonacci series using lambda expression in Java?"},"text":{"kind":"string","value":"The Fibonacci is a sequence of numbers in which every number after the first two numbers is the sum of the two preceding numbers like 0, 1, 1, 2, 3, 5, 8, 13, 21 and so on. The sequence of Fibonacci numbers defined by using \"F(n)=F(n-1)+F(n-2)\".\nIn the below example, we can implement the Fibonacci series with the help of Stream API and lambda expression. The Stream.iterate() method returns an infinite sequential ordered stream produced by iterative application of a function to an initial element seed, producing a stream consisting of seed, f(seed), f(f(seed)), etc.\nimport java.util.List;\nimport java.util.stream.*;\n\npublic class FibonacciTest {\n public static void main(String args[]) {\n System.out.println(FibonacciTest.generate(10));\n }\n public static List generate(int series) {\n return Stream.iterate(new int[]{0, 1}, s -> new int[]{s[1], s[0] + s[1]}) // lambda expression\n .limit(series)\n .map(n -> n[0])\n .collect(Collectors.toList());\n }\n}\n[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]"},"parsed":{"kind":"list like","value":[{"code":null,"e":1308,"s":1062,"text":"The Fibonacci is a sequence of numbers in which every number after the first two numbers is the sum of the two preceding numbers like 0, 1, 1, 2, 3, 5, 8, 13, 21 and so on. The sequence of Fibonacci numbers defined by using \"F(n)=F(n-1)+F(n-2)\"."},{"code":null,"e":1634,"s":1308,"text":"In the below example, we can implement the Fibonacci series with the help of Stream API and lambda expression. The Stream.iterate() method returns an infinite sequential ordered stream produced by iterative application of a function to an initial element seed, producing a stream consisting of seed, f(seed), f(f(seed)), etc."},{"code":null,"e":2060,"s":1634,"text":"import java.util.List;\nimport java.util.stream.*;\n\npublic class FibonacciTest {\n public static void main(String args[]) {\n System.out.println(FibonacciTest.generate(10));\n }\n public static List generate(int series) {\n return Stream.iterate(new int[]{0, 1}, s -> new int[]{s[1], s[0] + s[1]}) // lambda expression\n .limit(series)\n .map(n -> n[0])\n .collect(Collectors.toList());\n }\n}"},{"code":null,"e":2094,"s":2060,"text":"[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]"}],"string":"[\n {\n \"code\": null,\n \"e\": 1308,\n \"s\": 1062,\n \"text\": \"The Fibonacci is a sequence of numbers in which every number after the first two numbers is the sum of the two preceding numbers like 0, 1, 1, 2, 3, 5, 8, 13, 21 and so on. The sequence of Fibonacci numbers defined by using \\\"F(n)=F(n-1)+F(n-2)\\\".\"\n },\n {\n \"code\": null,\n \"e\": 1634,\n \"s\": 1308,\n \"text\": \"In the below example, we can implement the Fibonacci series with the help of Stream API and lambda expression. The Stream.iterate() method returns an infinite sequential ordered stream produced by iterative application of a function to an initial element seed, producing a stream consisting of seed, f(seed), f(f(seed)), etc.\"\n },\n {\n \"code\": null,\n \"e\": 2060,\n \"s\": 1634,\n \"text\": \"import java.util.List;\\nimport java.util.stream.*;\\n\\npublic class FibonacciTest {\\n public static void main(String args[]) {\\n System.out.println(FibonacciTest.generate(10));\\n }\\n public static List generate(int series) {\\n return Stream.iterate(new int[]{0, 1}, s -> new int[]{s[1], s[0] + s[1]}) // lambda expression\\n .limit(series)\\n .map(n -> n[0])\\n .collect(Collectors.toList());\\n }\\n}\"\n },\n {\n \"code\": null,\n \"e\": 2094,\n \"s\": 2060,\n \"text\": \"[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\"\n }\n]"}}},{"rowIdx":432,"cells":{"title":{"kind":"string","value":"PyCaret 2.1 is here — What’s new? | by Moez Ali | Towards Data Science"},"text":{"kind":"string","value":"We are excited to announce PyCaret 2.1 — update for the month of Aug 2020.\nPyCaret is an open-source, low-code machine learning library in Python that automates the machine learning workflow. It is an end-to-end machine learning and model management tool that speeds up the machine learning experiment cycle and makes you 10x more productive.\nIn comparison with the other open-source machine learning libraries, PyCaret is an alternate low-code library that can be used to replace hundreds of lines of code with few words only. This makes experiments exponentially fast and efficient.\nIf you haven’t heard or used PyCaret before, please see our previous announcement to get started quickly.\nInstalling PyCaret is very easy and takes only a few minutes. We strongly recommend using a virtual environment to avoid potential conflict with other libraries. See the following example code to create a conda environment and install pycaret within that conda environment:\n# create a conda environment conda create --name yourenvname python=3.6 # activate environment conda activate yourenvname # install pycaret pip install pycaret # create notebook kernel linked with the conda environment python -m ipykernel install --user --name yourenvname --display-name \"display-name\"\nIf you have PyCaret already installed, you can update it using pip:\npip install --upgrade pycaret\nIn PyCaret 2.0 we have announced GPU-enabled training for certain algorithms (XGBoost, LightGBM and Catboost). What’s new in 2.1 is now you can also tune the hyperparameters of those models on GPU.\n# train xgboost using gpuxgboost = create_model('xgboost', tree_method = 'gpu_hist')# tune xgboost tuned_xgboost = tune_model(xgboost)\nNo additional parameter needed inside tune_model function as it automatically inherits the tree_method from xgboost instance created using the create_model function. If you are interested in little comparison, here it is:\n100,000 rows with 88 features in a Multiclass problem with 8 classes\nSince the first release of PyCaret in April 2020, you can deploy trained models on AWS simply by using the deploy_model from your Notebook. In the recent release, we have added functionalities to support deployment on GCP as well as Microsoft Azure.\nTo deploy a model on Microsoft Azure, environment variables for connection string must be set. The connection string can be obtained from the ‘Access Keys’ of your storage account in Azure.\nOnce you have copied the connection string, you can set it as an environment variable. See example below:\nimport osos.environ['AZURE_STORAGE_CONNECTION_STRING'] = 'your-conn-string'from pycaret.classification import deploy_modeldeploy_model(model = model, model_name = 'model-name', platform = 'azure', authentication = {'container' : 'container-name'})\nBOOM! That’s it. Just by using one line of code, your entire machine learning pipeline is now shipped on the container in Microsoft Azure. You can access that using the load_model function.\nimport osos.environ['AZURE_STORAGE_CONNECTION_STRING'] = 'your-conn-string'from pycaret.classification import load_modelloaded_model = load_model(model_name = 'model-name', platform = 'azure', authentication = {'container' : 'container-name'})from pycaret.classification import predict_modelpredictions = predict_model(loaded_model, data = new-dataframe)\nTo deploy a model on Google Cloud Platform (GCP), you must create a project first either using a command line or GCP console. Once the project is created, you must create a service account and download the service account key as a JSON file, which is then used to set the environment variable.\nTo learn more about creating a service account, read the official documentation. Once you have created a service account and downloaded the JSON file from your GCP console you are ready for deployment.\nimport osos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'c:/path-to-json-file.json'from pycaret.classification import deploy_modeldeploy_model(model = model, model_name = 'model-name', platform = 'gcp', authentication = {'project' : 'project-name', 'bucket' : 'bucket-name'})\nModel uploaded. You can now access the model from the GCP bucket using the load_model function.\nimport osos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'c:/path-to-json-file.json'from pycaret.classification import load_modelloaded_model = load_model(model_name = 'model-name', platform = 'gcp', authentication = {'project' : 'project-name', 'bucket' : 'bucket-name'})from pycaret.classification import predict_modelpredictions = predict_model(loaded_model, data = new-dataframe)\nIn addition to using PyCaret’s native deployment functionalities, you can now also use all the MLFlow deployment capabilities. To use those, you must log your experiment using the log_experiment parameter in the setup function.\n# init setupexp1 = setup(data, target = 'target-name', log_experiment = True, experiment_name = 'exp-name')# create xgboost modelxgboost = create_model('xgboost')......# rest of your script# start mlflow server on localhost:5000!mlflow ui\nNow open https://localhost:5000 on your favorite browser.\nYou can see the details of run by clicking the “Start Time” shown on the left of “Run Name”. What you see inside is all the hyperparameters and scoring metrics of a trained model and if you scroll down a little, all the artifacts are shown as well (see below).\nA trained model along with other metadata files are stored under the directory “/model”. MLFlow follows a standard format for packaging machine learning models that can be used in a variety of downstream tools — for example, real-time serving through a REST API or batch inference on Apache Spark. If you want you can serve this model locally you can do that by using MLFlow command line.\nmlflow models serve -m local-path-to-model\nYou can then send the request to model using CURL to get the predictions.\ncurl http://127.0.0.1:5000/invocations -H 'Content-Type: application/json' -d '{ \"columns\": [\"age\", \"sex\", \"bmi\", \"children\", \"smoker\", \"region\"], \"data\": [[19, \"female\", 27.9, 0, \"yes\", \"southwest\"]]}'\n(Note: This functionality of MLFlow is not supported on Windows OS yet).\nMLFlow also provide integration with AWS Sagemaker and Azure Machine Learning Service. You can train models locally in a Docker container with SageMaker compatible environment or remotely on SageMaker. To deploy remotely to SageMaker you need to set up your environment and AWS user account.\nExample workflow using the MLflow CLI\nmlflow sagemaker build-and-push-container mlflow sagemaker run-local -m mlflow sagemaker deploy \nTo learn more about all deployment capabilities of MLFlow, click here.\nThe MLflow Model Registry component is a centralized model store, set of APIs, and UI, to collaboratively manage the full lifecycle of an MLflow Model. It provides model lineage (which MLflow experiment and run produced the model), model versioning, stage transitions (for example from staging to production), and annotations.\nIf running your own MLflow server, you must use a database-backed backend store in order to access the model registry. Click here for more information. However, if you are using Databricks or any of the managed Databricks services such as Azure Databricks, you don’t need to worry about setting up anything. It comes with all the bells and whistles you would ever need.\nThis is not ground-breaking but indeed a very useful addition for people using PyCaret for research and publications. The plot_model now has an additional parameter called “scale” through which you can control the resolution and generate high quality plot for your publications.\n# create linear regression modellr = create_model('lr')# plot in high-quality resolutionplot_model(lr, scale = 5) # default is 1\nThis is one of the most requested feature ever since release of the first version. Allowing to tune hyperparameters of a model using custom / user-defined function gives immense flexibility to data scientists. It is now possible to use user-defined custom loss functions using custom_scorer parameter in the tune_model function.\n# define the loss functiondef my_function(y_true, y_pred):......# create scorer using sklearnfrom sklearn.metrics import make_scorermy_own_scorer = make_scorer(my_function, needs_proba=True)# train catboost modelcatboost = create_model('catboost')# tune catboost using custom scorertuned_catboost = tune_model(catboost, custom_scorer = my_own_scorer)\nFeature selection is a fundamental step in machine learning. You dispose of a bunch of features and you want to select only the relevant ones and to discard the others. The aim is simplifying the problem by removing unuseful features which would introduce unnecessary noise.\nIn PyCaret 2.1 we have introduced implementation of Boruta algorithm in Python (originally implemented in R). Boruta is a pretty smart algorithm dating back to 2010 designed to automatically perform feature selection on a dataset. To use this, you simply have to pass the feature_selection_method within the setup function.\nexp1 = setup(data, target = 'target-var', feature_selection = True, feature_selection_method = 'boruta')\nTo read more about Boruta algorithm, click here.\nblacklist and whitelist parameters in compare_models function is now renamed to exclude and include with no change in functionality.\nTo set the upper limit on training time in compare_models function, new parameter budget_time has been added.\nPyCaret is now compatible with Pandas categorical datatype. Internally they are converted into object and are treated as the same way as object or bool is treated.\nNumeric Imputation New method zero has been added in the numeric_imputation in the setup function. When method is set to zero, missing values are replaced with constant 0.\nTo make the output more human-readable, the Label column returned by predict_model function now returns the original value instead of encoded value.\nTo learn more about all the updates in PyCaret 2.1, please see the release notes.\nThere is no limit to what you can achieve using the lightweight workflow automation library in Python. If you find this useful, please do not forget to give us ⭐️ on our GitHub repo.\nTo hear more about PyCaret follow us on LinkedIn and Youtube.\nUser GuideDocumentationOfficial TutorialsExample NotebooksOther Resources\nClick on the links below to see the documentation and working examples.\nClassificationRegressionClusteringAnomaly DetectionNatural Language ProcessingAssociation Rule Mining"},"parsed":{"kind":"list like","value":[{"code":null,"e":247,"s":172,"text":"We are excited to announce PyCaret 2.1 — update for the month of Aug 2020."},{"code":null,"e":515,"s":247,"text":"PyCaret is an open-source, low-code machine learning library in Python that automates the machine learning workflow. It is an end-to-end machine learning and model management tool that speeds up the machine learning experiment cycle and makes you 10x more productive."},{"code":null,"e":757,"s":515,"text":"In comparison with the other open-source machine learning libraries, PyCaret is an alternate low-code library that can be used to replace hundreds of lines of code with few words only. This makes experiments exponentially fast and efficient."},{"code":null,"e":863,"s":757,"text":"If you haven’t heard or used PyCaret before, please see our previous announcement to get started quickly."},{"code":null,"e":1137,"s":863,"text":"Installing PyCaret is very easy and takes only a few minutes. We strongly recommend using a virtual environment to avoid potential conflict with other libraries. See the following example code to create a conda environment and install pycaret within that conda environment:"},{"code":null,"e":1442,"s":1137,"text":"# create a conda environment conda create --name yourenvname python=3.6 # activate environment conda activate yourenvname # install pycaret pip install pycaret # create notebook kernel linked with the conda environment python -m ipykernel install --user --name yourenvname --display-name \"display-name\""},{"code":null,"e":1510,"s":1442,"text":"If you have PyCaret already installed, you can update it using pip:"},{"code":null,"e":1540,"s":1510,"text":"pip install --upgrade pycaret"},{"code":null,"e":1738,"s":1540,"text":"In PyCaret 2.0 we have announced GPU-enabled training for certain algorithms (XGBoost, LightGBM and Catboost). What’s new in 2.1 is now you can also tune the hyperparameters of those models on GPU."},{"code":null,"e":1873,"s":1738,"text":"# train xgboost using gpuxgboost = create_model('xgboost', tree_method = 'gpu_hist')# tune xgboost tuned_xgboost = tune_model(xgboost)"},{"code":null,"e":2095,"s":1873,"text":"No additional parameter needed inside tune_model function as it automatically inherits the tree_method from xgboost instance created using the create_model function. If you are interested in little comparison, here it is:"},{"code":null,"e":2164,"s":2095,"text":"100,000 rows with 88 features in a Multiclass problem with 8 classes"},{"code":null,"e":2414,"s":2164,"text":"Since the first release of PyCaret in April 2020, you can deploy trained models on AWS simply by using the deploy_model from your Notebook. In the recent release, we have added functionalities to support deployment on GCP as well as Microsoft Azure."},{"code":null,"e":2604,"s":2414,"text":"To deploy a model on Microsoft Azure, environment variables for connection string must be set. The connection string can be obtained from the ‘Access Keys’ of your storage account in Azure."},{"code":null,"e":2710,"s":2604,"text":"Once you have copied the connection string, you can set it as an environment variable. See example below:"},{"code":null,"e":2958,"s":2710,"text":"import osos.environ['AZURE_STORAGE_CONNECTION_STRING'] = 'your-conn-string'from pycaret.classification import deploy_modeldeploy_model(model = model, model_name = 'model-name', platform = 'azure', authentication = {'container' : 'container-name'})"},{"code":null,"e":3148,"s":2958,"text":"BOOM! That’s it. Just by using one line of code, your entire machine learning pipeline is now shipped on the container in Microsoft Azure. You can access that using the load_model function."},{"code":null,"e":3503,"s":3148,"text":"import osos.environ['AZURE_STORAGE_CONNECTION_STRING'] = 'your-conn-string'from pycaret.classification import load_modelloaded_model = load_model(model_name = 'model-name', platform = 'azure', authentication = {'container' : 'container-name'})from pycaret.classification import predict_modelpredictions = predict_model(loaded_model, data = new-dataframe)"},{"code":null,"e":3797,"s":3503,"text":"To deploy a model on Google Cloud Platform (GCP), you must create a project first either using a command line or GCP console. Once the project is created, you must create a service account and download the service account key as a JSON file, which is then used to set the environment variable."},{"code":null,"e":3999,"s":3797,"text":"To learn more about creating a service account, read the official documentation. Once you have created a service account and downloaded the JSON file from your GCP console you are ready for deployment."},{"code":null,"e":4275,"s":3999,"text":"import osos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'c:/path-to-json-file.json'from pycaret.classification import deploy_modeldeploy_model(model = model, model_name = 'model-name', platform = 'gcp', authentication = {'project' : 'project-name', 'bucket' : 'bucket-name'})"},{"code":null,"e":4371,"s":4275,"text":"Model uploaded. You can now access the model from the GCP bucket using the load_model function."},{"code":null,"e":4754,"s":4371,"text":"import osos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'c:/path-to-json-file.json'from pycaret.classification import load_modelloaded_model = load_model(model_name = 'model-name', platform = 'gcp', authentication = {'project' : 'project-name', 'bucket' : 'bucket-name'})from pycaret.classification import predict_modelpredictions = predict_model(loaded_model, data = new-dataframe)"},{"code":null,"e":4982,"s":4754,"text":"In addition to using PyCaret’s native deployment functionalities, you can now also use all the MLFlow deployment capabilities. To use those, you must log your experiment using the log_experiment parameter in the setup function."},{"code":null,"e":5221,"s":4982,"text":"# init setupexp1 = setup(data, target = 'target-name', log_experiment = True, experiment_name = 'exp-name')# create xgboost modelxgboost = create_model('xgboost')......# rest of your script# start mlflow server on localhost:5000!mlflow ui"},{"code":null,"e":5279,"s":5221,"text":"Now open https://localhost:5000 on your favorite browser."},{"code":null,"e":5540,"s":5279,"text":"You can see the details of run by clicking the “Start Time” shown on the left of “Run Name”. What you see inside is all the hyperparameters and scoring metrics of a trained model and if you scroll down a little, all the artifacts are shown as well (see below)."},{"code":null,"e":5929,"s":5540,"text":"A trained model along with other metadata files are stored under the directory “/model”. MLFlow follows a standard format for packaging machine learning models that can be used in a variety of downstream tools — for example, real-time serving through a REST API or batch inference on Apache Spark. If you want you can serve this model locally you can do that by using MLFlow command line."},{"code":null,"e":5972,"s":5929,"text":"mlflow models serve -m local-path-to-model"},{"code":null,"e":6046,"s":5972,"text":"You can then send the request to model using CURL to get the predictions."},{"code":null,"e":6255,"s":6046,"text":"curl http://127.0.0.1:5000/invocations -H 'Content-Type: application/json' -d '{ \"columns\": [\"age\", \"sex\", \"bmi\", \"children\", \"smoker\", \"region\"], \"data\": [[19, \"female\", 27.9, 0, \"yes\", \"southwest\"]]}'"},{"code":null,"e":6328,"s":6255,"text":"(Note: This functionality of MLFlow is not supported on Windows OS yet)."},{"code":null,"e":6620,"s":6328,"text":"MLFlow also provide integration with AWS Sagemaker and Azure Machine Learning Service. You can train models locally in a Docker container with SageMaker compatible environment or remotely on SageMaker. To deploy remotely to SageMaker you need to set up your environment and AWS user account."},{"code":null,"e":6658,"s":6620,"text":"Example workflow using the MLflow CLI"},{"code":null,"e":6782,"s":6658,"text":"mlflow sagemaker build-and-push-container mlflow sagemaker run-local -m mlflow sagemaker deploy "},{"code":null,"e":6853,"s":6782,"text":"To learn more about all deployment capabilities of MLFlow, click here."},{"code":null,"e":7180,"s":6853,"text":"The MLflow Model Registry component is a centralized model store, set of APIs, and UI, to collaboratively manage the full lifecycle of an MLflow Model. It provides model lineage (which MLflow experiment and run produced the model), model versioning, stage transitions (for example from staging to production), and annotations."},{"code":null,"e":7550,"s":7180,"text":"If running your own MLflow server, you must use a database-backed backend store in order to access the model registry. Click here for more information. However, if you are using Databricks or any of the managed Databricks services such as Azure Databricks, you don’t need to worry about setting up anything. It comes with all the bells and whistles you would ever need."},{"code":null,"e":7829,"s":7550,"text":"This is not ground-breaking but indeed a very useful addition for people using PyCaret for research and publications. The plot_model now has an additional parameter called “scale” through which you can control the resolution and generate high quality plot for your publications."},{"code":null,"e":7958,"s":7829,"text":"# create linear regression modellr = create_model('lr')# plot in high-quality resolutionplot_model(lr, scale = 5) # default is 1"},{"code":null,"e":8287,"s":7958,"text":"This is one of the most requested feature ever since release of the first version. Allowing to tune hyperparameters of a model using custom / user-defined function gives immense flexibility to data scientists. It is now possible to use user-defined custom loss functions using custom_scorer parameter in the tune_model function."},{"code":null,"e":8638,"s":8287,"text":"# define the loss functiondef my_function(y_true, y_pred):......# create scorer using sklearnfrom sklearn.metrics import make_scorermy_own_scorer = make_scorer(my_function, needs_proba=True)# train catboost modelcatboost = create_model('catboost')# tune catboost using custom scorertuned_catboost = tune_model(catboost, custom_scorer = my_own_scorer)"},{"code":null,"e":8913,"s":8638,"text":"Feature selection is a fundamental step in machine learning. You dispose of a bunch of features and you want to select only the relevant ones and to discard the others. The aim is simplifying the problem by removing unuseful features which would introduce unnecessary noise."},{"code":null,"e":9237,"s":8913,"text":"In PyCaret 2.1 we have introduced implementation of Boruta algorithm in Python (originally implemented in R). Boruta is a pretty smart algorithm dating back to 2010 designed to automatically perform feature selection on a dataset. To use this, you simply have to pass the feature_selection_method within the setup function."},{"code":null,"e":9342,"s":9237,"text":"exp1 = setup(data, target = 'target-var', feature_selection = True, feature_selection_method = 'boruta')"},{"code":null,"e":9391,"s":9342,"text":"To read more about Boruta algorithm, click here."},{"code":null,"e":9524,"s":9391,"text":"blacklist and whitelist parameters in compare_models function is now renamed to exclude and include with no change in functionality."},{"code":null,"e":9634,"s":9524,"text":"To set the upper limit on training time in compare_models function, new parameter budget_time has been added."},{"code":null,"e":9798,"s":9634,"text":"PyCaret is now compatible with Pandas categorical datatype. Internally they are converted into object and are treated as the same way as object or bool is treated."},{"code":null,"e":9970,"s":9798,"text":"Numeric Imputation New method zero has been added in the numeric_imputation in the setup function. When method is set to zero, missing values are replaced with constant 0."},{"code":null,"e":10119,"s":9970,"text":"To make the output more human-readable, the Label column returned by predict_model function now returns the original value instead of encoded value."},{"code":null,"e":10201,"s":10119,"text":"To learn more about all the updates in PyCaret 2.1, please see the release notes."},{"code":null,"e":10384,"s":10201,"text":"There is no limit to what you can achieve using the lightweight workflow automation library in Python. If you find this useful, please do not forget to give us ⭐️ on our GitHub repo."},{"code":null,"e":10446,"s":10384,"text":"To hear more about PyCaret follow us on LinkedIn and Youtube."},{"code":null,"e":10520,"s":10446,"text":"User GuideDocumentationOfficial TutorialsExample NotebooksOther Resources"},{"code":null,"e":10592,"s":10520,"text":"Click on the links below to see the documentation and working examples."}],"string":"[\n {\n \"code\": null,\n \"e\": 247,\n \"s\": 172,\n \"text\": \"We are excited to announce PyCaret 2.1 — update for the month of Aug 2020.\"\n },\n {\n \"code\": null,\n \"e\": 515,\n \"s\": 247,\n \"text\": \"PyCaret is an open-source, low-code machine learning library in Python that automates the machine learning workflow. It is an end-to-end machine learning and model management tool that speeds up the machine learning experiment cycle and makes you 10x more productive.\"\n },\n {\n \"code\": null,\n \"e\": 757,\n \"s\": 515,\n \"text\": \"In comparison with the other open-source machine learning libraries, PyCaret is an alternate low-code library that can be used to replace hundreds of lines of code with few words only. This makes experiments exponentially fast and efficient.\"\n },\n {\n \"code\": null,\n \"e\": 863,\n \"s\": 757,\n \"text\": \"If you haven’t heard or used PyCaret before, please see our previous announcement to get started quickly.\"\n },\n {\n \"code\": null,\n \"e\": 1137,\n \"s\": 863,\n \"text\": \"Installing PyCaret is very easy and takes only a few minutes. We strongly recommend using a virtual environment to avoid potential conflict with other libraries. See the following example code to create a conda environment and install pycaret within that conda environment:\"\n },\n {\n \"code\": null,\n \"e\": 1442,\n \"s\": 1137,\n \"text\": \"# create a conda environment conda create --name yourenvname python=3.6 # activate environment conda activate yourenvname # install pycaret pip install pycaret # create notebook kernel linked with the conda environment python -m ipykernel install --user --name yourenvname --display-name \\\"display-name\\\"\"\n },\n {\n \"code\": null,\n \"e\": 1510,\n \"s\": 1442,\n \"text\": \"If you have PyCaret already installed, you can update it using pip:\"\n },\n {\n \"code\": null,\n \"e\": 1540,\n \"s\": 1510,\n \"text\": \"pip install --upgrade pycaret\"\n },\n {\n \"code\": null,\n \"e\": 1738,\n \"s\": 1540,\n \"text\": \"In PyCaret 2.0 we have announced GPU-enabled training for certain algorithms (XGBoost, LightGBM and Catboost). What’s new in 2.1 is now you can also tune the hyperparameters of those models on GPU.\"\n },\n {\n \"code\": null,\n \"e\": 1873,\n \"s\": 1738,\n \"text\": \"# train xgboost using gpuxgboost = create_model('xgboost', tree_method = 'gpu_hist')# tune xgboost tuned_xgboost = tune_model(xgboost)\"\n },\n {\n \"code\": null,\n \"e\": 2095,\n \"s\": 1873,\n \"text\": \"No additional parameter needed inside tune_model function as it automatically inherits the tree_method from xgboost instance created using the create_model function. If you are interested in little comparison, here it is:\"\n },\n {\n \"code\": null,\n \"e\": 2164,\n \"s\": 2095,\n \"text\": \"100,000 rows with 88 features in a Multiclass problem with 8 classes\"\n },\n {\n \"code\": null,\n \"e\": 2414,\n \"s\": 2164,\n \"text\": \"Since the first release of PyCaret in April 2020, you can deploy trained models on AWS simply by using the deploy_model from your Notebook. In the recent release, we have added functionalities to support deployment on GCP as well as Microsoft Azure.\"\n },\n {\n \"code\": null,\n \"e\": 2604,\n \"s\": 2414,\n \"text\": \"To deploy a model on Microsoft Azure, environment variables for connection string must be set. The connection string can be obtained from the ‘Access Keys’ of your storage account in Azure.\"\n },\n {\n \"code\": null,\n \"e\": 2710,\n \"s\": 2604,\n \"text\": \"Once you have copied the connection string, you can set it as an environment variable. See example below:\"\n },\n {\n \"code\": null,\n \"e\": 2958,\n \"s\": 2710,\n \"text\": \"import osos.environ['AZURE_STORAGE_CONNECTION_STRING'] = 'your-conn-string'from pycaret.classification import deploy_modeldeploy_model(model = model, model_name = 'model-name', platform = 'azure', authentication = {'container' : 'container-name'})\"\n },\n {\n \"code\": null,\n \"e\": 3148,\n \"s\": 2958,\n \"text\": \"BOOM! That’s it. Just by using one line of code, your entire machine learning pipeline is now shipped on the container in Microsoft Azure. You can access that using the load_model function.\"\n },\n {\n \"code\": null,\n \"e\": 3503,\n \"s\": 3148,\n \"text\": \"import osos.environ['AZURE_STORAGE_CONNECTION_STRING'] = 'your-conn-string'from pycaret.classification import load_modelloaded_model = load_model(model_name = 'model-name', platform = 'azure', authentication = {'container' : 'container-name'})from pycaret.classification import predict_modelpredictions = predict_model(loaded_model, data = new-dataframe)\"\n },\n {\n \"code\": null,\n \"e\": 3797,\n \"s\": 3503,\n \"text\": \"To deploy a model on Google Cloud Platform (GCP), you must create a project first either using a command line or GCP console. Once the project is created, you must create a service account and download the service account key as a JSON file, which is then used to set the environment variable.\"\n },\n {\n \"code\": null,\n \"e\": 3999,\n \"s\": 3797,\n \"text\": \"To learn more about creating a service account, read the official documentation. Once you have created a service account and downloaded the JSON file from your GCP console you are ready for deployment.\"\n },\n {\n \"code\": null,\n \"e\": 4275,\n \"s\": 3999,\n \"text\": \"import osos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'c:/path-to-json-file.json'from pycaret.classification import deploy_modeldeploy_model(model = model, model_name = 'model-name', platform = 'gcp', authentication = {'project' : 'project-name', 'bucket' : 'bucket-name'})\"\n },\n {\n \"code\": null,\n \"e\": 4371,\n \"s\": 4275,\n \"text\": \"Model uploaded. You can now access the model from the GCP bucket using the load_model function.\"\n },\n {\n \"code\": null,\n \"e\": 4754,\n \"s\": 4371,\n \"text\": \"import osos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'c:/path-to-json-file.json'from pycaret.classification import load_modelloaded_model = load_model(model_name = 'model-name', platform = 'gcp', authentication = {'project' : 'project-name', 'bucket' : 'bucket-name'})from pycaret.classification import predict_modelpredictions = predict_model(loaded_model, data = new-dataframe)\"\n },\n {\n \"code\": null,\n \"e\": 4982,\n \"s\": 4754,\n \"text\": \"In addition to using PyCaret’s native deployment functionalities, you can now also use all the MLFlow deployment capabilities. To use those, you must log your experiment using the log_experiment parameter in the setup function.\"\n },\n {\n \"code\": null,\n \"e\": 5221,\n \"s\": 4982,\n \"text\": \"# init setupexp1 = setup(data, target = 'target-name', log_experiment = True, experiment_name = 'exp-name')# create xgboost modelxgboost = create_model('xgboost')......# rest of your script# start mlflow server on localhost:5000!mlflow ui\"\n },\n {\n \"code\": null,\n \"e\": 5279,\n \"s\": 5221,\n \"text\": \"Now open https://localhost:5000 on your favorite browser.\"\n },\n {\n \"code\": null,\n \"e\": 5540,\n \"s\": 5279,\n \"text\": \"You can see the details of run by clicking the “Start Time” shown on the left of “Run Name”. What you see inside is all the hyperparameters and scoring metrics of a trained model and if you scroll down a little, all the artifacts are shown as well (see below).\"\n },\n {\n \"code\": null,\n \"e\": 5929,\n \"s\": 5540,\n \"text\": \"A trained model along with other metadata files are stored under the directory “/model”. MLFlow follows a standard format for packaging machine learning models that can be used in a variety of downstream tools — for example, real-time serving through a REST API or batch inference on Apache Spark. If you want you can serve this model locally you can do that by using MLFlow command line.\"\n },\n {\n \"code\": null,\n \"e\": 5972,\n \"s\": 5929,\n \"text\": \"mlflow models serve -m local-path-to-model\"\n },\n {\n \"code\": null,\n \"e\": 6046,\n \"s\": 5972,\n \"text\": \"You can then send the request to model using CURL to get the predictions.\"\n },\n {\n \"code\": null,\n \"e\": 6255,\n \"s\": 6046,\n \"text\": \"curl http://127.0.0.1:5000/invocations -H 'Content-Type: application/json' -d '{ \\\"columns\\\": [\\\"age\\\", \\\"sex\\\", \\\"bmi\\\", \\\"children\\\", \\\"smoker\\\", \\\"region\\\"], \\\"data\\\": [[19, \\\"female\\\", 27.9, 0, \\\"yes\\\", \\\"southwest\\\"]]}'\"\n },\n {\n \"code\": null,\n \"e\": 6328,\n \"s\": 6255,\n \"text\": \"(Note: This functionality of MLFlow is not supported on Windows OS yet).\"\n },\n {\n \"code\": null,\n \"e\": 6620,\n \"s\": 6328,\n \"text\": \"MLFlow also provide integration with AWS Sagemaker and Azure Machine Learning Service. You can train models locally in a Docker container with SageMaker compatible environment or remotely on SageMaker. To deploy remotely to SageMaker you need to set up your environment and AWS user account.\"\n },\n {\n \"code\": null,\n \"e\": 6658,\n \"s\": 6620,\n \"text\": \"Example workflow using the MLflow CLI\"\n },\n {\n \"code\": null,\n \"e\": 6782,\n \"s\": 6658,\n \"text\": \"mlflow sagemaker build-and-push-container mlflow sagemaker run-local -m mlflow sagemaker deploy \"\n },\n {\n \"code\": null,\n \"e\": 6853,\n \"s\": 6782,\n \"text\": \"To learn more about all deployment capabilities of MLFlow, click here.\"\n },\n {\n \"code\": null,\n \"e\": 7180,\n \"s\": 6853,\n \"text\": \"The MLflow Model Registry component is a centralized model store, set of APIs, and UI, to collaboratively manage the full lifecycle of an MLflow Model. It provides model lineage (which MLflow experiment and run produced the model), model versioning, stage transitions (for example from staging to production), and annotations.\"\n },\n {\n \"code\": null,\n \"e\": 7550,\n \"s\": 7180,\n \"text\": \"If running your own MLflow server, you must use a database-backed backend store in order to access the model registry. Click here for more information. However, if you are using Databricks or any of the managed Databricks services such as Azure Databricks, you don’t need to worry about setting up anything. It comes with all the bells and whistles you would ever need.\"\n },\n {\n \"code\": null,\n \"e\": 7829,\n \"s\": 7550,\n \"text\": \"This is not ground-breaking but indeed a very useful addition for people using PyCaret for research and publications. The plot_model now has an additional parameter called “scale” through which you can control the resolution and generate high quality plot for your publications.\"\n },\n {\n \"code\": null,\n \"e\": 7958,\n \"s\": 7829,\n \"text\": \"# create linear regression modellr = create_model('lr')# plot in high-quality resolutionplot_model(lr, scale = 5) # default is 1\"\n },\n {\n \"code\": null,\n \"e\": 8287,\n \"s\": 7958,\n \"text\": \"This is one of the most requested feature ever since release of the first version. Allowing to tune hyperparameters of a model using custom / user-defined function gives immense flexibility to data scientists. It is now possible to use user-defined custom loss functions using custom_scorer parameter in the tune_model function.\"\n },\n {\n \"code\": null,\n \"e\": 8638,\n \"s\": 8287,\n \"text\": \"# define the loss functiondef my_function(y_true, y_pred):......# create scorer using sklearnfrom sklearn.metrics import make_scorermy_own_scorer = make_scorer(my_function, needs_proba=True)# train catboost modelcatboost = create_model('catboost')# tune catboost using custom scorertuned_catboost = tune_model(catboost, custom_scorer = my_own_scorer)\"\n },\n {\n \"code\": null,\n \"e\": 8913,\n \"s\": 8638,\n \"text\": \"Feature selection is a fundamental step in machine learning. You dispose of a bunch of features and you want to select only the relevant ones and to discard the others. The aim is simplifying the problem by removing unuseful features which would introduce unnecessary noise.\"\n },\n {\n \"code\": null,\n \"e\": 9237,\n \"s\": 8913,\n \"text\": \"In PyCaret 2.1 we have introduced implementation of Boruta algorithm in Python (originally implemented in R). Boruta is a pretty smart algorithm dating back to 2010 designed to automatically perform feature selection on a dataset. To use this, you simply have to pass the feature_selection_method within the setup function.\"\n },\n {\n \"code\": null,\n \"e\": 9342,\n \"s\": 9237,\n \"text\": \"exp1 = setup(data, target = 'target-var', feature_selection = True, feature_selection_method = 'boruta')\"\n },\n {\n \"code\": null,\n \"e\": 9391,\n \"s\": 9342,\n \"text\": \"To read more about Boruta algorithm, click here.\"\n },\n {\n \"code\": null,\n \"e\": 9524,\n \"s\": 9391,\n \"text\": \"blacklist and whitelist parameters in compare_models function is now renamed to exclude and include with no change in functionality.\"\n },\n {\n \"code\": null,\n \"e\": 9634,\n \"s\": 9524,\n \"text\": \"To set the upper limit on training time in compare_models function, new parameter budget_time has been added.\"\n },\n {\n \"code\": null,\n \"e\": 9798,\n \"s\": 9634,\n \"text\": \"PyCaret is now compatible with Pandas categorical datatype. Internally they are converted into object and are treated as the same way as object or bool is treated.\"\n },\n {\n \"code\": null,\n \"e\": 9970,\n \"s\": 9798,\n \"text\": \"Numeric Imputation New method zero has been added in the numeric_imputation in the setup function. When method is set to zero, missing values are replaced with constant 0.\"\n },\n {\n \"code\": null,\n \"e\": 10119,\n \"s\": 9970,\n \"text\": \"To make the output more human-readable, the Label column returned by predict_model function now returns the original value instead of encoded value.\"\n },\n {\n \"code\": null,\n \"e\": 10201,\n \"s\": 10119,\n \"text\": \"To learn more about all the updates in PyCaret 2.1, please see the release notes.\"\n },\n {\n \"code\": null,\n \"e\": 10384,\n \"s\": 10201,\n \"text\": \"There is no limit to what you can achieve using the lightweight workflow automation library in Python. If you find this useful, please do not forget to give us ⭐️ on our GitHub repo.\"\n },\n {\n \"code\": null,\n \"e\": 10446,\n \"s\": 10384,\n \"text\": \"To hear more about PyCaret follow us on LinkedIn and Youtube.\"\n },\n {\n \"code\": null,\n \"e\": 10520,\n \"s\": 10446,\n \"text\": \"User GuideDocumentationOfficial TutorialsExample NotebooksOther Resources\"\n },\n {\n \"code\": null,\n \"e\": 10592,\n \"s\": 10520,\n \"text\": \"Click on the links below to see the documentation and working examples.\"\n }\n]"}}},{"rowIdx":433,"cells":{"title":{"kind":"string","value":"Enhancements for Switch Statement in Java 13 - GeeksforGeeks"},"text":{"kind":"string","value":"24 Oct, 2020\nJava 12 improved the traditional switch statement and made it more useful. Java 13 further introduced new features. Before going into the details of new features, let’s have a look at the drawbacks faced by the traditional Switch statement.\n1. Default fall through due to missing break\nThe default fall-through behavior is error-prone. Let’s understand it with an example.\nswitch (itemCode) {\n case 001 : \n System.out.println(\"It's a laptop!\");\n break;\n case 002 :\n System.out.println(\"It's a desktop!\");\n break;\n case 003 :\n System.out.println(\"It's a mobile phone!\");\n break;\n default :\n System.out.println(\"Unknown device!\");\n}\n\nThe above code works by matching the corresponding case and executing the particular code block. As long as you provide the necessary break statements, it works fine.\nBut what happens if we forget any of the required break statements:\n switch (itemCode) {\n case 001 : \n System.out.println(\"It's a laptop!\");\n // missed out break here \n case 002 :\n System.out.println(\"It's a desktop!\");\n break;\n}\n\n\nHere, if we pass 001, the first case matches, and the code block executes. But due to missing break, execution falls through and continues for case 002. We get the following wrong output:\nIt's a laptop!\nIt's a desktop!\n\nClearly, this is not the intended output. It is a result of accidentally missing-out break statements.\n2. Multiple values per case not supported\nThere may be situations where similar processing is required for multiple case values. But the traditional switch makes to follow the fall through behaviour.\ncase 001:\ncase 002:\ncase 003:\nSystem.out.println(\"It's an electronic gadget!\");\n\nMuch improved switch accepts multiple values per case.\ncase 001, 002, 003 : \n System.out.println(\"It's an electronic gadget!\");\n\n\nEnhancements to switch statements were introduced by Java 12 and then further modified by Java 13.\nLet’s dive into the important features of this improved version of the Switch statement.\n1. Supports multiple values per case\nWith multiple values being specified per case, it simplifies the code structure and eliminates the need for using fall through.\nThe values need to be separated by commas and break should follow the case block.\nswitch (itemCode) {\n case 001, 002, 003 : \n System.out.println(\"It's an electronic gadget!\");\n break;\n \n case 004, 005:\n System.out.println(\"It's a mechanical device!\");\n break;\n}\n\n2. yield is used to return a value\nA new keyword yield has been introduced. It returns values from a switch branch only. \nWe don’t need a break after yield as it automatically terminates the switch expression.\nint val = switch (code) {\n case \"x\", \"y\" :\n yield 1;\n case \"z\", \"w\" :\n yield 2;\n}\n\n3. Switch can be used as an expression\nThe switch can now be used as an expression. This means the switch can now return values based on our input. There is a slight change in switch syntax to accommodate this change. A switch block needs to be delimited by a semicolon. The yield keyword is used to return values. No break required with the yield statement.\nLet’s have a look at a code snippet to understand these changes better.\nString text = switch (itemCode) {\n case 001 : \n yield \"It's a laptop!\";\n case 002 :\n yield \"It's a desktop!\"; \n case 003 :\n yield \"It's a mobile phone!\";\n default :\n throw new IllegalArgumentException(itemCode + \"is an unknown device!\");\n}\n\n4. Necessary to return value/exception\nThe switch expression is required to specify the handling of all the possible input values. Either we provide all the possible cases or specify the default one. This means, irrespective of the input value, switch expression should always return some value or explicitly throw an exception.\nFor instance, if the above code block is changed to –\nString text = switch (itemCode) {\n case 001 : \n yield \"It's a laptop!\";\n case 002 :\n yield \"It's a desktop!\"; \n case 003 :\n yield \"It's a mobile phone!\";\n // default :\n // throw new IllegalArgumentException(itemCode + \"is an unknown device!\");\n}\n\nThis will result in an error saying that all possible values have not been covered by the switch expression.\n5. Switch with arrows \nThe new arrow ⇾ syntax has been introduced for the switch. It can be used with the switch as an expression as well as a statement. \nThe statements on the right side of an ⇾ are executed if an exact case matches on the left side.\nOn the right side of ⇾ we can have any of the following –\nStatement / expression\nthrow statement\n{} block\nThe main advantage of this syntax is that we don’t need a break statement to avoid the default fall-through. So the rule is, if we need fall-through, use case: else if not use case ⇾. Also note, for all case branches it should be either case: or case ⇾. It cannot be different or different cases in a switch else it results in an error.\nswitch (itemCode) {\n case 001 -> System.out.println(\"It's a laptop!\");\n case 002 -> System.out.println(\"It's a desktop!\");\n case 003,004 -> System.out.println(\"It's a mobile phone!\");\n}\n\nAs we can see in the above code, the syntax can also be used for multiple values per case. \n6. Scope\nThe variables declared in the traditional switch exists until the end of the switch statement. If we want the variables to have a case level scope, we can use {} introduced by the enhanced switch in Java 13.\nswitch (errorCode) {\n case 101: {\n // This variable exists just in this {} block\n int num = 200;\n break;\n }\n case 300: {\n // This is ok, {} block has a separate scope\n int num = 300;\n break;\n }\n}\n\n7. Preview feature \nAfter diving into the features related to the enhanced switch, the point noteworthy is — the enhanced switch functionality is available only as a preview feature in Java 13. This means it is not enabled by default. To use it, we need to explicitly enable it.\nAt compile time, add the following params to javac:\njavac -- release 13 --enable-preview MyClass.java\n\nAt run time, add the following:\njava --enable-preview MyClass\n\nThe enhanced switch in Java 13 provides a number of impressive features to the traditional switch. However, it is still in the experiment phase and not yet meant for use in production.\nJava-Control-Flow\nJava\nJava-Control-Flow\nJava\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nStream In Java\nConstructors in Java\nExceptions in Java\nFunctional Interfaces in Java\nDifferent ways of Reading a text file in Java\nGenerics in Java\nIntroduction to Java\nComparator Interface in Java with Examples\nPriorityQueue in Java\nInternal Working of HashMap in Java"},"parsed":{"kind":"list like","value":[{"code":null,"e":25262,"s":25234,"text":"\n24 Oct, 2020"},{"code":null,"e":25503,"s":25262,"text":"Java 12 improved the traditional switch statement and made it more useful. Java 13 further introduced new features. Before going into the details of new features, let’s have a look at the drawbacks faced by the traditional Switch statement."},{"code":null,"e":25548,"s":25503,"text":"1. Default fall through due to missing break"},{"code":null,"e":25635,"s":25548,"text":"The default fall-through behavior is error-prone. Let’s understand it with an example."},{"code":null,"e":25955,"s":25635,"text":"switch (itemCode) {\n case 001 : \n System.out.println(\"It's a laptop!\");\n break;\n case 002 :\n System.out.println(\"It's a desktop!\");\n break;\n case 003 :\n System.out.println(\"It's a mobile phone!\");\n break;\n default :\n System.out.println(\"Unknown device!\");\n}\n"},{"code":null,"e":26122,"s":25955,"text":"The above code works by matching the corresponding case and executing the particular code block. As long as you provide the necessary break statements, it works fine."},{"code":null,"e":26190,"s":26122,"text":"But what happens if we forget any of the required break statements:"},{"code":null,"e":26388,"s":26190,"text":" switch (itemCode) {\n case 001 : \n System.out.println(\"It's a laptop!\");\n // missed out break here \n case 002 :\n System.out.println(\"It's a desktop!\");\n break;\n}\n\n"},{"code":null,"e":26576,"s":26388,"text":"Here, if we pass 001, the first case matches, and the code block executes. But due to missing break, execution falls through and continues for case 002. We get the following wrong output:"},{"code":null,"e":26608,"s":26576,"text":"It's a laptop!\nIt's a desktop!\n"},{"code":null,"e":26711,"s":26608,"text":"Clearly, this is not the intended output. It is a result of accidentally missing-out break statements."},{"code":null,"e":26753,"s":26711,"text":"2. Multiple values per case not supported"},{"code":null,"e":26911,"s":26753,"text":"There may be situations where similar processing is required for multiple case values. But the traditional switch makes to follow the fall through behaviour."},{"code":null,"e":26992,"s":26911,"text":"case 001:\ncase 002:\ncase 003:\nSystem.out.println(\"It's an electronic gadget!\");\n"},{"code":null,"e":27047,"s":26992,"text":"Much improved switch accepts multiple values per case."},{"code":null,"e":27129,"s":27047,"text":"case 001, 002, 003 : \n System.out.println(\"It's an electronic gadget!\");\n\n"},{"code":null,"e":27228,"s":27129,"text":"Enhancements to switch statements were introduced by Java 12 and then further modified by Java 13."},{"code":null,"e":27317,"s":27228,"text":"Let’s dive into the important features of this improved version of the Switch statement."},{"code":null,"e":27354,"s":27317,"text":"1. Supports multiple values per case"},{"code":null,"e":27482,"s":27354,"text":"With multiple values being specified per case, it simplifies the code structure and eliminates the need for using fall through."},{"code":null,"e":27564,"s":27482,"text":"The values need to be separated by commas and break should follow the case block."},{"code":null,"e":27786,"s":27564,"text":"switch (itemCode) {\n case 001, 002, 003 : \n System.out.println(\"It's an electronic gadget!\");\n break;\n \n case 004, 005:\n System.out.println(\"It's a mechanical device!\");\n break;\n}\n"},{"code":null,"e":27821,"s":27786,"text":"2. yield is used to return a value"},{"code":null,"e":27908,"s":27821,"text":"A new keyword yield has been introduced. It returns values from a switch branch only. "},{"code":null,"e":27996,"s":27908,"text":"We don’t need a break after yield as it automatically terminates the switch expression."},{"code":null,"e":28099,"s":27996,"text":"int val = switch (code) {\n case \"x\", \"y\" :\n yield 1;\n case \"z\", \"w\" :\n yield 2;\n}\n"},{"code":null,"e":28138,"s":28099,"text":"3. Switch can be used as an expression"},{"code":null,"e":28458,"s":28138,"text":"The switch can now be used as an expression. This means the switch can now return values based on our input. There is a slight change in switch syntax to accommodate this change. A switch block needs to be delimited by a semicolon. The yield keyword is used to return values. No break required with the yield statement."},{"code":null,"e":28530,"s":28458,"text":"Let’s have a look at a code snippet to understand these changes better."},{"code":null,"e":28818,"s":28530,"text":"String text = switch (itemCode) {\n case 001 : \n yield \"It's a laptop!\";\n case 002 :\n yield \"It's a desktop!\"; \n case 003 :\n yield \"It's a mobile phone!\";\n default :\n throw new IllegalArgumentException(itemCode + \"is an unknown device!\");\n}\n"},{"code":null,"e":28857,"s":28818,"text":"4. Necessary to return value/exception"},{"code":null,"e":29147,"s":28857,"text":"The switch expression is required to specify the handling of all the possible input values. Either we provide all the possible cases or specify the default one. This means, irrespective of the input value, switch expression should always return some value or explicitly throw an exception."},{"code":null,"e":29201,"s":29147,"text":"For instance, if the above code block is changed to –"},{"code":null,"e":29494,"s":29201,"text":"String text = switch (itemCode) {\n case 001 : \n yield \"It's a laptop!\";\n case 002 :\n yield \"It's a desktop!\"; \n case 003 :\n yield \"It's a mobile phone!\";\n // default :\n // throw new IllegalArgumentException(itemCode + \"is an unknown device!\");\n}\n"},{"code":null,"e":29603,"s":29494,"text":"This will result in an error saying that all possible values have not been covered by the switch expression."},{"code":null,"e":29626,"s":29603,"text":"5. Switch with arrows "},{"code":null,"e":29758,"s":29626,"text":"The new arrow ⇾ syntax has been introduced for the switch. It can be used with the switch as an expression as well as a statement. "},{"code":null,"e":29855,"s":29758,"text":"The statements on the right side of an ⇾ are executed if an exact case matches on the left side."},{"code":null,"e":29913,"s":29855,"text":"On the right side of ⇾ we can have any of the following –"},{"code":null,"e":29936,"s":29913,"text":"Statement / expression"},{"code":null,"e":29952,"s":29936,"text":"throw statement"},{"code":null,"e":29961,"s":29952,"text":"{} block"},{"code":null,"e":30298,"s":29961,"text":"The main advantage of this syntax is that we don’t need a break statement to avoid the default fall-through. So the rule is, if we need fall-through, use case: else if not use case ⇾. Also note, for all case branches it should be either case: or case ⇾. It cannot be different or different cases in a switch else it results in an error."},{"code":null,"e":30494,"s":30298,"text":"switch (itemCode) {\n case 001 -> System.out.println(\"It's a laptop!\");\n case 002 -> System.out.println(\"It's a desktop!\");\n case 003,004 -> System.out.println(\"It's a mobile phone!\");\n}\n"},{"code":null,"e":30586,"s":30494,"text":"As we can see in the above code, the syntax can also be used for multiple values per case. "},{"code":null,"e":30595,"s":30586,"text":"6. Scope"},{"code":null,"e":30803,"s":30595,"text":"The variables declared in the traditional switch exists until the end of the switch statement. If we want the variables to have a case level scope, we can use {} introduced by the enhanced switch in Java 13."},{"code":null,"e":31054,"s":30803,"text":"switch (errorCode) {\n case 101: {\n // This variable exists just in this {} block\n int num = 200;\n break;\n }\n case 300: {\n // This is ok, {} block has a separate scope\n int num = 300;\n break;\n }\n}\n"},{"code":null,"e":31074,"s":31054,"text":"7. Preview feature "},{"code":null,"e":31333,"s":31074,"text":"After diving into the features related to the enhanced switch, the point noteworthy is — the enhanced switch functionality is available only as a preview feature in Java 13. This means it is not enabled by default. To use it, we need to explicitly enable it."},{"code":null,"e":31385,"s":31333,"text":"At compile time, add the following params to javac:"},{"code":null,"e":31436,"s":31385,"text":"javac -- release 13 --enable-preview MyClass.java\n"},{"code":null,"e":31468,"s":31436,"text":"At run time, add the following:"},{"code":null,"e":31499,"s":31468,"text":"java --enable-preview MyClass\n"},{"code":null,"e":31684,"s":31499,"text":"The enhanced switch in Java 13 provides a number of impressive features to the traditional switch. However, it is still in the experiment phase and not yet meant for use in production."},{"code":null,"e":31702,"s":31684,"text":"Java-Control-Flow"},{"code":null,"e":31707,"s":31702,"text":"Java"},{"code":null,"e":31725,"s":31707,"text":"Java-Control-Flow"},{"code":null,"e":31730,"s":31725,"text":"Java"},{"code":null,"e":31828,"s":31730,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":31843,"s":31828,"text":"Stream In Java"},{"code":null,"e":31864,"s":31843,"text":"Constructors in Java"},{"code":null,"e":31883,"s":31864,"text":"Exceptions in Java"},{"code":null,"e":31913,"s":31883,"text":"Functional Interfaces in Java"},{"code":null,"e":31959,"s":31913,"text":"Different ways of Reading a text file in Java"},{"code":null,"e":31976,"s":31959,"text":"Generics in Java"},{"code":null,"e":31997,"s":31976,"text":"Introduction to Java"},{"code":null,"e":32040,"s":31997,"text":"Comparator Interface in Java with Examples"},{"code":null,"e":32062,"s":32040,"text":"PriorityQueue in Java"}],"string":"[\n {\n \"code\": null,\n \"e\": 25262,\n \"s\": 25234,\n \"text\": \"\\n24 Oct, 2020\"\n },\n {\n \"code\": null,\n \"e\": 25503,\n \"s\": 25262,\n \"text\": \"Java 12 improved the traditional switch statement and made it more useful. Java 13 further introduced new features. Before going into the details of new features, let’s have a look at the drawbacks faced by the traditional Switch statement.\"\n },\n {\n \"code\": null,\n \"e\": 25548,\n \"s\": 25503,\n \"text\": \"1. Default fall through due to missing break\"\n },\n {\n \"code\": null,\n \"e\": 25635,\n \"s\": 25548,\n \"text\": \"The default fall-through behavior is error-prone. Let’s understand it with an example.\"\n },\n {\n \"code\": null,\n \"e\": 25955,\n \"s\": 25635,\n \"text\": \"switch (itemCode) {\\n case 001 : \\n System.out.println(\\\"It's a laptop!\\\");\\n break;\\n case 002 :\\n System.out.println(\\\"It's a desktop!\\\");\\n break;\\n case 003 :\\n System.out.println(\\\"It's a mobile phone!\\\");\\n break;\\n default :\\n System.out.println(\\\"Unknown device!\\\");\\n}\\n\"\n },\n {\n \"code\": null,\n \"e\": 26122,\n \"s\": 25955,\n \"text\": \"The above code works by matching the corresponding case and executing the particular code block. As long as you provide the necessary break statements, it works fine.\"\n },\n {\n \"code\": null,\n \"e\": 26190,\n \"s\": 26122,\n \"text\": \"But what happens if we forget any of the required break statements:\"\n },\n {\n \"code\": null,\n \"e\": 26388,\n \"s\": 26190,\n \"text\": \" switch (itemCode) {\\n case 001 : \\n System.out.println(\\\"It's a laptop!\\\");\\n // missed out break here \\n case 002 :\\n System.out.println(\\\"It's a desktop!\\\");\\n break;\\n}\\n\\n\"\n },\n {\n \"code\": null,\n \"e\": 26576,\n \"s\": 26388,\n \"text\": \"Here, if we pass 001, the first case matches, and the code block executes. But due to missing break, execution falls through and continues for case 002. We get the following wrong output:\"\n },\n {\n \"code\": null,\n \"e\": 26608,\n \"s\": 26576,\n \"text\": \"It's a laptop!\\nIt's a desktop!\\n\"\n },\n {\n \"code\": null,\n \"e\": 26711,\n \"s\": 26608,\n \"text\": \"Clearly, this is not the intended output. It is a result of accidentally missing-out break statements.\"\n },\n {\n \"code\": null,\n \"e\": 26753,\n \"s\": 26711,\n \"text\": \"2. Multiple values per case not supported\"\n },\n {\n \"code\": null,\n \"e\": 26911,\n \"s\": 26753,\n \"text\": \"There may be situations where similar processing is required for multiple case values. But the traditional switch makes to follow the fall through behaviour.\"\n },\n {\n \"code\": null,\n \"e\": 26992,\n \"s\": 26911,\n \"text\": \"case 001:\\ncase 002:\\ncase 003:\\nSystem.out.println(\\\"It's an electronic gadget!\\\");\\n\"\n },\n {\n \"code\": null,\n \"e\": 27047,\n \"s\": 26992,\n \"text\": \"Much improved switch accepts multiple values per case.\"\n },\n {\n \"code\": null,\n \"e\": 27129,\n \"s\": 27047,\n \"text\": \"case 001, 002, 003 : \\n System.out.println(\\\"It's an electronic gadget!\\\");\\n\\n\"\n },\n {\n \"code\": null,\n \"e\": 27228,\n \"s\": 27129,\n \"text\": \"Enhancements to switch statements were introduced by Java 12 and then further modified by Java 13.\"\n },\n {\n \"code\": null,\n \"e\": 27317,\n \"s\": 27228,\n \"text\": \"Let’s dive into the important features of this improved version of the Switch statement.\"\n },\n {\n \"code\": null,\n \"e\": 27354,\n \"s\": 27317,\n \"text\": \"1. Supports multiple values per case\"\n },\n {\n \"code\": null,\n \"e\": 27482,\n \"s\": 27354,\n \"text\": \"With multiple values being specified per case, it simplifies the code structure and eliminates the need for using fall through.\"\n },\n {\n \"code\": null,\n \"e\": 27564,\n \"s\": 27482,\n \"text\": \"The values need to be separated by commas and break should follow the case block.\"\n },\n {\n \"code\": null,\n \"e\": 27786,\n \"s\": 27564,\n \"text\": \"switch (itemCode) {\\n case 001, 002, 003 : \\n System.out.println(\\\"It's an electronic gadget!\\\");\\n break;\\n \\n case 004, 005:\\n System.out.println(\\\"It's a mechanical device!\\\");\\n break;\\n}\\n\"\n },\n {\n \"code\": null,\n \"e\": 27821,\n \"s\": 27786,\n \"text\": \"2. yield is used to return a value\"\n },\n {\n \"code\": null,\n \"e\": 27908,\n \"s\": 27821,\n \"text\": \"A new keyword yield has been introduced. It returns values from a switch branch only. \"\n },\n {\n \"code\": null,\n \"e\": 27996,\n \"s\": 27908,\n \"text\": \"We don’t need a break after yield as it automatically terminates the switch expression.\"\n },\n {\n \"code\": null,\n \"e\": 28099,\n \"s\": 27996,\n \"text\": \"int val = switch (code) {\\n case \\\"x\\\", \\\"y\\\" :\\n yield 1;\\n case \\\"z\\\", \\\"w\\\" :\\n yield 2;\\n}\\n\"\n },\n {\n \"code\": null,\n \"e\": 28138,\n \"s\": 28099,\n \"text\": \"3. Switch can be used as an expression\"\n },\n {\n \"code\": null,\n \"e\": 28458,\n \"s\": 28138,\n \"text\": \"The switch can now be used as an expression. This means the switch can now return values based on our input. There is a slight change in switch syntax to accommodate this change. A switch block needs to be delimited by a semicolon. The yield keyword is used to return values. No break required with the yield statement.\"\n },\n {\n \"code\": null,\n \"e\": 28530,\n \"s\": 28458,\n \"text\": \"Let’s have a look at a code snippet to understand these changes better.\"\n },\n {\n \"code\": null,\n \"e\": 28818,\n \"s\": 28530,\n \"text\": \"String text = switch (itemCode) {\\n case 001 : \\n yield \\\"It's a laptop!\\\";\\n case 002 :\\n yield \\\"It's a desktop!\\\"; \\n case 003 :\\n yield \\\"It's a mobile phone!\\\";\\n default :\\n throw new IllegalArgumentException(itemCode + \\\"is an unknown device!\\\");\\n}\\n\"\n },\n {\n \"code\": null,\n \"e\": 28857,\n \"s\": 28818,\n \"text\": \"4. Necessary to return value/exception\"\n },\n {\n \"code\": null,\n \"e\": 29147,\n \"s\": 28857,\n \"text\": \"The switch expression is required to specify the handling of all the possible input values. Either we provide all the possible cases or specify the default one. This means, irrespective of the input value, switch expression should always return some value or explicitly throw an exception.\"\n },\n {\n \"code\": null,\n \"e\": 29201,\n \"s\": 29147,\n \"text\": \"For instance, if the above code block is changed to –\"\n },\n {\n \"code\": null,\n \"e\": 29494,\n \"s\": 29201,\n \"text\": \"String text = switch (itemCode) {\\n case 001 : \\n yield \\\"It's a laptop!\\\";\\n case 002 :\\n yield \\\"It's a desktop!\\\"; \\n case 003 :\\n yield \\\"It's a mobile phone!\\\";\\n // default :\\n // throw new IllegalArgumentException(itemCode + \\\"is an unknown device!\\\");\\n}\\n\"\n },\n {\n \"code\": null,\n \"e\": 29603,\n \"s\": 29494,\n \"text\": \"This will result in an error saying that all possible values have not been covered by the switch expression.\"\n },\n {\n \"code\": null,\n \"e\": 29626,\n \"s\": 29603,\n \"text\": \"5. Switch with arrows \"\n },\n {\n \"code\": null,\n \"e\": 29758,\n \"s\": 29626,\n \"text\": \"The new arrow ⇾ syntax has been introduced for the switch. It can be used with the switch as an expression as well as a statement. \"\n },\n {\n \"code\": null,\n \"e\": 29855,\n \"s\": 29758,\n \"text\": \"The statements on the right side of an ⇾ are executed if an exact case matches on the left side.\"\n },\n {\n \"code\": null,\n \"e\": 29913,\n \"s\": 29855,\n \"text\": \"On the right side of ⇾ we can have any of the following –\"\n },\n {\n \"code\": null,\n \"e\": 29936,\n \"s\": 29913,\n \"text\": \"Statement / expression\"\n },\n {\n \"code\": null,\n \"e\": 29952,\n \"s\": 29936,\n \"text\": \"throw statement\"\n },\n {\n \"code\": null,\n \"e\": 29961,\n \"s\": 29952,\n \"text\": \"{} block\"\n },\n {\n \"code\": null,\n \"e\": 30298,\n \"s\": 29961,\n \"text\": \"The main advantage of this syntax is that we don’t need a break statement to avoid the default fall-through. So the rule is, if we need fall-through, use case: else if not use case ⇾. Also note, for all case branches it should be either case: or case ⇾. It cannot be different or different cases in a switch else it results in an error.\"\n },\n {\n \"code\": null,\n \"e\": 30494,\n \"s\": 30298,\n \"text\": \"switch (itemCode) {\\n case 001 -> System.out.println(\\\"It's a laptop!\\\");\\n case 002 -> System.out.println(\\\"It's a desktop!\\\");\\n case 003,004 -> System.out.println(\\\"It's a mobile phone!\\\");\\n}\\n\"\n },\n {\n \"code\": null,\n \"e\": 30586,\n \"s\": 30494,\n \"text\": \"As we can see in the above code, the syntax can also be used for multiple values per case. \"\n },\n {\n \"code\": null,\n \"e\": 30595,\n \"s\": 30586,\n \"text\": \"6. Scope\"\n },\n {\n \"code\": null,\n \"e\": 30803,\n \"s\": 30595,\n \"text\": \"The variables declared in the traditional switch exists until the end of the switch statement. If we want the variables to have a case level scope, we can use {} introduced by the enhanced switch in Java 13.\"\n },\n {\n \"code\": null,\n \"e\": 31054,\n \"s\": 30803,\n \"text\": \"switch (errorCode) {\\n case 101: {\\n // This variable exists just in this {} block\\n int num = 200;\\n break;\\n }\\n case 300: {\\n // This is ok, {} block has a separate scope\\n int num = 300;\\n break;\\n }\\n}\\n\"\n },\n {\n \"code\": null,\n \"e\": 31074,\n \"s\": 31054,\n \"text\": \"7. Preview feature \"\n },\n {\n \"code\": null,\n \"e\": 31333,\n \"s\": 31074,\n \"text\": \"After diving into the features related to the enhanced switch, the point noteworthy is — the enhanced switch functionality is available only as a preview feature in Java 13. This means it is not enabled by default. To use it, we need to explicitly enable it.\"\n },\n {\n \"code\": null,\n \"e\": 31385,\n \"s\": 31333,\n \"text\": \"At compile time, add the following params to javac:\"\n },\n {\n \"code\": null,\n \"e\": 31436,\n \"s\": 31385,\n \"text\": \"javac -- release 13 --enable-preview MyClass.java\\n\"\n },\n {\n \"code\": null,\n \"e\": 31468,\n \"s\": 31436,\n \"text\": \"At run time, add the following:\"\n },\n {\n \"code\": null,\n \"e\": 31499,\n \"s\": 31468,\n \"text\": \"java --enable-preview MyClass\\n\"\n },\n {\n \"code\": null,\n \"e\": 31684,\n \"s\": 31499,\n \"text\": \"The enhanced switch in Java 13 provides a number of impressive features to the traditional switch. However, it is still in the experiment phase and not yet meant for use in production.\"\n },\n {\n \"code\": null,\n \"e\": 31702,\n \"s\": 31684,\n \"text\": \"Java-Control-Flow\"\n },\n {\n \"code\": null,\n \"e\": 31707,\n \"s\": 31702,\n \"text\": \"Java\"\n },\n {\n \"code\": null,\n \"e\": 31725,\n \"s\": 31707,\n \"text\": \"Java-Control-Flow\"\n },\n {\n \"code\": null,\n \"e\": 31730,\n \"s\": 31725,\n \"text\": \"Java\"\n },\n {\n \"code\": null,\n \"e\": 31828,\n \"s\": 31730,\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\": 31843,\n \"s\": 31828,\n \"text\": \"Stream In Java\"\n },\n {\n \"code\": null,\n \"e\": 31864,\n \"s\": 31843,\n \"text\": \"Constructors in Java\"\n },\n {\n \"code\": null,\n \"e\": 31883,\n \"s\": 31864,\n \"text\": \"Exceptions in Java\"\n },\n {\n \"code\": null,\n \"e\": 31913,\n \"s\": 31883,\n \"text\": \"Functional Interfaces in Java\"\n },\n {\n \"code\": null,\n \"e\": 31959,\n \"s\": 31913,\n \"text\": \"Different ways of Reading a text file in Java\"\n },\n {\n \"code\": null,\n \"e\": 31976,\n \"s\": 31959,\n \"text\": \"Generics in Java\"\n },\n {\n \"code\": null,\n \"e\": 31997,\n \"s\": 31976,\n \"text\": \"Introduction to Java\"\n },\n {\n \"code\": null,\n \"e\": 32040,\n \"s\": 31997,\n \"text\": \"Comparator Interface in Java with Examples\"\n },\n {\n \"code\": null,\n \"e\": 32062,\n \"s\": 32040,\n \"text\": \"PriorityQueue in Java\"\n }\n]"}}},{"rowIdx":434,"cells":{"title":{"kind":"string","value":"How to Read Data from Firebase Firestore in Android? - GeeksforGeeks"},"text":{"kind":"string","value":"17 Jan, 2021\n\nIn the previous article, we have seen on How to Add Data to Firebase Firestore in Android. This is the continuation of this series. Now we will see How to Read this added data inside our Firebase Firestore. Now we will move towards the implementation of this reading data in Android Firebase. \nWe will be creating a new screen in the previous application and inside that, we will display our data which we added inside our Firebase Firestore in the RecyclerView. We will read all data from Firebase Firestore inside our app. \nStep 1: Working with the activity_main.xml file\nGo to the activity_main.xml file add one more Button for showing the list of all added courses. Below is the code snippet and add the code at last. \nXML\n \n\n \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nNow below is the updated code for the activity_main.xml file after adding the above code snippet.\nXML\n \n\n \n \n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n\n\n\n\n\n\nStep 2: Now we will create new Activity for displaying our data from Firebase Firestore in RecyclerView\nTo create a new Activity we have to navigate to the app > java > your app’s package name > Right click on package name > New > Empty Activity and name your activity as CourseDetails and create new Activity. Make sure to select the empty activity. \nStep 3: Now we will move towards the implementation of XML in our Course Details activity\nNavigate to the app > res > layout > activity_course_details.xml and add the below code to it. \nXML\n \n\n \n \n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n \n \n \n\n\n\n\n\n\n\nStep 4: Now we will create a card layout for our item of RecyclerView\nTo create a new item for RecyclerView, navigate to the app > res > layout > Right-click on layout > New > layout resource file and name as course_item.xml and add below code to it. \nXML\n \n\n \n \n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n\n\n\n\n\n\nStep 5: Now we will create our Adapter class which will handle data for our RecyclerView items\nFor creating an Adapter class for our Recycler View, navigate to the app > java > Your app’s package name > Right-click on it and Click > New > Java class and name your class as CourseRVAdapter. After creating this class add the below code to it. Comments are added in the code to know in more detail. \nJava\n \n\n \n \n\n\n\n\n\n\n\n\n\n\nimport android.content.Context; \nimport android.view.LayoutInflater; \nimport android.view.View; \nimport android.view.ViewGroup; \nimport android.widget.TextView; \n \nimport androidx.annotation.NonNull; \nimport androidx.recyclerview.widget.RecyclerView; \n \nimport java.util.ArrayList; \n \npublic class CourseRVAdapter extends RecyclerView.Adapter { \n // creating variables for our ArrayList and context \n private ArrayList coursesArrayList; \n private Context context; \n \n // creating constructor for our adapter class \n public CourseRVAdapter(ArrayList coursesArrayList, Context context) { \n this.coursesArrayList = coursesArrayList; \n this.context = context; \n } \n \n @NonNull\n @Override\n public CourseRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { \n // passing our layout file for displaying our card item \n return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.course_item, parent, false)); \n } \n \n @Override\n public void onBindViewHolder(@NonNull CourseRVAdapter.ViewHolder holder, int position) { \n // setting data to our text views from our modal class. \n Courses courses = coursesArrayList.get(position); \n holder.courseNameTV.setText(courses.getCourseName()); \n holder.courseDurationTV.setText(courses.getCourseDuration()); \n holder.courseDescTV.setText(courses.getCourseDescription()); \n } \n \n @Override\n public int getItemCount() { \n // returning the size of our array list. \n return coursesArrayList.size(); \n } \n \n class ViewHolder extends RecyclerView.ViewHolder { \n // creating variables for our text views. \n private final TextView courseNameTV; \n private final TextView courseDurationTV; \n private final TextView courseDescTV; \n \n public ViewHolder(@NonNull View itemView) { \n super(itemView); \n // initializing our text views. \n courseNameTV = itemView.findViewById(R.id.idTVCourseName); \n courseDurationTV = itemView.findViewById(R.id.idTVCourseDuration); \n courseDescTV = itemView.findViewById(R.id.idTVCourseDescription); \n } \n } \n}\n\n\n\n\n\n\nStep 6: Working with the CourseDetails.java file\nAfter creating a new Adapter class for our RecyclerView, we have to move towards our CourseDetails.java file and add the below code to it. \nJava\n \n\n \n \n\n\n\n\n\n\n\n\n\n\nimport android.os.Bundle; \nimport android.view.View; \nimport android.widget.ProgressBar; \nimport android.widget.Toast; \n \nimport androidx.annotation.NonNull; \nimport androidx.appcompat.app.AppCompatActivity; \nimport androidx.recyclerview.widget.LinearLayoutManager; \nimport androidx.recyclerview.widget.RecyclerView; \n \nimport com.google.android.gms.tasks.OnFailureListener; \nimport com.google.android.gms.tasks.OnSuccessListener; \nimport com.google.firebase.firestore.DocumentSnapshot; \nimport com.google.firebase.firestore.FirebaseFirestore; \nimport com.google.firebase.firestore.QuerySnapshot; \n \nimport java.util.ArrayList; \nimport java.util.List; \n \npublic class CourseDetails extends AppCompatActivity { \n \n // creating variables for our recycler view, \n // array list, adapter, firebase firestore \n // and our progress bar. \n private RecyclerView courseRV; \n private ArrayList coursesArrayList; \n private CourseRVAdapter courseRVAdapter; \n private FirebaseFirestore db; \n ProgressBar loadingPB; \n \n @Override\n protected void onCreate(Bundle savedInstanceState) { \n super.onCreate(savedInstanceState); \n setContentView(R.layout.activity_course_details); \n \n // initializing our variables. \n courseRV = findViewById(R.id.idRVCourses); \n loadingPB = findViewById(R.id.idProgressBar); \n \n // initializing our variable for firebase \n // firestore and getting its instance. \n db = FirebaseFirestore.getInstance(); \n \n // creating our new array list \n coursesArrayList = new ArrayList<>(); \n courseRV.setHasFixedSize(true); \n courseRV.setLayoutManager(new LinearLayoutManager(this)); \n \n // adding our array list to our recycler view adapter class. \n courseRVAdapter = new CourseRVAdapter(coursesArrayList, this); \n \n // setting adapter to our recycler view. \n courseRV.setAdapter(courseRVAdapter); \n \n // below line is use to get the data from Firebase Firestore. \n // previously we were saving data on a reference of Courses \n // now we will be getting the data from the same reference. \n db.collection(\"Courses\").get() \n .addOnSuccessListener(new OnSuccessListener() { \n @Override\n public void onSuccess(QuerySnapshot queryDocumentSnapshots) { \n // after getting the data we are calling on success method \n // and inside this method we are checking if the received \n // query snapshot is empty or not. \n if (!queryDocumentSnapshots.isEmpty()) { \n // if the snapshot is not empty we are \n // hiding our progress bar and adding \n // our data in a list. \n loadingPB.setVisibility(View.GONE); \n List list = queryDocumentSnapshots.getDocuments(); \n for (DocumentSnapshot d : list) { \n // after getting this list we are passing \n // that list to our object class. \n Courses c = d.toObject(Courses.class); \n \n // and we will pass this object class \n // inside our arraylist which we have \n // created for recycler view. \n coursesArrayList.add(c); \n } \n // after adding the data to recycler view. \n // we are calling recycler view notifuDataSetChanged \n // method to notify that data has been changed in recycler view. \n courseRVAdapter.notifyDataSetChanged(); \n } else { \n // if the snapshot is empty we are displaying a toast message. \n Toast.makeText(CourseDetails.this, \"No data found in Database\", Toast.LENGTH_SHORT).show(); \n } \n } \n }).addOnFailureListener(new OnFailureListener() { \n @Override\n public void onFailure(@NonNull Exception e) { \n // if we do not get any data or any error we are displaying \n // a toast message that we do not get any data \n Toast.makeText(CourseDetails.this, \"Fail to get the data.\", Toast.LENGTH_SHORT).show(); \n } \n }); \n } \n}\n\n\n\n\n\n\nStep 7: Working with the MainActivity.java file\nIn the MainActivity.java file, we have to add an Intent to the CourseDetails.class file. Below is the code snippet to do so.\nJava\n \n\n \n \n\n\n\n\n\n\n\n\n\n\n// adding onclick listener to view data in new activity \nviewCoursesBtn.setOnClickListener(new View.OnClickListener() { \n @Override\n public void onClick(View v) { \n // opening a new activity on button click \n Intent i = new Intent(MainActivity.this,CourseDetails.class); \n startActivity(i); \n } \n });\n\n\n\n\n\n\nBelow is the updated code for the MainActivity.java file.\nJava\n \n\n \n \n\n\n\n\n\n\n\n\n\n\nimport android.content.Intent; \nimport android.os.Bundle; \nimport android.text.TextUtils; \nimport android.view.View; \nimport android.widget.Button; \nimport android.widget.EditText; \nimport android.widget.Toast; \n \nimport androidx.annotation.NonNull; \nimport androidx.appcompat.app.AppCompatActivity; \n \nimport com.google.android.gms.tasks.OnFailureListener; \nimport com.google.android.gms.tasks.OnSuccessListener; \nimport com.google.firebase.firestore.CollectionReference; \nimport com.google.firebase.firestore.DocumentReference; \nimport com.google.firebase.firestore.FirebaseFirestore; \n \npublic class MainActivity extends AppCompatActivity { \n \n // creating variables for our edit text \n private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt; \n \n // creating variable for button \n private Button submitCourseBtn, viewCoursesBtn; \n \n // creating a strings for storing \n // our values from edittext fields. \n private String courseName, courseDuration, courseDescription; \n \n // creating a variable \n // for firebasefirestore. \n private FirebaseFirestore db; \n \n @Override\n protected void onCreate(Bundle savedInstanceState) { \n super.onCreate(savedInstanceState); \n setContentView(R.layout.activity_main); \n \n // getting our instance \n // from Firebase Firestore. \n db = FirebaseFirestore.getInstance(); \n \n // initializing our edittext and buttons \n courseNameEdt = findViewById(R.id.idEdtCourseName); \n courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription); \n courseDurationEdt = findViewById(R.id.idEdtCourseDuration); \n submitCourseBtn = findViewById(R.id.idBtnSubmitCourse); \n viewCoursesBtn = findViewById(R.id.idBtnViewCourses); \n \n // adding onclick listener to view data in new activity \n viewCoursesBtn.setOnClickListener(new View.OnClickListener() { \n @Override\n public void onClick(View v) { \n // opening a new activity on button click \n Intent i = new Intent(MainActivity.this,CourseDetails.class); \n startActivity(i); \n } \n }); \n \n // adding on click listener for button \n submitCourseBtn.setOnClickListener(new View.OnClickListener() { \n @Override\n public void onClick(View v) { \n \n // getting data from edittext fields. \n courseName = courseNameEdt.getText().toString(); \n courseDescription = courseDescriptionEdt.getText().toString(); \n courseDuration = courseDurationEdt.getText().toString(); \n \n // validating the text fields if empty or not. \n if (TextUtils.isEmpty(courseName)) { \n courseNameEdt.setError(\"Please enter Course Name\"); \n } else if (TextUtils.isEmpty(courseDescription)) { \n courseDescriptionEdt.setError(\"Please enter Course Description\"); \n } else if (TextUtils.isEmpty(courseDuration)) { \n courseDurationEdt.setError(\"Please enter Course Duration\"); \n } else { \n // calling method to add data to Firebase Firestore. \n addDataToFirestore(courseName, courseDescription, courseDuration); \n } \n } \n }); \n } \n \n private void addDataToFirestore(String courseName, String courseDescription, String courseDuration) { \n \n // creating a collection reference \n // for our Firebase Firetore database. \n CollectionReference dbCourses = db.collection(\"Courses\"); \n \n // adding our data to our courses object class. \n Courses courses = new Courses(courseName, courseDescription, courseDuration); \n \n // below method is use to add data to Firebase Firestore. \n dbCourses.add(courses).addOnSuccessListener(new OnSuccessListener() { \n @Override\n public void onSuccess(DocumentReference documentReference) { \n // after the data addition is successful \n // we are displaying a success toast message. \n Toast.makeText(MainActivity.this, \"Your Course has been added to Firebase Firestore\", Toast.LENGTH_SHORT).show(); \n } \n }).addOnFailureListener(new OnFailureListener() { \n @Override\n public void onFailure(@NonNull Exception e) { \n // this method is called when the data addition process is failed. \n // displaying a toast message when data addition is failed. \n Toast.makeText(MainActivity.this, \"Fail to add course \\n\" + e, Toast.LENGTH_SHORT).show(); \n } \n }); \n } \n}\n\n\n\n\n\n\nAfter completing this process we have to add the data from our app in Firebase Console and after that click on View Added Courses button you will get to see the list of courses that we have added inside our Firebase Console. Below is the image of how our Firebase Firestore database will look like for only one recycler item. \nAfter completing this Run your app and see the output of the code.\n\nandroid\n\n\nTechnical Scripter 2020\n\n\nAndroid\n\n\nJava\n\n\nTechnical Scripter\n\nWriting code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n \nResource Raw Folder in Android Studio\nFlutter - Custom Bottom Navigation Bar\nHow to Read Data from SQLite Database in Android?\nRetrofit with Kotlin Coroutine in Android\nHow to Post Data to API using Retrofit in Android?\nArrays in Java\nSplit() String method in Java with examples\nFor-each loop in Java\nObject Oriented Programming (OOPs) Concept in Java\nReverse a string in Java"},"parsed":{"kind":"list like","value":[{"code":null,"e":26480,"s":26449,"text":" \n17 Jan, 2021\n"},{"code":null,"e":26774,"s":26480,"text":"In the previous article, we have seen on How to Add Data to Firebase Firestore in Android. This is the continuation of this series. Now we will see How to Read this added data inside our Firebase Firestore. Now we will move towards the implementation of this reading data in Android Firebase. "},{"code":null,"e":27006,"s":26774,"text":"We will be creating a new screen in the previous application and inside that, we will display our data which we added inside our Firebase Firestore in the RecyclerView. We will read all data from Firebase Firestore inside our app. "},{"code":null,"e":27054,"s":27006,"text":"Step 1: Working with the activity_main.xml file"},{"code":null,"e":27203,"s":27054,"text":"Go to the activity_main.xml file add one more Button for showing the list of all added courses. Below is the code snippet and add the code at last. "},{"code":null,"e":27207,"s":27203,"text":"XML"},{"code":"\n\n\n\n\n\n\n\n\n\n\n\n\n\n","e":27504,"s":27217,"text":null},{"code":null,"e":27602,"s":27504,"text":"Now below is the updated code for the activity_main.xml file after adding the above code snippet."},{"code":null,"e":27606,"s":27602,"text":"XML"},{"code":"\n\n\n\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n\n\n\n\n\n","e":29938,"s":27616,"text":null},{"code":null,"e":30042,"s":29938,"text":"Step 2: Now we will create new Activity for displaying our data from Firebase Firestore in RecyclerView"},{"code":null,"e":30290,"s":30042,"text":"To create a new Activity we have to navigate to the app > java > your app’s package name > Right click on package name > New > Empty Activity and name your activity as CourseDetails and create new Activity. Make sure to select the empty activity. "},{"code":null,"e":30380,"s":30290,"text":"Step 3: Now we will move towards the implementation of XML in our Course Details activity"},{"code":null,"e":30476,"s":30380,"text":"Navigate to the app > res > layout > activity_course_details.xml and add the below code to it. "},{"code":null,"e":30480,"s":30476,"text":"XML"},{"code":"\n\n\n\n\n\n\n \n \n \n \n \n \n \n \n \n\n\n\n\n\n\n","e":31320,"s":30490,"text":null},{"code":null,"e":31390,"s":31320,"text":"Step 4: Now we will create a card layout for our item of RecyclerView"},{"code":null,"e":31572,"s":31390,"text":"To create a new item for RecyclerView, navigate to the app > res > layout > Right-click on layout > New > layout resource file and name as course_item.xml and add below code to it. "},{"code":null,"e":31576,"s":31572,"text":"XML"},{"code":"\n\n\n\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n\n\n\n\n\n","e":33426,"s":31586,"text":null},{"code":null,"e":33521,"s":33426,"text":"Step 5: Now we will create our Adapter class which will handle data for our RecyclerView items"},{"code":null,"e":33824,"s":33521,"text":"For creating an Adapter class for our Recycler View, navigate to the app > java > Your app’s package name > Right-click on it and Click > New > Java class and name your class as CourseRVAdapter. After creating this class add the below code to it. Comments are added in the code to know in more detail. "},{"code":null,"e":33829,"s":33824,"text":"Java"},{"code":"\n\n\n\n\n\n\nimport android.content.Context; \nimport android.view.LayoutInflater; \nimport android.view.View; \nimport android.view.ViewGroup; \nimport android.widget.TextView; \n \nimport androidx.annotation.NonNull; \nimport androidx.recyclerview.widget.RecyclerView; \n \nimport java.util.ArrayList; \n \npublic class CourseRVAdapter extends RecyclerView.Adapter { \n // creating variables for our ArrayList and context \n private ArrayList coursesArrayList; \n private Context context; \n \n // creating constructor for our adapter class \n public CourseRVAdapter(ArrayList coursesArrayList, Context context) { \n this.coursesArrayList = coursesArrayList; \n this.context = context; \n } \n \n @NonNull\n @Override\n public CourseRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { \n // passing our layout file for displaying our card item \n return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.course_item, parent, false)); \n } \n \n @Override\n public void onBindViewHolder(@NonNull CourseRVAdapter.ViewHolder holder, int position) { \n // setting data to our text views from our modal class. \n Courses courses = coursesArrayList.get(position); \n holder.courseNameTV.setText(courses.getCourseName()); \n holder.courseDurationTV.setText(courses.getCourseDuration()); \n holder.courseDescTV.setText(courses.getCourseDescription()); \n } \n \n @Override\n public int getItemCount() { \n // returning the size of our array list. \n return coursesArrayList.size(); \n } \n \n class ViewHolder extends RecyclerView.ViewHolder { \n // creating variables for our text views. \n private final TextView courseNameTV; \n private final TextView courseDurationTV; \n private final TextView courseDescTV; \n \n public ViewHolder(@NonNull View itemView) { \n super(itemView); \n // initializing our text views. \n courseNameTV = itemView.findViewById(R.id.idTVCourseName); \n courseDurationTV = itemView.findViewById(R.id.idTVCourseDuration); \n courseDescTV = itemView.findViewById(R.id.idTVCourseDescription); \n } \n } \n}\n\n\n\n\n\n","e":36133,"s":33839,"text":null},{"code":null,"e":36182,"s":36133,"text":"Step 6: Working with the CourseDetails.java file"},{"code":null,"e":36322,"s":36182,"text":"After creating a new Adapter class for our RecyclerView, we have to move towards our CourseDetails.java file and add the below code to it. "},{"code":null,"e":36327,"s":36322,"text":"Java"},{"code":"\n\n\n\n\n\n\nimport android.os.Bundle; \nimport android.view.View; \nimport android.widget.ProgressBar; \nimport android.widget.Toast; \n \nimport androidx.annotation.NonNull; \nimport androidx.appcompat.app.AppCompatActivity; \nimport androidx.recyclerview.widget.LinearLayoutManager; \nimport androidx.recyclerview.widget.RecyclerView; \n \nimport com.google.android.gms.tasks.OnFailureListener; \nimport com.google.android.gms.tasks.OnSuccessListener; \nimport com.google.firebase.firestore.DocumentSnapshot; \nimport com.google.firebase.firestore.FirebaseFirestore; \nimport com.google.firebase.firestore.QuerySnapshot; \n \nimport java.util.ArrayList; \nimport java.util.List; \n \npublic class CourseDetails extends AppCompatActivity { \n \n // creating variables for our recycler view, \n // array list, adapter, firebase firestore \n // and our progress bar. \n private RecyclerView courseRV; \n private ArrayList coursesArrayList; \n private CourseRVAdapter courseRVAdapter; \n private FirebaseFirestore db; \n ProgressBar loadingPB; \n \n @Override\n protected void onCreate(Bundle savedInstanceState) { \n super.onCreate(savedInstanceState); \n setContentView(R.layout.activity_course_details); \n \n // initializing our variables. \n courseRV = findViewById(R.id.idRVCourses); \n loadingPB = findViewById(R.id.idProgressBar); \n \n // initializing our variable for firebase \n // firestore and getting its instance. \n db = FirebaseFirestore.getInstance(); \n \n // creating our new array list \n coursesArrayList = new ArrayList<>(); \n courseRV.setHasFixedSize(true); \n courseRV.setLayoutManager(new LinearLayoutManager(this)); \n \n // adding our array list to our recycler view adapter class. \n courseRVAdapter = new CourseRVAdapter(coursesArrayList, this); \n \n // setting adapter to our recycler view. \n courseRV.setAdapter(courseRVAdapter); \n \n // below line is use to get the data from Firebase Firestore. \n // previously we were saving data on a reference of Courses \n // now we will be getting the data from the same reference. \n db.collection(\"Courses\").get() \n .addOnSuccessListener(new OnSuccessListener() { \n @Override\n public void onSuccess(QuerySnapshot queryDocumentSnapshots) { \n // after getting the data we are calling on success method \n // and inside this method we are checking if the received \n // query snapshot is empty or not. \n if (!queryDocumentSnapshots.isEmpty()) { \n // if the snapshot is not empty we are \n // hiding our progress bar and adding \n // our data in a list. \n loadingPB.setVisibility(View.GONE); \n List list = queryDocumentSnapshots.getDocuments(); \n for (DocumentSnapshot d : list) { \n // after getting this list we are passing \n // that list to our object class. \n Courses c = d.toObject(Courses.class); \n \n // and we will pass this object class \n // inside our arraylist which we have \n // created for recycler view. \n coursesArrayList.add(c); \n } \n // after adding the data to recycler view. \n // we are calling recycler view notifuDataSetChanged \n // method to notify that data has been changed in recycler view. \n courseRVAdapter.notifyDataSetChanged(); \n } else { \n // if the snapshot is empty we are displaying a toast message. \n Toast.makeText(CourseDetails.this, \"No data found in Database\", Toast.LENGTH_SHORT).show(); \n } \n } \n }).addOnFailureListener(new OnFailureListener() { \n @Override\n public void onFailure(@NonNull Exception e) { \n // if we do not get any data or any error we are displaying \n // a toast message that we do not get any data \n Toast.makeText(CourseDetails.this, \"Fail to get the data.\", Toast.LENGTH_SHORT).show(); \n } \n }); \n } \n}\n\n\n\n\n\n","e":41109,"s":36337,"text":null},{"code":null,"e":41157,"s":41109,"text":"Step 7: Working with the MainActivity.java file"},{"code":null,"e":41282,"s":41157,"text":"In the MainActivity.java file, we have to add an Intent to the CourseDetails.class file. Below is the code snippet to do so."},{"code":null,"e":41287,"s":41282,"text":"Java"},{"code":"\n\n\n\n\n\n\n// adding onclick listener to view data in new activity \nviewCoursesBtn.setOnClickListener(new View.OnClickListener() { \n @Override\n public void onClick(View v) { \n // opening a new activity on button click \n Intent i = new Intent(MainActivity.this,CourseDetails.class); \n startActivity(i); \n } \n });\n\n\n\n\n\n","e":41691,"s":41297,"text":null},{"code":null,"e":41749,"s":41691,"text":"Below is the updated code for the MainActivity.java file."},{"code":null,"e":41754,"s":41749,"text":"Java"},{"code":"\n\n\n\n\n\n\nimport android.content.Intent; \nimport android.os.Bundle; \nimport android.text.TextUtils; \nimport android.view.View; \nimport android.widget.Button; \nimport android.widget.EditText; \nimport android.widget.Toast; \n \nimport androidx.annotation.NonNull; \nimport androidx.appcompat.app.AppCompatActivity; \n \nimport com.google.android.gms.tasks.OnFailureListener; \nimport com.google.android.gms.tasks.OnSuccessListener; \nimport com.google.firebase.firestore.CollectionReference; \nimport com.google.firebase.firestore.DocumentReference; \nimport com.google.firebase.firestore.FirebaseFirestore; \n \npublic class MainActivity extends AppCompatActivity { \n \n // creating variables for our edit text \n private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt; \n \n // creating variable for button \n private Button submitCourseBtn, viewCoursesBtn; \n \n // creating a strings for storing \n // our values from edittext fields. \n private String courseName, courseDuration, courseDescription; \n \n // creating a variable \n // for firebasefirestore. \n private FirebaseFirestore db; \n \n @Override\n protected void onCreate(Bundle savedInstanceState) { \n super.onCreate(savedInstanceState); \n setContentView(R.layout.activity_main); \n \n // getting our instance \n // from Firebase Firestore. \n db = FirebaseFirestore.getInstance(); \n \n // initializing our edittext and buttons \n courseNameEdt = findViewById(R.id.idEdtCourseName); \n courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription); \n courseDurationEdt = findViewById(R.id.idEdtCourseDuration); \n submitCourseBtn = findViewById(R.id.idBtnSubmitCourse); \n viewCoursesBtn = findViewById(R.id.idBtnViewCourses); \n \n // adding onclick listener to view data in new activity \n viewCoursesBtn.setOnClickListener(new View.OnClickListener() { \n @Override\n public void onClick(View v) { \n // opening a new activity on button click \n Intent i = new Intent(MainActivity.this,CourseDetails.class); \n startActivity(i); \n } \n }); \n \n // adding on click listener for button \n submitCourseBtn.setOnClickListener(new View.OnClickListener() { \n @Override\n public void onClick(View v) { \n \n // getting data from edittext fields. \n courseName = courseNameEdt.getText().toString(); \n courseDescription = courseDescriptionEdt.getText().toString(); \n courseDuration = courseDurationEdt.getText().toString(); \n \n // validating the text fields if empty or not. \n if (TextUtils.isEmpty(courseName)) { \n courseNameEdt.setError(\"Please enter Course Name\"); \n } else if (TextUtils.isEmpty(courseDescription)) { \n courseDescriptionEdt.setError(\"Please enter Course Description\"); \n } else if (TextUtils.isEmpty(courseDuration)) { \n courseDurationEdt.setError(\"Please enter Course Duration\"); \n } else { \n // calling method to add data to Firebase Firestore. \n addDataToFirestore(courseName, courseDescription, courseDuration); \n } \n } \n }); \n } \n \n private void addDataToFirestore(String courseName, String courseDescription, String courseDuration) { \n \n // creating a collection reference \n // for our Firebase Firetore database. \n CollectionReference dbCourses = db.collection(\"Courses\"); \n \n // adding our data to our courses object class. \n Courses courses = new Courses(courseName, courseDescription, courseDuration); \n \n // below method is use to add data to Firebase Firestore. \n dbCourses.add(courses).addOnSuccessListener(new OnSuccessListener() { \n @Override\n public void onSuccess(DocumentReference documentReference) { \n // after the data addition is successful \n // we are displaying a success toast message. \n Toast.makeText(MainActivity.this, \"Your Course has been added to Firebase Firestore\", Toast.LENGTH_SHORT).show(); \n } \n }).addOnFailureListener(new OnFailureListener() { \n @Override\n public void onFailure(@NonNull Exception e) { \n // this method is called when the data addition process is failed. \n // displaying a toast message when data addition is failed. \n Toast.makeText(MainActivity.this, \"Fail to add course \\n\" + e, Toast.LENGTH_SHORT).show(); \n } \n }); \n } \n}\n\n\n\n\n\n","e":46572,"s":41764,"text":null},{"code":null,"e":46899,"s":46572,"text":"After completing this process we have to add the data from our app in Firebase Console and after that click on View Added Courses button you will get to see the list of courses that we have added inside our Firebase Console. Below is the image of how our Firebase Firestore database will look like for only one recycler item. "},{"code":null,"e":46966,"s":46899,"text":"After completing this Run your app and see the output of the code."},{"code":null,"e":46976,"s":46966,"text":"\nandroid\n"},{"code":null,"e":47002,"s":46976,"text":"\nTechnical Scripter 2020\n"},{"code":null,"e":47012,"s":47002,"text":"\nAndroid\n"},{"code":null,"e":47019,"s":47012,"text":"\nJava\n"},{"code":null,"e":47040,"s":47019,"text":"\nTechnical Scripter\n"},{"code":null,"e":47245,"s":47040,"text":"Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "},{"code":null,"e":47283,"s":47245,"text":"Resource Raw Folder in Android Studio"},{"code":null,"e":47322,"s":47283,"text":"Flutter - Custom Bottom Navigation Bar"},{"code":null,"e":47372,"s":47322,"text":"How to Read Data from SQLite Database in Android?"},{"code":null,"e":47414,"s":47372,"text":"Retrofit with Kotlin Coroutine in Android"},{"code":null,"e":47465,"s":47414,"text":"How to Post Data to API using Retrofit in Android?"},{"code":null,"e":47480,"s":47465,"text":"Arrays in Java"},{"code":null,"e":47524,"s":47480,"text":"Split() String method in Java with examples"},{"code":null,"e":47546,"s":47524,"text":"For-each loop in Java"},{"code":null,"e":47597,"s":47546,"text":"Object Oriented Programming (OOPs) Concept in Java"}],"string":"[\n {\n \"code\": null,\n \"e\": 26480,\n \"s\": 26449,\n \"text\": \" \\n17 Jan, 2021\\n\"\n },\n {\n \"code\": null,\n \"e\": 26774,\n \"s\": 26480,\n \"text\": \"In the previous article, we have seen on How to Add Data to Firebase Firestore in Android. This is the continuation of this series. Now we will see How to Read this added data inside our Firebase Firestore. Now we will move towards the implementation of this reading data in Android Firebase. \"\n },\n {\n \"code\": null,\n \"e\": 27006,\n \"s\": 26774,\n \"text\": \"We will be creating a new screen in the previous application and inside that, we will display our data which we added inside our Firebase Firestore in the RecyclerView. We will read all data from Firebase Firestore inside our app. \"\n },\n {\n \"code\": null,\n \"e\": 27054,\n \"s\": 27006,\n \"text\": \"Step 1: Working with the activity_main.xml file\"\n },\n {\n \"code\": null,\n \"e\": 27203,\n \"s\": 27054,\n \"text\": \"Go to the activity_main.xml file add one more Button for showing the list of all added courses. Below is the code snippet and add the code at last. \"\n },\n {\n \"code\": null,\n \"e\": 27207,\n \"s\": 27203,\n \"text\": \"XML\"\n },\n {\n \"code\": \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\",\n \"e\": 27504,\n \"s\": 27217,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 27602,\n \"s\": 27504,\n \"text\": \"Now below is the updated code for the activity_main.xml file after adding the above code snippet.\"\n },\n {\n \"code\": null,\n \"e\": 27606,\n \"s\": 27602,\n \"text\": \"XML\"\n },\n {\n \"code\": \"\\n\\n\\n\\n\\n\\n\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n\\n\\n\\n\\n\\n\\n\",\n \"e\": 29938,\n \"s\": 27616,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 30042,\n \"s\": 29938,\n \"text\": \"Step 2: Now we will create new Activity for displaying our data from Firebase Firestore in RecyclerView\"\n },\n {\n \"code\": null,\n \"e\": 30290,\n \"s\": 30042,\n \"text\": \"To create a new Activity we have to navigate to the app > java > your app’s package name > Right click on package name > New > Empty Activity and name your activity as CourseDetails and create new Activity. Make sure to select the empty activity. \"\n },\n {\n \"code\": null,\n \"e\": 30380,\n \"s\": 30290,\n \"text\": \"Step 3: Now we will move towards the implementation of XML in our Course Details activity\"\n },\n {\n \"code\": null,\n \"e\": 30476,\n \"s\": 30380,\n \"text\": \"Navigate to the app > res > layout > activity_course_details.xml and add the below code to it. \"\n },\n {\n \"code\": null,\n \"e\": 30480,\n \"s\": 30476,\n \"text\": \"XML\"\n },\n {\n \"code\": \"\\n\\n\\n\\n\\n\\n\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n\\n\\n\\n\\n\\n\\n\",\n \"e\": 31320,\n \"s\": 30490,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 31390,\n \"s\": 31320,\n \"text\": \"Step 4: Now we will create a card layout for our item of RecyclerView\"\n },\n {\n \"code\": null,\n \"e\": 31572,\n \"s\": 31390,\n \"text\": \"To create a new item for RecyclerView, navigate to the app > res > layout > Right-click on layout > New > layout resource file and name as course_item.xml and add below code to it. \"\n },\n {\n \"code\": null,\n \"e\": 31576,\n \"s\": 31572,\n \"text\": \"XML\"\n },\n {\n \"code\": \"\\n\\n\\n\\n\\n\\n\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n\\n\\n\\n\\n\\n\\n\",\n \"e\": 33426,\n \"s\": 31586,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 33521,\n \"s\": 33426,\n \"text\": \"Step 5: Now we will create our Adapter class which will handle data for our RecyclerView items\"\n },\n {\n \"code\": null,\n \"e\": 33824,\n \"s\": 33521,\n \"text\": \"For creating an Adapter class for our Recycler View, navigate to the app > java > Your app’s package name > Right-click on it and Click > New > Java class and name your class as CourseRVAdapter. After creating this class add the below code to it. Comments are added in the code to know in more detail. \"\n },\n {\n \"code\": null,\n \"e\": 33829,\n \"s\": 33824,\n \"text\": \"Java\"\n },\n {\n \"code\": \"\\n\\n\\n\\n\\n\\n\\nimport android.content.Context; \\nimport android.view.LayoutInflater; \\nimport android.view.View; \\nimport android.view.ViewGroup; \\nimport android.widget.TextView; \\n \\nimport androidx.annotation.NonNull; \\nimport androidx.recyclerview.widget.RecyclerView; \\n \\nimport java.util.ArrayList; \\n \\npublic class CourseRVAdapter extends RecyclerView.Adapter { \\n // creating variables for our ArrayList and context \\n private ArrayList coursesArrayList; \\n private Context context; \\n \\n // creating constructor for our adapter class \\n public CourseRVAdapter(ArrayList coursesArrayList, Context context) { \\n this.coursesArrayList = coursesArrayList; \\n this.context = context; \\n } \\n \\n @NonNull\\n @Override\\n public CourseRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { \\n // passing our layout file for displaying our card item \\n return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.course_item, parent, false)); \\n } \\n \\n @Override\\n public void onBindViewHolder(@NonNull CourseRVAdapter.ViewHolder holder, int position) { \\n // setting data to our text views from our modal class. \\n Courses courses = coursesArrayList.get(position); \\n holder.courseNameTV.setText(courses.getCourseName()); \\n holder.courseDurationTV.setText(courses.getCourseDuration()); \\n holder.courseDescTV.setText(courses.getCourseDescription()); \\n } \\n \\n @Override\\n public int getItemCount() { \\n // returning the size of our array list. \\n return coursesArrayList.size(); \\n } \\n \\n class ViewHolder extends RecyclerView.ViewHolder { \\n // creating variables for our text views. \\n private final TextView courseNameTV; \\n private final TextView courseDurationTV; \\n private final TextView courseDescTV; \\n \\n public ViewHolder(@NonNull View itemView) { \\n super(itemView); \\n // initializing our text views. \\n courseNameTV = itemView.findViewById(R.id.idTVCourseName); \\n courseDurationTV = itemView.findViewById(R.id.idTVCourseDuration); \\n courseDescTV = itemView.findViewById(R.id.idTVCourseDescription); \\n } \\n } \\n}\\n\\n\\n\\n\\n\\n\",\n \"e\": 36133,\n \"s\": 33839,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 36182,\n \"s\": 36133,\n \"text\": \"Step 6: Working with the CourseDetails.java file\"\n },\n {\n \"code\": null,\n \"e\": 36322,\n \"s\": 36182,\n \"text\": \"After creating a new Adapter class for our RecyclerView, we have to move towards our CourseDetails.java file and add the below code to it. \"\n },\n {\n \"code\": null,\n \"e\": 36327,\n \"s\": 36322,\n \"text\": \"Java\"\n },\n {\n \"code\": \"\\n\\n\\n\\n\\n\\n\\nimport android.os.Bundle; \\nimport android.view.View; \\nimport android.widget.ProgressBar; \\nimport android.widget.Toast; \\n \\nimport androidx.annotation.NonNull; \\nimport androidx.appcompat.app.AppCompatActivity; \\nimport androidx.recyclerview.widget.LinearLayoutManager; \\nimport androidx.recyclerview.widget.RecyclerView; \\n \\nimport com.google.android.gms.tasks.OnFailureListener; \\nimport com.google.android.gms.tasks.OnSuccessListener; \\nimport com.google.firebase.firestore.DocumentSnapshot; \\nimport com.google.firebase.firestore.FirebaseFirestore; \\nimport com.google.firebase.firestore.QuerySnapshot; \\n \\nimport java.util.ArrayList; \\nimport java.util.List; \\n \\npublic class CourseDetails extends AppCompatActivity { \\n \\n // creating variables for our recycler view, \\n // array list, adapter, firebase firestore \\n // and our progress bar. \\n private RecyclerView courseRV; \\n private ArrayList coursesArrayList; \\n private CourseRVAdapter courseRVAdapter; \\n private FirebaseFirestore db; \\n ProgressBar loadingPB; \\n \\n @Override\\n protected void onCreate(Bundle savedInstanceState) { \\n super.onCreate(savedInstanceState); \\n setContentView(R.layout.activity_course_details); \\n \\n // initializing our variables. \\n courseRV = findViewById(R.id.idRVCourses); \\n loadingPB = findViewById(R.id.idProgressBar); \\n \\n // initializing our variable for firebase \\n // firestore and getting its instance. \\n db = FirebaseFirestore.getInstance(); \\n \\n // creating our new array list \\n coursesArrayList = new ArrayList<>(); \\n courseRV.setHasFixedSize(true); \\n courseRV.setLayoutManager(new LinearLayoutManager(this)); \\n \\n // adding our array list to our recycler view adapter class. \\n courseRVAdapter = new CourseRVAdapter(coursesArrayList, this); \\n \\n // setting adapter to our recycler view. \\n courseRV.setAdapter(courseRVAdapter); \\n \\n // below line is use to get the data from Firebase Firestore. \\n // previously we were saving data on a reference of Courses \\n // now we will be getting the data from the same reference. \\n db.collection(\\\"Courses\\\").get() \\n .addOnSuccessListener(new OnSuccessListener() { \\n @Override\\n public void onSuccess(QuerySnapshot queryDocumentSnapshots) { \\n // after getting the data we are calling on success method \\n // and inside this method we are checking if the received \\n // query snapshot is empty or not. \\n if (!queryDocumentSnapshots.isEmpty()) { \\n // if the snapshot is not empty we are \\n // hiding our progress bar and adding \\n // our data in a list. \\n loadingPB.setVisibility(View.GONE); \\n List list = queryDocumentSnapshots.getDocuments(); \\n for (DocumentSnapshot d : list) { \\n // after getting this list we are passing \\n // that list to our object class. \\n Courses c = d.toObject(Courses.class); \\n \\n // and we will pass this object class \\n // inside our arraylist which we have \\n // created for recycler view. \\n coursesArrayList.add(c); \\n } \\n // after adding the data to recycler view. \\n // we are calling recycler view notifuDataSetChanged \\n // method to notify that data has been changed in recycler view. \\n courseRVAdapter.notifyDataSetChanged(); \\n } else { \\n // if the snapshot is empty we are displaying a toast message. \\n Toast.makeText(CourseDetails.this, \\\"No data found in Database\\\", Toast.LENGTH_SHORT).show(); \\n } \\n } \\n }).addOnFailureListener(new OnFailureListener() { \\n @Override\\n public void onFailure(@NonNull Exception e) { \\n // if we do not get any data or any error we are displaying \\n // a toast message that we do not get any data \\n Toast.makeText(CourseDetails.this, \\\"Fail to get the data.\\\", Toast.LENGTH_SHORT).show(); \\n } \\n }); \\n } \\n}\\n\\n\\n\\n\\n\\n\",\n \"e\": 41109,\n \"s\": 36337,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 41157,\n \"s\": 41109,\n \"text\": \"Step 7: Working with the MainActivity.java file\"\n },\n {\n \"code\": null,\n \"e\": 41282,\n \"s\": 41157,\n \"text\": \"In the MainActivity.java file, we have to add an Intent to the CourseDetails.class file. Below is the code snippet to do so.\"\n },\n {\n \"code\": null,\n \"e\": 41287,\n \"s\": 41282,\n \"text\": \"Java\"\n },\n {\n \"code\": \"\\n\\n\\n\\n\\n\\n\\n// adding onclick listener to view data in new activity \\nviewCoursesBtn.setOnClickListener(new View.OnClickListener() { \\n @Override\\n public void onClick(View v) { \\n // opening a new activity on button click \\n Intent i = new Intent(MainActivity.this,CourseDetails.class); \\n startActivity(i); \\n } \\n });\\n\\n\\n\\n\\n\\n\",\n \"e\": 41691,\n \"s\": 41297,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 41749,\n \"s\": 41691,\n \"text\": \"Below is the updated code for the MainActivity.java file.\"\n },\n {\n \"code\": null,\n \"e\": 41754,\n \"s\": 41749,\n \"text\": \"Java\"\n },\n {\n \"code\": \"\\n\\n\\n\\n\\n\\n\\nimport android.content.Intent; \\nimport android.os.Bundle; \\nimport android.text.TextUtils; \\nimport android.view.View; \\nimport android.widget.Button; \\nimport android.widget.EditText; \\nimport android.widget.Toast; \\n \\nimport androidx.annotation.NonNull; \\nimport androidx.appcompat.app.AppCompatActivity; \\n \\nimport com.google.android.gms.tasks.OnFailureListener; \\nimport com.google.android.gms.tasks.OnSuccessListener; \\nimport com.google.firebase.firestore.CollectionReference; \\nimport com.google.firebase.firestore.DocumentReference; \\nimport com.google.firebase.firestore.FirebaseFirestore; \\n \\npublic class MainActivity extends AppCompatActivity { \\n \\n // creating variables for our edit text \\n private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt; \\n \\n // creating variable for button \\n private Button submitCourseBtn, viewCoursesBtn; \\n \\n // creating a strings for storing \\n // our values from edittext fields. \\n private String courseName, courseDuration, courseDescription; \\n \\n // creating a variable \\n // for firebasefirestore. \\n private FirebaseFirestore db; \\n \\n @Override\\n protected void onCreate(Bundle savedInstanceState) { \\n super.onCreate(savedInstanceState); \\n setContentView(R.layout.activity_main); \\n \\n // getting our instance \\n // from Firebase Firestore. \\n db = FirebaseFirestore.getInstance(); \\n \\n // initializing our edittext and buttons \\n courseNameEdt = findViewById(R.id.idEdtCourseName); \\n courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription); \\n courseDurationEdt = findViewById(R.id.idEdtCourseDuration); \\n submitCourseBtn = findViewById(R.id.idBtnSubmitCourse); \\n viewCoursesBtn = findViewById(R.id.idBtnViewCourses); \\n \\n // adding onclick listener to view data in new activity \\n viewCoursesBtn.setOnClickListener(new View.OnClickListener() { \\n @Override\\n public void onClick(View v) { \\n // opening a new activity on button click \\n Intent i = new Intent(MainActivity.this,CourseDetails.class); \\n startActivity(i); \\n } \\n }); \\n \\n // adding on click listener for button \\n submitCourseBtn.setOnClickListener(new View.OnClickListener() { \\n @Override\\n public void onClick(View v) { \\n \\n // getting data from edittext fields. \\n courseName = courseNameEdt.getText().toString(); \\n courseDescription = courseDescriptionEdt.getText().toString(); \\n courseDuration = courseDurationEdt.getText().toString(); \\n \\n // validating the text fields if empty or not. \\n if (TextUtils.isEmpty(courseName)) { \\n courseNameEdt.setError(\\\"Please enter Course Name\\\"); \\n } else if (TextUtils.isEmpty(courseDescription)) { \\n courseDescriptionEdt.setError(\\\"Please enter Course Description\\\"); \\n } else if (TextUtils.isEmpty(courseDuration)) { \\n courseDurationEdt.setError(\\\"Please enter Course Duration\\\"); \\n } else { \\n // calling method to add data to Firebase Firestore. \\n addDataToFirestore(courseName, courseDescription, courseDuration); \\n } \\n } \\n }); \\n } \\n \\n private void addDataToFirestore(String courseName, String courseDescription, String courseDuration) { \\n \\n // creating a collection reference \\n // for our Firebase Firetore database. \\n CollectionReference dbCourses = db.collection(\\\"Courses\\\"); \\n \\n // adding our data to our courses object class. \\n Courses courses = new Courses(courseName, courseDescription, courseDuration); \\n \\n // below method is use to add data to Firebase Firestore. \\n dbCourses.add(courses).addOnSuccessListener(new OnSuccessListener() { \\n @Override\\n public void onSuccess(DocumentReference documentReference) { \\n // after the data addition is successful \\n // we are displaying a success toast message. \\n Toast.makeText(MainActivity.this, \\\"Your Course has been added to Firebase Firestore\\\", Toast.LENGTH_SHORT).show(); \\n } \\n }).addOnFailureListener(new OnFailureListener() { \\n @Override\\n public void onFailure(@NonNull Exception e) { \\n // this method is called when the data addition process is failed. \\n // displaying a toast message when data addition is failed. \\n Toast.makeText(MainActivity.this, \\\"Fail to add course \\\\n\\\" + e, Toast.LENGTH_SHORT).show(); \\n } \\n }); \\n } \\n}\\n\\n\\n\\n\\n\\n\",\n \"e\": 46572,\n \"s\": 41764,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 46899,\n \"s\": 46572,\n \"text\": \"After completing this process we have to add the data from our app in Firebase Console and after that click on View Added Courses button you will get to see the list of courses that we have added inside our Firebase Console. Below is the image of how our Firebase Firestore database will look like for only one recycler item. \"\n },\n {\n \"code\": null,\n \"e\": 46966,\n \"s\": 46899,\n \"text\": \"After completing this Run your app and see the output of the code.\"\n },\n {\n \"code\": null,\n \"e\": 46976,\n \"s\": 46966,\n \"text\": \"\\nandroid\\n\"\n },\n {\n \"code\": null,\n \"e\": 47002,\n \"s\": 46976,\n \"text\": \"\\nTechnical Scripter 2020\\n\"\n },\n {\n \"code\": null,\n \"e\": 47012,\n \"s\": 47002,\n \"text\": \"\\nAndroid\\n\"\n },\n {\n \"code\": null,\n \"e\": 47019,\n \"s\": 47012,\n \"text\": \"\\nJava\\n\"\n },\n {\n \"code\": null,\n \"e\": 47040,\n \"s\": 47019,\n \"text\": \"\\nTechnical Scripter\\n\"\n },\n {\n \"code\": null,\n \"e\": 47245,\n \"s\": 47040,\n \"text\": \"Writing code in comment? \\n Please use ide.geeksforgeeks.org, \\n generate link and share the link here.\\n \"\n },\n {\n \"code\": null,\n \"e\": 47283,\n \"s\": 47245,\n \"text\": \"Resource Raw Folder in Android Studio\"\n },\n {\n \"code\": null,\n \"e\": 47322,\n \"s\": 47283,\n \"text\": \"Flutter - Custom Bottom Navigation Bar\"\n },\n {\n \"code\": null,\n \"e\": 47372,\n \"s\": 47322,\n \"text\": \"How to Read Data from SQLite Database in Android?\"\n },\n {\n \"code\": null,\n \"e\": 47414,\n \"s\": 47372,\n \"text\": \"Retrofit with Kotlin Coroutine in Android\"\n },\n {\n \"code\": null,\n \"e\": 47465,\n \"s\": 47414,\n \"text\": \"How to Post Data to API using Retrofit in Android?\"\n },\n {\n \"code\": null,\n \"e\": 47480,\n \"s\": 47465,\n \"text\": \"Arrays in Java\"\n },\n {\n \"code\": null,\n \"e\": 47524,\n \"s\": 47480,\n \"text\": \"Split() String method in Java with examples\"\n },\n {\n \"code\": null,\n \"e\": 47546,\n \"s\": 47524,\n \"text\": \"For-each loop in Java\"\n },\n {\n \"code\": null,\n \"e\": 47597,\n \"s\": 47546,\n \"text\": \"Object Oriented Programming (OOPs) Concept in Java\"\n }\n]"}}},{"rowIdx":435,"cells":{"title":{"kind":"string","value":"How to create a comment in a pull request using ocktokit? - GeeksforGeeks"},"text":{"kind":"string","value":"13 Dec, 2021\nIntroduction: The Octokit client can be used to send requests to GitHub’s REST API and queries to GitHub’s GraphQL API. The octokit package integrates the three main Octokit libraries:\nAPI client (REST API requests, GraphQL API queries, Authentication)App client (GitHub App & installations, Webhooks, OAuth)Action client (Pre-authenticated API client for single repository).\nAPI client (REST API requests, GraphQL API queries, Authentication)\nApp client (GitHub App & installations, Webhooks, OAuth)\nAction client (Pre-authenticated API client for single repository).\nApproach: We are going to create a script using Github’s API Client octokit/rest.js through which we will comment on a pull request as soon as it opened .\nBelow is the step-by-step implementation of the above approach.\n \nStep 1: Initialize a node project \nFirst of all the create a root folder named as GFG:\nmkdir GFG\nNavigate into the GFG folder:\ncd GFG\nInitialize this folder as a node repository:\nnpm init\nAfter this, you will find a package.json file at the root of your project.\nStep 2: Create a new Github action\nCreate a new file named as action.yml with the below content:\nname: 'GeeksForGeeks'\ndescription: 'Say \"GeeksForGeeks\" to new pull requests'\nauthor: '[GFG]'\n\ninputs:\n GITHUB_TOKEN:\n description: 'GitHub token'\n required: true\n\nruns:\n using: 'node12'\n main: 'dist/index.js' \nAn action is declared above with the name GeeksForGeeks taking one input GITHUB_TOKEN which should run in node12 version and the main entry point is set to ‘dist/index.js’.\nStep3: Create the base file for the app to run\nFirst of all install two dependencies to use ocktokit and context payloads of pull request.\nnpm install @actions/core @actions/github\nCreate a src directory. Then create an action.js file in src directory with the following content:\nJavascript\nconst core = require('@actions/core');const github = require('@actions/github');const { context } = require('@actions/github')const GITHUB_TOKEN = core.getInput('GITHUB_TOKEN');const octokit = github.getOctokit(GITHUB_TOKEN); const { pull_request } = context.payload; async function run() { await octokit.rest.issues.createComment({ ...context.repo, issue_number: pull_request.number, body: 'Thank you for submitting a pull request! We will try to review this as soon as we can.' });} run();\nWhat we are doing above is:\nAfter the two dependencies are installed they are imported into the file.\nconst core = require('@actions/core');\nconst github = require('@actions/github');\nIn each function which requires access to the github api, use the following to create octokit.\nconst GITHUB_TOKEN = core.getInput('GITHUB_TOKEN');\nconst octokit = github.getOctokit(GITHUB_TOKEN);\nNow as we have got the octokit instance, we can now create comment using Github API’s client ocktokit.\noctokit.rest.issues.createComment({\n owner,\n repo,\n issue_number,\n body,\n});\nStep 4: Building src/action.js with Vercel’s ncc\nWhile we’re not yet doing anything inside of our src/action.js that requires anything more than node to run, we’re going to set up our Action to build and compile into a dist folder which is what our Action will use to actually run the code.\nIf you remember, we set the main attribute inside of action.yml to dist/index.js!\nTo start, we can first install ncc from Vercel, which will take our scripts and dependencies and package it all up in one file for us.\nIn your terminal, install the file with:\nnpm install @vercel/ncc\nNext, inside of our package.json file, under the scripts object, let’s add a new script:\n\"scripts\": {\n \"build\": \"ncc build src/action.js -o dist\"\n ...,\n},\nThis sets up a new script so any time we run the build command, it will tell ncc to build our Action script and output it into the dist folder.\nWe can try it out by running:\nnpm run build\nAnd once it’s finished, you should now see a dist folder at the root of your project with an index.js file inside of it. If you look inside it, you might notice a bunch of weird-looking code. ncc uses webpack to compile our script so that it’s able to be used as a module, allowing different processes to understand it. The reason we’re compiling our script is when GitHub tries to use our Action from another repository, it doesn’t have all of the dependencies available. Packaging it up in a single file allows our script to work with just that one file!\nOutput:\nrkbhola5\nGitHub\nJavaScript-Questions\nNodeJS-Questions\nJavaScript\nNode.js\nWeb Technologies\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nRemove elements from a JavaScript Array\nDifference between var, let and const keywords in JavaScript\nDifference Between PUT and PATCH Request\nJavaScript | Promises\nHow to get character array from string in JavaScript?\nInstallation of Node.js on Linux\nHow to update Node.js and NPM to next version ?\nNode.js fs.readFileSync() Method\nNode.js fs.writeFile() Method\nNode.js fs.readFile() Method"},"parsed":{"kind":"list like","value":[{"code":null,"e":26915,"s":26887,"text":"\n13 Dec, 2021"},{"code":null,"e":27100,"s":26915,"text":"Introduction: The Octokit client can be used to send requests to GitHub’s REST API and queries to GitHub’s GraphQL API. The octokit package integrates the three main Octokit libraries:"},{"code":null,"e":27291,"s":27100,"text":"API client (REST API requests, GraphQL API queries, Authentication)App client (GitHub App & installations, Webhooks, OAuth)Action client (Pre-authenticated API client for single repository)."},{"code":null,"e":27359,"s":27291,"text":"API client (REST API requests, GraphQL API queries, Authentication)"},{"code":null,"e":27416,"s":27359,"text":"App client (GitHub App & installations, Webhooks, OAuth)"},{"code":null,"e":27484,"s":27416,"text":"Action client (Pre-authenticated API client for single repository)."},{"code":null,"e":27640,"s":27484,"text":"Approach: We are going to create a script using Github’s API Client octokit/rest.js through which we will comment on a pull request as soon as it opened ."},{"code":null,"e":27704,"s":27640,"text":"Below is the step-by-step implementation of the above approach."},{"code":null,"e":27741,"s":27706,"text":"Step 1: Initialize a node project "},{"code":null,"e":27793,"s":27741,"text":"First of all the create a root folder named as GFG:"},{"code":null,"e":27803,"s":27793,"text":"mkdir GFG"},{"code":null,"e":27833,"s":27803,"text":"Navigate into the GFG folder:"},{"code":null,"e":27840,"s":27833,"text":"cd GFG"},{"code":null,"e":27885,"s":27840,"text":"Initialize this folder as a node repository:"},{"code":null,"e":27894,"s":27885,"text":"npm init"},{"code":null,"e":27969,"s":27894,"text":"After this, you will find a package.json file at the root of your project."},{"code":null,"e":28004,"s":27969,"text":"Step 2: Create a new Github action"},{"code":null,"e":28066,"s":28004,"text":"Create a new file named as action.yml with the below content:"},{"code":null,"e":28286,"s":28066,"text":"name: 'GeeksForGeeks'\ndescription: 'Say \"GeeksForGeeks\" to new pull requests'\nauthor: '[GFG]'\n\ninputs:\n GITHUB_TOKEN:\n description: 'GitHub token'\n required: true\n\nruns:\n using: 'node12'\n main: 'dist/index.js' "},{"code":null,"e":28459,"s":28286,"text":"An action is declared above with the name GeeksForGeeks taking one input GITHUB_TOKEN which should run in node12 version and the main entry point is set to ‘dist/index.js’."},{"code":null,"e":28506,"s":28459,"text":"Step3: Create the base file for the app to run"},{"code":null,"e":28598,"s":28506,"text":"First of all install two dependencies to use ocktokit and context payloads of pull request."},{"code":null,"e":28640,"s":28598,"text":"npm install @actions/core @actions/github"},{"code":null,"e":28739,"s":28640,"text":"Create a src directory. Then create an action.js file in src directory with the following content:"},{"code":null,"e":28750,"s":28739,"text":"Javascript"},{"code":"const core = require('@actions/core');const github = require('@actions/github');const { context } = require('@actions/github')const GITHUB_TOKEN = core.getInput('GITHUB_TOKEN');const octokit = github.getOctokit(GITHUB_TOKEN); const { pull_request } = context.payload; async function run() { await octokit.rest.issues.createComment({ ...context.repo, issue_number: pull_request.number, body: 'Thank you for submitting a pull request! We will try to review this as soon as we can.' });} run();","e":29265,"s":28750,"text":null},{"code":null,"e":29293,"s":29265,"text":"What we are doing above is:"},{"code":null,"e":29367,"s":29293,"text":"After the two dependencies are installed they are imported into the file."},{"code":null,"e":29449,"s":29367,"text":"const core = require('@actions/core');\nconst github = require('@actions/github');"},{"code":null,"e":29544,"s":29449,"text":"In each function which requires access to the github api, use the following to create octokit."},{"code":null,"e":29645,"s":29544,"text":"const GITHUB_TOKEN = core.getInput('GITHUB_TOKEN');\nconst octokit = github.getOctokit(GITHUB_TOKEN);"},{"code":null,"e":29748,"s":29645,"text":"Now as we have got the octokit instance, we can now create comment using Github API’s client ocktokit."},{"code":null,"e":29829,"s":29748,"text":"octokit.rest.issues.createComment({\n owner,\n repo,\n issue_number,\n body,\n});"},{"code":null,"e":29878,"s":29829,"text":"Step 4: Building src/action.js with Vercel’s ncc"},{"code":null,"e":30120,"s":29878,"text":"While we’re not yet doing anything inside of our src/action.js that requires anything more than node to run, we’re going to set up our Action to build and compile into a dist folder which is what our Action will use to actually run the code."},{"code":null,"e":30202,"s":30120,"text":"If you remember, we set the main attribute inside of action.yml to dist/index.js!"},{"code":null,"e":30337,"s":30202,"text":"To start, we can first install ncc from Vercel, which will take our scripts and dependencies and package it all up in one file for us."},{"code":null,"e":30378,"s":30337,"text":"In your terminal, install the file with:"},{"code":null,"e":30402,"s":30378,"text":"npm install @vercel/ncc"},{"code":null,"e":30491,"s":30402,"text":"Next, inside of our package.json file, under the scripts object, let’s add a new script:"},{"code":null,"e":30557,"s":30491,"text":"\"scripts\": {\n \"build\": \"ncc build src/action.js -o dist\"\n ...,\n},"},{"code":null,"e":30701,"s":30557,"text":"This sets up a new script so any time we run the build command, it will tell ncc to build our Action script and output it into the dist folder."},{"code":null,"e":30731,"s":30701,"text":"We can try it out by running:"},{"code":null,"e":30745,"s":30731,"text":"npm run build"},{"code":null,"e":31302,"s":30745,"text":"And once it’s finished, you should now see a dist folder at the root of your project with an index.js file inside of it. If you look inside it, you might notice a bunch of weird-looking code. ncc uses webpack to compile our script so that it’s able to be used as a module, allowing different processes to understand it. The reason we’re compiling our script is when GitHub tries to use our Action from another repository, it doesn’t have all of the dependencies available. Packaging it up in a single file allows our script to work with just that one file!"},{"code":null,"e":31310,"s":31302,"text":"Output:"},{"code":null,"e":31319,"s":31310,"text":"rkbhola5"},{"code":null,"e":31326,"s":31319,"text":"GitHub"},{"code":null,"e":31347,"s":31326,"text":"JavaScript-Questions"},{"code":null,"e":31364,"s":31347,"text":"NodeJS-Questions"},{"code":null,"e":31375,"s":31364,"text":"JavaScript"},{"code":null,"e":31383,"s":31375,"text":"Node.js"},{"code":null,"e":31400,"s":31383,"text":"Web Technologies"},{"code":null,"e":31498,"s":31400,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":31538,"s":31498,"text":"Remove elements from a JavaScript Array"},{"code":null,"e":31599,"s":31538,"text":"Difference between var, let and const keywords in JavaScript"},{"code":null,"e":31640,"s":31599,"text":"Difference Between PUT and PATCH Request"},{"code":null,"e":31662,"s":31640,"text":"JavaScript | Promises"},{"code":null,"e":31716,"s":31662,"text":"How to get character array from string in JavaScript?"},{"code":null,"e":31749,"s":31716,"text":"Installation of Node.js on Linux"},{"code":null,"e":31797,"s":31749,"text":"How to update Node.js and NPM to next version ?"},{"code":null,"e":31830,"s":31797,"text":"Node.js fs.readFileSync() Method"},{"code":null,"e":31860,"s":31830,"text":"Node.js fs.writeFile() Method"}],"string":"[\n {\n \"code\": null,\n \"e\": 26915,\n \"s\": 26887,\n \"text\": \"\\n13 Dec, 2021\"\n },\n {\n \"code\": null,\n \"e\": 27100,\n \"s\": 26915,\n \"text\": \"Introduction: The Octokit client can be used to send requests to GitHub’s REST API and queries to GitHub’s GraphQL API. The octokit package integrates the three main Octokit libraries:\"\n },\n {\n \"code\": null,\n \"e\": 27291,\n \"s\": 27100,\n \"text\": \"API client (REST API requests, GraphQL API queries, Authentication)App client (GitHub App & installations, Webhooks, OAuth)Action client (Pre-authenticated API client for single repository).\"\n },\n {\n \"code\": null,\n \"e\": 27359,\n \"s\": 27291,\n \"text\": \"API client (REST API requests, GraphQL API queries, Authentication)\"\n },\n {\n \"code\": null,\n \"e\": 27416,\n \"s\": 27359,\n \"text\": \"App client (GitHub App & installations, Webhooks, OAuth)\"\n },\n {\n \"code\": null,\n \"e\": 27484,\n \"s\": 27416,\n \"text\": \"Action client (Pre-authenticated API client for single repository).\"\n },\n {\n \"code\": null,\n \"e\": 27640,\n \"s\": 27484,\n \"text\": \"Approach: We are going to create a script using Github’s API Client octokit/rest.js through which we will comment on a pull request as soon as it opened .\"\n },\n {\n \"code\": null,\n \"e\": 27704,\n \"s\": 27640,\n \"text\": \"Below is the step-by-step implementation of the above approach.\"\n },\n {\n \"code\": null,\n \"e\": 27741,\n \"s\": 27706,\n \"text\": \"Step 1: Initialize a node project \"\n },\n {\n \"code\": null,\n \"e\": 27793,\n \"s\": 27741,\n \"text\": \"First of all the create a root folder named as GFG:\"\n },\n {\n \"code\": null,\n \"e\": 27803,\n \"s\": 27793,\n \"text\": \"mkdir GFG\"\n },\n {\n \"code\": null,\n \"e\": 27833,\n \"s\": 27803,\n \"text\": \"Navigate into the GFG folder:\"\n },\n {\n \"code\": null,\n \"e\": 27840,\n \"s\": 27833,\n \"text\": \"cd GFG\"\n },\n {\n \"code\": null,\n \"e\": 27885,\n \"s\": 27840,\n \"text\": \"Initialize this folder as a node repository:\"\n },\n {\n \"code\": null,\n \"e\": 27894,\n \"s\": 27885,\n \"text\": \"npm init\"\n },\n {\n \"code\": null,\n \"e\": 27969,\n \"s\": 27894,\n \"text\": \"After this, you will find a package.json file at the root of your project.\"\n },\n {\n \"code\": null,\n \"e\": 28004,\n \"s\": 27969,\n \"text\": \"Step 2: Create a new Github action\"\n },\n {\n \"code\": null,\n \"e\": 28066,\n \"s\": 28004,\n \"text\": \"Create a new file named as action.yml with the below content:\"\n },\n {\n \"code\": null,\n \"e\": 28286,\n \"s\": 28066,\n \"text\": \"name: 'GeeksForGeeks'\\ndescription: 'Say \\\"GeeksForGeeks\\\" to new pull requests'\\nauthor: '[GFG]'\\n\\ninputs:\\n GITHUB_TOKEN:\\n description: 'GitHub token'\\n required: true\\n\\nruns:\\n using: 'node12'\\n main: 'dist/index.js' \"\n },\n {\n \"code\": null,\n \"e\": 28459,\n \"s\": 28286,\n \"text\": \"An action is declared above with the name GeeksForGeeks taking one input GITHUB_TOKEN which should run in node12 version and the main entry point is set to ‘dist/index.js’.\"\n },\n {\n \"code\": null,\n \"e\": 28506,\n \"s\": 28459,\n \"text\": \"Step3: Create the base file for the app to run\"\n },\n {\n \"code\": null,\n \"e\": 28598,\n \"s\": 28506,\n \"text\": \"First of all install two dependencies to use ocktokit and context payloads of pull request.\"\n },\n {\n \"code\": null,\n \"e\": 28640,\n \"s\": 28598,\n \"text\": \"npm install @actions/core @actions/github\"\n },\n {\n \"code\": null,\n \"e\": 28739,\n \"s\": 28640,\n \"text\": \"Create a src directory. Then create an action.js file in src directory with the following content:\"\n },\n {\n \"code\": null,\n \"e\": 28750,\n \"s\": 28739,\n \"text\": \"Javascript\"\n },\n {\n \"code\": \"const core = require('@actions/core');const github = require('@actions/github');const { context } = require('@actions/github')const GITHUB_TOKEN = core.getInput('GITHUB_TOKEN');const octokit = github.getOctokit(GITHUB_TOKEN); const { pull_request } = context.payload; async function run() { await octokit.rest.issues.createComment({ ...context.repo, issue_number: pull_request.number, body: 'Thank you for submitting a pull request! We will try to review this as soon as we can.' });} run();\",\n \"e\": 29265,\n \"s\": 28750,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 29293,\n \"s\": 29265,\n \"text\": \"What we are doing above is:\"\n },\n {\n \"code\": null,\n \"e\": 29367,\n \"s\": 29293,\n \"text\": \"After the two dependencies are installed they are imported into the file.\"\n },\n {\n \"code\": null,\n \"e\": 29449,\n \"s\": 29367,\n \"text\": \"const core = require('@actions/core');\\nconst github = require('@actions/github');\"\n },\n {\n \"code\": null,\n \"e\": 29544,\n \"s\": 29449,\n \"text\": \"In each function which requires access to the github api, use the following to create octokit.\"\n },\n {\n \"code\": null,\n \"e\": 29645,\n \"s\": 29544,\n \"text\": \"const GITHUB_TOKEN = core.getInput('GITHUB_TOKEN');\\nconst octokit = github.getOctokit(GITHUB_TOKEN);\"\n },\n {\n \"code\": null,\n \"e\": 29748,\n \"s\": 29645,\n \"text\": \"Now as we have got the octokit instance, we can now create comment using Github API’s client ocktokit.\"\n },\n {\n \"code\": null,\n \"e\": 29829,\n \"s\": 29748,\n \"text\": \"octokit.rest.issues.createComment({\\n owner,\\n repo,\\n issue_number,\\n body,\\n});\"\n },\n {\n \"code\": null,\n \"e\": 29878,\n \"s\": 29829,\n \"text\": \"Step 4: Building src/action.js with Vercel’s ncc\"\n },\n {\n \"code\": null,\n \"e\": 30120,\n \"s\": 29878,\n \"text\": \"While we’re not yet doing anything inside of our src/action.js that requires anything more than node to run, we’re going to set up our Action to build and compile into a dist folder which is what our Action will use to actually run the code.\"\n },\n {\n \"code\": null,\n \"e\": 30202,\n \"s\": 30120,\n \"text\": \"If you remember, we set the main attribute inside of action.yml to dist/index.js!\"\n },\n {\n \"code\": null,\n \"e\": 30337,\n \"s\": 30202,\n \"text\": \"To start, we can first install ncc from Vercel, which will take our scripts and dependencies and package it all up in one file for us.\"\n },\n {\n \"code\": null,\n \"e\": 30378,\n \"s\": 30337,\n \"text\": \"In your terminal, install the file with:\"\n },\n {\n \"code\": null,\n \"e\": 30402,\n \"s\": 30378,\n \"text\": \"npm install @vercel/ncc\"\n },\n {\n \"code\": null,\n \"e\": 30491,\n \"s\": 30402,\n \"text\": \"Next, inside of our package.json file, under the scripts object, let’s add a new script:\"\n },\n {\n \"code\": null,\n \"e\": 30557,\n \"s\": 30491,\n \"text\": \"\\\"scripts\\\": {\\n \\\"build\\\": \\\"ncc build src/action.js -o dist\\\"\\n ...,\\n},\"\n },\n {\n \"code\": null,\n \"e\": 30701,\n \"s\": 30557,\n \"text\": \"This sets up a new script so any time we run the build command, it will tell ncc to build our Action script and output it into the dist folder.\"\n },\n {\n \"code\": null,\n \"e\": 30731,\n \"s\": 30701,\n \"text\": \"We can try it out by running:\"\n },\n {\n \"code\": null,\n \"e\": 30745,\n \"s\": 30731,\n \"text\": \"npm run build\"\n },\n {\n \"code\": null,\n \"e\": 31302,\n \"s\": 30745,\n \"text\": \"And once it’s finished, you should now see a dist folder at the root of your project with an index.js file inside of it. If you look inside it, you might notice a bunch of weird-looking code. ncc uses webpack to compile our script so that it’s able to be used as a module, allowing different processes to understand it. The reason we’re compiling our script is when GitHub tries to use our Action from another repository, it doesn’t have all of the dependencies available. Packaging it up in a single file allows our script to work with just that one file!\"\n },\n {\n \"code\": null,\n \"e\": 31310,\n \"s\": 31302,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 31319,\n \"s\": 31310,\n \"text\": \"rkbhola5\"\n },\n {\n \"code\": null,\n \"e\": 31326,\n \"s\": 31319,\n \"text\": \"GitHub\"\n },\n {\n \"code\": null,\n \"e\": 31347,\n \"s\": 31326,\n \"text\": \"JavaScript-Questions\"\n },\n {\n \"code\": null,\n \"e\": 31364,\n \"s\": 31347,\n \"text\": \"NodeJS-Questions\"\n },\n {\n \"code\": null,\n \"e\": 31375,\n \"s\": 31364,\n \"text\": \"JavaScript\"\n },\n {\n \"code\": null,\n \"e\": 31383,\n \"s\": 31375,\n \"text\": \"Node.js\"\n },\n {\n \"code\": null,\n \"e\": 31400,\n \"s\": 31383,\n \"text\": \"Web Technologies\"\n },\n {\n \"code\": null,\n \"e\": 31498,\n \"s\": 31400,\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\": 31538,\n \"s\": 31498,\n \"text\": \"Remove elements from a JavaScript Array\"\n },\n {\n \"code\": null,\n \"e\": 31599,\n \"s\": 31538,\n \"text\": \"Difference between var, let and const keywords in JavaScript\"\n },\n {\n \"code\": null,\n \"e\": 31640,\n \"s\": 31599,\n \"text\": \"Difference Between PUT and PATCH Request\"\n },\n {\n \"code\": null,\n \"e\": 31662,\n \"s\": 31640,\n \"text\": \"JavaScript | Promises\"\n },\n {\n \"code\": null,\n \"e\": 31716,\n \"s\": 31662,\n \"text\": \"How to get character array from string in JavaScript?\"\n },\n {\n \"code\": null,\n \"e\": 31749,\n \"s\": 31716,\n \"text\": \"Installation of Node.js on Linux\"\n },\n {\n \"code\": null,\n \"e\": 31797,\n \"s\": 31749,\n \"text\": \"How to update Node.js and NPM to next version ?\"\n },\n {\n \"code\": null,\n \"e\": 31830,\n \"s\": 31797,\n \"text\": \"Node.js fs.readFileSync() Method\"\n },\n {\n \"code\": null,\n \"e\": 31860,\n \"s\": 31830,\n \"text\": \"Node.js fs.writeFile() Method\"\n }\n]"}}},{"rowIdx":436,"cells":{"title":{"kind":"string","value":"Explaining Your Machine Learning Models with SHAP and LIME! | by David Hundley | Towards Data Science"},"text":{"kind":"string","value":"Hello there all! Welcome back again to another data science quick tip. This particular post is most interesting for me not only because this is the most complex subject we’ve tackled to date, but it’s also one that I just spent the last few hours learning myself. And of course, what better way to learn than to figure out how to teach it to the masses?\nBefore getting into it, I’ve uploaded all the work shown in this post to a singular Jupyter notebook. You can find it at my personal GitHub if you’d like to follow along more closely.\nSo even though this is a very complex topic behind the scenes, I’m going to intentionally dial it down as much as possible for the widest possible audience. Even though this is ultimately a post designed for data science practitioners, I think it’s equally important for any business person to understand why they should care about this topic.\nPrior to jumping into how to calculate/visualize these values, let’s build some intuition on why would we would even care about this topic.\nIf you’re familiar at all with machine learning in general, you know that you pop some data into a predictive model and that it produces an outputted prediction on the other side. But let’s be honest: do you know what’s really going on inside in that model? Remember, we’re talking about algorithms doing a lot of fancy math under the hood. In reality, this is probably what your ML model looks like to you right now:\nYou really have no idea what’s going on in that black box. The math totally obscures how important those features are in your model. So what if Features 1 and 2 are carrying all the weight and that Features 3 and 4 are not adding any value at all to the model? What you’d prefer to see is something that looks more like this:\nOkay, we’re obviously using layman’s terms in our example here. But this stuff is important because if your models are relying on one 1 or 2 features to be doing all the predictive power, that might indicate something is wrong. It also might indicate that you’re using some sort of feature that may be considered to be morally incorrect. For example, many companies today will steer clear of using things like gender or ethnicity within their models because they tend to produce a lot of undesired bias in a model.\nUnderstanding these concepts always makes more sense through a tangible example, so we’re going to return to the dataset we’ve been using the last few posts to concretely demo both SHAP and LIME: the Titanic dataset.\nAlright, so in the last few post where we’ve used the Titanic dataset, we created models that were pretty poor since our focus was more on learning a new skill. In order to effectively demo both SHAP and LIME, we really need a model that shows some level of “trying” (?) so that we can see how ML explainability will play out. Now, I’m not going to spend time in this post showing you all my code for that data cleansing and modeling piece (which you can definitely find in my GitHub here), but I’ll summarize quickly the features that go into producing the end model.\nPClass: Notes the ticket class the person boarded the ship with. (Either 1st, 2nd, or 3rd.)\nAge Bins: Based on the person’s age, they are segmented into general people groups. These groups include child, teen, young adult, adult, elder, and unknown.\nSex (Gender): Notes whether the person is male or female.\nCabin Section: If the person had a cabin, I pulled out what section they might be in. These can either be A, B, C, or no cabin.\nEmbarked: Notes one of three locations from which the person originally departed.\nSibSp (Sibling / Spouse): Notes how many siblings and/or spouses the person had onboard the ship with them.\nParch (Parent / Child): Notes how many parents / children the person had onboard the ship with them.\nFor the actual model itself, I’m choosing to use a simple Random Forest Classifier from Scikit-Learn. Splitting the data into training and validation sets, I get the following metrics with the validation set:\nThe metrics aren’t exactly great, but that’s fine for our learning here. At least we’ll get to see in the next section how important these features necessarily are. Let’s move on!\nAt this point, we currently have no idea how our Random Forest model is using the features to make its predictions. I’m going to wager a guess that Sex and Age Bin are influential factors, but we don’t know that quite yet.\nThis is where smart people developed complex algorithms based on game theory to generate these things to better explain our current black box. Of course, I’m referring to SHAP and LIME. Now, I’m going to be 100% honest: I’m not very familiar with how these algorithms work under the hood, so I’m not even going to attempt to do that in this post. Instead, I’ll point you to this post about SHAP and this other post about LIME.\nJust like Scikit-Learn abstracts away the underlying algorithms for our Random Forest classifier, there are some neat Python libraries that we’ll use that abstract away the inner workings of both SHAP and LIME. To use those, all you need to do is a simple pip install for both:\npip install shappip install lime\nAt a high level, the way both of these work is that you give your training data and model to an “explainer”, and then you’re later able to pass any observation to the “explainer” which will tell you the feature importance of that model. That might sound like gobbledegook right now, but we’ll make this extra clear with our Titanic example!\nFirst, we need to pull two people from our validation set that we know respectively did not survive and survive. The reason for this is because we’re going to run these through our SHAP and LIME explainers to understand which characteristics about these people had the most influence for survivability according to our model. (Again, you can see this work in my notebook.)\nLet’s start off with SHAP. The syntax here is pretty simple. We’ll first instantiate the SHAP explainer object, fit our Random Forest Classifier (rfc) to the object, and plug in each respective person to generate their explainable SHAP values. The code below shows you how to do it for person 1. To do the same for person 2, simply swap out the appropriate values.\n# Importing the SHAP libraryimport shap# Instantiating the SHAP explainer using our trained RFC modelshap_explainer = shap.TreeExplainer(rfc)shap.initjs()# Getting SHAP values for person 1person_1_shap_values = shap_explainer.shap_values(person_1)# Visualizing plot of expected survivability of person 1shap.force_plot(shap_explainer.expected_value[1], person_1_shap_values[1], person_1)# Visualizing impact of each feature for person 1shap.summary_plot(person_1_shap_values, person_1)\nAnd that’s really all there is to it! Let’s take a look at the actual output from what we just did above in the screenshots below. First up, person 1.\nAccording to the top visual, our model predicted a 94% chance that person 1 survived, which is correct. It’s a little difficult to read, but look at the second visual, it looks like the most influential factors included the gender of the person, whether or not the person had a 3rd class ticket, and if the person was a child. In this case, person 1 was a female child, so those two factors alone drove our model most to say yes, this person probably survived.\nLet’s look at person 2 now.\nOur model here predicted that the person probably did not survive, and it is unfortunately correct. Again looking at the influential factors here, it looks like person 2 here was an adult male that did not have a cabin. I’m no history buff, but I would guess women and children were rescued off the boat first, so it makes a lot of sense to me that person 1 (a female child) did survive and person 2 (a male adult) did not.\nAlright, let’s move onto our LIME explainer!\nThe syntax for using LIME is a little bit different, but conceptually speaking, both SHAP and LIME are doing a lot of similar stuff.\n# Importing LIMEimport lime.lime_tabular# Defining our LIME explainerlime_explainer = lime.lime_tabular.LimeTabularExplainer(X_train.values, mode = 'classification', feature_names = X_train.columns, class_names = ['Did Not Survive', 'Survived'])# Defining a quick function that can be used to explain the instance passedpredict_rfc_prob = lambda x: rfc.predict_proba(x).astype(float)# Viewing LIME explainability for person 1person_1_lime = lime_explainer.explain_instance(person_1.iloc[0].values, predict_rfc_prob, num_features = 10)person_1_lime.show_in_notebook()\nLet’s take a look at what LIME shows us for each person.\nI’m a little biased here, but I think the UI for these LIME values is a lot easier to read that SHAP. We see the same prediction probabilities for whether each person did or did not survive. In the center, we see how influential the top 10 features were. Compared to SHAP, LIME has a tiny difference in its explainability, but they’re largely the same. We again see that Sex is a huge influencing factor here as well as whether or not the person was a child. On the right, they nicely display the precise values for this particular observation.\nSo which one is better: SHAP or LIME? I’m going to say neither. While each complement each other quite well, I think it’s important to show your business users both just to give them the best picture on which features are most explainable. I don’t think anybody can definitively say either SHAP or LIME is always more accurate, so show them both. The syntax is easy enough to chug out, anyway!\nThat wraps up another post! Hope you all enjoyed this one. I’d say this one has been my favorite to learn and write about so far, and I look forward to applying this in my own work moving forward. Catch you all in the next post!"},"parsed":{"kind":"list like","value":[{"code":null,"e":526,"s":172,"text":"Hello there all! Welcome back again to another data science quick tip. This particular post is most interesting for me not only because this is the most complex subject we’ve tackled to date, but it’s also one that I just spent the last few hours learning myself. And of course, what better way to learn than to figure out how to teach it to the masses?"},{"code":null,"e":710,"s":526,"text":"Before getting into it, I’ve uploaded all the work shown in this post to a singular Jupyter notebook. You can find it at my personal GitHub if you’d like to follow along more closely."},{"code":null,"e":1054,"s":710,"text":"So even though this is a very complex topic behind the scenes, I’m going to intentionally dial it down as much as possible for the widest possible audience. Even though this is ultimately a post designed for data science practitioners, I think it’s equally important for any business person to understand why they should care about this topic."},{"code":null,"e":1194,"s":1054,"text":"Prior to jumping into how to calculate/visualize these values, let’s build some intuition on why would we would even care about this topic."},{"code":null,"e":1612,"s":1194,"text":"If you’re familiar at all with machine learning in general, you know that you pop some data into a predictive model and that it produces an outputted prediction on the other side. But let’s be honest: do you know what’s really going on inside in that model? Remember, we’re talking about algorithms doing a lot of fancy math under the hood. In reality, this is probably what your ML model looks like to you right now:"},{"code":null,"e":1938,"s":1612,"text":"You really have no idea what’s going on in that black box. The math totally obscures how important those features are in your model. So what if Features 1 and 2 are carrying all the weight and that Features 3 and 4 are not adding any value at all to the model? What you’d prefer to see is something that looks more like this:"},{"code":null,"e":2453,"s":1938,"text":"Okay, we’re obviously using layman’s terms in our example here. But this stuff is important because if your models are relying on one 1 or 2 features to be doing all the predictive power, that might indicate something is wrong. It also might indicate that you’re using some sort of feature that may be considered to be morally incorrect. For example, many companies today will steer clear of using things like gender or ethnicity within their models because they tend to produce a lot of undesired bias in a model."},{"code":null,"e":2670,"s":2453,"text":"Understanding these concepts always makes more sense through a tangible example, so we’re going to return to the dataset we’ve been using the last few posts to concretely demo both SHAP and LIME: the Titanic dataset."},{"code":null,"e":3239,"s":2670,"text":"Alright, so in the last few post where we’ve used the Titanic dataset, we created models that were pretty poor since our focus was more on learning a new skill. In order to effectively demo both SHAP and LIME, we really need a model that shows some level of “trying” (?) so that we can see how ML explainability will play out. Now, I’m not going to spend time in this post showing you all my code for that data cleansing and modeling piece (which you can definitely find in my GitHub here), but I’ll summarize quickly the features that go into producing the end model."},{"code":null,"e":3331,"s":3239,"text":"PClass: Notes the ticket class the person boarded the ship with. (Either 1st, 2nd, or 3rd.)"},{"code":null,"e":3489,"s":3331,"text":"Age Bins: Based on the person’s age, they are segmented into general people groups. These groups include child, teen, young adult, adult, elder, and unknown."},{"code":null,"e":3547,"s":3489,"text":"Sex (Gender): Notes whether the person is male or female."},{"code":null,"e":3675,"s":3547,"text":"Cabin Section: If the person had a cabin, I pulled out what section they might be in. These can either be A, B, C, or no cabin."},{"code":null,"e":3757,"s":3675,"text":"Embarked: Notes one of three locations from which the person originally departed."},{"code":null,"e":3865,"s":3757,"text":"SibSp (Sibling / Spouse): Notes how many siblings and/or spouses the person had onboard the ship with them."},{"code":null,"e":3966,"s":3865,"text":"Parch (Parent / Child): Notes how many parents / children the person had onboard the ship with them."},{"code":null,"e":4175,"s":3966,"text":"For the actual model itself, I’m choosing to use a simple Random Forest Classifier from Scikit-Learn. Splitting the data into training and validation sets, I get the following metrics with the validation set:"},{"code":null,"e":4355,"s":4175,"text":"The metrics aren’t exactly great, but that’s fine for our learning here. At least we’ll get to see in the next section how important these features necessarily are. Let’s move on!"},{"code":null,"e":4578,"s":4355,"text":"At this point, we currently have no idea how our Random Forest model is using the features to make its predictions. I’m going to wager a guess that Sex and Age Bin are influential factors, but we don’t know that quite yet."},{"code":null,"e":5005,"s":4578,"text":"This is where smart people developed complex algorithms based on game theory to generate these things to better explain our current black box. Of course, I’m referring to SHAP and LIME. Now, I’m going to be 100% honest: I’m not very familiar with how these algorithms work under the hood, so I’m not even going to attempt to do that in this post. Instead, I’ll point you to this post about SHAP and this other post about LIME."},{"code":null,"e":5283,"s":5005,"text":"Just like Scikit-Learn abstracts away the underlying algorithms for our Random Forest classifier, there are some neat Python libraries that we’ll use that abstract away the inner workings of both SHAP and LIME. To use those, all you need to do is a simple pip install for both:"},{"code":null,"e":5316,"s":5283,"text":"pip install shappip install lime"},{"code":null,"e":5657,"s":5316,"text":"At a high level, the way both of these work is that you give your training data and model to an “explainer”, and then you’re later able to pass any observation to the “explainer” which will tell you the feature importance of that model. That might sound like gobbledegook right now, but we’ll make this extra clear with our Titanic example!"},{"code":null,"e":6030,"s":5657,"text":"First, we need to pull two people from our validation set that we know respectively did not survive and survive. The reason for this is because we’re going to run these through our SHAP and LIME explainers to understand which characteristics about these people had the most influence for survivability according to our model. (Again, you can see this work in my notebook.)"},{"code":null,"e":6395,"s":6030,"text":"Let’s start off with SHAP. The syntax here is pretty simple. We’ll first instantiate the SHAP explainer object, fit our Random Forest Classifier (rfc) to the object, and plug in each respective person to generate their explainable SHAP values. The code below shows you how to do it for person 1. To do the same for person 2, simply swap out the appropriate values."},{"code":null,"e":6881,"s":6395,"text":"# Importing the SHAP libraryimport shap# Instantiating the SHAP explainer using our trained RFC modelshap_explainer = shap.TreeExplainer(rfc)shap.initjs()# Getting SHAP values for person 1person_1_shap_values = shap_explainer.shap_values(person_1)# Visualizing plot of expected survivability of person 1shap.force_plot(shap_explainer.expected_value[1], person_1_shap_values[1], person_1)# Visualizing impact of each feature for person 1shap.summary_plot(person_1_shap_values, person_1)"},{"code":null,"e":7032,"s":6881,"text":"And that’s really all there is to it! Let’s take a look at the actual output from what we just did above in the screenshots below. First up, person 1."},{"code":null,"e":7493,"s":7032,"text":"According to the top visual, our model predicted a 94% chance that person 1 survived, which is correct. It’s a little difficult to read, but look at the second visual, it looks like the most influential factors included the gender of the person, whether or not the person had a 3rd class ticket, and if the person was a child. In this case, person 1 was a female child, so those two factors alone drove our model most to say yes, this person probably survived."},{"code":null,"e":7521,"s":7493,"text":"Let’s look at person 2 now."},{"code":null,"e":7945,"s":7521,"text":"Our model here predicted that the person probably did not survive, and it is unfortunately correct. Again looking at the influential factors here, it looks like person 2 here was an adult male that did not have a cabin. I’m no history buff, but I would guess women and children were rescued off the boat first, so it makes a lot of sense to me that person 1 (a female child) did survive and person 2 (a male adult) did not."},{"code":null,"e":7990,"s":7945,"text":"Alright, let’s move onto our LIME explainer!"},{"code":null,"e":8123,"s":7990,"text":"The syntax for using LIME is a little bit different, but conceptually speaking, both SHAP and LIME are doing a lot of similar stuff."},{"code":null,"e":8690,"s":8123,"text":"# Importing LIMEimport lime.lime_tabular# Defining our LIME explainerlime_explainer = lime.lime_tabular.LimeTabularExplainer(X_train.values, mode = 'classification', feature_names = X_train.columns, class_names = ['Did Not Survive', 'Survived'])# Defining a quick function that can be used to explain the instance passedpredict_rfc_prob = lambda x: rfc.predict_proba(x).astype(float)# Viewing LIME explainability for person 1person_1_lime = lime_explainer.explain_instance(person_1.iloc[0].values, predict_rfc_prob, num_features = 10)person_1_lime.show_in_notebook()"},{"code":null,"e":8747,"s":8690,"text":"Let’s take a look at what LIME shows us for each person."},{"code":null,"e":9292,"s":8747,"text":"I’m a little biased here, but I think the UI for these LIME values is a lot easier to read that SHAP. We see the same prediction probabilities for whether each person did or did not survive. In the center, we see how influential the top 10 features were. Compared to SHAP, LIME has a tiny difference in its explainability, but they’re largely the same. We again see that Sex is a huge influencing factor here as well as whether or not the person was a child. On the right, they nicely display the precise values for this particular observation."},{"code":null,"e":9686,"s":9292,"text":"So which one is better: SHAP or LIME? I’m going to say neither. While each complement each other quite well, I think it’s important to show your business users both just to give them the best picture on which features are most explainable. I don’t think anybody can definitively say either SHAP or LIME is always more accurate, so show them both. The syntax is easy enough to chug out, anyway!"}],"string":"[\n {\n \"code\": null,\n \"e\": 526,\n \"s\": 172,\n \"text\": \"Hello there all! Welcome back again to another data science quick tip. This particular post is most interesting for me not only because this is the most complex subject we’ve tackled to date, but it’s also one that I just spent the last few hours learning myself. And of course, what better way to learn than to figure out how to teach it to the masses?\"\n },\n {\n \"code\": null,\n \"e\": 710,\n \"s\": 526,\n \"text\": \"Before getting into it, I’ve uploaded all the work shown in this post to a singular Jupyter notebook. You can find it at my personal GitHub if you’d like to follow along more closely.\"\n },\n {\n \"code\": null,\n \"e\": 1054,\n \"s\": 710,\n \"text\": \"So even though this is a very complex topic behind the scenes, I’m going to intentionally dial it down as much as possible for the widest possible audience. Even though this is ultimately a post designed for data science practitioners, I think it’s equally important for any business person to understand why they should care about this topic.\"\n },\n {\n \"code\": null,\n \"e\": 1194,\n \"s\": 1054,\n \"text\": \"Prior to jumping into how to calculate/visualize these values, let’s build some intuition on why would we would even care about this topic.\"\n },\n {\n \"code\": null,\n \"e\": 1612,\n \"s\": 1194,\n \"text\": \"If you’re familiar at all with machine learning in general, you know that you pop some data into a predictive model and that it produces an outputted prediction on the other side. But let’s be honest: do you know what’s really going on inside in that model? Remember, we’re talking about algorithms doing a lot of fancy math under the hood. In reality, this is probably what your ML model looks like to you right now:\"\n },\n {\n \"code\": null,\n \"e\": 1938,\n \"s\": 1612,\n \"text\": \"You really have no idea what’s going on in that black box. The math totally obscures how important those features are in your model. So what if Features 1 and 2 are carrying all the weight and that Features 3 and 4 are not adding any value at all to the model? What you’d prefer to see is something that looks more like this:\"\n },\n {\n \"code\": null,\n \"e\": 2453,\n \"s\": 1938,\n \"text\": \"Okay, we’re obviously using layman’s terms in our example here. But this stuff is important because if your models are relying on one 1 or 2 features to be doing all the predictive power, that might indicate something is wrong. It also might indicate that you’re using some sort of feature that may be considered to be morally incorrect. For example, many companies today will steer clear of using things like gender or ethnicity within their models because they tend to produce a lot of undesired bias in a model.\"\n },\n {\n \"code\": null,\n \"e\": 2670,\n \"s\": 2453,\n \"text\": \"Understanding these concepts always makes more sense through a tangible example, so we’re going to return to the dataset we’ve been using the last few posts to concretely demo both SHAP and LIME: the Titanic dataset.\"\n },\n {\n \"code\": null,\n \"e\": 3239,\n \"s\": 2670,\n \"text\": \"Alright, so in the last few post where we’ve used the Titanic dataset, we created models that were pretty poor since our focus was more on learning a new skill. In order to effectively demo both SHAP and LIME, we really need a model that shows some level of “trying” (?) so that we can see how ML explainability will play out. Now, I’m not going to spend time in this post showing you all my code for that data cleansing and modeling piece (which you can definitely find in my GitHub here), but I’ll summarize quickly the features that go into producing the end model.\"\n },\n {\n \"code\": null,\n \"e\": 3331,\n \"s\": 3239,\n \"text\": \"PClass: Notes the ticket class the person boarded the ship with. (Either 1st, 2nd, or 3rd.)\"\n },\n {\n \"code\": null,\n \"e\": 3489,\n \"s\": 3331,\n \"text\": \"Age Bins: Based on the person’s age, they are segmented into general people groups. These groups include child, teen, young adult, adult, elder, and unknown.\"\n },\n {\n \"code\": null,\n \"e\": 3547,\n \"s\": 3489,\n \"text\": \"Sex (Gender): Notes whether the person is male or female.\"\n },\n {\n \"code\": null,\n \"e\": 3675,\n \"s\": 3547,\n \"text\": \"Cabin Section: If the person had a cabin, I pulled out what section they might be in. These can either be A, B, C, or no cabin.\"\n },\n {\n \"code\": null,\n \"e\": 3757,\n \"s\": 3675,\n \"text\": \"Embarked: Notes one of three locations from which the person originally departed.\"\n },\n {\n \"code\": null,\n \"e\": 3865,\n \"s\": 3757,\n \"text\": \"SibSp (Sibling / Spouse): Notes how many siblings and/or spouses the person had onboard the ship with them.\"\n },\n {\n \"code\": null,\n \"e\": 3966,\n \"s\": 3865,\n \"text\": \"Parch (Parent / Child): Notes how many parents / children the person had onboard the ship with them.\"\n },\n {\n \"code\": null,\n \"e\": 4175,\n \"s\": 3966,\n \"text\": \"For the actual model itself, I’m choosing to use a simple Random Forest Classifier from Scikit-Learn. Splitting the data into training and validation sets, I get the following metrics with the validation set:\"\n },\n {\n \"code\": null,\n \"e\": 4355,\n \"s\": 4175,\n \"text\": \"The metrics aren’t exactly great, but that’s fine for our learning here. At least we’ll get to see in the next section how important these features necessarily are. Let’s move on!\"\n },\n {\n \"code\": null,\n \"e\": 4578,\n \"s\": 4355,\n \"text\": \"At this point, we currently have no idea how our Random Forest model is using the features to make its predictions. I’m going to wager a guess that Sex and Age Bin are influential factors, but we don’t know that quite yet.\"\n },\n {\n \"code\": null,\n \"e\": 5005,\n \"s\": 4578,\n \"text\": \"This is where smart people developed complex algorithms based on game theory to generate these things to better explain our current black box. Of course, I’m referring to SHAP and LIME. Now, I’m going to be 100% honest: I’m not very familiar with how these algorithms work under the hood, so I’m not even going to attempt to do that in this post. Instead, I’ll point you to this post about SHAP and this other post about LIME.\"\n },\n {\n \"code\": null,\n \"e\": 5283,\n \"s\": 5005,\n \"text\": \"Just like Scikit-Learn abstracts away the underlying algorithms for our Random Forest classifier, there are some neat Python libraries that we’ll use that abstract away the inner workings of both SHAP and LIME. To use those, all you need to do is a simple pip install for both:\"\n },\n {\n \"code\": null,\n \"e\": 5316,\n \"s\": 5283,\n \"text\": \"pip install shappip install lime\"\n },\n {\n \"code\": null,\n \"e\": 5657,\n \"s\": 5316,\n \"text\": \"At a high level, the way both of these work is that you give your training data and model to an “explainer”, and then you’re later able to pass any observation to the “explainer” which will tell you the feature importance of that model. That might sound like gobbledegook right now, but we’ll make this extra clear with our Titanic example!\"\n },\n {\n \"code\": null,\n \"e\": 6030,\n \"s\": 5657,\n \"text\": \"First, we need to pull two people from our validation set that we know respectively did not survive and survive. The reason for this is because we’re going to run these through our SHAP and LIME explainers to understand which characteristics about these people had the most influence for survivability according to our model. (Again, you can see this work in my notebook.)\"\n },\n {\n \"code\": null,\n \"e\": 6395,\n \"s\": 6030,\n \"text\": \"Let’s start off with SHAP. The syntax here is pretty simple. We’ll first instantiate the SHAP explainer object, fit our Random Forest Classifier (rfc) to the object, and plug in each respective person to generate their explainable SHAP values. The code below shows you how to do it for person 1. To do the same for person 2, simply swap out the appropriate values.\"\n },\n {\n \"code\": null,\n \"e\": 6881,\n \"s\": 6395,\n \"text\": \"# Importing the SHAP libraryimport shap# Instantiating the SHAP explainer using our trained RFC modelshap_explainer = shap.TreeExplainer(rfc)shap.initjs()# Getting SHAP values for person 1person_1_shap_values = shap_explainer.shap_values(person_1)# Visualizing plot of expected survivability of person 1shap.force_plot(shap_explainer.expected_value[1], person_1_shap_values[1], person_1)# Visualizing impact of each feature for person 1shap.summary_plot(person_1_shap_values, person_1)\"\n },\n {\n \"code\": null,\n \"e\": 7032,\n \"s\": 6881,\n \"text\": \"And that’s really all there is to it! Let’s take a look at the actual output from what we just did above in the screenshots below. First up, person 1.\"\n },\n {\n \"code\": null,\n \"e\": 7493,\n \"s\": 7032,\n \"text\": \"According to the top visual, our model predicted a 94% chance that person 1 survived, which is correct. It’s a little difficult to read, but look at the second visual, it looks like the most influential factors included the gender of the person, whether or not the person had a 3rd class ticket, and if the person was a child. In this case, person 1 was a female child, so those two factors alone drove our model most to say yes, this person probably survived.\"\n },\n {\n \"code\": null,\n \"e\": 7521,\n \"s\": 7493,\n \"text\": \"Let’s look at person 2 now.\"\n },\n {\n \"code\": null,\n \"e\": 7945,\n \"s\": 7521,\n \"text\": \"Our model here predicted that the person probably did not survive, and it is unfortunately correct. Again looking at the influential factors here, it looks like person 2 here was an adult male that did not have a cabin. I’m no history buff, but I would guess women and children were rescued off the boat first, so it makes a lot of sense to me that person 1 (a female child) did survive and person 2 (a male adult) did not.\"\n },\n {\n \"code\": null,\n \"e\": 7990,\n \"s\": 7945,\n \"text\": \"Alright, let’s move onto our LIME explainer!\"\n },\n {\n \"code\": null,\n \"e\": 8123,\n \"s\": 7990,\n \"text\": \"The syntax for using LIME is a little bit different, but conceptually speaking, both SHAP and LIME are doing a lot of similar stuff.\"\n },\n {\n \"code\": null,\n \"e\": 8690,\n \"s\": 8123,\n \"text\": \"# Importing LIMEimport lime.lime_tabular# Defining our LIME explainerlime_explainer = lime.lime_tabular.LimeTabularExplainer(X_train.values, mode = 'classification', feature_names = X_train.columns, class_names = ['Did Not Survive', 'Survived'])# Defining a quick function that can be used to explain the instance passedpredict_rfc_prob = lambda x: rfc.predict_proba(x).astype(float)# Viewing LIME explainability for person 1person_1_lime = lime_explainer.explain_instance(person_1.iloc[0].values, predict_rfc_prob, num_features = 10)person_1_lime.show_in_notebook()\"\n },\n {\n \"code\": null,\n \"e\": 8747,\n \"s\": 8690,\n \"text\": \"Let’s take a look at what LIME shows us for each person.\"\n },\n {\n \"code\": null,\n \"e\": 9292,\n \"s\": 8747,\n \"text\": \"I’m a little biased here, but I think the UI for these LIME values is a lot easier to read that SHAP. We see the same prediction probabilities for whether each person did or did not survive. In the center, we see how influential the top 10 features were. Compared to SHAP, LIME has a tiny difference in its explainability, but they’re largely the same. We again see that Sex is a huge influencing factor here as well as whether or not the person was a child. On the right, they nicely display the precise values for this particular observation.\"\n },\n {\n \"code\": null,\n \"e\": 9686,\n \"s\": 9292,\n \"text\": \"So which one is better: SHAP or LIME? I’m going to say neither. While each complement each other quite well, I think it’s important to show your business users both just to give them the best picture on which features are most explainable. I don’t think anybody can definitively say either SHAP or LIME is always more accurate, so show them both. The syntax is easy enough to chug out, anyway!\"\n }\n]"}}},{"rowIdx":437,"cells":{"title":{"kind":"string","value":"ssh - Unix, Linux Command"},"text":{"kind":"string","value":"ssh\nconnects and logs into the specified\n hostname\n(with optional\n user\nname).\nThe user must prove\nhis/her identity to the remote machine using one of several methods\ndepending on the protocol version used (see below).\n\n\nIf\n command\nis specified,\nit is executed on the remote host instead of a login shell.\n\n\nThe options are as follows:\n\n\nAgent forwarding should be enabled with caution.\nUsers with the ability to bypass file permissions on the remote host\n(for the agent’s Unix-domain socket)\ncan access the local agent through the forwarded connection.\nAn attacker cannot obtain key material from the agent,\nhowever they can perform operations on the keys that enable them to\nauthenticate using the identities loaded into the agent.\n\n\nProtocol version 1 allows specification of a single cipher.\nThe supported values are\n\"3des\",\n\"blowfish\",\nand\n\"des\".\n 3des\n(triple-des) is an encrypt-decrypt-encrypt triple with three different keys.\nIt is believed to be secure.\n blowfish\nis a fast block cipher; it appears very secure and is much faster than\n 3des.\n des\nis only supported in the\nssh\nclient for interoperability with legacy protocol 1 implementations\nthat do not support the\n 3des\ncipher.\nIts use is strongly discouraged due to cryptographic weaknesses.\nThe default is\n\"3des\".\n\n\nFor protocol version 2,\n cipher_spec\nis a comma-separated list of ciphers\nlisted in order of preference.\nThe supported ciphers are:\n3des-cbc,\naes128-cbc,\naes192-cbc,\naes256-cbc,\naes128-ctr,\naes192-ctr,\naes256-ctr,\narcfour128,\narcfour256,\narcfour,\nblowfish-cbc,\nand\ncast128-cbc.\nThe default is:\n\naes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour128,\narcfour256,arcfour,aes192-cbc,aes256-cbc,aes128-ctr,\naes192-ctr,aes256-ctr\n\n\nIPv6 addresses can be specified with an alternative syntax:\n.Sm off\n.Xo \n[bind_address /]\n port\n\n\n\n\nPort forwardings can also be specified in the configuration file.\nPrivileged ports can be forwarded only when\nlogging in as root on the remote machine.\nIPv6 addresses can be specified by enclosing the address in square braces or\nusing an alternative syntax:\n.Sm off\n.Xo \n[bind_address /]\n host / port /\n hostport\n\n\nBy default, the listening socket on the server will be bound to the loopback\ninterface only.\nThis may be overriden by specifying a\n bind_address.\nAn empty\n bind_address,\nor the address\n‘*’,\nindicates that the remote socket should listen on all interfaces.\nSpecifying a remote\n bind_address\nwill only succeed if the server’s\n GatewayPorts\noption is enabled (see\nsshd_config(5)).\n\n\nX11 forwarding should be enabled with caution.\nUsers with the ability to bypass file permissions on the remote host\n(for the user’s X authorization database)\ncan access the local X11 display through the forwarded connection.\nAn attacker may then be able to perform activities such as keystroke monitoring.\n\n\nFor this reason, X11 forwarding is subjected to X11 SECURITY extension\nrestrictions by default.\nPlease refer to the\nssh\n-Y \noption and the\n ForwardX11Trusted\ndirective in\nssh_config(5)\nfor more information.\n\n\nssh\nmay additionally obtain configuration data from\na per-user configuration file and a system-wide configuration file.\nThe file format and configuration options are described in\nssh_config(5).\n\n\nssh\nexits with the exit status of the remote command or with 255\nif an error occurred.\n\n\nThe methods available for authentication are:\nhost-based authentication,\npublic key authentication,\nchallenge-response authentication,\nand password authentication.\nAuthentication methods are tried in the order specified above,\nthough protocol 2 has a configuration option to change the default order:\n PreferredAuthentications.\n\n\nHost-based authentication works as follows:\nIf the machine the user logs in from is listed in\n /etc/hosts.equiv\nor\n /etc/ssh/shosts.equiv\non the remote machine, and the user names are\nthe same on both sides, or if the files\n ~/.rhosts\nor\n ~/.shosts\nexist in the user’s home directory on the\nremote machine and contain a line containing the name of the client\nmachine and the name of the user on that machine, the user is\nconsidered for login.\nAdditionally, the server\n must\nbe able to verify the client’s\nhost key (see the description of\n /etc/ssh/ssh_known_hosts\nand\n ~/.ssh/known_hosts,\nbelow)\nfor login to be permitted.\nThis authentication method closes security holes due to IP\nspoofing, DNS spoofing, and routing spoofing.\n[Note to the administrator:\n /etc/hosts.equiv,\n ~/.rhosts,\nand the rlogin/rsh protocol in general, are inherently insecure and should be\ndisabled if security is desired.]\n\n\nPublic key authentication works as follows:\nThe scheme is based on public-key cryptography,\nusing cryptosystems\nwhere encryption and decryption are done using separate keys,\nand it is unfeasible to derive the decryption key from the encryption key.\nThe idea is that each user creates a public/private\nkey pair for authentication purposes.\nThe server knows the public key, and only the user knows the private key.\nssh\nimplements public key authentication protocol automatically,\nusing either the RSA or DSA algorithms.\nProtocol 1 is restricted to using only RSA keys,\nbut protocol 2 may use either.\nThe\nHISTORY\nsection of\nssl(8)\ncontains a brief discussion of the two algorithms.\n\n\nThe file\n ~/.ssh/authorized_keys\nlists the public keys that are permitted for logging in.\nWhen the user logs in, the\nssh\nprogram tells the server which key pair it would like to use for\nauthentication.\nThe client proves that it has access to the private key\nand the server checks that the corresponding public key\nis authorized to accept the account.\n\n\nThe user creates his/her key pair by running\nssh-keygen(1).\nThis stores the private key in\n ~/.ssh/identity\n(protocol 1),\n ~/.ssh/id_dsa\n(protocol 2 DSA),\nor\n ~/.ssh/id_rsa\n(protocol 2 RSA)\nand stores the public key in\n ~/.ssh/identity.pub\n(protocol 1),\n ~/.ssh/id_dsa.pub\n(protocol 2 DSA),\nor\n ~/.ssh/id_rsa.pub\n(protocol 2 RSA)\nin the user’s home directory.\nThe user should then copy the public key\nto\n ~/.ssh/authorized_keys\nin his/her home directory on the remote machine.\nThe\n authorized_keys\nfile corresponds to the conventional\n ~/.rhosts\nfile, and has one key\nper line, though the lines can be very long.\nAfter this, the user can log in without giving the password.\n\n\nThe most convenient way to use public key authentication may be with an\nauthentication agent.\nSee\nssh-agent(1)\nfor more information.\n\n\nChallenge-response authentication works as follows:\nThe server sends an arbitrary\n\"challenge\"\ntext, and prompts for a response.\nProtocol 2 allows multiple challenges and responses;\nprotocol 1 is restricted to just one challenge/response.\nExamples of challenge-response authentication include\nBSD Authentication (see\nlogin.conf(5))\nand PAM (some non-OpenBSD systems).\n\n\nFinally, if other authentication methods fail,\nssh\nprompts the user for a password.\nThe password is sent to the remote\nhost for checking; however, since all communications are encrypted,\nthe password cannot be seen by someone listening on the network.\n\n\nssh\nautomatically maintains and checks a database containing\nidentification for all hosts it has ever been used with.\nHost keys are stored in\n ~/.ssh/known_hosts\nin the user’s home directory.\nAdditionally, the file\n /etc/ssh/ssh_known_hosts\nis automatically checked for known hosts.\nAny new hosts are automatically added to the user’s file.\nIf a host’s identification ever changes,\nssh\nwarns about this and disables password authentication to prevent\nserver spoofing or man-in-the-middle attacks,\nwhich could otherwise be used to circumvent the encryption.\nThe\n StrictHostKeyChecking\noption can be used to control logins to machines whose\nhost key is not known or has changed.\n\n\nWhen the user’s identity has been accepted by the server, the server\neither executes the given command, or logs into the machine and gives\nthe user a normal shell on the remote machine.\nAll communication with\nthe remote command or shell will be automatically encrypted.\n\n\nIf a pseudo-terminal has been allocated (normal login session), the\nuser may use the escape characters noted below.\n\n\nIf no pseudo-tty has been allocated,\nthe session is transparent and can be used to reliably transfer binary data.\nOn most systems, setting the escape character to\n\"none\"\nwill also make the session transparent even if a tty is used.\n\n\nThe session terminates when the command or shell on the remote\nmachine exits and all X11 and TCP connections have been closed.\n\n\nA single tilde character can be sent as\n ~~\nor by following the tilde by a character other than those described below.\nThe escape character must always follow a newline to be interpreted as\nspecial.\nThe escape character can be changed in configuration files using the\n EscapeChar\nconfiguration directive or on the command line by the\n-e \noption.\n\n\nThe supported escapes (assuming the default\n‘~’)\nare:\n\n\nIn the example below, we look at encrypting communication between\nan IRC client and server, even though the IRC server does not directly\nsupport encrypted communications.\nThis works as follows:\nthe user connects to the remote host using\nssh,\nspecifying a port to be used to forward connections\nto the remote server.\nAfter that it is possible to start the service which is to be encrypted\non the client machine,\nconnecting to the same local port,\nand\nssh\nwill encrypt and forward the connection.\n\n\nThe following example tunnels an IRC session from client machine\n\"127.0.0.1\"\n(localhost)\nto remote server\n\"server.example.com\":\n\n$ ssh -f -L 1234:localhost:6667 server.example.com sleep 10\n$ irc -c ’#users’ -p 1234 pinky 127.0.0.1\n\n\nThis tunnels a connection to IRC server\n\"server.example.com\",\njoining channel\n\"#users\",\nnickname\n\"pinky\",\nusing port 1234.\nIt doesn’t matter which port is used,\nas long as it’s greater than 1023\n(remember, only root can open sockets on privileged ports)\nand doesn’t conflict with any ports already in use.\nThe connection is forwarded to port 6667 on the remote server,\nsince that’s the standard port for IRC services.\n\n\nThe\n-f \noption backgrounds\nssh\nand the remote command\n\"sleep 10\"\nis specified to allow an amount of time\n(10 seconds, in the example)\nto start the service which is to be tunnelled.\nIf no connections are made within the time specified,\nssh\nwill exit.\n\n\nThe\n DISPLAY\nvalue set by\nssh\nwill point to the server machine, but with a display number greater than zero.\nThis is normal, and happens because\nssh\ncreates a\n\"proxy\"\nX server on the server machine for forwarding the\nconnections over the encrypted channel.\n\n\nssh\nwill also automatically set up Xauthority data on the server machine.\nFor this purpose, it will generate a random authorization cookie,\nstore it in Xauthority on the server, and verify that any forwarded\nconnections carry this cookie and replace it by the real cookie when\nthe connection is opened.\nThe real authentication cookie is never\nsent to the server machine (and no cookies are sent in the plain).\n\n\nIf the\n ForwardAgent\nvariable is set to\n\"yes\"\n(or see the description of the\n-A \nand\n-a \noptions above) and\nthe user is using an authentication agent, the connection to the agent\nis automatically forwarded to the remote side.\n\n\n\n $ ssh-keygen -l -f /etc/ssh/ssh_host_rsa_key\n\n\n\nIf the fingerprint is already known,\nit can be matched and verified,\nand the key can be accepted.\nIf the fingerprint is unknown,\nan alternative method of verification is available:\nSSH fingerprints verified by DNS.\nAn additional resource record (RR),\nSSHFP,\nis added to a zonefile\nand the connecting client is able to match the fingerprint\nwith that of the key presented.\n\n\nIn this example, we are connecting a client to a server,\n\"host.example.com\".\nThe SSHFP resource records should first be added to the zonefile for\nhost.example.com:\n\n$ ssh-keygen -f /etc/ssh/ssh_host_rsa_key.pub -r host.example.com.\n$ ssh-keygen -f /etc/ssh/ssh_host_dsa_key.pub -r host.example.com.\n\n\nThe output lines will have to be added to the zonefile.\nTo check that the zone is answering fingerprint queries:\n\n\n\n $ dig -t SSHFP host.example.com\n\n\n\nFinally the client connects:\n\n$ ssh -o \"VerifyHostKeyDNS ask\" host.example.com\n[...]\nMatching host key fingerprint found in DNS.\nAre you sure you want to continue connecting (yes/no)?\n\n\nSee the\n VerifyHostKeyDNS\noption in\nssh_config(5)\nfor more information.\n\n\nThe following example would connect client network 10.0.50.0/24\nwith remote network 10.0.99.0/24, provided that the SSH server\nrunning on the gateway to the remote network,\nat 192.168.1.15, allows it:\n\n# ssh -f -w 0:1 192.168.1.15 true\n# ifconfig tun0 10.0.50.1 10.0.99.1 netmask 255.255.255.252\n\n\nClient access may be more finely tuned via the\n /root/.ssh/authorized_keys\nfile (see below) and the\n PermitRootLogin\nserver option.\nThe following entry would permit connections on the first\ntun(4)\ndevice from user\n\"jane\"\nand on the second device from user\n\"john\",\nif\n PermitRootLogin\nis set to\n\"forced-commands-only\":\n\ntunnel=\"1\",command=\"sh /etc/netstart tun1\" ssh-rsa ... jane\ntunnel=\"2\",command=\"sh /etc/netstart tun1\" ssh-rsa ... john\n\n\nSince a SSH-based setup entails a fair amount of overhead,\nit may be more suited to temporary setups,\nsuch as for wireless VPNs.\nMore permanent VPNs are better provided by tools such as\nipsecctl(8)\nand\nisakmpd(8).\n\n\nAdditionally,\nssh\nreads\n ~/.ssh/environment,\nand adds lines of the format\n\"VARNAME=value\"\nto the environment if the file exists and users are allowed to\nchange their environment.\nFor more information, see the\n PermitUserEnvironment\noption in\nsshd_config(5).\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nAdvertisements\n\n\n 129 Lectures \n 23 hours \n\n Eduonix Learning Solutions\n\n 5 Lectures \n 4.5 hours \n\n Frahaan Hussain\n\n 35 Lectures \n 2 hours \n\n Pradeep D\n\n 41 Lectures \n 2.5 hours \n\n Musab Zayadneh\n\n 46 Lectures \n 4 hours \n\n GUHARAJANM\n\n 6 Lectures \n 4 hours \n\n Uplatz\n Print\n Add Notes\n Bookmark this page"},"parsed":{"kind":"list like","value":[{"code":null,"e":10798,"s":10577,"text":"\nssh\nconnects and logs into the specified\n hostname\n(with optional\n user\nname).\nThe user must prove\nhis/her identity to the remote machine using one of several methods\ndepending on the protocol version used (see below).\n"},{"code":null,"e":10886,"s":10798,"text":"\nIf\n command\nis specified,\nit is executed on the remote host instead of a login shell.\n"},{"code":null,"e":10916,"s":10886,"text":"\nThe options are as follows:\n"},{"code":null,"e":11314,"s":10916,"text":"\nAgent forwarding should be enabled with caution.\nUsers with the ability to bypass file permissions on the remote host\n(for the agent’s Unix-domain socket)\ncan access the local agent through the forwarded connection.\nAn attacker cannot obtain key material from the agent,\nhowever they can perform operations on the keys that enable them to\nauthenticate using the identities loaded into the agent.\n"},{"code":null,"e":11859,"s":11314,"text":"\nProtocol version 1 allows specification of a single cipher.\nThe supported values are\n\"3des\",\n\"blowfish\",\nand\n\"des\".\n 3des\n(triple-des) is an encrypt-decrypt-encrypt triple with three different keys.\nIt is believed to be secure.\n blowfish\nis a fast block cipher; it appears very secure and is much faster than\n 3des.\n des\nis only supported in the\nssh\nclient for interoperability with legacy protocol 1 implementations\nthat do not support the\n 3des\ncipher.\nIts use is strongly discouraged due to cryptographic weaknesses.\nThe default is\n\"3des\".\n"},{"code":null,"e":12155,"s":11859,"text":"\nFor protocol version 2,\n cipher_spec\nis a comma-separated list of ciphers\nlisted in order of preference.\nThe supported ciphers are:\n3des-cbc,\naes128-cbc,\naes192-cbc,\naes256-cbc,\naes128-ctr,\naes192-ctr,\naes256-ctr,\narcfour128,\narcfour256,\narcfour,\nblowfish-cbc,\nand\ncast128-cbc.\nThe default is:\n"},{"code":null,"e":12288,"s":12155,"text":"aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour128,\narcfour256,arcfour,aes192-cbc,aes256-cbc,aes128-ctr,\naes192-ctr,aes256-ctr\n"},{"code":null,"e":12386,"s":12288,"text":"\nIPv6 addresses can be specified with an alternative syntax:\n.Sm off\n.Xo \n[bind_address /]\n port\n"},{"code":null,"e":12703,"s":12388,"text":"\nPort forwardings can also be specified in the configuration file.\nPrivileged ports can be forwarded only when\nlogging in as root on the remote machine.\nIPv6 addresses can be specified by enclosing the address in square braces or\nusing an alternative syntax:\n.Sm off\n.Xo \n[bind_address /]\n host / port /\n hostport\n"},{"code":null,"e":13083,"s":12703,"text":"\nBy default, the listening socket on the server will be bound to the loopback\ninterface only.\nThis may be overriden by specifying a\n bind_address.\nAn empty\n bind_address,\nor the address\n‘*’,\nindicates that the remote socket should listen on all interfaces.\nSpecifying a remote\n bind_address\nwill only succeed if the server’s\n GatewayPorts\noption is enabled (see\nsshd_config(5)).\n"},{"code":null,"e":13391,"s":13083,"text":"\nX11 forwarding should be enabled with caution.\nUsers with the ability to bypass file permissions on the remote host\n(for the user’s X authorization database)\ncan access the local X11 display through the forwarded connection.\nAn attacker may then be able to perform activities such as keystroke monitoring.\n"},{"code":null,"e":13600,"s":13391,"text":"\nFor this reason, X11 forwarding is subjected to X11 SECURITY extension\nrestrictions by default.\nPlease refer to the\nssh\n-Y \noption and the\n ForwardX11Trusted\ndirective in\nssh_config(5)\nfor more information.\n"},{"code":null,"e":13796,"s":13600,"text":"\nssh\nmay additionally obtain configuration data from\na per-user configuration file and a system-wide configuration file.\nThe file format and configuration options are described in\nssh_config(5).\n"},{"code":null,"e":13885,"s":13796,"text":"\nssh\nexits with the exit status of the remote command or with 255\nif an error occurred.\n"},{"code":null,"e":14215,"s":13885,"text":"\nThe methods available for authentication are:\nhost-based authentication,\npublic key authentication,\nchallenge-response authentication,\nand password authentication.\nAuthentication methods are tried in the order specified above,\nthough protocol 2 has a configuration option to change the default order:\n PreferredAuthentications.\n"},{"code":null,"e":15116,"s":14215,"text":"\nHost-based authentication works as follows:\nIf the machine the user logs in from is listed in\n /etc/hosts.equiv\nor\n /etc/ssh/shosts.equiv\non the remote machine, and the user names are\nthe same on both sides, or if the files\n ~/.rhosts\nor\n ~/.shosts\nexist in the user’s home directory on the\nremote machine and contain a line containing the name of the client\nmachine and the name of the user on that machine, the user is\nconsidered for login.\nAdditionally, the server\n must\nbe able to verify the client’s\nhost key (see the description of\n /etc/ssh/ssh_known_hosts\nand\n ~/.ssh/known_hosts,\nbelow)\nfor login to be permitted.\nThis authentication method closes security holes due to IP\nspoofing, DNS spoofing, and routing spoofing.\n[Note to the administrator:\n /etc/hosts.equiv,\n ~/.rhosts,\nand the rlogin/rsh protocol in general, are inherently insecure and should be\ndisabled if security is desired.]\n"},{"code":null,"e":15797,"s":15116,"text":"\nPublic key authentication works as follows:\nThe scheme is based on public-key cryptography,\nusing cryptosystems\nwhere encryption and decryption are done using separate keys,\nand it is unfeasible to derive the decryption key from the encryption key.\nThe idea is that each user creates a public/private\nkey pair for authentication purposes.\nThe server knows the public key, and only the user knows the private key.\nssh\nimplements public key authentication protocol automatically,\nusing either the RSA or DSA algorithms.\nProtocol 1 is restricted to using only RSA keys,\nbut protocol 2 may use either.\nThe\nHISTORY\nsection of\nssl(8)\ncontains a brief discussion of the two algorithms.\n"},{"code":null,"e":16150,"s":15797,"text":"\nThe file\n ~/.ssh/authorized_keys\nlists the public keys that are permitted for logging in.\nWhen the user logs in, the\nssh\nprogram tells the server which key pair it would like to use for\nauthentication.\nThe client proves that it has access to the private key\nand the server checks that the corresponding public key\nis authorized to accept the account.\n"},{"code":null,"e":16826,"s":16150,"text":"\nThe user creates his/her key pair by running\nssh-keygen(1).\nThis stores the private key in\n ~/.ssh/identity\n(protocol 1),\n ~/.ssh/id_dsa\n(protocol 2 DSA),\nor\n ~/.ssh/id_rsa\n(protocol 2 RSA)\nand stores the public key in\n ~/.ssh/identity.pub\n(protocol 1),\n ~/.ssh/id_dsa.pub\n(protocol 2 DSA),\nor\n ~/.ssh/id_rsa.pub\n(protocol 2 RSA)\nin the user’s home directory.\nThe user should then copy the public key\nto\n ~/.ssh/authorized_keys\nin his/her home directory on the remote machine.\nThe\n authorized_keys\nfile corresponds to the conventional\n ~/.rhosts\nfile, and has one key\nper line, though the lines can be very long.\nAfter this, the user can log in without giving the password.\n"},{"code":null,"e":16961,"s":16826,"text":"\nThe most convenient way to use public key authentication may be with an\nauthentication agent.\nSee\nssh-agent(1)\nfor more information.\n"},{"code":null,"e":17330,"s":16961,"text":"\nChallenge-response authentication works as follows:\nThe server sends an arbitrary\n\"challenge\"\ntext, and prompts for a response.\nProtocol 2 allows multiple challenges and responses;\nprotocol 1 is restricted to just one challenge/response.\nExamples of challenge-response authentication include\nBSD Authentication (see\nlogin.conf(5))\nand PAM (some non-OpenBSD systems).\n"},{"code":null,"e":17584,"s":17330,"text":"\nFinally, if other authentication methods fail,\nssh\nprompts the user for a password.\nThe password is sent to the remote\nhost for checking; however, since all communications are encrypted,\nthe password cannot be seen by someone listening on the network.\n"},{"code":null,"e":18263,"s":17584,"text":"\nssh\nautomatically maintains and checks a database containing\nidentification for all hosts it has ever been used with.\nHost keys are stored in\n ~/.ssh/known_hosts\nin the user’s home directory.\nAdditionally, the file\n /etc/ssh/ssh_known_hosts\nis automatically checked for known hosts.\nAny new hosts are automatically added to the user’s file.\nIf a host’s identification ever changes,\nssh\nwarns about this and disables password authentication to prevent\nserver spoofing or man-in-the-middle attacks,\nwhich could otherwise be used to circumvent the encryption.\nThe\n StrictHostKeyChecking\noption can be used to control logins to machines whose\nhost key is not known or has changed.\n"},{"code":null,"e":18535,"s":18263,"text":"\nWhen the user’s identity has been accepted by the server, the server\neither executes the given command, or logs into the machine and gives\nthe user a normal shell on the remote machine.\nAll communication with\nthe remote command or shell will be automatically encrypted.\n"},{"code":null,"e":18653,"s":18535,"text":"\nIf a pseudo-terminal has been allocated (normal login session), the\nuser may use the escape characters noted below.\n"},{"code":null,"e":18887,"s":18653,"text":"\nIf no pseudo-tty has been allocated,\nthe session is transparent and can be used to reliably transfer binary data.\nOn most systems, setting the escape character to\n\"none\"\nwill also make the session transparent even if a tty is used.\n"},{"code":null,"e":19016,"s":18887,"text":"\nThe session terminates when the command or shell on the remote\nmachine exits and all X11 and TCP connections have been closed.\n"},{"code":null,"e":19364,"s":19016,"text":"\nA single tilde character can be sent as\n ~~\nor by following the tilde by a character other than those described below.\nThe escape character must always follow a newline to be interpreted as\nspecial.\nThe escape character can be changed in configuration files using the\n EscapeChar\nconfiguration directive or on the command line by the\n-e \noption.\n"},{"code":null,"e":19420,"s":19364,"text":"\nThe supported escapes (assuming the default\n‘~’)\nare:\n"},{"code":null,"e":19917,"s":19420,"text":"\nIn the example below, we look at encrypting communication between\nan IRC client and server, even though the IRC server does not directly\nsupport encrypted communications.\nThis works as follows:\nthe user connects to the remote host using\nssh,\nspecifying a port to be used to forward connections\nto the remote server.\nAfter that it is possible to start the service which is to be encrypted\non the client machine,\nconnecting to the same local port,\nand\nssh\nwill encrypt and forward the connection.\n"},{"code":null,"e":20047,"s":19917,"text":"\nThe following example tunnels an IRC session from client machine\n\"127.0.0.1\"\n(localhost)\nto remote server\n\"server.example.com\":\n"},{"code":null,"e":20150,"s":20047,"text":"$ ssh -f -L 1234:localhost:6667 server.example.com sleep 10\n$ irc -c ’#users’ -p 1234 pinky 127.0.0.1\n"},{"code":null,"e":20570,"s":20150,"text":"\nThis tunnels a connection to IRC server\n\"server.example.com\",\njoining channel\n\"#users\",\nnickname\n\"pinky\",\nusing port 1234.\nIt doesn’t matter which port is used,\nas long as it’s greater than 1023\n(remember, only root can open sockets on privileged ports)\nand doesn’t conflict with any ports already in use.\nThe connection is forwarded to port 6667 on the remote server,\nsince that’s the standard port for IRC services.\n"},{"code":null,"e":20822,"s":20570,"text":"\nThe\n-f \noption backgrounds\nssh\nand the remote command\n\"sleep 10\"\nis specified to allow an amount of time\n(10 seconds, in the example)\nto start the service which is to be tunnelled.\nIf no connections are made within the time specified,\nssh\nwill exit.\n"},{"code":null,"e":21081,"s":20822,"text":"\nThe\n DISPLAY\nvalue set by\nssh\nwill point to the server machine, but with a display number greater than zero.\nThis is normal, and happens because\nssh\ncreates a\n\"proxy\"\nX server on the server machine for forwarding the\nconnections over the encrypted channel.\n"},{"code":null,"e":21493,"s":21081,"text":"\nssh\nwill also automatically set up Xauthority data on the server machine.\nFor this purpose, it will generate a random authorization cookie,\nstore it in Xauthority on the server, and verify that any forwarded\nconnections carry this cookie and replace it by the real cookie when\nthe connection is opened.\nThe real authentication cookie is never\nsent to the server machine (and no cookies are sent in the plain).\n"},{"code":null,"e":21721,"s":21493,"text":"\nIf the\n ForwardAgent\nvariable is set to\n\"yes\"\n(or see the description of the\n-A \nand\n-a \noptions above) and\nthe user is using an authentication agent, the connection to the agent\nis automatically forwarded to the remote side.\n"},{"code":null,"e":21773,"s":21723,"text":" $ ssh-keygen -l -f /etc/ssh/ssh_host_rsa_key"},{"code":null,"e":22149,"s":21775,"text":"\nIf the fingerprint is already known,\nit can be matched and verified,\nand the key can be accepted.\nIf the fingerprint is unknown,\nan alternative method of verification is available:\nSSH fingerprints verified by DNS.\nAn additional resource record (RR),\nSSHFP,\nis added to a zonefile\nand the connecting client is able to match the fingerprint\nwith that of the key presented.\n"},{"code":null,"e":22315,"s":22149,"text":"\nIn this example, we are connecting a client to a server,\n\"host.example.com\".\nThe SSHFP resource records should first be added to the zonefile for\nhost.example.com:\n"},{"code":null,"e":22450,"s":22315,"text":"$ ssh-keygen -f /etc/ssh/ssh_host_rsa_key.pub -r host.example.com.\n$ ssh-keygen -f /etc/ssh/ssh_host_dsa_key.pub -r host.example.com.\n"},{"code":null,"e":22565,"s":22450,"text":"\nThe output lines will have to be added to the zonefile.\nTo check that the zone is answering fingerprint queries:\n"},{"code":null,"e":22604,"s":22567,"text":" $ dig -t SSHFP host.example.com"},{"code":null,"e":22637,"s":22606,"text":"\nFinally the client connects:\n"},{"code":null,"e":22792,"s":22637,"text":"$ ssh -o \"VerifyHostKeyDNS ask\" host.example.com\n[...]\nMatching host key fingerprint found in DNS.\nAre you sure you want to continue connecting (yes/no)?\n"},{"code":null,"e":22866,"s":22792,"text":"\nSee the\n VerifyHostKeyDNS\noption in\nssh_config(5)\nfor more information.\n"},{"code":null,"e":23069,"s":22866,"text":"\nThe following example would connect client network 10.0.50.0/24\nwith remote network 10.0.99.0/24, provided that the SSH server\nrunning on the gateway to the remote network,\nat 192.168.1.15, allows it:\n"},{"code":null,"e":23164,"s":23069,"text":"# ssh -f -w 0:1 192.168.1.15 true\n# ifconfig tun0 10.0.50.1 10.0.99.1 netmask 255.255.255.252\n"},{"code":null,"e":23484,"s":23164,"text":"\nClient access may be more finely tuned via the\n /root/.ssh/authorized_keys\nfile (see below) and the\n PermitRootLogin\nserver option.\nThe following entry would permit connections on the first\ntun(4)\ndevice from user\n\"jane\"\nand on the second device from user\n\"john\",\nif\n PermitRootLogin\nis set to\n\"forced-commands-only\":\n"},{"code":null,"e":23605,"s":23484,"text":"tunnel=\"1\",command=\"sh /etc/netstart tun1\" ssh-rsa ... jane\ntunnel=\"2\",command=\"sh /etc/netstart tun1\" ssh-rsa ... john\n"},{"code":null,"e":23821,"s":23605,"text":"\nSince a SSH-based setup entails a fair amount of overhead,\nit may be more suited to temporary setups,\nsuch as for wireless VPNs.\nMore permanent VPNs are better provided by tools such as\nipsecctl(8)\nand\nisakmpd(8).\n"},{"code":null,"e":24081,"s":23821,"text":"\nAdditionally,\nssh\nreads\n ~/.ssh/environment,\nand adds lines of the format\n\"VARNAME=value\"\nto the environment if the file exists and users are allowed to\nchange their environment.\nFor more information, see the\n PermitUserEnvironment\noption in\nsshd_config(5).\n"},{"code":null,"e":24126,"s":24109,"text":"\nAdvertisements\n"},{"code":null,"e":24161,"s":24126,"text":"\n 129 Lectures \n 23 hours \n"},{"code":null,"e":24189,"s":24161,"text":" Eduonix Learning Solutions"},{"code":null,"e":24223,"s":24189,"text":"\n 5 Lectures \n 4.5 hours \n"},{"code":null,"e":24240,"s":24223,"text":" Frahaan Hussain"},{"code":null,"e":24273,"s":24240,"text":"\n 35 Lectures \n 2 hours \n"},{"code":null,"e":24284,"s":24273,"text":" Pradeep D"},{"code":null,"e":24319,"s":24284,"text":"\n 41 Lectures \n 2.5 hours \n"},{"code":null,"e":24335,"s":24319,"text":" Musab Zayadneh"},{"code":null,"e":24368,"s":24335,"text":"\n 46 Lectures \n 4 hours \n"},{"code":null,"e":24380,"s":24368,"text":" GUHARAJANM"},{"code":null,"e":24412,"s":24380,"text":"\n 6 Lectures \n 4 hours \n"},{"code":null,"e":24420,"s":24412,"text":" Uplatz"},{"code":null,"e":24427,"s":24420,"text":" Print"},{"code":null,"e":24438,"s":24427,"text":" Add Notes"}],"string":"[\n {\n \"code\": null,\n \"e\": 10798,\n \"s\": 10577,\n \"text\": \"\\nssh\\nconnects and logs into the specified\\n hostname\\n(with optional\\n user\\nname).\\nThe user must prove\\nhis/her identity to the remote machine using one of several methods\\ndepending on the protocol version used (see below).\\n\"\n },\n {\n \"code\": null,\n \"e\": 10886,\n \"s\": 10798,\n \"text\": \"\\nIf\\n command\\nis specified,\\nit is executed on the remote host instead of a login shell.\\n\"\n },\n {\n \"code\": null,\n \"e\": 10916,\n \"s\": 10886,\n \"text\": \"\\nThe options are as follows:\\n\"\n },\n {\n \"code\": null,\n \"e\": 11314,\n \"s\": 10916,\n \"text\": \"\\nAgent forwarding should be enabled with caution.\\nUsers with the ability to bypass file permissions on the remote host\\n(for the agent’s Unix-domain socket)\\ncan access the local agent through the forwarded connection.\\nAn attacker cannot obtain key material from the agent,\\nhowever they can perform operations on the keys that enable them to\\nauthenticate using the identities loaded into the agent.\\n\"\n },\n {\n \"code\": null,\n \"e\": 11859,\n \"s\": 11314,\n \"text\": \"\\nProtocol version 1 allows specification of a single cipher.\\nThe supported values are\\n\\\"3des\\\",\\n\\\"blowfish\\\",\\nand\\n\\\"des\\\".\\n 3des\\n(triple-des) is an encrypt-decrypt-encrypt triple with three different keys.\\nIt is believed to be secure.\\n blowfish\\nis a fast block cipher; it appears very secure and is much faster than\\n 3des.\\n des\\nis only supported in the\\nssh\\nclient for interoperability with legacy protocol 1 implementations\\nthat do not support the\\n 3des\\ncipher.\\nIts use is strongly discouraged due to cryptographic weaknesses.\\nThe default is\\n\\\"3des\\\".\\n\"\n },\n {\n \"code\": null,\n \"e\": 12155,\n \"s\": 11859,\n \"text\": \"\\nFor protocol version 2,\\n cipher_spec\\nis a comma-separated list of ciphers\\nlisted in order of preference.\\nThe supported ciphers are:\\n3des-cbc,\\naes128-cbc,\\naes192-cbc,\\naes256-cbc,\\naes128-ctr,\\naes192-ctr,\\naes256-ctr,\\narcfour128,\\narcfour256,\\narcfour,\\nblowfish-cbc,\\nand\\ncast128-cbc.\\nThe default is:\\n\"\n },\n {\n \"code\": null,\n \"e\": 12288,\n \"s\": 12155,\n \"text\": \"aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour128,\\narcfour256,arcfour,aes192-cbc,aes256-cbc,aes128-ctr,\\naes192-ctr,aes256-ctr\\n\"\n },\n {\n \"code\": null,\n \"e\": 12386,\n \"s\": 12288,\n \"text\": \"\\nIPv6 addresses can be specified with an alternative syntax:\\n.Sm off\\n.Xo \\n[bind_address /]\\n port\\n\"\n },\n {\n \"code\": null,\n \"e\": 12703,\n \"s\": 12388,\n \"text\": \"\\nPort forwardings can also be specified in the configuration file.\\nPrivileged ports can be forwarded only when\\nlogging in as root on the remote machine.\\nIPv6 addresses can be specified by enclosing the address in square braces or\\nusing an alternative syntax:\\n.Sm off\\n.Xo \\n[bind_address /]\\n host / port /\\n hostport\\n\"\n },\n {\n \"code\": null,\n \"e\": 13083,\n \"s\": 12703,\n \"text\": \"\\nBy default, the listening socket on the server will be bound to the loopback\\ninterface only.\\nThis may be overriden by specifying a\\n bind_address.\\nAn empty\\n bind_address,\\nor the address\\n‘*’,\\nindicates that the remote socket should listen on all interfaces.\\nSpecifying a remote\\n bind_address\\nwill only succeed if the server’s\\n GatewayPorts\\noption is enabled (see\\nsshd_config(5)).\\n\"\n },\n {\n \"code\": null,\n \"e\": 13391,\n \"s\": 13083,\n \"text\": \"\\nX11 forwarding should be enabled with caution.\\nUsers with the ability to bypass file permissions on the remote host\\n(for the user’s X authorization database)\\ncan access the local X11 display through the forwarded connection.\\nAn attacker may then be able to perform activities such as keystroke monitoring.\\n\"\n },\n {\n \"code\": null,\n \"e\": 13600,\n \"s\": 13391,\n \"text\": \"\\nFor this reason, X11 forwarding is subjected to X11 SECURITY extension\\nrestrictions by default.\\nPlease refer to the\\nssh\\n-Y \\noption and the\\n ForwardX11Trusted\\ndirective in\\nssh_config(5)\\nfor more information.\\n\"\n },\n {\n \"code\": null,\n \"e\": 13796,\n \"s\": 13600,\n \"text\": \"\\nssh\\nmay additionally obtain configuration data from\\na per-user configuration file and a system-wide configuration file.\\nThe file format and configuration options are described in\\nssh_config(5).\\n\"\n },\n {\n \"code\": null,\n \"e\": 13885,\n \"s\": 13796,\n \"text\": \"\\nssh\\nexits with the exit status of the remote command or with 255\\nif an error occurred.\\n\"\n },\n {\n \"code\": null,\n \"e\": 14215,\n \"s\": 13885,\n \"text\": \"\\nThe methods available for authentication are:\\nhost-based authentication,\\npublic key authentication,\\nchallenge-response authentication,\\nand password authentication.\\nAuthentication methods are tried in the order specified above,\\nthough protocol 2 has a configuration option to change the default order:\\n PreferredAuthentications.\\n\"\n },\n {\n \"code\": null,\n \"e\": 15116,\n \"s\": 14215,\n \"text\": \"\\nHost-based authentication works as follows:\\nIf the machine the user logs in from is listed in\\n /etc/hosts.equiv\\nor\\n /etc/ssh/shosts.equiv\\non the remote machine, and the user names are\\nthe same on both sides, or if the files\\n ~/.rhosts\\nor\\n ~/.shosts\\nexist in the user’s home directory on the\\nremote machine and contain a line containing the name of the client\\nmachine and the name of the user on that machine, the user is\\nconsidered for login.\\nAdditionally, the server\\n must\\nbe able to verify the client’s\\nhost key (see the description of\\n /etc/ssh/ssh_known_hosts\\nand\\n ~/.ssh/known_hosts,\\nbelow)\\nfor login to be permitted.\\nThis authentication method closes security holes due to IP\\nspoofing, DNS spoofing, and routing spoofing.\\n[Note to the administrator:\\n /etc/hosts.equiv,\\n ~/.rhosts,\\nand the rlogin/rsh protocol in general, are inherently insecure and should be\\ndisabled if security is desired.]\\n\"\n },\n {\n \"code\": null,\n \"e\": 15797,\n \"s\": 15116,\n \"text\": \"\\nPublic key authentication works as follows:\\nThe scheme is based on public-key cryptography,\\nusing cryptosystems\\nwhere encryption and decryption are done using separate keys,\\nand it is unfeasible to derive the decryption key from the encryption key.\\nThe idea is that each user creates a public/private\\nkey pair for authentication purposes.\\nThe server knows the public key, and only the user knows the private key.\\nssh\\nimplements public key authentication protocol automatically,\\nusing either the RSA or DSA algorithms.\\nProtocol 1 is restricted to using only RSA keys,\\nbut protocol 2 may use either.\\nThe\\nHISTORY\\nsection of\\nssl(8)\\ncontains a brief discussion of the two algorithms.\\n\"\n },\n {\n \"code\": null,\n \"e\": 16150,\n \"s\": 15797,\n \"text\": \"\\nThe file\\n ~/.ssh/authorized_keys\\nlists the public keys that are permitted for logging in.\\nWhen the user logs in, the\\nssh\\nprogram tells the server which key pair it would like to use for\\nauthentication.\\nThe client proves that it has access to the private key\\nand the server checks that the corresponding public key\\nis authorized to accept the account.\\n\"\n },\n {\n \"code\": null,\n \"e\": 16826,\n \"s\": 16150,\n \"text\": \"\\nThe user creates his/her key pair by running\\nssh-keygen(1).\\nThis stores the private key in\\n ~/.ssh/identity\\n(protocol 1),\\n ~/.ssh/id_dsa\\n(protocol 2 DSA),\\nor\\n ~/.ssh/id_rsa\\n(protocol 2 RSA)\\nand stores the public key in\\n ~/.ssh/identity.pub\\n(protocol 1),\\n ~/.ssh/id_dsa.pub\\n(protocol 2 DSA),\\nor\\n ~/.ssh/id_rsa.pub\\n(protocol 2 RSA)\\nin the user’s home directory.\\nThe user should then copy the public key\\nto\\n ~/.ssh/authorized_keys\\nin his/her home directory on the remote machine.\\nThe\\n authorized_keys\\nfile corresponds to the conventional\\n ~/.rhosts\\nfile, and has one key\\nper line, though the lines can be very long.\\nAfter this, the user can log in without giving the password.\\n\"\n },\n {\n \"code\": null,\n \"e\": 16961,\n \"s\": 16826,\n \"text\": \"\\nThe most convenient way to use public key authentication may be with an\\nauthentication agent.\\nSee\\nssh-agent(1)\\nfor more information.\\n\"\n },\n {\n \"code\": null,\n \"e\": 17330,\n \"s\": 16961,\n \"text\": \"\\nChallenge-response authentication works as follows:\\nThe server sends an arbitrary\\n\\\"challenge\\\"\\ntext, and prompts for a response.\\nProtocol 2 allows multiple challenges and responses;\\nprotocol 1 is restricted to just one challenge/response.\\nExamples of challenge-response authentication include\\nBSD Authentication (see\\nlogin.conf(5))\\nand PAM (some non-OpenBSD systems).\\n\"\n },\n {\n \"code\": null,\n \"e\": 17584,\n \"s\": 17330,\n \"text\": \"\\nFinally, if other authentication methods fail,\\nssh\\nprompts the user for a password.\\nThe password is sent to the remote\\nhost for checking; however, since all communications are encrypted,\\nthe password cannot be seen by someone listening on the network.\\n\"\n },\n {\n \"code\": null,\n \"e\": 18263,\n \"s\": 17584,\n \"text\": \"\\nssh\\nautomatically maintains and checks a database containing\\nidentification for all hosts it has ever been used with.\\nHost keys are stored in\\n ~/.ssh/known_hosts\\nin the user’s home directory.\\nAdditionally, the file\\n /etc/ssh/ssh_known_hosts\\nis automatically checked for known hosts.\\nAny new hosts are automatically added to the user’s file.\\nIf a host’s identification ever changes,\\nssh\\nwarns about this and disables password authentication to prevent\\nserver spoofing or man-in-the-middle attacks,\\nwhich could otherwise be used to circumvent the encryption.\\nThe\\n StrictHostKeyChecking\\noption can be used to control logins to machines whose\\nhost key is not known or has changed.\\n\"\n },\n {\n \"code\": null,\n \"e\": 18535,\n \"s\": 18263,\n \"text\": \"\\nWhen the user’s identity has been accepted by the server, the server\\neither executes the given command, or logs into the machine and gives\\nthe user a normal shell on the remote machine.\\nAll communication with\\nthe remote command or shell will be automatically encrypted.\\n\"\n },\n {\n \"code\": null,\n \"e\": 18653,\n \"s\": 18535,\n \"text\": \"\\nIf a pseudo-terminal has been allocated (normal login session), the\\nuser may use the escape characters noted below.\\n\"\n },\n {\n \"code\": null,\n \"e\": 18887,\n \"s\": 18653,\n \"text\": \"\\nIf no pseudo-tty has been allocated,\\nthe session is transparent and can be used to reliably transfer binary data.\\nOn most systems, setting the escape character to\\n\\\"none\\\"\\nwill also make the session transparent even if a tty is used.\\n\"\n },\n {\n \"code\": null,\n \"e\": 19016,\n \"s\": 18887,\n \"text\": \"\\nThe session terminates when the command or shell on the remote\\nmachine exits and all X11 and TCP connections have been closed.\\n\"\n },\n {\n \"code\": null,\n \"e\": 19364,\n \"s\": 19016,\n \"text\": \"\\nA single tilde character can be sent as\\n ~~\\nor by following the tilde by a character other than those described below.\\nThe escape character must always follow a newline to be interpreted as\\nspecial.\\nThe escape character can be changed in configuration files using the\\n EscapeChar\\nconfiguration directive or on the command line by the\\n-e \\noption.\\n\"\n },\n {\n \"code\": null,\n \"e\": 19420,\n \"s\": 19364,\n \"text\": \"\\nThe supported escapes (assuming the default\\n‘~’)\\nare:\\n\"\n },\n {\n \"code\": null,\n \"e\": 19917,\n \"s\": 19420,\n \"text\": \"\\nIn the example below, we look at encrypting communication between\\nan IRC client and server, even though the IRC server does not directly\\nsupport encrypted communications.\\nThis works as follows:\\nthe user connects to the remote host using\\nssh,\\nspecifying a port to be used to forward connections\\nto the remote server.\\nAfter that it is possible to start the service which is to be encrypted\\non the client machine,\\nconnecting to the same local port,\\nand\\nssh\\nwill encrypt and forward the connection.\\n\"\n },\n {\n \"code\": null,\n \"e\": 20047,\n \"s\": 19917,\n \"text\": \"\\nThe following example tunnels an IRC session from client machine\\n\\\"127.0.0.1\\\"\\n(localhost)\\nto remote server\\n\\\"server.example.com\\\":\\n\"\n },\n {\n \"code\": null,\n \"e\": 20150,\n \"s\": 20047,\n \"text\": \"$ ssh -f -L 1234:localhost:6667 server.example.com sleep 10\\n$ irc -c ’#users’ -p 1234 pinky 127.0.0.1\\n\"\n },\n {\n \"code\": null,\n \"e\": 20570,\n \"s\": 20150,\n \"text\": \"\\nThis tunnels a connection to IRC server\\n\\\"server.example.com\\\",\\njoining channel\\n\\\"#users\\\",\\nnickname\\n\\\"pinky\\\",\\nusing port 1234.\\nIt doesn’t matter which port is used,\\nas long as it’s greater than 1023\\n(remember, only root can open sockets on privileged ports)\\nand doesn’t conflict with any ports already in use.\\nThe connection is forwarded to port 6667 on the remote server,\\nsince that’s the standard port for IRC services.\\n\"\n },\n {\n \"code\": null,\n \"e\": 20822,\n \"s\": 20570,\n \"text\": \"\\nThe\\n-f \\noption backgrounds\\nssh\\nand the remote command\\n\\\"sleep 10\\\"\\nis specified to allow an amount of time\\n(10 seconds, in the example)\\nto start the service which is to be tunnelled.\\nIf no connections are made within the time specified,\\nssh\\nwill exit.\\n\"\n },\n {\n \"code\": null,\n \"e\": 21081,\n \"s\": 20822,\n \"text\": \"\\nThe\\n DISPLAY\\nvalue set by\\nssh\\nwill point to the server machine, but with a display number greater than zero.\\nThis is normal, and happens because\\nssh\\ncreates a\\n\\\"proxy\\\"\\nX server on the server machine for forwarding the\\nconnections over the encrypted channel.\\n\"\n },\n {\n \"code\": null,\n \"e\": 21493,\n \"s\": 21081,\n \"text\": \"\\nssh\\nwill also automatically set up Xauthority data on the server machine.\\nFor this purpose, it will generate a random authorization cookie,\\nstore it in Xauthority on the server, and verify that any forwarded\\nconnections carry this cookie and replace it by the real cookie when\\nthe connection is opened.\\nThe real authentication cookie is never\\nsent to the server machine (and no cookies are sent in the plain).\\n\"\n },\n {\n \"code\": null,\n \"e\": 21721,\n \"s\": 21493,\n \"text\": \"\\nIf the\\n ForwardAgent\\nvariable is set to\\n\\\"yes\\\"\\n(or see the description of the\\n-A \\nand\\n-a \\noptions above) and\\nthe user is using an authentication agent, the connection to the agent\\nis automatically forwarded to the remote side.\\n\"\n },\n {\n \"code\": null,\n \"e\": 21773,\n \"s\": 21723,\n \"text\": \" $ ssh-keygen -l -f /etc/ssh/ssh_host_rsa_key\"\n },\n {\n \"code\": null,\n \"e\": 22149,\n \"s\": 21775,\n \"text\": \"\\nIf the fingerprint is already known,\\nit can be matched and verified,\\nand the key can be accepted.\\nIf the fingerprint is unknown,\\nan alternative method of verification is available:\\nSSH fingerprints verified by DNS.\\nAn additional resource record (RR),\\nSSHFP,\\nis added to a zonefile\\nand the connecting client is able to match the fingerprint\\nwith that of the key presented.\\n\"\n },\n {\n \"code\": null,\n \"e\": 22315,\n \"s\": 22149,\n \"text\": \"\\nIn this example, we are connecting a client to a server,\\n\\\"host.example.com\\\".\\nThe SSHFP resource records should first be added to the zonefile for\\nhost.example.com:\\n\"\n },\n {\n \"code\": null,\n \"e\": 22450,\n \"s\": 22315,\n \"text\": \"$ ssh-keygen -f /etc/ssh/ssh_host_rsa_key.pub -r host.example.com.\\n$ ssh-keygen -f /etc/ssh/ssh_host_dsa_key.pub -r host.example.com.\\n\"\n },\n {\n \"code\": null,\n \"e\": 22565,\n \"s\": 22450,\n \"text\": \"\\nThe output lines will have to be added to the zonefile.\\nTo check that the zone is answering fingerprint queries:\\n\"\n },\n {\n \"code\": null,\n \"e\": 22604,\n \"s\": 22567,\n \"text\": \" $ dig -t SSHFP host.example.com\"\n },\n {\n \"code\": null,\n \"e\": 22637,\n \"s\": 22606,\n \"text\": \"\\nFinally the client connects:\\n\"\n },\n {\n \"code\": null,\n \"e\": 22792,\n \"s\": 22637,\n \"text\": \"$ ssh -o \\\"VerifyHostKeyDNS ask\\\" host.example.com\\n[...]\\nMatching host key fingerprint found in DNS.\\nAre you sure you want to continue connecting (yes/no)?\\n\"\n },\n {\n \"code\": null,\n \"e\": 22866,\n \"s\": 22792,\n \"text\": \"\\nSee the\\n VerifyHostKeyDNS\\noption in\\nssh_config(5)\\nfor more information.\\n\"\n },\n {\n \"code\": null,\n \"e\": 23069,\n \"s\": 22866,\n \"text\": \"\\nThe following example would connect client network 10.0.50.0/24\\nwith remote network 10.0.99.0/24, provided that the SSH server\\nrunning on the gateway to the remote network,\\nat 192.168.1.15, allows it:\\n\"\n },\n {\n \"code\": null,\n \"e\": 23164,\n \"s\": 23069,\n \"text\": \"# ssh -f -w 0:1 192.168.1.15 true\\n# ifconfig tun0 10.0.50.1 10.0.99.1 netmask 255.255.255.252\\n\"\n },\n {\n \"code\": null,\n \"e\": 23484,\n \"s\": 23164,\n \"text\": \"\\nClient access may be more finely tuned via the\\n /root/.ssh/authorized_keys\\nfile (see below) and the\\n PermitRootLogin\\nserver option.\\nThe following entry would permit connections on the first\\ntun(4)\\ndevice from user\\n\\\"jane\\\"\\nand on the second device from user\\n\\\"john\\\",\\nif\\n PermitRootLogin\\nis set to\\n\\\"forced-commands-only\\\":\\n\"\n },\n {\n \"code\": null,\n \"e\": 23605,\n \"s\": 23484,\n \"text\": \"tunnel=\\\"1\\\",command=\\\"sh /etc/netstart tun1\\\" ssh-rsa ... jane\\ntunnel=\\\"2\\\",command=\\\"sh /etc/netstart tun1\\\" ssh-rsa ... john\\n\"\n },\n {\n \"code\": null,\n \"e\": 23821,\n \"s\": 23605,\n \"text\": \"\\nSince a SSH-based setup entails a fair amount of overhead,\\nit may be more suited to temporary setups,\\nsuch as for wireless VPNs.\\nMore permanent VPNs are better provided by tools such as\\nipsecctl(8)\\nand\\nisakmpd(8).\\n\"\n },\n {\n \"code\": null,\n \"e\": 24081,\n \"s\": 23821,\n \"text\": \"\\nAdditionally,\\nssh\\nreads\\n ~/.ssh/environment,\\nand adds lines of the format\\n\\\"VARNAME=value\\\"\\nto the environment if the file exists and users are allowed to\\nchange their environment.\\nFor more information, see the\\n PermitUserEnvironment\\noption in\\nsshd_config(5).\\n\"\n },\n {\n \"code\": null,\n \"e\": 24126,\n \"s\": 24109,\n \"text\": \"\\nAdvertisements\\n\"\n },\n {\n \"code\": null,\n \"e\": 24161,\n \"s\": 24126,\n \"text\": \"\\n 129 Lectures \\n 23 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 24189,\n \"s\": 24161,\n \"text\": \" Eduonix Learning Solutions\"\n },\n {\n \"code\": null,\n \"e\": 24223,\n \"s\": 24189,\n \"text\": \"\\n 5 Lectures \\n 4.5 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 24240,\n \"s\": 24223,\n \"text\": \" Frahaan Hussain\"\n },\n {\n \"code\": null,\n \"e\": 24273,\n \"s\": 24240,\n \"text\": \"\\n 35 Lectures \\n 2 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 24284,\n \"s\": 24273,\n \"text\": \" Pradeep D\"\n },\n {\n \"code\": null,\n \"e\": 24319,\n \"s\": 24284,\n \"text\": \"\\n 41 Lectures \\n 2.5 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 24335,\n \"s\": 24319,\n \"text\": \" Musab Zayadneh\"\n },\n {\n \"code\": null,\n \"e\": 24368,\n \"s\": 24335,\n \"text\": \"\\n 46 Lectures \\n 4 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 24380,\n \"s\": 24368,\n \"text\": \" GUHARAJANM\"\n },\n {\n \"code\": null,\n \"e\": 24412,\n \"s\": 24380,\n \"text\": \"\\n 6 Lectures \\n 4 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 24420,\n \"s\": 24412,\n \"text\": \" Uplatz\"\n },\n {\n \"code\": null,\n \"e\": 24427,\n \"s\": 24420,\n \"text\": \" Print\"\n },\n {\n \"code\": null,\n \"e\": 24438,\n \"s\": 24427,\n \"text\": \" Add Notes\"\n }\n]"}}},{"rowIdx":438,"cells":{"title":{"kind":"string","value":"Google Charts - Stacked Column Chart"},"text":{"kind":"string","value":"Following is an example of a stacked column chart. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example.\nWe've used isStacked configuration to show stacked chart.\n// Set chart options\nvar options = {\n isStacked: true\n};\ngooglecharts_column_stacked.htm\n\n \n Google Charts Tutorial\n \n \n \n \n \n
\n
\n \n \n\nVerify the result.\n Print\n Add Notes\n Bookmark this page"},"parsed":{"kind":"list like","value":[{"code":null,"e":2456,"s":2261,"text":"Following is an example of a stacked column chart. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example."},{"code":null,"e":2514,"s":2456,"text":"We've used isStacked configuration to show stacked chart."},{"code":null,"e":2573,"s":2514,"text":"// Set chart options\nvar options = {\n isStacked: true\n};"},{"code":null,"e":2605,"s":2573,"text":"googlecharts_column_stacked.htm"},{"code":null,"e":3835,"s":2605,"text":"\n \n Google Charts Tutorial\n \n \n \n \n \n
\n
\n \n \n"},{"code":null,"e":3854,"s":3835,"text":"Verify the result."},{"code":null,"e":3861,"s":3854,"text":" Print"},{"code":null,"e":3872,"s":3861,"text":" Add Notes"}],"string":"[\n {\n \"code\": null,\n \"e\": 2456,\n \"s\": 2261,\n \"text\": \"Following is an example of a stacked column chart. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example.\"\n },\n {\n \"code\": null,\n \"e\": 2514,\n \"s\": 2456,\n \"text\": \"We've used isStacked configuration to show stacked chart.\"\n },\n {\n \"code\": null,\n \"e\": 2573,\n \"s\": 2514,\n \"text\": \"// Set chart options\\nvar options = {\\n isStacked: true\\n};\"\n },\n {\n \"code\": null,\n \"e\": 2605,\n \"s\": 2573,\n \"text\": \"googlecharts_column_stacked.htm\"\n },\n {\n \"code\": null,\n \"e\": 3835,\n \"s\": 2605,\n \"text\": \"\\n \\n Google Charts Tutorial\\n \\n \\n \\n \\n \\n
\\n
\\n \\n \\n\"\n },\n {\n \"code\": null,\n \"e\": 3854,\n \"s\": 3835,\n \"text\": \"Verify the result.\"\n },\n {\n \"code\": null,\n \"e\": 3861,\n \"s\": 3854,\n \"text\": \" Print\"\n },\n {\n \"code\": null,\n \"e\": 3872,\n \"s\": 3861,\n \"text\": \" Add Notes\"\n }\n]"}}},{"rowIdx":439,"cells":{"title":{"kind":"string","value":"How Region of Interest (ROI) works in OpenCV using C++?"},"text":{"kind":"string","value":"To separate a particular portion from the image, we have to locate the area first. Then we\nhave to copy that area from the main image to another matrix. This is how the ROI in\nOpenCV works.\nIn this example, two matrices have been declared at the beginning. After that, an image named 'image_name.jpg' has been loaded into the 'image1' matrix. The next line 'image2=image1 (Rect(100, 100, 120, 120));' requires special attention. This line is cropping out the defined region of the image and storing it in the 'image2' matrix.\nThe figure shows what we have done here with the 'Rect(100,100,120,120)' code. The\nbasic form of this line of code is 'Rect(x, y,x1,y1)'. Here x and y defines the rectangle's starting point and x1 and y1represents the endpoint of the rectangle. By changing these values, we can change the size of the rectangle.\nThe following program demonstrates the working of Region of Interest in OpenCV:\n#include\n#include\n#include\nusing namespace std;\nusing namespace cv;\nint main() {\n Mat image1; //Declaring a matrix named 'image1'//\n Mat image2; //Declaring a matrix named 'image2'//\n image1 = imread(\"RGB.png\"); //Loading an image name 'image_name.png into image1 matrix//\n image2 = image1(Rect(100, 100, 120, 120)); //imposing a rectangle on\n image1//\n namedWindow(\"Image_Window1\"); //Declaring an window to show actual image//\n namedWindow(\"Image_Window2\"); //Declaring an window to show ROI//\n imshow(\"Image_Window1\", image1); //Showing actual image//\n imshow(\"Image_Window2\", image2);\n waitKey(0);\n return 0;\n}"},"parsed":{"kind":"list like","value":[{"code":null,"e":1252,"s":1062,"text":"To separate a particular portion from the image, we have to locate the area first. Then we\nhave to copy that area from the main image to another matrix. This is how the ROI in\nOpenCV works."},{"code":null,"e":1588,"s":1252,"text":"In this example, two matrices have been declared at the beginning. After that, an image named 'image_name.jpg' has been loaded into the 'image1' matrix. The next line 'image2=image1 (Rect(100, 100, 120, 120));' requires special attention. This line is cropping out the defined region of the image and storing it in the 'image2' matrix."},{"code":null,"e":1900,"s":1588,"text":"The figure shows what we have done here with the 'Rect(100,100,120,120)' code. The\nbasic form of this line of code is 'Rect(x, y,x1,y1)'. Here x and y defines the rectangle's starting point and x1 and y1represents the endpoint of the rectangle. By changing these values, we can change the size of the rectangle."},{"code":null,"e":1980,"s":1900,"text":"The following program demonstrates the working of Region of Interest in OpenCV:"},{"code":null,"e":2617,"s":1980,"text":"#include\n#include\n#include\nusing namespace std;\nusing namespace cv;\nint main() {\n Mat image1; //Declaring a matrix named 'image1'//\n Mat image2; //Declaring a matrix named 'image2'//\n image1 = imread(\"RGB.png\"); //Loading an image name 'image_name.png into image1 matrix//\n image2 = image1(Rect(100, 100, 120, 120)); //imposing a rectangle on\n image1//\n namedWindow(\"Image_Window1\"); //Declaring an window to show actual image//\n namedWindow(\"Image_Window2\"); //Declaring an window to show ROI//\n imshow(\"Image_Window1\", image1); //Showing actual image//\n imshow(\"Image_Window2\", image2);\n waitKey(0);\n return 0;\n}"}],"string":"[\n {\n \"code\": null,\n \"e\": 1252,\n \"s\": 1062,\n \"text\": \"To separate a particular portion from the image, we have to locate the area first. Then we\\nhave to copy that area from the main image to another matrix. This is how the ROI in\\nOpenCV works.\"\n },\n {\n \"code\": null,\n \"e\": 1588,\n \"s\": 1252,\n \"text\": \"In this example, two matrices have been declared at the beginning. After that, an image named 'image_name.jpg' has been loaded into the 'image1' matrix. The next line 'image2=image1 (Rect(100, 100, 120, 120));' requires special attention. This line is cropping out the defined region of the image and storing it in the 'image2' matrix.\"\n },\n {\n \"code\": null,\n \"e\": 1900,\n \"s\": 1588,\n \"text\": \"The figure shows what we have done here with the 'Rect(100,100,120,120)' code. The\\nbasic form of this line of code is 'Rect(x, y,x1,y1)'. Here x and y defines the rectangle's starting point and x1 and y1represents the endpoint of the rectangle. By changing these values, we can change the size of the rectangle.\"\n },\n {\n \"code\": null,\n \"e\": 1980,\n \"s\": 1900,\n \"text\": \"The following program demonstrates the working of Region of Interest in OpenCV:\"\n },\n {\n \"code\": null,\n \"e\": 2617,\n \"s\": 1980,\n \"text\": \"#include\\n#include\\n#include\\nusing namespace std;\\nusing namespace cv;\\nint main() {\\n Mat image1; //Declaring a matrix named 'image1'//\\n Mat image2; //Declaring a matrix named 'image2'//\\n image1 = imread(\\\"RGB.png\\\"); //Loading an image name 'image_name.png into image1 matrix//\\n image2 = image1(Rect(100, 100, 120, 120)); //imposing a rectangle on\\n image1//\\n namedWindow(\\\"Image_Window1\\\"); //Declaring an window to show actual image//\\n namedWindow(\\\"Image_Window2\\\"); //Declaring an window to show ROI//\\n imshow(\\\"Image_Window1\\\", image1); //Showing actual image//\\n imshow(\\\"Image_Window2\\\", image2);\\n waitKey(0);\\n return 0;\\n}\"\n }\n]"}}},{"rowIdx":440,"cells":{"title":{"kind":"string","value":"Bitonic Sort - GeeksforGeeks"},"text":{"kind":"string","value":"12 Apr, 2022\nBackground\nBitonic Sort is a classic parallel algorithm for sorting. \nBitonic sort does O(n Log 2n) comparisons.\nThe number of comparisons done by Bitonic sort are more than popular sorting algorithms like Merge Sort [ does O(nLogn) comparisons], but Bitonice sort is better for parallel implementation because we always compare elements in predefined sequence and the sequence of comparison doesn’t depend on data. Therefore it is suitable for implementation in hardware and parallel processor array.\nBitonic Sort must be done if number of elements to sort are 2^n. The procedure of bitonic sequence fails if the number of elements are not in the aforementioned quantity precisely.\nTo understand Bitonic Sort, we must first understand what is Bitonic Sequence and how to make a given sequence Bitonic. \nBitonic Sequence\nA sequence is called Bitonic if it is first increasing, then decreasing. In other words, an array arr[0..n-i] is Bitonic if there exists an index i where 0<=i<=n-1 such that \nx0 <= x1 .....<= xi and xi >= xi+1..... >= xn-1 \nA sequence, sorted in increasing order is considered Bitonic with the decreasing part as empty. Similarly, decreasing order sequence is considered Bitonic with the increasing part as empty.A rotation of Bitonic Sequence is also bitonic.\nA sequence, sorted in increasing order is considered Bitonic with the decreasing part as empty. Similarly, decreasing order sequence is considered Bitonic with the increasing part as empty.\nA rotation of Bitonic Sequence is also bitonic.\nHow to form a Bitonic Sequence from a random input? We start by forming 4-element bitonic sequences from consecutive 2-element sequence. Consider 4-element in sequence x0, x1, x2, x3. We sort x0 and x1 in ascending order and x2 and x3 in descending order. We then concatenate the two pairs to form a 4 element bitonic sequence. Next, we take two 4 element bitonic sequences, sorting one in ascending order, the other in descending order (using the Bitonic Sort which we will discuss below), and so on, until we obtain the bitonic sequence.\nExample: Convert the following sequence to bitonic sequence: 3, 7, 4, 8, 6, 2, 1, 5 \nStep 1: Consider each 2-consecutive elements as bitonic sequence and apply bitonic sort on each 2- pair elements. In next step, take two 4 element bitonic sequences and so on.\nNote: x0 and x1 are sorted in ascending order and x2 and x3 in descending order and so on\nStep 2: Two 4 element bitonic sequences: A(3,7,8,4) and B(2,6,5,1) with comparator length as 2 \nAfter this step, we’ll get Bitonic sequence of length 8. \n 3, 4, 7, 8, 6, 5, 2, 1\nBitonic Sorting\nIt mainly involves two steps. \nForming a bitonic sequence (discussed above in detail). After this step we reach the fourth stage in below diagram, i.e., the array becomes {3, 4, 7, 8, 6, 5, 2, 1}Creating one sorted sequence from bitonic sequence: After first step, first half is sorted in increasing order and second half in decreasing order. We compare first element of first half with first element of second half, then second element of first half with second element of second, and so on. We exchange elements if an element of first half is smaller. After above compare and exchange steps, we get two bitonic sequences in array. See fifth stage in below diagram. In the fifth stage, we have {3, 4, 2, 1, 6, 5, 7, 8}. If we take a closer look at the elements, we can notice that there are two bitonic sequences of length n/2 such that all elements in first bitonic sequence {3, 4, 2, 1} are smaller than all elements of second bitonic sequence {6, 5, 7, 8}. We repeat the same process within two bitonic sequences and we get four bitonic sequences of length n/4 such that all elements of leftmost bitonic sequence are smaller and all elements of rightmost. See sixth stage in below diagram, arrays is {2, 1, 3, 4, 6, 5, 7, 8}. If we repeat this process one more time we get 8 bitonic sequences of size n/8 which is 1. Since all these bitonic sequence are sorted and every bitonic sequence has one element, we get the sorted array.\nForming a bitonic sequence (discussed above in detail). After this step we reach the fourth stage in below diagram, i.e., the array becomes {3, 4, 7, 8, 6, 5, 2, 1}\nCreating one sorted sequence from bitonic sequence: After first step, first half is sorted in increasing order and second half in decreasing order. We compare first element of first half with first element of second half, then second element of first half with second element of second, and so on. We exchange elements if an element of first half is smaller. After above compare and exchange steps, we get two bitonic sequences in array. See fifth stage in below diagram. In the fifth stage, we have {3, 4, 2, 1, 6, 5, 7, 8}. If we take a closer look at the elements, we can notice that there are two bitonic sequences of length n/2 such that all elements in first bitonic sequence {3, 4, 2, 1} are smaller than all elements of second bitonic sequence {6, 5, 7, 8}. We repeat the same process within two bitonic sequences and we get four bitonic sequences of length n/4 such that all elements of leftmost bitonic sequence are smaller and all elements of rightmost. See sixth stage in below diagram, arrays is {2, 1, 3, 4, 6, 5, 7, 8}. If we repeat this process one more time we get 8 bitonic sequences of size n/8 which is 1. Since all these bitonic sequence are sorted and every bitonic sequence has one element, we get the sorted array.\nBelow are implementations of Bitonic Sort. \nC++\nJava\nPython3\nC#\nJavascript\n/* C++ Program for Bitonic Sort. Note that this program works only when size of input is a power of 2. */#includeusing namespace std; /*The parameter dir indicates the sorting direction, ASCENDING or DESCENDING; if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are interchanged.*/void compAndSwap(int a[], int i, int j, int dir){ if (dir==(a[i]>a[j])) swap(a[i],a[j]);} /*It recursively sorts a bitonic sequence in ascending order, if dir = 1, and in descending order otherwise (means dir=0). The sequence to be sorted starts at index position low, the parameter cnt is the number of elements to be sorted.*/void bitonicMerge(int a[], int low, int cnt, int dir){ if (cnt>1) { int k = cnt/2; for (int i=low; i1) { int k = cnt/2; // sort in ascending order since dir here is 1 bitonicSort(a, low, k, 1); // sort in descending order since dir here is 0 bitonicSort(a, low+k, k, 0); // Will merge whole sequence in ascending order // since dir=1. bitonicMerge(a,low, cnt, dir); }} /* Caller of bitonicSort for sorting the entire array of length N in ASCENDING order */void sort(int a[], int N, int up){ bitonicSort(a,0, N, up);} // Driver codeint main(){ int a[]= {3, 7, 4, 8, 6, 2, 1, 5}; int N = sizeof(a)/sizeof(a[0]); int up = 1; // means sort in ascending order sort(a, N, up); printf(\"Sorted array: \\n\"); for (int i=0; i a[j]) agrees with the direction, then a[i] and a[j] are interchanged. */ void compAndSwap(int a[], int i, int j, int dir) { if ( (a[i] > a[j] && dir == 1) || (a[i] < a[j] && dir == 0)) { // Swapping elements int temp = a[i]; a[i] = a[j]; a[j] = temp; } } /* It recursively sorts a bitonic sequence in ascending order, if dir = 1, and in descending order otherwise (means dir=0). The sequence to be sorted starts at index position low, the parameter cnt is the number of elements to be sorted.*/ void bitonicMerge(int a[], int low, int cnt, int dir) { if (cnt>1) { int k = cnt/2; for (int i=low; i1) { int k = cnt/2; // sort in ascending order since dir here is 1 bitonicSort(a, low, k, 1); // sort in descending order since dir here is 0 bitonicSort(a,low+k, k, 0); // Will merge whole sequence in ascending order // since dir=1. bitonicMerge(a, low, cnt, dir); } } /*Caller of bitonicSort for sorting the entire array of length N in ASCENDING order */ void sort(int a[], int N, int up) { bitonicSort(a, 0, N, up); } /* A utility function to print array of size n */ static void printArray(int arr[]) { int n = arr.length; for (int i=0; i a[j]) agrees with the direction,# then a[i] and a[j] are interchanged.*/def compAndSwap(a, i, j, dire): if (dire==1 and a[i] > a[j]) or (dire==0 and a[i] < a[j]): a[i],a[j] = a[j],a[i] # It recursively sorts a bitonic sequence in ascending order,# if dir = 1, and in descending order otherwise (means dir=0).# The sequence to be sorted starts at index position low,# the parameter cnt is the number of elements to be sorted.def bitonicMerge(a, low, cnt, dire): if cnt > 1: k = cnt//2 for i in range(low , low+k): compAndSwap(a, i, i+k, dire) bitonicMerge(a, low, k, dire) bitonicMerge(a, low+k, k, dire) # This function first produces a bitonic sequence by recursively# sorting its two halves in opposite sorting orders, and then# calls bitonicMerge to make them in the same orderdef bitonicSort(a, low, cnt,dire): if cnt > 1: k = cnt//2 bitonicSort(a, low, k, 1) bitonicSort(a, low+k, k, 0) bitonicMerge(a, low, cnt, dire) # Caller of bitonicSort for sorting the entire array of length N# in ASCENDING orderdef sort(a,N, up): bitonicSort(a,0, N, up) # Driver code to test abovea = [3, 7, 4, 8, 6, 2, 1, 5]n = len(a)up = 1 sort(a, n, up)print (\"\\n\\nSorted array is\")for i in range(n): print(\"%d\" %a[i],end=\" \")\n/* C# Program for Bitonic Sort. Note that this program works only when size of input is a power of 2. */using System; /*The parameter dir indicates the sorting direction, ASCENDING or DESCENDING; if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are interchanged.*/class GFG{ /* To swap values */ static void Swap(ref T lhs, ref T rhs) { T temp; temp = lhs; lhs = rhs; rhs = temp; } public static void compAndSwap(int[] a, int i, int j, int dir) { int k; if((a[i]>a[j])) k=1; else k=0; if (dir==k) Swap(ref a[i],ref a[j]); } /*It recursively sorts a bitonic sequence in ascending order, if dir = 1, and in descending order otherwise (means dir=0). The sequence to be sorted starts at index position low, the parameter cnt is the number of elements to be sorted.*/ public static void bitonicMerge(int[] a, int low, int cnt, int dir) { if (cnt>1) { int k = cnt/2; for (int i=low; i1) { int k = cnt/2; // sort in ascending order since dir here is 1 bitonicSort(a, low, k, 1); // sort in descending order since dir here is 0 bitonicSort(a, low+k, k, 0); // Will merge whole sequence in ascending order // since dir=1. bitonicMerge(a,low, cnt, dir); } } /* Caller of bitonicSort for sorting the entire array of length N in ASCENDING order */ public static void sort(int[] a, int N, int up) { bitonicSort(a,0, N, up); } // Driver code static void Main() { int[] a= {3, 7, 4, 8, 6, 2, 1, 5}; int N = a.Length; int up = 1; // means sort in ascending order sort(a, N, up); Console.Write(\"Sorted array: \\n\"); for (int i=0; i /* JavaScript program for Bitonic Sort. Note that this program works only when size of input is a power of 2. */ /* The parameter dir indicates the sorting direction, ASCENDING or DESCENDING; if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are interchanged. */ function compAndSwap(a, i, j, dir) { if ((a[i] > a[j] && dir === 1) || (a[i] < a[j] && dir === 0)) { // Swapping elements var temp = a[i]; a[i] = a[j]; a[j] = temp; } } /* It recursively sorts a bitonic sequence in ascending order, if dir = 1, and in descending order otherwise (means dir=0). The sequence to be sorted starts at index position low, the parameter cnt is the number of elements to be sorted.*/ function bitonicMerge(a, low, cnt, dir) { if (cnt > 1) { var k = parseInt(cnt / 2); for (var i = low; i < low + k; i++) compAndSwap(a, i, i + k, dir); bitonicMerge(a, low, k, dir); bitonicMerge(a, low + k, k, dir); } } /* This function first produces a bitonic sequence by recursively sorting its two halves in opposite sorting orders, and then calls bitonicMerge to make them in the same order */ function bitonicSort(a, low, cnt, dir) { if (cnt > 1) { var k = parseInt(cnt / 2); // sort in ascending order since dir here is 1 bitonicSort(a, low, k, 1); // sort in descending order since dir here is 0 bitonicSort(a, low + k, k, 0); // Will merge whole sequence in ascending order // since dir=1. bitonicMerge(a, low, cnt, dir); } } /*Caller of bitonicSort for sorting the entire array of length N in ASCENDING order */ function sort(a, N, up) { bitonicSort(a, 0, N, up); } /* A utility function to print array of size n */ function printArray(arr) { var n = arr.length; for (var i = 0; i < n; ++i) document.write(arr[i] + \" \"); document.write(\"
\"); } // Driver method var a = [3, 7, 4, 8, 6, 2, 1, 5]; var up = 1; sort(a, a.length, up); document.write(\"Sorted array:
\"); printArray(a); \nOutput: \nSorted array: \n1 2 3 4 5 6 7 8\n \nAnalysis of Bitonic Sort\nTo form a sorted sequence of length n from two sorted sequences of length n/2, log(n) comparisons are required (for example: log(8) = 3 when sequence size. Therefore, The number of comparisons T(n) of the entire sorting is given by:T(n) = log(n) + T(n/2)The solution of this recurrence equation isT(n) = log(n) + log(n)-1 + log(n)-2 + ... + 1 = log(n) · (log(n)+1) / 2As, each stage of the sorting network consists of n/2 comparators. Therefore total ?(n log2n) comparators.\nReferences: 1. https://www.youtube.com/watch?v=GEQ8y26blEY 2. http://www.iti.fh-flensburg.de/lang/algorithmen/sortieren/bitonic/bitonicen.htm 3. https://en.wikipedia.org/wiki/Bitonic_sorterThis article is contributed by Rahul Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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. \nDrRoot_\nshantanukonwar\nrdtank\nkk9826225\nsagar0719kumar\namartyaniel20\nsimmytarika5\nSorting\nSorting\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nstd::sort() in C++ STL\nTime Complexities of all Sorting Algorithms\nRadix Sort\nMerge two sorted arrays\nSort an array of 0s, 1s and 2s\nPython Program for Bubble Sort\nSorting Vector of Pairs in C++ | Set 1 (Sort by first and second)\nk largest(or smallest) elements in an array\nsort() in Python\nCount Inversions in an array | Set 1 (Using Merge Sort)"},"parsed":{"kind":"list like","value":[{"code":null,"e":23634,"s":23606,"text":"\n12 Apr, 2022"},{"code":null,"e":23645,"s":23634,"text":"Background"},{"code":null,"e":23704,"s":23645,"text":"Bitonic Sort is a classic parallel algorithm for sorting. "},{"code":null,"e":23747,"s":23704,"text":"Bitonic sort does O(n Log 2n) comparisons."},{"code":null,"e":24136,"s":23747,"text":"The number of comparisons done by Bitonic sort are more than popular sorting algorithms like Merge Sort [ does O(nLogn) comparisons], but Bitonice sort is better for parallel implementation because we always compare elements in predefined sequence and the sequence of comparison doesn’t depend on data. Therefore it is suitable for implementation in hardware and parallel processor array."},{"code":null,"e":24317,"s":24136,"text":"Bitonic Sort must be done if number of elements to sort are 2^n. The procedure of bitonic sequence fails if the number of elements are not in the aforementioned quantity precisely."},{"code":null,"e":24439,"s":24317,"text":"To understand Bitonic Sort, we must first understand what is Bitonic Sequence and how to make a given sequence Bitonic. "},{"code":null,"e":24456,"s":24439,"text":"Bitonic Sequence"},{"code":null,"e":24632,"s":24456,"text":"A sequence is called Bitonic if it is first increasing, then decreasing. In other words, an array arr[0..n-i] is Bitonic if there exists an index i where 0<=i<=n-1 such that "},{"code":null,"e":24683,"s":24632,"text":"x0 <= x1 .....<= xi and xi >= xi+1..... >= xn-1 "},{"code":null,"e":24920,"s":24683,"text":"A sequence, sorted in increasing order is considered Bitonic with the decreasing part as empty. Similarly, decreasing order sequence is considered Bitonic with the increasing part as empty.A rotation of Bitonic Sequence is also bitonic."},{"code":null,"e":25110,"s":24920,"text":"A sequence, sorted in increasing order is considered Bitonic with the decreasing part as empty. Similarly, decreasing order sequence is considered Bitonic with the increasing part as empty."},{"code":null,"e":25158,"s":25110,"text":"A rotation of Bitonic Sequence is also bitonic."},{"code":null,"e":25698,"s":25158,"text":"How to form a Bitonic Sequence from a random input? We start by forming 4-element bitonic sequences from consecutive 2-element sequence. Consider 4-element in sequence x0, x1, x2, x3. We sort x0 and x1 in ascending order and x2 and x3 in descending order. We then concatenate the two pairs to form a 4 element bitonic sequence. Next, we take two 4 element bitonic sequences, sorting one in ascending order, the other in descending order (using the Bitonic Sort which we will discuss below), and so on, until we obtain the bitonic sequence."},{"code":null,"e":25783,"s":25698,"text":"Example: Convert the following sequence to bitonic sequence: 3, 7, 4, 8, 6, 2, 1, 5 "},{"code":null,"e":25959,"s":25783,"text":"Step 1: Consider each 2-consecutive elements as bitonic sequence and apply bitonic sort on each 2- pair elements. In next step, take two 4 element bitonic sequences and so on."},{"code":null,"e":26049,"s":25959,"text":"Note: x0 and x1 are sorted in ascending order and x2 and x3 in descending order and so on"},{"code":null,"e":26145,"s":26049,"text":"Step 2: Two 4 element bitonic sequences: A(3,7,8,4) and B(2,6,5,1) with comparator length as 2 "},{"code":null,"e":26203,"s":26145,"text":"After this step, we’ll get Bitonic sequence of length 8. "},{"code":null,"e":26227,"s":26203,"text":" 3, 4, 7, 8, 6, 5, 2, 1"},{"code":null,"e":26243,"s":26227,"text":"Bitonic Sorting"},{"code":null,"e":26275,"s":26243,"text":"It mainly involves two steps. "},{"code":null,"e":27678,"s":26275,"text":"Forming a bitonic sequence (discussed above in detail). After this step we reach the fourth stage in below diagram, i.e., the array becomes {3, 4, 7, 8, 6, 5, 2, 1}Creating one sorted sequence from bitonic sequence: After first step, first half is sorted in increasing order and second half in decreasing order. We compare first element of first half with first element of second half, then second element of first half with second element of second, and so on. We exchange elements if an element of first half is smaller. After above compare and exchange steps, we get two bitonic sequences in array. See fifth stage in below diagram. In the fifth stage, we have {3, 4, 2, 1, 6, 5, 7, 8}. If we take a closer look at the elements, we can notice that there are two bitonic sequences of length n/2 such that all elements in first bitonic sequence {3, 4, 2, 1} are smaller than all elements of second bitonic sequence {6, 5, 7, 8}. We repeat the same process within two bitonic sequences and we get four bitonic sequences of length n/4 such that all elements of leftmost bitonic sequence are smaller and all elements of rightmost. See sixth stage in below diagram, arrays is {2, 1, 3, 4, 6, 5, 7, 8}. If we repeat this process one more time we get 8 bitonic sequences of size n/8 which is 1. Since all these bitonic sequence are sorted and every bitonic sequence has one element, we get the sorted array."},{"code":null,"e":27843,"s":27678,"text":"Forming a bitonic sequence (discussed above in detail). After this step we reach the fourth stage in below diagram, i.e., the array becomes {3, 4, 7, 8, 6, 5, 2, 1}"},{"code":null,"e":29082,"s":27843,"text":"Creating one sorted sequence from bitonic sequence: After first step, first half is sorted in increasing order and second half in decreasing order. We compare first element of first half with first element of second half, then second element of first half with second element of second, and so on. We exchange elements if an element of first half is smaller. After above compare and exchange steps, we get two bitonic sequences in array. See fifth stage in below diagram. In the fifth stage, we have {3, 4, 2, 1, 6, 5, 7, 8}. If we take a closer look at the elements, we can notice that there are two bitonic sequences of length n/2 such that all elements in first bitonic sequence {3, 4, 2, 1} are smaller than all elements of second bitonic sequence {6, 5, 7, 8}. We repeat the same process within two bitonic sequences and we get four bitonic sequences of length n/4 such that all elements of leftmost bitonic sequence are smaller and all elements of rightmost. See sixth stage in below diagram, arrays is {2, 1, 3, 4, 6, 5, 7, 8}. If we repeat this process one more time we get 8 bitonic sequences of size n/8 which is 1. Since all these bitonic sequence are sorted and every bitonic sequence has one element, we get the sorted array."},{"code":null,"e":29126,"s":29082,"text":"Below are implementations of Bitonic Sort. "},{"code":null,"e":29130,"s":29126,"text":"C++"},{"code":null,"e":29135,"s":29130,"text":"Java"},{"code":null,"e":29143,"s":29135,"text":"Python3"},{"code":null,"e":29146,"s":29143,"text":"C#"},{"code":null,"e":29157,"s":29146,"text":"Javascript"},{"code":"/* C++ Program for Bitonic Sort. Note that this program works only when size of input is a power of 2. */#includeusing namespace std; /*The parameter dir indicates the sorting direction, ASCENDING or DESCENDING; if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are interchanged.*/void compAndSwap(int a[], int i, int j, int dir){ if (dir==(a[i]>a[j])) swap(a[i],a[j]);} /*It recursively sorts a bitonic sequence in ascending order, if dir = 1, and in descending order otherwise (means dir=0). The sequence to be sorted starts at index position low, the parameter cnt is the number of elements to be sorted.*/void bitonicMerge(int a[], int low, int cnt, int dir){ if (cnt>1) { int k = cnt/2; for (int i=low; i1) { int k = cnt/2; // sort in ascending order since dir here is 1 bitonicSort(a, low, k, 1); // sort in descending order since dir here is 0 bitonicSort(a, low+k, k, 0); // Will merge whole sequence in ascending order // since dir=1. bitonicMerge(a,low, cnt, dir); }} /* Caller of bitonicSort for sorting the entire array of length N in ASCENDING order */void sort(int a[], int N, int up){ bitonicSort(a,0, N, up);} // Driver codeint main(){ int a[]= {3, 7, 4, 8, 6, 2, 1, 5}; int N = sizeof(a)/sizeof(a[0]); int up = 1; // means sort in ascending order sort(a, N, up); printf(\"Sorted array: \\n\"); for (int i=0; i a[j]) agrees with the direction, then a[i] and a[j] are interchanged. */ void compAndSwap(int a[], int i, int j, int dir) { if ( (a[i] > a[j] && dir == 1) || (a[i] < a[j] && dir == 0)) { // Swapping elements int temp = a[i]; a[i] = a[j]; a[j] = temp; } } /* It recursively sorts a bitonic sequence in ascending order, if dir = 1, and in descending order otherwise (means dir=0). The sequence to be sorted starts at index position low, the parameter cnt is the number of elements to be sorted.*/ void bitonicMerge(int a[], int low, int cnt, int dir) { if (cnt>1) { int k = cnt/2; for (int i=low; i1) { int k = cnt/2; // sort in ascending order since dir here is 1 bitonicSort(a, low, k, 1); // sort in descending order since dir here is 0 bitonicSort(a,low+k, k, 0); // Will merge whole sequence in ascending order // since dir=1. bitonicMerge(a, low, cnt, dir); } } /*Caller of bitonicSort for sorting the entire array of length N in ASCENDING order */ void sort(int a[], int N, int up) { bitonicSort(a, 0, N, up); } /* A utility function to print array of size n */ static void printArray(int arr[]) { int n = arr.length; for (int i=0; i a[j]) agrees with the direction,# then a[i] and a[j] are interchanged.*/def compAndSwap(a, i, j, dire): if (dire==1 and a[i] > a[j]) or (dire==0 and a[i] < a[j]): a[i],a[j] = a[j],a[i] # It recursively sorts a bitonic sequence in ascending order,# if dir = 1, and in descending order otherwise (means dir=0).# The sequence to be sorted starts at index position low,# the parameter cnt is the number of elements to be sorted.def bitonicMerge(a, low, cnt, dire): if cnt > 1: k = cnt//2 for i in range(low , low+k): compAndSwap(a, i, i+k, dire) bitonicMerge(a, low, k, dire) bitonicMerge(a, low+k, k, dire) # This function first produces a bitonic sequence by recursively# sorting its two halves in opposite sorting orders, and then# calls bitonicMerge to make them in the same orderdef bitonicSort(a, low, cnt,dire): if cnt > 1: k = cnt//2 bitonicSort(a, low, k, 1) bitonicSort(a, low+k, k, 0) bitonicMerge(a, low, cnt, dire) # Caller of bitonicSort for sorting the entire array of length N# in ASCENDING orderdef sort(a,N, up): bitonicSort(a,0, N, up) # Driver code to test abovea = [3, 7, 4, 8, 6, 2, 1, 5]n = len(a)up = 1 sort(a, n, up)print (\"\\n\\nSorted array is\")for i in range(n): print(\"%d\" %a[i],end=\" \")","e":35067,"s":33563,"text":null},{"code":"/* C# Program for Bitonic Sort. Note that this program works only when size of input is a power of 2. */using System; /*The parameter dir indicates the sorting direction, ASCENDING or DESCENDING; if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are interchanged.*/class GFG{ /* To swap values */ static void Swap(ref T lhs, ref T rhs) { T temp; temp = lhs; lhs = rhs; rhs = temp; } public static void compAndSwap(int[] a, int i, int j, int dir) { int k; if((a[i]>a[j])) k=1; else k=0; if (dir==k) Swap(ref a[i],ref a[j]); } /*It recursively sorts a bitonic sequence in ascending order, if dir = 1, and in descending order otherwise (means dir=0). The sequence to be sorted starts at index position low, the parameter cnt is the number of elements to be sorted.*/ public static void bitonicMerge(int[] a, int low, int cnt, int dir) { if (cnt>1) { int k = cnt/2; for (int i=low; i1) { int k = cnt/2; // sort in ascending order since dir here is 1 bitonicSort(a, low, k, 1); // sort in descending order since dir here is 0 bitonicSort(a, low+k, k, 0); // Will merge whole sequence in ascending order // since dir=1. bitonicMerge(a,low, cnt, dir); } } /* Caller of bitonicSort for sorting the entire array of length N in ASCENDING order */ public static void sort(int[] a, int N, int up) { bitonicSort(a,0, N, up); } // Driver code static void Main() { int[] a= {3, 7, 4, 8, 6, 2, 1, 5}; int N = a.Length; int up = 1; // means sort in ascending order sort(a, N, up); Console.Write(\"Sorted array: \\n\"); for (int i=0; i /* JavaScript program for Bitonic Sort. Note that this program works only when size of input is a power of 2. */ /* The parameter dir indicates the sorting direction, ASCENDING or DESCENDING; if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are interchanged. */ function compAndSwap(a, i, j, dir) { if ((a[i] > a[j] && dir === 1) || (a[i] < a[j] && dir === 0)) { // Swapping elements var temp = a[i]; a[i] = a[j]; a[j] = temp; } } /* It recursively sorts a bitonic sequence in ascending order, if dir = 1, and in descending order otherwise (means dir=0). The sequence to be sorted starts at index position low, the parameter cnt is the number of elements to be sorted.*/ function bitonicMerge(a, low, cnt, dir) { if (cnt > 1) { var k = parseInt(cnt / 2); for (var i = low; i < low + k; i++) compAndSwap(a, i, i + k, dir); bitonicMerge(a, low, k, dir); bitonicMerge(a, low + k, k, dir); } } /* This function first produces a bitonic sequence by recursively sorting its two halves in opposite sorting orders, and then calls bitonicMerge to make them in the same order */ function bitonicSort(a, low, cnt, dir) { if (cnt > 1) { var k = parseInt(cnt / 2); // sort in ascending order since dir here is 1 bitonicSort(a, low, k, 1); // sort in descending order since dir here is 0 bitonicSort(a, low + k, k, 0); // Will merge whole sequence in ascending order // since dir=1. bitonicMerge(a, low, cnt, dir); } } /*Caller of bitonicSort for sorting the entire array of length N in ASCENDING order */ function sort(a, N, up) { bitonicSort(a, 0, N, up); } /* A utility function to print array of size n */ function printArray(arr) { var n = arr.length; for (var i = 0; i < n; ++i) document.write(arr[i] + \" \"); document.write(\"
\"); } // Driver method var a = [3, 7, 4, 8, 6, 2, 1, 5]; var up = 1; sort(a, a.length, up); document.write(\"Sorted array:
\"); printArray(a); ","e":39874,"s":37563,"text":null},{"code":null,"e":39884,"s":39874,"text":"Output: "},{"code":null,"e":39915,"s":39884,"text":"Sorted array: \n1 2 3 4 5 6 7 8"},{"code":null,"e":39942,"s":39917,"text":"Analysis of Bitonic Sort"},{"code":null,"e":40417,"s":39942,"text":"To form a sorted sequence of length n from two sorted sequences of length n/2, log(n) comparisons are required (for example: log(8) = 3 when sequence size. Therefore, The number of comparisons T(n) of the entire sorting is given by:T(n) = log(n) + T(n/2)The solution of this recurrence equation isT(n) = log(n) + log(n)-1 + log(n)-2 + ... + 1 = log(n) · (log(n)+1) / 2As, each stage of the sorting network consists of n/2 comparators. Therefore total ?(n log2n) comparators."},{"code":null,"e":40999,"s":40417,"text":"References: 1. https://www.youtube.com/watch?v=GEQ8y26blEY 2. http://www.iti.fh-flensburg.de/lang/algorithmen/sortieren/bitonic/bitonicen.htm 3. https://en.wikipedia.org/wiki/Bitonic_sorterThis article is contributed by Rahul Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "},{"code":null,"e":41007,"s":40999,"text":"DrRoot_"},{"code":null,"e":41022,"s":41007,"text":"shantanukonwar"},{"code":null,"e":41029,"s":41022,"text":"rdtank"},{"code":null,"e":41039,"s":41029,"text":"kk9826225"},{"code":null,"e":41054,"s":41039,"text":"sagar0719kumar"},{"code":null,"e":41068,"s":41054,"text":"amartyaniel20"},{"code":null,"e":41081,"s":41068,"text":"simmytarika5"},{"code":null,"e":41089,"s":41081,"text":"Sorting"},{"code":null,"e":41097,"s":41089,"text":"Sorting"},{"code":null,"e":41195,"s":41097,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":41218,"s":41195,"text":"std::sort() in C++ STL"},{"code":null,"e":41262,"s":41218,"text":"Time Complexities of all Sorting Algorithms"},{"code":null,"e":41273,"s":41262,"text":"Radix Sort"},{"code":null,"e":41297,"s":41273,"text":"Merge two sorted arrays"},{"code":null,"e":41328,"s":41297,"text":"Sort an array of 0s, 1s and 2s"},{"code":null,"e":41359,"s":41328,"text":"Python Program for Bubble Sort"},{"code":null,"e":41425,"s":41359,"text":"Sorting Vector of Pairs in C++ | Set 1 (Sort by first and second)"},{"code":null,"e":41469,"s":41425,"text":"k largest(or smallest) elements in an array"},{"code":null,"e":41486,"s":41469,"text":"sort() in Python"}],"string":"[\n {\n \"code\": null,\n \"e\": 23634,\n \"s\": 23606,\n \"text\": \"\\n12 Apr, 2022\"\n },\n {\n \"code\": null,\n \"e\": 23645,\n \"s\": 23634,\n \"text\": \"Background\"\n },\n {\n \"code\": null,\n \"e\": 23704,\n \"s\": 23645,\n \"text\": \"Bitonic Sort is a classic parallel algorithm for sorting. \"\n },\n {\n \"code\": null,\n \"e\": 23747,\n \"s\": 23704,\n \"text\": \"Bitonic sort does O(n Log 2n) comparisons.\"\n },\n {\n \"code\": null,\n \"e\": 24136,\n \"s\": 23747,\n \"text\": \"The number of comparisons done by Bitonic sort are more than popular sorting algorithms like Merge Sort [ does O(nLogn) comparisons], but Bitonice sort is better for parallel implementation because we always compare elements in predefined sequence and the sequence of comparison doesn’t depend on data. Therefore it is suitable for implementation in hardware and parallel processor array.\"\n },\n {\n \"code\": null,\n \"e\": 24317,\n \"s\": 24136,\n \"text\": \"Bitonic Sort must be done if number of elements to sort are 2^n. The procedure of bitonic sequence fails if the number of elements are not in the aforementioned quantity precisely.\"\n },\n {\n \"code\": null,\n \"e\": 24439,\n \"s\": 24317,\n \"text\": \"To understand Bitonic Sort, we must first understand what is Bitonic Sequence and how to make a given sequence Bitonic. \"\n },\n {\n \"code\": null,\n \"e\": 24456,\n \"s\": 24439,\n \"text\": \"Bitonic Sequence\"\n },\n {\n \"code\": null,\n \"e\": 24632,\n \"s\": 24456,\n \"text\": \"A sequence is called Bitonic if it is first increasing, then decreasing. In other words, an array arr[0..n-i] is Bitonic if there exists an index i where 0<=i<=n-1 such that \"\n },\n {\n \"code\": null,\n \"e\": 24683,\n \"s\": 24632,\n \"text\": \"x0 <= x1 .....<= xi and xi >= xi+1..... >= xn-1 \"\n },\n {\n \"code\": null,\n \"e\": 24920,\n \"s\": 24683,\n \"text\": \"A sequence, sorted in increasing order is considered Bitonic with the decreasing part as empty. Similarly, decreasing order sequence is considered Bitonic with the increasing part as empty.A rotation of Bitonic Sequence is also bitonic.\"\n },\n {\n \"code\": null,\n \"e\": 25110,\n \"s\": 24920,\n \"text\": \"A sequence, sorted in increasing order is considered Bitonic with the decreasing part as empty. Similarly, decreasing order sequence is considered Bitonic with the increasing part as empty.\"\n },\n {\n \"code\": null,\n \"e\": 25158,\n \"s\": 25110,\n \"text\": \"A rotation of Bitonic Sequence is also bitonic.\"\n },\n {\n \"code\": null,\n \"e\": 25698,\n \"s\": 25158,\n \"text\": \"How to form a Bitonic Sequence from a random input? We start by forming 4-element bitonic sequences from consecutive 2-element sequence. Consider 4-element in sequence x0, x1, x2, x3. We sort x0 and x1 in ascending order and x2 and x3 in descending order. We then concatenate the two pairs to form a 4 element bitonic sequence. Next, we take two 4 element bitonic sequences, sorting one in ascending order, the other in descending order (using the Bitonic Sort which we will discuss below), and so on, until we obtain the bitonic sequence.\"\n },\n {\n \"code\": null,\n \"e\": 25783,\n \"s\": 25698,\n \"text\": \"Example: Convert the following sequence to bitonic sequence: 3, 7, 4, 8, 6, 2, 1, 5 \"\n },\n {\n \"code\": null,\n \"e\": 25959,\n \"s\": 25783,\n \"text\": \"Step 1: Consider each 2-consecutive elements as bitonic sequence and apply bitonic sort on each 2- pair elements. In next step, take two 4 element bitonic sequences and so on.\"\n },\n {\n \"code\": null,\n \"e\": 26049,\n \"s\": 25959,\n \"text\": \"Note: x0 and x1 are sorted in ascending order and x2 and x3 in descending order and so on\"\n },\n {\n \"code\": null,\n \"e\": 26145,\n \"s\": 26049,\n \"text\": \"Step 2: Two 4 element bitonic sequences: A(3,7,8,4) and B(2,6,5,1) with comparator length as 2 \"\n },\n {\n \"code\": null,\n \"e\": 26203,\n \"s\": 26145,\n \"text\": \"After this step, we’ll get Bitonic sequence of length 8. \"\n },\n {\n \"code\": null,\n \"e\": 26227,\n \"s\": 26203,\n \"text\": \" 3, 4, 7, 8, 6, 5, 2, 1\"\n },\n {\n \"code\": null,\n \"e\": 26243,\n \"s\": 26227,\n \"text\": \"Bitonic Sorting\"\n },\n {\n \"code\": null,\n \"e\": 26275,\n \"s\": 26243,\n \"text\": \"It mainly involves two steps. \"\n },\n {\n \"code\": null,\n \"e\": 27678,\n \"s\": 26275,\n \"text\": \"Forming a bitonic sequence (discussed above in detail). After this step we reach the fourth stage in below diagram, i.e., the array becomes {3, 4, 7, 8, 6, 5, 2, 1}Creating one sorted sequence from bitonic sequence: After first step, first half is sorted in increasing order and second half in decreasing order. We compare first element of first half with first element of second half, then second element of first half with second element of second, and so on. We exchange elements if an element of first half is smaller. After above compare and exchange steps, we get two bitonic sequences in array. See fifth stage in below diagram. In the fifth stage, we have {3, 4, 2, 1, 6, 5, 7, 8}. If we take a closer look at the elements, we can notice that there are two bitonic sequences of length n/2 such that all elements in first bitonic sequence {3, 4, 2, 1} are smaller than all elements of second bitonic sequence {6, 5, 7, 8}. We repeat the same process within two bitonic sequences and we get four bitonic sequences of length n/4 such that all elements of leftmost bitonic sequence are smaller and all elements of rightmost. See sixth stage in below diagram, arrays is {2, 1, 3, 4, 6, 5, 7, 8}. If we repeat this process one more time we get 8 bitonic sequences of size n/8 which is 1. Since all these bitonic sequence are sorted and every bitonic sequence has one element, we get the sorted array.\"\n },\n {\n \"code\": null,\n \"e\": 27843,\n \"s\": 27678,\n \"text\": \"Forming a bitonic sequence (discussed above in detail). After this step we reach the fourth stage in below diagram, i.e., the array becomes {3, 4, 7, 8, 6, 5, 2, 1}\"\n },\n {\n \"code\": null,\n \"e\": 29082,\n \"s\": 27843,\n \"text\": \"Creating one sorted sequence from bitonic sequence: After first step, first half is sorted in increasing order and second half in decreasing order. We compare first element of first half with first element of second half, then second element of first half with second element of second, and so on. We exchange elements if an element of first half is smaller. After above compare and exchange steps, we get two bitonic sequences in array. See fifth stage in below diagram. In the fifth stage, we have {3, 4, 2, 1, 6, 5, 7, 8}. If we take a closer look at the elements, we can notice that there are two bitonic sequences of length n/2 such that all elements in first bitonic sequence {3, 4, 2, 1} are smaller than all elements of second bitonic sequence {6, 5, 7, 8}. We repeat the same process within two bitonic sequences and we get four bitonic sequences of length n/4 such that all elements of leftmost bitonic sequence are smaller and all elements of rightmost. See sixth stage in below diagram, arrays is {2, 1, 3, 4, 6, 5, 7, 8}. If we repeat this process one more time we get 8 bitonic sequences of size n/8 which is 1. Since all these bitonic sequence are sorted and every bitonic sequence has one element, we get the sorted array.\"\n },\n {\n \"code\": null,\n \"e\": 29126,\n \"s\": 29082,\n \"text\": \"Below are implementations of Bitonic Sort. \"\n },\n {\n \"code\": null,\n \"e\": 29130,\n \"s\": 29126,\n \"text\": \"C++\"\n },\n {\n \"code\": null,\n \"e\": 29135,\n \"s\": 29130,\n \"text\": \"Java\"\n },\n {\n \"code\": null,\n \"e\": 29143,\n \"s\": 29135,\n \"text\": \"Python3\"\n },\n {\n \"code\": null,\n \"e\": 29146,\n \"s\": 29143,\n \"text\": \"C#\"\n },\n {\n \"code\": null,\n \"e\": 29157,\n \"s\": 29146,\n \"text\": \"Javascript\"\n },\n {\n \"code\": \"/* C++ Program for Bitonic Sort. Note that this program works only when size of input is a power of 2. */#includeusing namespace std; /*The parameter dir indicates the sorting direction, ASCENDING or DESCENDING; if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are interchanged.*/void compAndSwap(int a[], int i, int j, int dir){ if (dir==(a[i]>a[j])) swap(a[i],a[j]);} /*It recursively sorts a bitonic sequence in ascending order, if dir = 1, and in descending order otherwise (means dir=0). The sequence to be sorted starts at index position low, the parameter cnt is the number of elements to be sorted.*/void bitonicMerge(int a[], int low, int cnt, int dir){ if (cnt>1) { int k = cnt/2; for (int i=low; i1) { int k = cnt/2; // sort in ascending order since dir here is 1 bitonicSort(a, low, k, 1); // sort in descending order since dir here is 0 bitonicSort(a, low+k, k, 0); // Will merge whole sequence in ascending order // since dir=1. bitonicMerge(a,low, cnt, dir); }} /* Caller of bitonicSort for sorting the entire array of length N in ASCENDING order */void sort(int a[], int N, int up){ bitonicSort(a,0, N, up);} // Driver codeint main(){ int a[]= {3, 7, 4, 8, 6, 2, 1, 5}; int N = sizeof(a)/sizeof(a[0]); int up = 1; // means sort in ascending order sort(a, N, up); printf(\\\"Sorted array: \\\\n\\\"); for (int i=0; i a[j]) agrees with the direction, then a[i] and a[j] are interchanged. */ void compAndSwap(int a[], int i, int j, int dir) { if ( (a[i] > a[j] && dir == 1) || (a[i] < a[j] && dir == 0)) { // Swapping elements int temp = a[i]; a[i] = a[j]; a[j] = temp; } } /* It recursively sorts a bitonic sequence in ascending order, if dir = 1, and in descending order otherwise (means dir=0). The sequence to be sorted starts at index position low, the parameter cnt is the number of elements to be sorted.*/ void bitonicMerge(int a[], int low, int cnt, int dir) { if (cnt>1) { int k = cnt/2; for (int i=low; i1) { int k = cnt/2; // sort in ascending order since dir here is 1 bitonicSort(a, low, k, 1); // sort in descending order since dir here is 0 bitonicSort(a,low+k, k, 0); // Will merge whole sequence in ascending order // since dir=1. bitonicMerge(a, low, cnt, dir); } } /*Caller of bitonicSort for sorting the entire array of length N in ASCENDING order */ void sort(int a[], int N, int up) { bitonicSort(a, 0, N, up); } /* A utility function to print array of size n */ static void printArray(int arr[]) { int n = arr.length; for (int i=0; i a[j]) agrees with the direction,# then a[i] and a[j] are interchanged.*/def compAndSwap(a, i, j, dire): if (dire==1 and a[i] > a[j]) or (dire==0 and a[i] < a[j]): a[i],a[j] = a[j],a[i] # It recursively sorts a bitonic sequence in ascending order,# if dir = 1, and in descending order otherwise (means dir=0).# The sequence to be sorted starts at index position low,# the parameter cnt is the number of elements to be sorted.def bitonicMerge(a, low, cnt, dire): if cnt > 1: k = cnt//2 for i in range(low , low+k): compAndSwap(a, i, i+k, dire) bitonicMerge(a, low, k, dire) bitonicMerge(a, low+k, k, dire) # This function first produces a bitonic sequence by recursively# sorting its two halves in opposite sorting orders, and then# calls bitonicMerge to make them in the same orderdef bitonicSort(a, low, cnt,dire): if cnt > 1: k = cnt//2 bitonicSort(a, low, k, 1) bitonicSort(a, low+k, k, 0) bitonicMerge(a, low, cnt, dire) # Caller of bitonicSort for sorting the entire array of length N# in ASCENDING orderdef sort(a,N, up): bitonicSort(a,0, N, up) # Driver code to test abovea = [3, 7, 4, 8, 6, 2, 1, 5]n = len(a)up = 1 sort(a, n, up)print (\\\"\\\\n\\\\nSorted array is\\\")for i in range(n): print(\\\"%d\\\" %a[i],end=\\\" \\\")\",\n \"e\": 35067,\n \"s\": 33563,\n \"text\": null\n },\n {\n \"code\": \"/* C# Program for Bitonic Sort. Note that this program works only when size of input is a power of 2. */using System; /*The parameter dir indicates the sorting direction, ASCENDING or DESCENDING; if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are interchanged.*/class GFG{ /* To swap values */ static void Swap(ref T lhs, ref T rhs) { T temp; temp = lhs; lhs = rhs; rhs = temp; } public static void compAndSwap(int[] a, int i, int j, int dir) { int k; if((a[i]>a[j])) k=1; else k=0; if (dir==k) Swap(ref a[i],ref a[j]); } /*It recursively sorts a bitonic sequence in ascending order, if dir = 1, and in descending order otherwise (means dir=0). The sequence to be sorted starts at index position low, the parameter cnt is the number of elements to be sorted.*/ public static void bitonicMerge(int[] a, int low, int cnt, int dir) { if (cnt>1) { int k = cnt/2; for (int i=low; i1) { int k = cnt/2; // sort in ascending order since dir here is 1 bitonicSort(a, low, k, 1); // sort in descending order since dir here is 0 bitonicSort(a, low+k, k, 0); // Will merge whole sequence in ascending order // since dir=1. bitonicMerge(a,low, cnt, dir); } } /* Caller of bitonicSort for sorting the entire array of length N in ASCENDING order */ public static void sort(int[] a, int N, int up) { bitonicSort(a,0, N, up); } // Driver code static void Main() { int[] a= {3, 7, 4, 8, 6, 2, 1, 5}; int N = a.Length; int up = 1; // means sort in ascending order sort(a, N, up); Console.Write(\\\"Sorted array: \\\\n\\\"); for (int i=0; i /* JavaScript program for Bitonic Sort. Note that this program works only when size of input is a power of 2. */ /* The parameter dir indicates the sorting direction, ASCENDING or DESCENDING; if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are interchanged. */ function compAndSwap(a, i, j, dir) { if ((a[i] > a[j] && dir === 1) || (a[i] < a[j] && dir === 0)) { // Swapping elements var temp = a[i]; a[i] = a[j]; a[j] = temp; } } /* It recursively sorts a bitonic sequence in ascending order, if dir = 1, and in descending order otherwise (means dir=0). The sequence to be sorted starts at index position low, the parameter cnt is the number of elements to be sorted.*/ function bitonicMerge(a, low, cnt, dir) { if (cnt > 1) { var k = parseInt(cnt / 2); for (var i = low; i < low + k; i++) compAndSwap(a, i, i + k, dir); bitonicMerge(a, low, k, dir); bitonicMerge(a, low + k, k, dir); } } /* This function first produces a bitonic sequence by recursively sorting its two halves in opposite sorting orders, and then calls bitonicMerge to make them in the same order */ function bitonicSort(a, low, cnt, dir) { if (cnt > 1) { var k = parseInt(cnt / 2); // sort in ascending order since dir here is 1 bitonicSort(a, low, k, 1); // sort in descending order since dir here is 0 bitonicSort(a, low + k, k, 0); // Will merge whole sequence in ascending order // since dir=1. bitonicMerge(a, low, cnt, dir); } } /*Caller of bitonicSort for sorting the entire array of length N in ASCENDING order */ function sort(a, N, up) { bitonicSort(a, 0, N, up); } /* A utility function to print array of size n */ function printArray(arr) { var n = arr.length; for (var i = 0; i < n; ++i) document.write(arr[i] + \\\" \\\"); document.write(\\\"
\\\"); } // Driver method var a = [3, 7, 4, 8, 6, 2, 1, 5]; var up = 1; sort(a, a.length, up); document.write(\\\"Sorted array:
\\\"); printArray(a); \",\n \"e\": 39874,\n \"s\": 37563,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 39884,\n \"s\": 39874,\n \"text\": \"Output: \"\n },\n {\n \"code\": null,\n \"e\": 39915,\n \"s\": 39884,\n \"text\": \"Sorted array: \\n1 2 3 4 5 6 7 8\"\n },\n {\n \"code\": null,\n \"e\": 39942,\n \"s\": 39917,\n \"text\": \"Analysis of Bitonic Sort\"\n },\n {\n \"code\": null,\n \"e\": 40417,\n \"s\": 39942,\n \"text\": \"To form a sorted sequence of length n from two sorted sequences of length n/2, log(n) comparisons are required (for example: log(8) = 3 when sequence size. Therefore, The number of comparisons T(n) of the entire sorting is given by:T(n) = log(n) + T(n/2)The solution of this recurrence equation isT(n) = log(n) + log(n)-1 + log(n)-2 + ... + 1 = log(n) · (log(n)+1) / 2As, each stage of the sorting network consists of n/2 comparators. Therefore total ?(n log2n) comparators.\"\n },\n {\n \"code\": null,\n \"e\": 40999,\n \"s\": 40417,\n \"text\": \"References: 1. https://www.youtube.com/watch?v=GEQ8y26blEY 2. http://www.iti.fh-flensburg.de/lang/algorithmen/sortieren/bitonic/bitonicen.htm 3. https://en.wikipedia.org/wiki/Bitonic_sorterThis article is contributed by Rahul Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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. \"\n },\n {\n \"code\": null,\n \"e\": 41007,\n \"s\": 40999,\n \"text\": \"DrRoot_\"\n },\n {\n \"code\": null,\n \"e\": 41022,\n \"s\": 41007,\n \"text\": \"shantanukonwar\"\n },\n {\n \"code\": null,\n \"e\": 41029,\n \"s\": 41022,\n \"text\": \"rdtank\"\n },\n {\n \"code\": null,\n \"e\": 41039,\n \"s\": 41029,\n \"text\": \"kk9826225\"\n },\n {\n \"code\": null,\n \"e\": 41054,\n \"s\": 41039,\n \"text\": \"sagar0719kumar\"\n },\n {\n \"code\": null,\n \"e\": 41068,\n \"s\": 41054,\n \"text\": \"amartyaniel20\"\n },\n {\n \"code\": null,\n \"e\": 41081,\n \"s\": 41068,\n \"text\": \"simmytarika5\"\n },\n {\n \"code\": null,\n \"e\": 41089,\n \"s\": 41081,\n \"text\": \"Sorting\"\n },\n {\n \"code\": null,\n \"e\": 41097,\n \"s\": 41089,\n \"text\": \"Sorting\"\n },\n {\n \"code\": null,\n \"e\": 41195,\n \"s\": 41097,\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\": 41218,\n \"s\": 41195,\n \"text\": \"std::sort() in C++ STL\"\n },\n {\n \"code\": null,\n \"e\": 41262,\n \"s\": 41218,\n \"text\": \"Time Complexities of all Sorting Algorithms\"\n },\n {\n \"code\": null,\n \"e\": 41273,\n \"s\": 41262,\n \"text\": \"Radix Sort\"\n },\n {\n \"code\": null,\n \"e\": 41297,\n \"s\": 41273,\n \"text\": \"Merge two sorted arrays\"\n },\n {\n \"code\": null,\n \"e\": 41328,\n \"s\": 41297,\n \"text\": \"Sort an array of 0s, 1s and 2s\"\n },\n {\n \"code\": null,\n \"e\": 41359,\n \"s\": 41328,\n \"text\": \"Python Program for Bubble Sort\"\n },\n {\n \"code\": null,\n \"e\": 41425,\n \"s\": 41359,\n \"text\": \"Sorting Vector of Pairs in C++ | Set 1 (Sort by first and second)\"\n },\n {\n \"code\": null,\n \"e\": 41469,\n \"s\": 41425,\n \"text\": \"k largest(or smallest) elements in an array\"\n },\n {\n \"code\": null,\n \"e\": 41486,\n \"s\": 41469,\n \"text\": \"sort() in Python\"\n }\n]"}}},{"rowIdx":441,"cells":{"title":{"kind":"string","value":"Calculating n-th real root using binary search - GeeksforGeeks"},"text":{"kind":"string","value":"28 Mar, 2022\nGiven two number x and n, find n-th root of x. \nExamples: \nInput : 5 2Output : 2.2360679768025875\nInput : x = 5, n = 3Output : 1.70997594668\nIn order to calculate nth root of a number, we can use the following procedure. \nIf x lies in the range [0, 1) then we set the lower limit low = x and upper limit high = 1, because for this range of numbers the nth root is always greater than the given number and can never exceed 1.eg- Otherwise, we take low = 1 and high = x.Declare a variable named epsilon and initialize it for accuracy you need. Say epsilon=0.01, then we can guarantee that our guess for nth root of the given number will be correct up to 2 decimal places.Declare a variable guess and initialize it to guess=(low+high)/2.Run a loop such that: if the absolute error of our guess is more than epsilon then do: if guessn > x, then high=guesselse low=guessMaking a new better guess i.e., guess=(low+high)/2.If the absolute error of our guess is less than epsilon then exit the loop.\nIf x lies in the range [0, 1) then we set the lower limit low = x and upper limit high = 1, because for this range of numbers the nth root is always greater than the given number and can never exceed 1.eg- \nOtherwise, we take low = 1 and high = x.\nDeclare a variable named epsilon and initialize it for accuracy you need. Say epsilon=0.01, then we can guarantee that our guess for nth root of the given number will be correct up to 2 decimal places.\nDeclare a variable guess and initialize it to guess=(low+high)/2.\nRun a loop such that: if the absolute error of our guess is more than epsilon then do: if guessn > x, then high=guesselse low=guessMaking a new better guess i.e., guess=(low+high)/2.If the absolute error of our guess is less than epsilon then exit the loop.\nif the absolute error of our guess is more than epsilon then do: if guessn > x, then high=guesselse low=guessMaking a new better guess i.e., guess=(low+high)/2.\nif guessn > x, then high=guesselse low=guessMaking a new better guess i.e., guess=(low+high)/2.\nif guessn > x, then high=guess\nelse low=guess\nMaking a new better guess i.e., guess=(low+high)/2.\nIf the absolute error of our guess is less than epsilon then exit the loop.\nAbsolute Error: Absolute Error can be calculated as abs(guessn -x) \nC++\nJava\nPython3\nC#\nJavascript\n// C++ Program to find// n-th real root of x#include using namespace std; void findNthRoot(double x, int n){ // Initialize boundary values double low, high; if (x >= 0 and x <= 1) { low = x; high = 1; } else { low = 1; high = x; } // Used for taking approximations // of the answer double epsilon = 0.00000001; // Do binary search double guess = (low + high) / 2; while (abs((pow(guess, n)) - x) >= epsilon) { if (pow(guess, n) > x) { high = guess; } else { low = guess; } guess = (low + high) / 2; } cout << fixed << setprecision(16) << guess;} // Driver codeint main(){ double x = 5; int n = 2; findNthRoot(x, n);} // This code is contributed// by Subhadeep\n// Java Program to find n-th real root of xclass GFG{ static void findNthRoot(double x, int n) { // Initialize boundary values double low, high; if (x >= 0 && x <= 1) { low = x; high = 1; } else { low = 1; high = x; } // used for taking approximations // of the answer double epsilon = 0.00000001; // Do binary search double guess = (low + high) / 2; while (Math.abs((Math.pow(guess, n)) - x) >= epsilon) { if (Math.pow(guess, n) > x) { high = guess; } else { low = guess; } guess = (low + high) / 2; } System.out.println(guess); } // Driver code public static void main(String[] args) { double x = 5; int n = 2; findNthRoot(x, n); }} // This code is contributed// by mits\n# Python Program to find n-th real root# of x def findNthRoot(x, n): # Initialize boundary values x = float(x) n = int(n) if (x >= 0 and x <= 1): low = x high = 1 else: low = 1 high = x # used for taking approximations # of the answer epsilon = 0.00000001 # Do binary search guess = (low + high) / 2 while abs(guess ** n - x) >= epsilon: if guess ** n > x: high = guess else: low = guess guess = (low + high) / 2 print(guess) # Driver codex = 5n = 2findNthRoot(x, n)\n// C# Program to find n-th real root of x using System; public class GFG { static void findNthRoot(double x, int n) { // Initialize boundary values double low, high; if (x >= 0 && x <= 1) { low = x; high = 1; } else { low = 1; high = x; } // used for taking approximations // of the answer double epsilon = 0.00000001; // Do binary search double guess = (low + high) / 2; while (Math.Abs((Math.Pow(guess, n)) - x) >= epsilon) { if (Math.Pow(guess, n) > x) { high = guess; } else { low = guess; } guess = (low + high) / 2; } Console.WriteLine(guess); } // Driver code static public void Main() { double x = 5; int n = 2; findNthRoot(x, n); }} // This code is contributed by akt_mit\n\n2.2360679768025875\nTime Complexity: O( log( x * 10d)*logguess(n) )\nAuxiliary Space: O(1)\nHere d is the number of decimal places upto which we want the result accurately.\nExplanation of first example with epsilon = 0.01\nSince taking too small value of epsilon as taken in our program might not be feasible for\nexplanation because it will increase the number of steps drastically so for the sake of\nsimplicity we are taking epsilon = 0.01\nThe above procedure will work as follows:\nSay we have to calculate the then x = 5, low = 1, high = 5.Taking epsilon = 0.01First Guess:guess = (1 + 5) / 2 = 3Absolute error = |32 - 5| = 4 > epsilonguess2 = 9 > 5(x) then high = guess --> high = 3Second Guess:guess = (1 + 3) / 2 = 2Absolute error = |22 - 5| = 1 > epsilonguess2 = 4 > 5(x) then low = guess --> low = 2Third Guess:guess = (2 + 3) / 2 = 2.5Absolute error = |2.52 - 5| = 1.25 > epsilonguess2 = 6.25 > 5(x) then high = guess --> high = 2.5and proceeding so on we will get the correct up to 2 decimal places i.e., = 2.23600456We will ignore the digits after 2 decimal places since they may or may not be correct.\ntufan_gupta2000\nMithun Kumar\njit_t\nmdrashidmeraj2002\ndivyeshrabadiya07\nrohanthakurarmy\nBinary Search\nMathematical\nMathematical\nBinary Search\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nModulo Operator (%) in C/C++ with Examples\nProgram to find GCD or HCF of two numbers\nMerge two sorted arrays\nPrime Numbers\nProgram to find sum of elements in a given array\nProgram for factorial of a number\nProgram for Decimal to Binary Conversion\nSieve of Eratosthenes\nOperators in C / C++\nThe Knight's tour problem | Backtracking-1"},"parsed":{"kind":"list like","value":[{"code":null,"e":24906,"s":24878,"text":"\n28 Mar, 2022"},{"code":null,"e":24954,"s":24906,"text":"Given two number x and n, find n-th root of x. "},{"code":null,"e":24965,"s":24954,"text":"Examples: "},{"code":null,"e":25004,"s":24965,"text":"Input : 5 2Output : 2.2360679768025875"},{"code":null,"e":25048,"s":25004,"text":"Input : x = 5, n = 3Output : 1.70997594668"},{"code":null,"e":25130,"s":25048,"text":"In order to calculate nth root of a number, we can use the following procedure. "},{"code":null,"e":25900,"s":25130,"text":"If x lies in the range [0, 1) then we set the lower limit low = x and upper limit high = 1, because for this range of numbers the nth root is always greater than the given number and can never exceed 1.eg- Otherwise, we take low = 1 and high = x.Declare a variable named epsilon and initialize it for accuracy you need. Say epsilon=0.01, then we can guarantee that our guess for nth root of the given number will be correct up to 2 decimal places.Declare a variable guess and initialize it to guess=(low+high)/2.Run a loop such that: if the absolute error of our guess is more than epsilon then do: if guessn > x, then high=guesselse low=guessMaking a new better guess i.e., guess=(low+high)/2.If the absolute error of our guess is less than epsilon then exit the loop."},{"code":null,"e":26107,"s":25900,"text":"If x lies in the range [0, 1) then we set the lower limit low = x and upper limit high = 1, because for this range of numbers the nth root is always greater than the given number and can never exceed 1.eg- "},{"code":null,"e":26148,"s":26107,"text":"Otherwise, we take low = 1 and high = x."},{"code":null,"e":26350,"s":26148,"text":"Declare a variable named epsilon and initialize it for accuracy you need. Say epsilon=0.01, then we can guarantee that our guess for nth root of the given number will be correct up to 2 decimal places."},{"code":null,"e":26416,"s":26350,"text":"Declare a variable guess and initialize it to guess=(low+high)/2."},{"code":null,"e":26674,"s":26416,"text":"Run a loop such that: if the absolute error of our guess is more than epsilon then do: if guessn > x, then high=guesselse low=guessMaking a new better guess i.e., guess=(low+high)/2.If the absolute error of our guess is less than epsilon then exit the loop."},{"code":null,"e":26835,"s":26674,"text":"if the absolute error of our guess is more than epsilon then do: if guessn > x, then high=guesselse low=guessMaking a new better guess i.e., guess=(low+high)/2."},{"code":null,"e":26931,"s":26835,"text":"if guessn > x, then high=guesselse low=guessMaking a new better guess i.e., guess=(low+high)/2."},{"code":null,"e":26962,"s":26931,"text":"if guessn > x, then high=guess"},{"code":null,"e":26977,"s":26962,"text":"else low=guess"},{"code":null,"e":27029,"s":26977,"text":"Making a new better guess i.e., guess=(low+high)/2."},{"code":null,"e":27105,"s":27029,"text":"If the absolute error of our guess is less than epsilon then exit the loop."},{"code":null,"e":27173,"s":27105,"text":"Absolute Error: Absolute Error can be calculated as abs(guessn -x) "},{"code":null,"e":27177,"s":27173,"text":"C++"},{"code":null,"e":27182,"s":27177,"text":"Java"},{"code":null,"e":27190,"s":27182,"text":"Python3"},{"code":null,"e":27193,"s":27190,"text":"C#"},{"code":null,"e":27204,"s":27193,"text":"Javascript"},{"code":"// C++ Program to find// n-th real root of x#include using namespace std; void findNthRoot(double x, int n){ // Initialize boundary values double low, high; if (x >= 0 and x <= 1) { low = x; high = 1; } else { low = 1; high = x; } // Used for taking approximations // of the answer double epsilon = 0.00000001; // Do binary search double guess = (low + high) / 2; while (abs((pow(guess, n)) - x) >= epsilon) { if (pow(guess, n) > x) { high = guess; } else { low = guess; } guess = (low + high) / 2; } cout << fixed << setprecision(16) << guess;} // Driver codeint main(){ double x = 5; int n = 2; findNthRoot(x, n);} // This code is contributed// by Subhadeep","e":28042,"s":27204,"text":null},{"code":"// Java Program to find n-th real root of xclass GFG{ static void findNthRoot(double x, int n) { // Initialize boundary values double low, high; if (x >= 0 && x <= 1) { low = x; high = 1; } else { low = 1; high = x; } // used for taking approximations // of the answer double epsilon = 0.00000001; // Do binary search double guess = (low + high) / 2; while (Math.abs((Math.pow(guess, n)) - x) >= epsilon) { if (Math.pow(guess, n) > x) { high = guess; } else { low = guess; } guess = (low + high) / 2; } System.out.println(guess); } // Driver code public static void main(String[] args) { double x = 5; int n = 2; findNthRoot(x, n); }} // This code is contributed// by mits","e":29046,"s":28042,"text":null},{"code":"# Python Program to find n-th real root# of x def findNthRoot(x, n): # Initialize boundary values x = float(x) n = int(n) if (x >= 0 and x <= 1): low = x high = 1 else: low = 1 high = x # used for taking approximations # of the answer epsilon = 0.00000001 # Do binary search guess = (low + high) / 2 while abs(guess ** n - x) >= epsilon: if guess ** n > x: high = guess else: low = guess guess = (low + high) / 2 print(guess) # Driver codex = 5n = 2findNthRoot(x, n)","e":29625,"s":29046,"text":null},{"code":"// C# Program to find n-th real root of x using System; public class GFG { static void findNthRoot(double x, int n) { // Initialize boundary values double low, high; if (x >= 0 && x <= 1) { low = x; high = 1; } else { low = 1; high = x; } // used for taking approximations // of the answer double epsilon = 0.00000001; // Do binary search double guess = (low + high) / 2; while (Math.Abs((Math.Pow(guess, n)) - x) >= epsilon) { if (Math.Pow(guess, n) > x) { high = guess; } else { low = guess; } guess = (low + high) / 2; } Console.WriteLine(guess); } // Driver code static public void Main() { double x = 5; int n = 2; findNthRoot(x, n); }} // This code is contributed by akt_mit","e":30637,"s":29625,"text":null},{"code":"","e":31547,"s":30637,"text":null},{"code":null,"e":31566,"s":31547,"text":"2.2360679768025875"},{"code":null,"e":31614,"s":31566,"text":"Time Complexity: O( log( x * 10d)*logguess(n) )"},{"code":null,"e":31636,"s":31614,"text":"Auxiliary Space: O(1)"},{"code":null,"e":31717,"s":31636,"text":"Here d is the number of decimal places upto which we want the result accurately."},{"code":null,"e":31766,"s":31717,"text":"Explanation of first example with epsilon = 0.01"},{"code":null,"e":32658,"s":31766,"text":"Since taking too small value of epsilon as taken in our program might not be feasible for\nexplanation because it will increase the number of steps drastically so for the sake of\nsimplicity we are taking epsilon = 0.01\nThe above procedure will work as follows:\nSay we have to calculate the then x = 5, low = 1, high = 5.Taking epsilon = 0.01First Guess:guess = (1 + 5) / 2 = 3Absolute error = |32 - 5| = 4 > epsilonguess2 = 9 > 5(x) then high = guess --> high = 3Second Guess:guess = (1 + 3) / 2 = 2Absolute error = |22 - 5| = 1 > epsilonguess2 = 4 > 5(x) then low = guess --> low = 2Third Guess:guess = (2 + 3) / 2 = 2.5Absolute error = |2.52 - 5| = 1.25 > epsilonguess2 = 6.25 > 5(x) then high = guess --> high = 2.5and proceeding so on we will get the correct up to 2 decimal places i.e., = 2.23600456We will ignore the digits after 2 decimal places since they may or may not be correct."},{"code":null,"e":32674,"s":32658,"text":"tufan_gupta2000"},{"code":null,"e":32687,"s":32674,"text":"Mithun Kumar"},{"code":null,"e":32693,"s":32687,"text":"jit_t"},{"code":null,"e":32711,"s":32693,"text":"mdrashidmeraj2002"},{"code":null,"e":32729,"s":32711,"text":"divyeshrabadiya07"},{"code":null,"e":32745,"s":32729,"text":"rohanthakurarmy"},{"code":null,"e":32759,"s":32745,"text":"Binary Search"},{"code":null,"e":32772,"s":32759,"text":"Mathematical"},{"code":null,"e":32785,"s":32772,"text":"Mathematical"},{"code":null,"e":32799,"s":32785,"text":"Binary Search"},{"code":null,"e":32897,"s":32799,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":32940,"s":32897,"text":"Modulo Operator (%) in C/C++ with Examples"},{"code":null,"e":32982,"s":32940,"text":"Program to find GCD or HCF of two numbers"},{"code":null,"e":33006,"s":32982,"text":"Merge two sorted arrays"},{"code":null,"e":33020,"s":33006,"text":"Prime Numbers"},{"code":null,"e":33069,"s":33020,"text":"Program to find sum of elements in a given array"},{"code":null,"e":33103,"s":33069,"text":"Program for factorial of a number"},{"code":null,"e":33144,"s":33103,"text":"Program for Decimal to Binary Conversion"},{"code":null,"e":33166,"s":33144,"text":"Sieve of Eratosthenes"},{"code":null,"e":33187,"s":33166,"text":"Operators in C / C++"}],"string":"[\n {\n \"code\": null,\n \"e\": 24906,\n \"s\": 24878,\n \"text\": \"\\n28 Mar, 2022\"\n },\n {\n \"code\": null,\n \"e\": 24954,\n \"s\": 24906,\n \"text\": \"Given two number x and n, find n-th root of x. \"\n },\n {\n \"code\": null,\n \"e\": 24965,\n \"s\": 24954,\n \"text\": \"Examples: \"\n },\n {\n \"code\": null,\n \"e\": 25004,\n \"s\": 24965,\n \"text\": \"Input : 5 2Output : 2.2360679768025875\"\n },\n {\n \"code\": null,\n \"e\": 25048,\n \"s\": 25004,\n \"text\": \"Input : x = 5, n = 3Output : 1.70997594668\"\n },\n {\n \"code\": null,\n \"e\": 25130,\n \"s\": 25048,\n \"text\": \"In order to calculate nth root of a number, we can use the following procedure. \"\n },\n {\n \"code\": null,\n \"e\": 25900,\n \"s\": 25130,\n \"text\": \"If x lies in the range [0, 1) then we set the lower limit low = x and upper limit high = 1, because for this range of numbers the nth root is always greater than the given number and can never exceed 1.eg- Otherwise, we take low = 1 and high = x.Declare a variable named epsilon and initialize it for accuracy you need. Say epsilon=0.01, then we can guarantee that our guess for nth root of the given number will be correct up to 2 decimal places.Declare a variable guess and initialize it to guess=(low+high)/2.Run a loop such that: if the absolute error of our guess is more than epsilon then do: if guessn > x, then high=guesselse low=guessMaking a new better guess i.e., guess=(low+high)/2.If the absolute error of our guess is less than epsilon then exit the loop.\"\n },\n {\n \"code\": null,\n \"e\": 26107,\n \"s\": 25900,\n \"text\": \"If x lies in the range [0, 1) then we set the lower limit low = x and upper limit high = 1, because for this range of numbers the nth root is always greater than the given number and can never exceed 1.eg- \"\n },\n {\n \"code\": null,\n \"e\": 26148,\n \"s\": 26107,\n \"text\": \"Otherwise, we take low = 1 and high = x.\"\n },\n {\n \"code\": null,\n \"e\": 26350,\n \"s\": 26148,\n \"text\": \"Declare a variable named epsilon and initialize it for accuracy you need. Say epsilon=0.01, then we can guarantee that our guess for nth root of the given number will be correct up to 2 decimal places.\"\n },\n {\n \"code\": null,\n \"e\": 26416,\n \"s\": 26350,\n \"text\": \"Declare a variable guess and initialize it to guess=(low+high)/2.\"\n },\n {\n \"code\": null,\n \"e\": 26674,\n \"s\": 26416,\n \"text\": \"Run a loop such that: if the absolute error of our guess is more than epsilon then do: if guessn > x, then high=guesselse low=guessMaking a new better guess i.e., guess=(low+high)/2.If the absolute error of our guess is less than epsilon then exit the loop.\"\n },\n {\n \"code\": null,\n \"e\": 26835,\n \"s\": 26674,\n \"text\": \"if the absolute error of our guess is more than epsilon then do: if guessn > x, then high=guesselse low=guessMaking a new better guess i.e., guess=(low+high)/2.\"\n },\n {\n \"code\": null,\n \"e\": 26931,\n \"s\": 26835,\n \"text\": \"if guessn > x, then high=guesselse low=guessMaking a new better guess i.e., guess=(low+high)/2.\"\n },\n {\n \"code\": null,\n \"e\": 26962,\n \"s\": 26931,\n \"text\": \"if guessn > x, then high=guess\"\n },\n {\n \"code\": null,\n \"e\": 26977,\n \"s\": 26962,\n \"text\": \"else low=guess\"\n },\n {\n \"code\": null,\n \"e\": 27029,\n \"s\": 26977,\n \"text\": \"Making a new better guess i.e., guess=(low+high)/2.\"\n },\n {\n \"code\": null,\n \"e\": 27105,\n \"s\": 27029,\n \"text\": \"If the absolute error of our guess is less than epsilon then exit the loop.\"\n },\n {\n \"code\": null,\n \"e\": 27173,\n \"s\": 27105,\n \"text\": \"Absolute Error: Absolute Error can be calculated as abs(guessn -x) \"\n },\n {\n \"code\": null,\n \"e\": 27177,\n \"s\": 27173,\n \"text\": \"C++\"\n },\n {\n \"code\": null,\n \"e\": 27182,\n \"s\": 27177,\n \"text\": \"Java\"\n },\n {\n \"code\": null,\n \"e\": 27190,\n \"s\": 27182,\n \"text\": \"Python3\"\n },\n {\n \"code\": null,\n \"e\": 27193,\n \"s\": 27190,\n \"text\": \"C#\"\n },\n {\n \"code\": null,\n \"e\": 27204,\n \"s\": 27193,\n \"text\": \"Javascript\"\n },\n {\n \"code\": \"// C++ Program to find// n-th real root of x#include using namespace std; void findNthRoot(double x, int n){ // Initialize boundary values double low, high; if (x >= 0 and x <= 1) { low = x; high = 1; } else { low = 1; high = x; } // Used for taking approximations // of the answer double epsilon = 0.00000001; // Do binary search double guess = (low + high) / 2; while (abs((pow(guess, n)) - x) >= epsilon) { if (pow(guess, n) > x) { high = guess; } else { low = guess; } guess = (low + high) / 2; } cout << fixed << setprecision(16) << guess;} // Driver codeint main(){ double x = 5; int n = 2; findNthRoot(x, n);} // This code is contributed// by Subhadeep\",\n \"e\": 28042,\n \"s\": 27204,\n \"text\": null\n },\n {\n \"code\": \"// Java Program to find n-th real root of xclass GFG{ static void findNthRoot(double x, int n) { // Initialize boundary values double low, high; if (x >= 0 && x <= 1) { low = x; high = 1; } else { low = 1; high = x; } // used for taking approximations // of the answer double epsilon = 0.00000001; // Do binary search double guess = (low + high) / 2; while (Math.abs((Math.pow(guess, n)) - x) >= epsilon) { if (Math.pow(guess, n) > x) { high = guess; } else { low = guess; } guess = (low + high) / 2; } System.out.println(guess); } // Driver code public static void main(String[] args) { double x = 5; int n = 2; findNthRoot(x, n); }} // This code is contributed// by mits\",\n \"e\": 29046,\n \"s\": 28042,\n \"text\": null\n },\n {\n \"code\": \"# Python Program to find n-th real root# of x def findNthRoot(x, n): # Initialize boundary values x = float(x) n = int(n) if (x >= 0 and x <= 1): low = x high = 1 else: low = 1 high = x # used for taking approximations # of the answer epsilon = 0.00000001 # Do binary search guess = (low + high) / 2 while abs(guess ** n - x) >= epsilon: if guess ** n > x: high = guess else: low = guess guess = (low + high) / 2 print(guess) # Driver codex = 5n = 2findNthRoot(x, n)\",\n \"e\": 29625,\n \"s\": 29046,\n \"text\": null\n },\n {\n \"code\": \"// C# Program to find n-th real root of x using System; public class GFG { static void findNthRoot(double x, int n) { // Initialize boundary values double low, high; if (x >= 0 && x <= 1) { low = x; high = 1; } else { low = 1; high = x; } // used for taking approximations // of the answer double epsilon = 0.00000001; // Do binary search double guess = (low + high) / 2; while (Math.Abs((Math.Pow(guess, n)) - x) >= epsilon) { if (Math.Pow(guess, n) > x) { high = guess; } else { low = guess; } guess = (low + high) / 2; } Console.WriteLine(guess); } // Driver code static public void Main() { double x = 5; int n = 2; findNthRoot(x, n); }} // This code is contributed by akt_mit\",\n \"e\": 30637,\n \"s\": 29625,\n \"text\": null\n },\n {\n \"code\": \"\",\n \"e\": 31547,\n \"s\": 30637,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 31566,\n \"s\": 31547,\n \"text\": \"2.2360679768025875\"\n },\n {\n \"code\": null,\n \"e\": 31614,\n \"s\": 31566,\n \"text\": \"Time Complexity: O( log( x * 10d)*logguess(n) )\"\n },\n {\n \"code\": null,\n \"e\": 31636,\n \"s\": 31614,\n \"text\": \"Auxiliary Space: O(1)\"\n },\n {\n \"code\": null,\n \"e\": 31717,\n \"s\": 31636,\n \"text\": \"Here d is the number of decimal places upto which we want the result accurately.\"\n },\n {\n \"code\": null,\n \"e\": 31766,\n \"s\": 31717,\n \"text\": \"Explanation of first example with epsilon = 0.01\"\n },\n {\n \"code\": null,\n \"e\": 32658,\n \"s\": 31766,\n \"text\": \"Since taking too small value of epsilon as taken in our program might not be feasible for\\nexplanation because it will increase the number of steps drastically so for the sake of\\nsimplicity we are taking epsilon = 0.01\\nThe above procedure will work as follows:\\nSay we have to calculate the then x = 5, low = 1, high = 5.Taking epsilon = 0.01First Guess:guess = (1 + 5) / 2 = 3Absolute error = |32 - 5| = 4 > epsilonguess2 = 9 > 5(x) then high = guess --> high = 3Second Guess:guess = (1 + 3) / 2 = 2Absolute error = |22 - 5| = 1 > epsilonguess2 = 4 > 5(x) then low = guess --> low = 2Third Guess:guess = (2 + 3) / 2 = 2.5Absolute error = |2.52 - 5| = 1.25 > epsilonguess2 = 6.25 > 5(x) then high = guess --> high = 2.5and proceeding so on we will get the correct up to 2 decimal places i.e., = 2.23600456We will ignore the digits after 2 decimal places since they may or may not be correct.\"\n },\n {\n \"code\": null,\n \"e\": 32674,\n \"s\": 32658,\n \"text\": \"tufan_gupta2000\"\n },\n {\n \"code\": null,\n \"e\": 32687,\n \"s\": 32674,\n \"text\": \"Mithun Kumar\"\n },\n {\n \"code\": null,\n \"e\": 32693,\n \"s\": 32687,\n \"text\": \"jit_t\"\n },\n {\n \"code\": null,\n \"e\": 32711,\n \"s\": 32693,\n \"text\": \"mdrashidmeraj2002\"\n },\n {\n \"code\": null,\n \"e\": 32729,\n \"s\": 32711,\n \"text\": \"divyeshrabadiya07\"\n },\n {\n \"code\": null,\n \"e\": 32745,\n \"s\": 32729,\n \"text\": \"rohanthakurarmy\"\n },\n {\n \"code\": null,\n \"e\": 32759,\n \"s\": 32745,\n \"text\": \"Binary Search\"\n },\n {\n \"code\": null,\n \"e\": 32772,\n \"s\": 32759,\n \"text\": \"Mathematical\"\n },\n {\n \"code\": null,\n \"e\": 32785,\n \"s\": 32772,\n \"text\": \"Mathematical\"\n },\n {\n \"code\": null,\n \"e\": 32799,\n \"s\": 32785,\n \"text\": \"Binary Search\"\n },\n {\n \"code\": null,\n \"e\": 32897,\n \"s\": 32799,\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\": 32940,\n \"s\": 32897,\n \"text\": \"Modulo Operator (%) in C/C++ with Examples\"\n },\n {\n \"code\": null,\n \"e\": 32982,\n \"s\": 32940,\n \"text\": \"Program to find GCD or HCF of two numbers\"\n },\n {\n \"code\": null,\n \"e\": 33006,\n \"s\": 32982,\n \"text\": \"Merge two sorted arrays\"\n },\n {\n \"code\": null,\n \"e\": 33020,\n \"s\": 33006,\n \"text\": \"Prime Numbers\"\n },\n {\n \"code\": null,\n \"e\": 33069,\n \"s\": 33020,\n \"text\": \"Program to find sum of elements in a given array\"\n },\n {\n \"code\": null,\n \"e\": 33103,\n \"s\": 33069,\n \"text\": \"Program for factorial of a number\"\n },\n {\n \"code\": null,\n \"e\": 33144,\n \"s\": 33103,\n \"text\": \"Program for Decimal to Binary Conversion\"\n },\n {\n \"code\": null,\n \"e\": 33166,\n \"s\": 33144,\n \"text\": \"Sieve of Eratosthenes\"\n },\n {\n \"code\": null,\n \"e\": 33187,\n \"s\": 33166,\n \"text\": \"Operators in C / C++\"\n }\n]"}}},{"rowIdx":442,"cells":{"title":{"kind":"string","value":"How to prevent Cloning to break a Singleton Class Pattern?"},"text":{"kind":"string","value":"A Singleton pattern states that a class can have a single instance and multiple instances are not permitted to be created. For this purpose, we make the constructor of the class a private and return a instance via a static method. But using cloning, we can still create multiple instance of a class. See the example below −\npublic class Tester{\n public static void main(String[] args)\n throws CloneNotSupportedException {\n A a = A.getInstance();\n A b = (A)a.clone();\n\n System.out.println(a.hashCode());\n System.out.println(b.hashCode());\n }\n}\n\nclass A implements Cloneable {\n private static A a;\n private A(){}\n\n public static A getInstance(){\n if(a == null){\n a = new A();\n }\n return a;\n }\n\n @Override\n protected Object clone()\n throws CloneNotSupportedException {\n return super.clone();\n }\n}\n705927765\n366712642\nHere you can see, we've created another object of a Singleton class. Let's see how to prevent such a situation −\nReturn the same object in the clone method as well.\n@Override\nprotected Object clone()\nthrows CloneNotSupportedException {\n return getInstance();\n}\n705927765\n705927765"},"parsed":{"kind":"list like","value":[{"code":null,"e":1386,"s":1062,"text":"A Singleton pattern states that a class can have a single instance and multiple instances are not permitted to be created. For this purpose, we make the constructor of the class a private and return a instance via a static method. But using cloning, we can still create multiple instance of a class. See the example below −"},{"code":null,"e":1926,"s":1386,"text":"public class Tester{\n public static void main(String[] args)\n throws CloneNotSupportedException {\n A a = A.getInstance();\n A b = (A)a.clone();\n\n System.out.println(a.hashCode());\n System.out.println(b.hashCode());\n }\n}\n\nclass A implements Cloneable {\n private static A a;\n private A(){}\n\n public static A getInstance(){\n if(a == null){\n a = new A();\n }\n return a;\n }\n\n @Override\n protected Object clone()\n throws CloneNotSupportedException {\n return super.clone();\n }\n}"},{"code":null,"e":1946,"s":1926,"text":"705927765\n366712642"},{"code":null,"e":2059,"s":1946,"text":"Here you can see, we've created another object of a Singleton class. Let's see how to prevent such a situation −"},{"code":null,"e":2111,"s":2059,"text":"Return the same object in the clone method as well."},{"code":null,"e":2209,"s":2111,"text":"@Override\nprotected Object clone()\nthrows CloneNotSupportedException {\n return getInstance();\n}"},{"code":null,"e":2229,"s":2209,"text":"705927765\n705927765"}],"string":"[\n {\n \"code\": null,\n \"e\": 1386,\n \"s\": 1062,\n \"text\": \"A Singleton pattern states that a class can have a single instance and multiple instances are not permitted to be created. For this purpose, we make the constructor of the class a private and return a instance via a static method. But using cloning, we can still create multiple instance of a class. See the example below −\"\n },\n {\n \"code\": null,\n \"e\": 1926,\n \"s\": 1386,\n \"text\": \"public class Tester{\\n public static void main(String[] args)\\n throws CloneNotSupportedException {\\n A a = A.getInstance();\\n A b = (A)a.clone();\\n\\n System.out.println(a.hashCode());\\n System.out.println(b.hashCode());\\n }\\n}\\n\\nclass A implements Cloneable {\\n private static A a;\\n private A(){}\\n\\n public static A getInstance(){\\n if(a == null){\\n a = new A();\\n }\\n return a;\\n }\\n\\n @Override\\n protected Object clone()\\n throws CloneNotSupportedException {\\n return super.clone();\\n }\\n}\"\n },\n {\n \"code\": null,\n \"e\": 1946,\n \"s\": 1926,\n \"text\": \"705927765\\n366712642\"\n },\n {\n \"code\": null,\n \"e\": 2059,\n \"s\": 1946,\n \"text\": \"Here you can see, we've created another object of a Singleton class. Let's see how to prevent such a situation −\"\n },\n {\n \"code\": null,\n \"e\": 2111,\n \"s\": 2059,\n \"text\": \"Return the same object in the clone method as well.\"\n },\n {\n \"code\": null,\n \"e\": 2209,\n \"s\": 2111,\n \"text\": \"@Override\\nprotected Object clone()\\nthrows CloneNotSupportedException {\\n return getInstance();\\n}\"\n },\n {\n \"code\": null,\n \"e\": 2229,\n \"s\": 2209,\n \"text\": \"705927765\\n705927765\"\n }\n]"}}},{"rowIdx":443,"cells":{"title":{"kind":"string","value":"Capitalize first letter of a column in Pandas dataframe - GeeksforGeeks"},"text":{"kind":"string","value":"06 Dec, 2018\nAnalyzing real-world data is somewhat difficult because we need to take various things into consideration. Apart from getting the useful data from large datasets, keeping data in required format is also very important.\nOne might encounter a situation where we need to capitalize any specific column in given dataframe. Let’s see how can we capitalize first letter of a column in Pandas dataframe.\nLet’s create a dataframe from the dict of lists.\n# Create a simple dataframe # importing pandas as pdimport pandas as pd # creating a dataframedf = pd.DataFrame({'A': ['john', 'bODAY', 'minA', 'Peter', 'nicky'], 'B': ['masters', 'graduate', 'graduate', 'Masters', 'Graduate'], 'C': [27, 23, 21, 23, 24]}) df\nOutput:\nThere are certain methods we can change/modify the case of column in pandas dataframe. Let’s see how can we capitalize first letter of columns using capitalize() method.\nMethod #1:\n# Create a simple dataframe # importing pandas as pdimport pandas as pd # creating a dataframedf = pd.DataFrame({'A': ['john', 'bODAY', 'minA', 'Peter', 'nicky'], 'B': ['masters', 'graduate', 'graduate', 'Masters', 'Graduate'], 'C': [27, 23, 21, 23, 24]}) df['A'] = df['A'].str.capitalize() df\nOutput: Method #2: Using lambda with capitalize() method\n# Create a simple dataframe # importing pandas as pdimport pandas as pd # creating a dataframedf = pd.DataFrame({'A': ['john', 'bODAY', 'minA', 'Peter', 'nicky'], 'B': ['masters', 'graduate', 'graduate', 'Masters', 'Graduate'], 'C': [27, 23, 21, 23, 24]}) df['A'].apply(lambda x: x.capitalize())\nOutput:\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\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\nReading and Writing to text files in Python\n*args and **kwargs in Python\nHow To Convert Python Dictionary To JSON?"},"parsed":{"kind":"list like","value":[{"code":null,"e":24956,"s":24928,"text":"\n06 Dec, 2018"},{"code":null,"e":25175,"s":24956,"text":"Analyzing real-world data is somewhat difficult because we need to take various things into consideration. Apart from getting the useful data from large datasets, keeping data in required format is also very important."},{"code":null,"e":25353,"s":25175,"text":"One might encounter a situation where we need to capitalize any specific column in given dataframe. Let’s see how can we capitalize first letter of a column in Pandas dataframe."},{"code":null,"e":25402,"s":25353,"text":"Let’s create a dataframe from the dict of lists."},{"code":"# Create a simple dataframe # importing pandas as pdimport pandas as pd # creating a dataframedf = pd.DataFrame({'A': ['john', 'bODAY', 'minA', 'Peter', 'nicky'], 'B': ['masters', 'graduate', 'graduate', 'Masters', 'Graduate'], 'C': [27, 23, 21, 23, 24]}) df","e":25737,"s":25402,"text":null},{"code":null,"e":25745,"s":25737,"text":"Output:"},{"code":null,"e":25915,"s":25745,"text":"There are certain methods we can change/modify the case of column in pandas dataframe. Let’s see how can we capitalize first letter of columns using capitalize() method."},{"code":null,"e":25926,"s":25915,"text":"Method #1:"},{"code":"# Create a simple dataframe # importing pandas as pdimport pandas as pd # creating a dataframedf = pd.DataFrame({'A': ['john', 'bODAY', 'minA', 'Peter', 'nicky'], 'B': ['masters', 'graduate', 'graduate', 'Masters', 'Graduate'], 'C': [27, 23, 21, 23, 24]}) df['A'] = df['A'].str.capitalize() df","e":26297,"s":25926,"text":null},{"code":null,"e":26354,"s":26297,"text":"Output: Method #2: Using lambda with capitalize() method"},{"code":"# Create a simple dataframe # importing pandas as pdimport pandas as pd # creating a dataframedf = pd.DataFrame({'A': ['john', 'bODAY', 'minA', 'Peter', 'nicky'], 'B': ['masters', 'graduate', 'graduate', 'Masters', 'Graduate'], 'C': [27, 23, 21, 23, 24]}) df['A'].apply(lambda x: x.capitalize())","e":26726,"s":26354,"text":null},{"code":null,"e":26734,"s":26726,"text":"Output:"},{"code":null,"e":26759,"s":26734,"text":"pandas-dataframe-program"},{"code":null,"e":26783,"s":26759,"text":"Python pandas-dataFrame"},{"code":null,"e":26797,"s":26783,"text":"Python-pandas"},{"code":null,"e":26804,"s":26797,"text":"Python"},{"code":null,"e":26902,"s":26804,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":26920,"s":26902,"text":"Python Dictionary"},{"code":null,"e":26942,"s":26920,"text":"Enumerate() in Python"},{"code":null,"e":26974,"s":26942,"text":"How to Install PIP on Windows ?"},{"code":null,"e":27004,"s":26974,"text":"Iterate over a list in Python"},{"code":null,"e":27046,"s":27004,"text":"Different ways to create Pandas Dataframe"},{"code":null,"e":27072,"s":27046,"text":"Python String | replace()"},{"code":null,"e":27109,"s":27072,"text":"Create a Pandas DataFrame from Lists"},{"code":null,"e":27153,"s":27109,"text":"Reading and Writing to text files in Python"},{"code":null,"e":27182,"s":27153,"text":"*args and **kwargs in Python"}],"string":"[\n {\n \"code\": null,\n \"e\": 24956,\n \"s\": 24928,\n \"text\": \"\\n06 Dec, 2018\"\n },\n {\n \"code\": null,\n \"e\": 25175,\n \"s\": 24956,\n \"text\": \"Analyzing real-world data is somewhat difficult because we need to take various things into consideration. Apart from getting the useful data from large datasets, keeping data in required format is also very important.\"\n },\n {\n \"code\": null,\n \"e\": 25353,\n \"s\": 25175,\n \"text\": \"One might encounter a situation where we need to capitalize any specific column in given dataframe. Let’s see how can we capitalize first letter of a column in Pandas dataframe.\"\n },\n {\n \"code\": null,\n \"e\": 25402,\n \"s\": 25353,\n \"text\": \"Let’s create a dataframe from the dict of lists.\"\n },\n {\n \"code\": \"# Create a simple dataframe # importing pandas as pdimport pandas as pd # creating a dataframedf = pd.DataFrame({'A': ['john', 'bODAY', 'minA', 'Peter', 'nicky'], 'B': ['masters', 'graduate', 'graduate', 'Masters', 'Graduate'], 'C': [27, 23, 21, 23, 24]}) df\",\n \"e\": 25737,\n \"s\": 25402,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 25745,\n \"s\": 25737,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 25915,\n \"s\": 25745,\n \"text\": \"There are certain methods we can change/modify the case of column in pandas dataframe. Let’s see how can we capitalize first letter of columns using capitalize() method.\"\n },\n {\n \"code\": null,\n \"e\": 25926,\n \"s\": 25915,\n \"text\": \"Method #1:\"\n },\n {\n \"code\": \"# Create a simple dataframe # importing pandas as pdimport pandas as pd # creating a dataframedf = pd.DataFrame({'A': ['john', 'bODAY', 'minA', 'Peter', 'nicky'], 'B': ['masters', 'graduate', 'graduate', 'Masters', 'Graduate'], 'C': [27, 23, 21, 23, 24]}) df['A'] = df['A'].str.capitalize() df\",\n \"e\": 26297,\n \"s\": 25926,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 26354,\n \"s\": 26297,\n \"text\": \"Output: Method #2: Using lambda with capitalize() method\"\n },\n {\n \"code\": \"# Create a simple dataframe # importing pandas as pdimport pandas as pd # creating a dataframedf = pd.DataFrame({'A': ['john', 'bODAY', 'minA', 'Peter', 'nicky'], 'B': ['masters', 'graduate', 'graduate', 'Masters', 'Graduate'], 'C': [27, 23, 21, 23, 24]}) df['A'].apply(lambda x: x.capitalize())\",\n \"e\": 26726,\n \"s\": 26354,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 26734,\n \"s\": 26726,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 26759,\n \"s\": 26734,\n \"text\": \"pandas-dataframe-program\"\n },\n {\n \"code\": null,\n \"e\": 26783,\n \"s\": 26759,\n \"text\": \"Python pandas-dataFrame\"\n },\n {\n \"code\": null,\n \"e\": 26797,\n \"s\": 26783,\n \"text\": \"Python-pandas\"\n },\n {\n \"code\": null,\n \"e\": 26804,\n \"s\": 26797,\n \"text\": \"Python\"\n },\n {\n \"code\": null,\n \"e\": 26902,\n \"s\": 26804,\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\": 26920,\n \"s\": 26902,\n \"text\": \"Python Dictionary\"\n },\n {\n \"code\": null,\n \"e\": 26942,\n \"s\": 26920,\n \"text\": \"Enumerate() in Python\"\n },\n {\n \"code\": null,\n \"e\": 26974,\n \"s\": 26942,\n \"text\": \"How to Install PIP on Windows ?\"\n },\n {\n \"code\": null,\n \"e\": 27004,\n \"s\": 26974,\n \"text\": \"Iterate over a list in Python\"\n },\n {\n \"code\": null,\n \"e\": 27046,\n \"s\": 27004,\n \"text\": \"Different ways to create Pandas Dataframe\"\n },\n {\n \"code\": null,\n \"e\": 27072,\n \"s\": 27046,\n \"text\": \"Python String | replace()\"\n },\n {\n \"code\": null,\n \"e\": 27109,\n \"s\": 27072,\n \"text\": \"Create a Pandas DataFrame from Lists\"\n },\n {\n \"code\": null,\n \"e\": 27153,\n \"s\": 27109,\n \"text\": \"Reading and Writing to text files in Python\"\n },\n {\n \"code\": null,\n \"e\": 27182,\n \"s\": 27153,\n \"text\": \"*args and **kwargs in Python\"\n }\n]"}}},{"rowIdx":444,"cells":{"title":{"kind":"string","value":"Properties getOrDefault(key, defaultValue) method in Java with Examples - GeeksforGeeks"},"text":{"kind":"string","value":"10 Dec, 2019\nThe getOrDefault(key, defaultValue) method of Properties class is used to get the value mapped to this key, passed as the parameter, in this Properties object. This method will fetch the corresponding value to this key, if present, and return it. If there is no such mapping, then it returns the defaultValue.\nSyntax:\npublic Object getOrDefault(Object key, Object defaultValue)\nParameters: This method accepts two parameter:\nkey: whose mapping is to be checked in this Properties object.\ndefaultValue: which is the default mapping of the key\nReturns: This method returns the value fetched corresponding to this key, if present. If there is no such mapping, then it returns the defaultValue.\nBelow programs illustrate the getOrDefault(key, defaultValue) method:\nProgram 1:\n// Java program to demonstrate// getOrDefault(key, defaultValue) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); properties.put(\"Pen\", 10); properties.put(\"Book\", 500); properties.put(\"Clothes\", 400); properties.put(\"Mobile\", 5000); // Print Properties details System.out.println(\"Properties: \" + properties.toString()); // Getting the value of Pen System.out.println(\"Value of Pen: \" + properties .getOrDefault(\"Pen\", 200)); // Getting the value of Phone System.out.println(\"Value of Phone: \" + properties .getOrDefault(\"Phone\", 200)); }}\nProperties: {Book=500, Mobile=5000, Pen=10, Clothes=400}\nValue of Pen: 10\nValue of Phone: 200\n\nProgram 2:\n// Java program to demonstrate// getOrDefault(key, defaultValue) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); properties.put(1, \"100RS\"); properties.put(2, \"500RS\"); properties.put(3, \"1000RS\"); // Print Properties details System.out.println(\"Current Properties: \" + properties.toString()); // Getting the value of 1 System.out.println(\"Value of 1: \" + properties .getOrDefault(1, \"200RS\")); // Getting the value of 5 System.out.println(\"Value of 5: \" + properties .getOrDefault(5, \"200RS\")); }}\nCurrent Properties: {3=1000RS, 2=500RS, 1=100RS}\nValue of 1: 100RS\nValue of 5: 200RS\n\nReferences: https://docs.oracle.com/javase/9/docs/api/java/util/Properties.html#getOrDefault-java.lang.Object-java.lang.Object-\nAkanksha_Rai\nJava - util package\nJava-Functions\nJava-Properties\nJava\nJava\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nComments\nOld Comments\nInitialize an ArrayList in Java\nOverriding in Java\nMultidimensional Arrays in Java\nLinkedList in Java\nPriorityQueue in Java\nArrayList in Java\nQueue Interface In Java\nStack Class in Java\nCollections.sort() in Java with Examples\nInitializing a List in Java"},"parsed":{"kind":"list like","value":[{"code":null,"e":23971,"s":23943,"text":"\n10 Dec, 2019"},{"code":null,"e":24281,"s":23971,"text":"The getOrDefault(key, defaultValue) method of Properties class is used to get the value mapped to this key, passed as the parameter, in this Properties object. This method will fetch the corresponding value to this key, if present, and return it. If there is no such mapping, then it returns the defaultValue."},{"code":null,"e":24289,"s":24281,"text":"Syntax:"},{"code":null,"e":24349,"s":24289,"text":"public Object getOrDefault(Object key, Object defaultValue)"},{"code":null,"e":24396,"s":24349,"text":"Parameters: This method accepts two parameter:"},{"code":null,"e":24459,"s":24396,"text":"key: whose mapping is to be checked in this Properties object."},{"code":null,"e":24513,"s":24459,"text":"defaultValue: which is the default mapping of the key"},{"code":null,"e":24662,"s":24513,"text":"Returns: This method returns the value fetched corresponding to this key, if present. If there is no such mapping, then it returns the defaultValue."},{"code":null,"e":24732,"s":24662,"text":"Below programs illustrate the getOrDefault(key, defaultValue) method:"},{"code":null,"e":24743,"s":24732,"text":"Program 1:"},{"code":"// Java program to demonstrate// getOrDefault(key, defaultValue) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); properties.put(\"Pen\", 10); properties.put(\"Book\", 500); properties.put(\"Clothes\", 400); properties.put(\"Mobile\", 5000); // Print Properties details System.out.println(\"Properties: \" + properties.toString()); // Getting the value of Pen System.out.println(\"Value of Pen: \" + properties .getOrDefault(\"Pen\", 200)); // Getting the value of Phone System.out.println(\"Value of Phone: \" + properties .getOrDefault(\"Phone\", 200)); }}","e":25673,"s":24743,"text":null},{"code":null,"e":25768,"s":25673,"text":"Properties: {Book=500, Mobile=5000, Pen=10, Clothes=400}\nValue of Pen: 10\nValue of Phone: 200\n"},{"code":null,"e":25779,"s":25768,"text":"Program 2:"},{"code":"// Java program to demonstrate// getOrDefault(key, defaultValue) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); properties.put(1, \"100RS\"); properties.put(2, \"500RS\"); properties.put(3, \"1000RS\"); // Print Properties details System.out.println(\"Current Properties: \" + properties.toString()); // Getting the value of 1 System.out.println(\"Value of 1: \" + properties .getOrDefault(1, \"200RS\")); // Getting the value of 5 System.out.println(\"Value of 5: \" + properties .getOrDefault(5, \"200RS\")); }}","e":26663,"s":25779,"text":null},{"code":null,"e":26749,"s":26663,"text":"Current Properties: {3=1000RS, 2=500RS, 1=100RS}\nValue of 1: 100RS\nValue of 5: 200RS\n"},{"code":null,"e":26877,"s":26749,"text":"References: https://docs.oracle.com/javase/9/docs/api/java/util/Properties.html#getOrDefault-java.lang.Object-java.lang.Object-"},{"code":null,"e":26890,"s":26877,"text":"Akanksha_Rai"},{"code":null,"e":26910,"s":26890,"text":"Java - util package"},{"code":null,"e":26925,"s":26910,"text":"Java-Functions"},{"code":null,"e":26941,"s":26925,"text":"Java-Properties"},{"code":null,"e":26946,"s":26941,"text":"Java"},{"code":null,"e":26951,"s":26946,"text":"Java"},{"code":null,"e":27049,"s":26951,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":27058,"s":27049,"text":"Comments"},{"code":null,"e":27071,"s":27058,"text":"Old Comments"},{"code":null,"e":27103,"s":27071,"text":"Initialize an ArrayList in Java"},{"code":null,"e":27122,"s":27103,"text":"Overriding in Java"},{"code":null,"e":27154,"s":27122,"text":"Multidimensional Arrays in Java"},{"code":null,"e":27173,"s":27154,"text":"LinkedList in Java"},{"code":null,"e":27195,"s":27173,"text":"PriorityQueue in Java"},{"code":null,"e":27213,"s":27195,"text":"ArrayList in Java"},{"code":null,"e":27237,"s":27213,"text":"Queue Interface In Java"},{"code":null,"e":27257,"s":27237,"text":"Stack Class in Java"},{"code":null,"e":27298,"s":27257,"text":"Collections.sort() in Java with Examples"}],"string":"[\n {\n \"code\": null,\n \"e\": 23971,\n \"s\": 23943,\n \"text\": \"\\n10 Dec, 2019\"\n },\n {\n \"code\": null,\n \"e\": 24281,\n \"s\": 23971,\n \"text\": \"The getOrDefault(key, defaultValue) method of Properties class is used to get the value mapped to this key, passed as the parameter, in this Properties object. This method will fetch the corresponding value to this key, if present, and return it. If there is no such mapping, then it returns the defaultValue.\"\n },\n {\n \"code\": null,\n \"e\": 24289,\n \"s\": 24281,\n \"text\": \"Syntax:\"\n },\n {\n \"code\": null,\n \"e\": 24349,\n \"s\": 24289,\n \"text\": \"public Object getOrDefault(Object key, Object defaultValue)\"\n },\n {\n \"code\": null,\n \"e\": 24396,\n \"s\": 24349,\n \"text\": \"Parameters: This method accepts two parameter:\"\n },\n {\n \"code\": null,\n \"e\": 24459,\n \"s\": 24396,\n \"text\": \"key: whose mapping is to be checked in this Properties object.\"\n },\n {\n \"code\": null,\n \"e\": 24513,\n \"s\": 24459,\n \"text\": \"defaultValue: which is the default mapping of the key\"\n },\n {\n \"code\": null,\n \"e\": 24662,\n \"s\": 24513,\n \"text\": \"Returns: This method returns the value fetched corresponding to this key, if present. If there is no such mapping, then it returns the defaultValue.\"\n },\n {\n \"code\": null,\n \"e\": 24732,\n \"s\": 24662,\n \"text\": \"Below programs illustrate the getOrDefault(key, defaultValue) method:\"\n },\n {\n \"code\": null,\n \"e\": 24743,\n \"s\": 24732,\n \"text\": \"Program 1:\"\n },\n {\n \"code\": \"// Java program to demonstrate// getOrDefault(key, defaultValue) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); properties.put(\\\"Pen\\\", 10); properties.put(\\\"Book\\\", 500); properties.put(\\\"Clothes\\\", 400); properties.put(\\\"Mobile\\\", 5000); // Print Properties details System.out.println(\\\"Properties: \\\" + properties.toString()); // Getting the value of Pen System.out.println(\\\"Value of Pen: \\\" + properties .getOrDefault(\\\"Pen\\\", 200)); // Getting the value of Phone System.out.println(\\\"Value of Phone: \\\" + properties .getOrDefault(\\\"Phone\\\", 200)); }}\",\n \"e\": 25673,\n \"s\": 24743,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 25768,\n \"s\": 25673,\n \"text\": \"Properties: {Book=500, Mobile=5000, Pen=10, Clothes=400}\\nValue of Pen: 10\\nValue of Phone: 200\\n\"\n },\n {\n \"code\": null,\n \"e\": 25779,\n \"s\": 25768,\n \"text\": \"Program 2:\"\n },\n {\n \"code\": \"// Java program to demonstrate// getOrDefault(key, defaultValue) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); properties.put(1, \\\"100RS\\\"); properties.put(2, \\\"500RS\\\"); properties.put(3, \\\"1000RS\\\"); // Print Properties details System.out.println(\\\"Current Properties: \\\" + properties.toString()); // Getting the value of 1 System.out.println(\\\"Value of 1: \\\" + properties .getOrDefault(1, \\\"200RS\\\")); // Getting the value of 5 System.out.println(\\\"Value of 5: \\\" + properties .getOrDefault(5, \\\"200RS\\\")); }}\",\n \"e\": 26663,\n \"s\": 25779,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 26749,\n \"s\": 26663,\n \"text\": \"Current Properties: {3=1000RS, 2=500RS, 1=100RS}\\nValue of 1: 100RS\\nValue of 5: 200RS\\n\"\n },\n {\n \"code\": null,\n \"e\": 26877,\n \"s\": 26749,\n \"text\": \"References: https://docs.oracle.com/javase/9/docs/api/java/util/Properties.html#getOrDefault-java.lang.Object-java.lang.Object-\"\n },\n {\n \"code\": null,\n \"e\": 26890,\n \"s\": 26877,\n \"text\": \"Akanksha_Rai\"\n },\n {\n \"code\": null,\n \"e\": 26910,\n \"s\": 26890,\n \"text\": \"Java - util package\"\n },\n {\n \"code\": null,\n \"e\": 26925,\n \"s\": 26910,\n \"text\": \"Java-Functions\"\n },\n {\n \"code\": null,\n \"e\": 26941,\n \"s\": 26925,\n \"text\": \"Java-Properties\"\n },\n {\n \"code\": null,\n \"e\": 26946,\n \"s\": 26941,\n \"text\": \"Java\"\n },\n {\n \"code\": null,\n \"e\": 26951,\n \"s\": 26946,\n \"text\": \"Java\"\n },\n {\n \"code\": null,\n \"e\": 27049,\n \"s\": 26951,\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\": 27058,\n \"s\": 27049,\n \"text\": \"Comments\"\n },\n {\n \"code\": null,\n \"e\": 27071,\n \"s\": 27058,\n \"text\": \"Old Comments\"\n },\n {\n \"code\": null,\n \"e\": 27103,\n \"s\": 27071,\n \"text\": \"Initialize an ArrayList in Java\"\n },\n {\n \"code\": null,\n \"e\": 27122,\n \"s\": 27103,\n \"text\": \"Overriding in Java\"\n },\n {\n \"code\": null,\n \"e\": 27154,\n \"s\": 27122,\n \"text\": \"Multidimensional Arrays in Java\"\n },\n {\n \"code\": null,\n \"e\": 27173,\n \"s\": 27154,\n \"text\": \"LinkedList in Java\"\n },\n {\n \"code\": null,\n \"e\": 27195,\n \"s\": 27173,\n \"text\": \"PriorityQueue in Java\"\n },\n {\n \"code\": null,\n \"e\": 27213,\n \"s\": 27195,\n \"text\": \"ArrayList in Java\"\n },\n {\n \"code\": null,\n \"e\": 27237,\n \"s\": 27213,\n \"text\": \"Queue Interface In Java\"\n },\n {\n \"code\": null,\n \"e\": 27257,\n \"s\": 27237,\n \"text\": \"Stack Class in Java\"\n },\n {\n \"code\": null,\n \"e\": 27298,\n \"s\": 27257,\n \"text\": \"Collections.sort() in Java with Examples\"\n }\n]"}}},{"rowIdx":445,"cells":{"title":{"kind":"string","value":"Understand Text Summarization and create your own summarizer in python | by Praveen Dubey | Towards Data Science"},"text":{"kind":"string","value":"We all interact with applications which uses text summarization. Many of those applications are for the platform which publishes articles on daily news, entertainment, sports. With our busy schedule, we prefer to read the summary of those article before we decide to jump in for reading entire article. Reading a summary help us to identify the interest area, gives a brief context of the story.\nSummarization can be defined as a task of producing a concise and fluent summary while preserving key information and overall meaning.\nSummarization systems often have additional evidence they can utilize in order to specify the most important topics of document(s). For example, when summarizing blogs, there are discussions or comments coming after the blog post that are good sources of information to determine which parts of the blog are critical and interesting.\nIn scientific paper summarization, there is a considerable amount of information such as cited papers and conference information which can be leveraged to identify important sentences in the original paper.\nIn general there are two types of summarization, abstractive and extractive summarization.\nAbstractive Summarization: Abstractive methods select words based on semantic understanding, even those words did not appear in the source documents. It aims at producing important material in a new way. They interpret and examine the text using advanced natural language techniques in order to generate a new shorter text that conveys the most critical information from the original text.\nAbstractive Summarization: Abstractive methods select words based on semantic understanding, even those words did not appear in the source documents. It aims at producing important material in a new way. They interpret and examine the text using advanced natural language techniques in order to generate a new shorter text that conveys the most critical information from the original text.\nIt can be correlated to the way human reads a text article or blog post and then summarizes in their own word.\nInput document → understand context → semantics → create own summary.\n2. Extractive Summarization: Extractive methods attempt to summarize articles by selecting a subset of words that retain the most important points.\nThis approach weights the important part of sentences and uses the same to form the summary. Different algorithm and techniques are used to define weights for the sentences and further rank them based on importance and similarity among each other.\nInput document → sentences similarity → weight sentences → select sentences with higher rank.\nThe limited study is available for abstractive summarization as it requires a deeper understanding of the text as compared to the extractive approach.\nPurely extractive summaries often times give better results compared to automatic abstractive summaries. This is because of the fact that abstractive summarization methods cope with problems such as semantic representation,inference and natural language generation which is relatively harder than data-driven approaches such as sentence extraction.\nThere are many techniques available to generate extractive summarization. To keep it simple, I will be using an unsupervised learning approach to find the sentences similarity and rank them. One benefit of this will be, you don’t need to train and build a model prior start using it for your project.\nIt’s good to understand Cosine similarity to make the best use of code you are going to see. Cosine similarity is a measure of similarity between two non-zero vectors of an inner product space that measures the cosine of the angle between them. Since we will be representing our sentences as the bunch of vectors, we can use it to find the similarity among sentences. Its measures cosine of the angle between vectors. Angle will be 0 if sentences are similar.\nAll good till now..? Hope so :)\nNext, Below is our code flow to generate summarize text:-\nInput article → split into sentences → remove stop words → build a similarity matrix → generate rank based on matrix → pick top N sentences for summary.\nLet’s create these methods.\nfrom nltk.corpus import stopwordsfrom nltk.cluster.util import cosine_distanceimport numpy as npimport networkx as nx\ndef read_article(file_name): file = open(file_name, \"r\") filedata = file.readlines() article = filedata[0].split(\". \") sentences = [] for sentence in article: print(sentence) sentences.append(sentence.replace(\"[^a-zA-Z]\", \" \").split(\" \")) sentences.pop() return sentences\nThis is where we will be using cosine similarity to find similarity between sentences.\ndef build_similarity_matrix(sentences, stop_words): # Create an empty similarity matrix similarity_matrix = np.zeros((len(sentences), len(sentences))) for idx1 in range(len(sentences)): for idx2 in range(len(sentences)): if idx1 == idx2: #ignore if both are same sentences continue similarity_matrix[idx1][idx2] = sentence_similarity(sentences[idx1], sentences[idx2], stop_words)return similarity_matrix\nMethod will keep calling all other helper function to keep our summarization pipeline going. Make sure to take a look at all # Steps in below code.\ndef generate_summary(file_name, top_n=5): stop_words = stopwords.words('english') summarize_text = [] # Step 1 - Read text and tokenize sentences = read_article(file_name) # Step 2 - Generate Similary Martix across sentences sentence_similarity_martix = build_similarity_matrix(sentences, stop_words) # Step 3 - Rank sentences in similarity martix sentence_similarity_graph = nx.from_numpy_array(sentence_similarity_martix) scores = nx.pagerank(sentence_similarity_graph) # Step 4 - Sort the rank and pick top sentences ranked_sentence = sorted(((scores[i],s) for i,s in enumerate(sentences)), reverse=True) print(\"Indexes of top ranked_sentence order are \", ranked_sentence)for i in range(top_n): summarize_text.append(\" \".join(ranked_sentence[i][1])) # Step 5 - Offcourse, output the summarize texr print(\"Summarize Text: \\n\", \". \".join(summarize_text))\nAll put together, here is the complete code.\nThe complete text from an article titled Microsoft Launches Intelligent Cloud Hub To Upskill Students In AI & Cloud Technologies\nIn an attempt to build an AI-ready workforce, Microsoft announced Intelligent Cloud Hub which has been launched to empower the next generation of students with AI-ready skills. Envisioned as a three-year collaborative program, Intelligent Cloud Hub will support around 100 institutions with AI infrastructure, course content and curriculum, developer support, development tools and give students access to cloud and AI services. As part of the program, the Redmond giant which wants to expand its reach and is planning to build a strong developer ecosystem in India with the program will set up the core AI infrastructure and IoT Hub for the selected campuses. The company will provide AI development tools and Azure AI services such as Microsoft Cognitive Services, Bot Services and Azure Machine Learning.According to Manish Prakash, Country General Manager-PS, Health and Education, Microsoft India, said, \"With AI being the defining technology of our time, it is transforming lives and industry and the jobs of tomorrow will require a different skillset. This will require more collaborations and training and working with AI. That’s why it has become more critical than ever for educational institutions to integrate new cloud and AI technologies. The program is an attempt to ramp up the institutional set-up and build capabilities among the educators to educate the workforce of tomorrow.\" The program aims to build up the cognitive skills and in-depth understanding of developing intelligent cloud connected solutions for applications across industry. Earlier in April this year, the company announced Microsoft Professional Program In AI as a learning track open to the public. The program was developed to provide job ready skills to programmers who wanted to hone their skills in AI and data science with a series of online courses which featured hands-on labs and expert instructors as well. This program also included developer-focused AI school that provided a bunch of assets to help build AI skills.\n(source: analyticsindiamag.com)\nand the summarized text with 2 lines as an input is\nEnvisioned as a three-year collaborative program, Intelligent Cloud Hub will support around 100 institutions with AI infrastructure, course content and curriculum, developer support, development tools and give students access to cloud and AI services. The company will provide AI development tools and Azure AI services such as Microsoft Cognitive Services, Bot Services and Azure Machine Learning. According to Manish Prakash, Country General Manager-PS, Health and Education, Microsoft India, said, \"With AI being the defining technology of our time, it is transforming lives and industry and the jobs of tomorrow will require a different skillset.\nAs you can see, it does a pretty good job. You can further customized it to reduce to number to character instead of lines.\nIt is important to understand that we have used textrank as an approach to rank the sentences. TextRank does not rely on any previous training data and can work with any arbitrary piece of text. TextRank is a general purpose graph-based ranking algorithm for NLP.\nThere are much-advanced techniques available for text summarization. If you are new to it, you can start with an interesting research paper named Text Summarization Techniques: A Brief Survey\nSurvey of the State of the Art in Natural Language Generation: Core tasks, applications and evaluation is a much more detailed research paper which you can go through for better understanding.\nHope this would have given you a brief overview of text summarization and sample demonstration of code to summarize the text. You can start with the above research papers for advance knowledge and approaches to solve this problem.\nThe code shown here is available on my GitHub. You can download and play around with it.\nYou can follow me on Medium, Twitter, and LinkedIn, For any question, reach out to me on email (praveend806 [at] gmail [dot] com)."},"parsed":{"kind":"list like","value":[{"code":null,"e":568,"s":172,"text":"We all interact with applications which uses text summarization. Many of those applications are for the platform which publishes articles on daily news, entertainment, sports. With our busy schedule, we prefer to read the summary of those article before we decide to jump in for reading entire article. Reading a summary help us to identify the interest area, gives a brief context of the story."},{"code":null,"e":703,"s":568,"text":"Summarization can be defined as a task of producing a concise and fluent summary while preserving key information and overall meaning."},{"code":null,"e":1037,"s":703,"text":"Summarization systems often have additional evidence they can utilize in order to specify the most important topics of document(s). For example, when summarizing blogs, there are discussions or comments coming after the blog post that are good sources of information to determine which parts of the blog are critical and interesting."},{"code":null,"e":1244,"s":1037,"text":"In scientific paper summarization, there is a considerable amount of information such as cited papers and conference information which can be leveraged to identify important sentences in the original paper."},{"code":null,"e":1335,"s":1244,"text":"In general there are two types of summarization, abstractive and extractive summarization."},{"code":null,"e":1725,"s":1335,"text":"Abstractive Summarization: Abstractive methods select words based on semantic understanding, even those words did not appear in the source documents. It aims at producing important material in a new way. They interpret and examine the text using advanced natural language techniques in order to generate a new shorter text that conveys the most critical information from the original text."},{"code":null,"e":2115,"s":1725,"text":"Abstractive Summarization: Abstractive methods select words based on semantic understanding, even those words did not appear in the source documents. It aims at producing important material in a new way. They interpret and examine the text using advanced natural language techniques in order to generate a new shorter text that conveys the most critical information from the original text."},{"code":null,"e":2226,"s":2115,"text":"It can be correlated to the way human reads a text article or blog post and then summarizes in their own word."},{"code":null,"e":2296,"s":2226,"text":"Input document → understand context → semantics → create own summary."},{"code":null,"e":2444,"s":2296,"text":"2. Extractive Summarization: Extractive methods attempt to summarize articles by selecting a subset of words that retain the most important points."},{"code":null,"e":2692,"s":2444,"text":"This approach weights the important part of sentences and uses the same to form the summary. Different algorithm and techniques are used to define weights for the sentences and further rank them based on importance and similarity among each other."},{"code":null,"e":2786,"s":2692,"text":"Input document → sentences similarity → weight sentences → select sentences with higher rank."},{"code":null,"e":2937,"s":2786,"text":"The limited study is available for abstractive summarization as it requires a deeper understanding of the text as compared to the extractive approach."},{"code":null,"e":3286,"s":2937,"text":"Purely extractive summaries often times give better results compared to automatic abstractive summaries. This is because of the fact that abstractive summarization methods cope with problems such as semantic representation,inference and natural language generation which is relatively harder than data-driven approaches such as sentence extraction."},{"code":null,"e":3587,"s":3286,"text":"There are many techniques available to generate extractive summarization. To keep it simple, I will be using an unsupervised learning approach to find the sentences similarity and rank them. One benefit of this will be, you don’t need to train and build a model prior start using it for your project."},{"code":null,"e":4047,"s":3587,"text":"It’s good to understand Cosine similarity to make the best use of code you are going to see. Cosine similarity is a measure of similarity between two non-zero vectors of an inner product space that measures the cosine of the angle between them. Since we will be representing our sentences as the bunch of vectors, we can use it to find the similarity among sentences. Its measures cosine of the angle between vectors. Angle will be 0 if sentences are similar."},{"code":null,"e":4079,"s":4047,"text":"All good till now..? Hope so :)"},{"code":null,"e":4137,"s":4079,"text":"Next, Below is our code flow to generate summarize text:-"},{"code":null,"e":4290,"s":4137,"text":"Input article → split into sentences → remove stop words → build a similarity matrix → generate rank based on matrix → pick top N sentences for summary."},{"code":null,"e":4318,"s":4290,"text":"Let’s create these methods."},{"code":null,"e":4436,"s":4318,"text":"from nltk.corpus import stopwordsfrom nltk.cluster.util import cosine_distanceimport numpy as npimport networkx as nx"},{"code":null,"e":4742,"s":4436,"text":"def read_article(file_name): file = open(file_name, \"r\") filedata = file.readlines() article = filedata[0].split(\". \") sentences = [] for sentence in article: print(sentence) sentences.append(sentence.replace(\"[^a-zA-Z]\", \" \").split(\" \")) sentences.pop() return sentences"},{"code":null,"e":4829,"s":4742,"text":"This is where we will be using cosine similarity to find similarity between sentences."},{"code":null,"e":5288,"s":4829,"text":"def build_similarity_matrix(sentences, stop_words): # Create an empty similarity matrix similarity_matrix = np.zeros((len(sentences), len(sentences))) for idx1 in range(len(sentences)): for idx2 in range(len(sentences)): if idx1 == idx2: #ignore if both are same sentences continue similarity_matrix[idx1][idx2] = sentence_similarity(sentences[idx1], sentences[idx2], stop_words)return similarity_matrix"},{"code":null,"e":5436,"s":5288,"text":"Method will keep calling all other helper function to keep our summarization pipeline going. Make sure to take a look at all # Steps in below code."},{"code":null,"e":6344,"s":5436,"text":"def generate_summary(file_name, top_n=5): stop_words = stopwords.words('english') summarize_text = [] # Step 1 - Read text and tokenize sentences = read_article(file_name) # Step 2 - Generate Similary Martix across sentences sentence_similarity_martix = build_similarity_matrix(sentences, stop_words) # Step 3 - Rank sentences in similarity martix sentence_similarity_graph = nx.from_numpy_array(sentence_similarity_martix) scores = nx.pagerank(sentence_similarity_graph) # Step 4 - Sort the rank and pick top sentences ranked_sentence = sorted(((scores[i],s) for i,s in enumerate(sentences)), reverse=True) print(\"Indexes of top ranked_sentence order are \", ranked_sentence)for i in range(top_n): summarize_text.append(\" \".join(ranked_sentence[i][1])) # Step 5 - Offcourse, output the summarize texr print(\"Summarize Text: \\n\", \". \".join(summarize_text))"},{"code":null,"e":6389,"s":6344,"text":"All put together, here is the complete code."},{"code":null,"e":6518,"s":6389,"text":"The complete text from an article titled Microsoft Launches Intelligent Cloud Hub To Upskill Students In AI & Cloud Technologies"},{"code":null,"e":8534,"s":6518,"text":"In an attempt to build an AI-ready workforce, Microsoft announced Intelligent Cloud Hub which has been launched to empower the next generation of students with AI-ready skills. Envisioned as a three-year collaborative program, Intelligent Cloud Hub will support around 100 institutions with AI infrastructure, course content and curriculum, developer support, development tools and give students access to cloud and AI services. As part of the program, the Redmond giant which wants to expand its reach and is planning to build a strong developer ecosystem in India with the program will set up the core AI infrastructure and IoT Hub for the selected campuses. The company will provide AI development tools and Azure AI services such as Microsoft Cognitive Services, Bot Services and Azure Machine Learning.According to Manish Prakash, Country General Manager-PS, Health and Education, Microsoft India, said, \"With AI being the defining technology of our time, it is transforming lives and industry and the jobs of tomorrow will require a different skillset. This will require more collaborations and training and working with AI. That’s why it has become more critical than ever for educational institutions to integrate new cloud and AI technologies. The program is an attempt to ramp up the institutional set-up and build capabilities among the educators to educate the workforce of tomorrow.\" The program aims to build up the cognitive skills and in-depth understanding of developing intelligent cloud connected solutions for applications across industry. Earlier in April this year, the company announced Microsoft Professional Program In AI as a learning track open to the public. The program was developed to provide job ready skills to programmers who wanted to hone their skills in AI and data science with a series of online courses which featured hands-on labs and expert instructors as well. This program also included developer-focused AI school that provided a bunch of assets to help build AI skills."},{"code":null,"e":8566,"s":8534,"text":"(source: analyticsindiamag.com)"},{"code":null,"e":8618,"s":8566,"text":"and the summarized text with 2 lines as an input is"},{"code":null,"e":9269,"s":8618,"text":"Envisioned as a three-year collaborative program, Intelligent Cloud Hub will support around 100 institutions with AI infrastructure, course content and curriculum, developer support, development tools and give students access to cloud and AI services. The company will provide AI development tools and Azure AI services such as Microsoft Cognitive Services, Bot Services and Azure Machine Learning. According to Manish Prakash, Country General Manager-PS, Health and Education, Microsoft India, said, \"With AI being the defining technology of our time, it is transforming lives and industry and the jobs of tomorrow will require a different skillset."},{"code":null,"e":9393,"s":9269,"text":"As you can see, it does a pretty good job. You can further customized it to reduce to number to character instead of lines."},{"code":null,"e":9657,"s":9393,"text":"It is important to understand that we have used textrank as an approach to rank the sentences. TextRank does not rely on any previous training data and can work with any arbitrary piece of text. TextRank is a general purpose graph-based ranking algorithm for NLP."},{"code":null,"e":9849,"s":9657,"text":"There are much-advanced techniques available for text summarization. If you are new to it, you can start with an interesting research paper named Text Summarization Techniques: A Brief Survey"},{"code":null,"e":10042,"s":9849,"text":"Survey of the State of the Art in Natural Language Generation: Core tasks, applications and evaluation is a much more detailed research paper which you can go through for better understanding."},{"code":null,"e":10273,"s":10042,"text":"Hope this would have given you a brief overview of text summarization and sample demonstration of code to summarize the text. You can start with the above research papers for advance knowledge and approaches to solve this problem."},{"code":null,"e":10362,"s":10273,"text":"The code shown here is available on my GitHub. You can download and play around with it."}],"string":"[\n {\n \"code\": null,\n \"e\": 568,\n \"s\": 172,\n \"text\": \"We all interact with applications which uses text summarization. Many of those applications are for the platform which publishes articles on daily news, entertainment, sports. With our busy schedule, we prefer to read the summary of those article before we decide to jump in for reading entire article. Reading a summary help us to identify the interest area, gives a brief context of the story.\"\n },\n {\n \"code\": null,\n \"e\": 703,\n \"s\": 568,\n \"text\": \"Summarization can be defined as a task of producing a concise and fluent summary while preserving key information and overall meaning.\"\n },\n {\n \"code\": null,\n \"e\": 1037,\n \"s\": 703,\n \"text\": \"Summarization systems often have additional evidence they can utilize in order to specify the most important topics of document(s). For example, when summarizing blogs, there are discussions or comments coming after the blog post that are good sources of information to determine which parts of the blog are critical and interesting.\"\n },\n {\n \"code\": null,\n \"e\": 1244,\n \"s\": 1037,\n \"text\": \"In scientific paper summarization, there is a considerable amount of information such as cited papers and conference information which can be leveraged to identify important sentences in the original paper.\"\n },\n {\n \"code\": null,\n \"e\": 1335,\n \"s\": 1244,\n \"text\": \"In general there are two types of summarization, abstractive and extractive summarization.\"\n },\n {\n \"code\": null,\n \"e\": 1725,\n \"s\": 1335,\n \"text\": \"Abstractive Summarization: Abstractive methods select words based on semantic understanding, even those words did not appear in the source documents. It aims at producing important material in a new way. They interpret and examine the text using advanced natural language techniques in order to generate a new shorter text that conveys the most critical information from the original text.\"\n },\n {\n \"code\": null,\n \"e\": 2115,\n \"s\": 1725,\n \"text\": \"Abstractive Summarization: Abstractive methods select words based on semantic understanding, even those words did not appear in the source documents. It aims at producing important material in a new way. They interpret and examine the text using advanced natural language techniques in order to generate a new shorter text that conveys the most critical information from the original text.\"\n },\n {\n \"code\": null,\n \"e\": 2226,\n \"s\": 2115,\n \"text\": \"It can be correlated to the way human reads a text article or blog post and then summarizes in their own word.\"\n },\n {\n \"code\": null,\n \"e\": 2296,\n \"s\": 2226,\n \"text\": \"Input document → understand context → semantics → create own summary.\"\n },\n {\n \"code\": null,\n \"e\": 2444,\n \"s\": 2296,\n \"text\": \"2. Extractive Summarization: Extractive methods attempt to summarize articles by selecting a subset of words that retain the most important points.\"\n },\n {\n \"code\": null,\n \"e\": 2692,\n \"s\": 2444,\n \"text\": \"This approach weights the important part of sentences and uses the same to form the summary. Different algorithm and techniques are used to define weights for the sentences and further rank them based on importance and similarity among each other.\"\n },\n {\n \"code\": null,\n \"e\": 2786,\n \"s\": 2692,\n \"text\": \"Input document → sentences similarity → weight sentences → select sentences with higher rank.\"\n },\n {\n \"code\": null,\n \"e\": 2937,\n \"s\": 2786,\n \"text\": \"The limited study is available for abstractive summarization as it requires a deeper understanding of the text as compared to the extractive approach.\"\n },\n {\n \"code\": null,\n \"e\": 3286,\n \"s\": 2937,\n \"text\": \"Purely extractive summaries often times give better results compared to automatic abstractive summaries. This is because of the fact that abstractive summarization methods cope with problems such as semantic representation,inference and natural language generation which is relatively harder than data-driven approaches such as sentence extraction.\"\n },\n {\n \"code\": null,\n \"e\": 3587,\n \"s\": 3286,\n \"text\": \"There are many techniques available to generate extractive summarization. To keep it simple, I will be using an unsupervised learning approach to find the sentences similarity and rank them. One benefit of this will be, you don’t need to train and build a model prior start using it for your project.\"\n },\n {\n \"code\": null,\n \"e\": 4047,\n \"s\": 3587,\n \"text\": \"It’s good to understand Cosine similarity to make the best use of code you are going to see. Cosine similarity is a measure of similarity between two non-zero vectors of an inner product space that measures the cosine of the angle between them. Since we will be representing our sentences as the bunch of vectors, we can use it to find the similarity among sentences. Its measures cosine of the angle between vectors. Angle will be 0 if sentences are similar.\"\n },\n {\n \"code\": null,\n \"e\": 4079,\n \"s\": 4047,\n \"text\": \"All good till now..? Hope so :)\"\n },\n {\n \"code\": null,\n \"e\": 4137,\n \"s\": 4079,\n \"text\": \"Next, Below is our code flow to generate summarize text:-\"\n },\n {\n \"code\": null,\n \"e\": 4290,\n \"s\": 4137,\n \"text\": \"Input article → split into sentences → remove stop words → build a similarity matrix → generate rank based on matrix → pick top N sentences for summary.\"\n },\n {\n \"code\": null,\n \"e\": 4318,\n \"s\": 4290,\n \"text\": \"Let’s create these methods.\"\n },\n {\n \"code\": null,\n \"e\": 4436,\n \"s\": 4318,\n \"text\": \"from nltk.corpus import stopwordsfrom nltk.cluster.util import cosine_distanceimport numpy as npimport networkx as nx\"\n },\n {\n \"code\": null,\n \"e\": 4742,\n \"s\": 4436,\n \"text\": \"def read_article(file_name): file = open(file_name, \\\"r\\\") filedata = file.readlines() article = filedata[0].split(\\\". \\\") sentences = [] for sentence in article: print(sentence) sentences.append(sentence.replace(\\\"[^a-zA-Z]\\\", \\\" \\\").split(\\\" \\\")) sentences.pop() return sentences\"\n },\n {\n \"code\": null,\n \"e\": 4829,\n \"s\": 4742,\n \"text\": \"This is where we will be using cosine similarity to find similarity between sentences.\"\n },\n {\n \"code\": null,\n \"e\": 5288,\n \"s\": 4829,\n \"text\": \"def build_similarity_matrix(sentences, stop_words): # Create an empty similarity matrix similarity_matrix = np.zeros((len(sentences), len(sentences))) for idx1 in range(len(sentences)): for idx2 in range(len(sentences)): if idx1 == idx2: #ignore if both are same sentences continue similarity_matrix[idx1][idx2] = sentence_similarity(sentences[idx1], sentences[idx2], stop_words)return similarity_matrix\"\n },\n {\n \"code\": null,\n \"e\": 5436,\n \"s\": 5288,\n \"text\": \"Method will keep calling all other helper function to keep our summarization pipeline going. Make sure to take a look at all # Steps in below code.\"\n },\n {\n \"code\": null,\n \"e\": 6344,\n \"s\": 5436,\n \"text\": \"def generate_summary(file_name, top_n=5): stop_words = stopwords.words('english') summarize_text = [] # Step 1 - Read text and tokenize sentences = read_article(file_name) # Step 2 - Generate Similary Martix across sentences sentence_similarity_martix = build_similarity_matrix(sentences, stop_words) # Step 3 - Rank sentences in similarity martix sentence_similarity_graph = nx.from_numpy_array(sentence_similarity_martix) scores = nx.pagerank(sentence_similarity_graph) # Step 4 - Sort the rank and pick top sentences ranked_sentence = sorted(((scores[i],s) for i,s in enumerate(sentences)), reverse=True) print(\\\"Indexes of top ranked_sentence order are \\\", ranked_sentence)for i in range(top_n): summarize_text.append(\\\" \\\".join(ranked_sentence[i][1])) # Step 5 - Offcourse, output the summarize texr print(\\\"Summarize Text: \\\\n\\\", \\\". \\\".join(summarize_text))\"\n },\n {\n \"code\": null,\n \"e\": 6389,\n \"s\": 6344,\n \"text\": \"All put together, here is the complete code.\"\n },\n {\n \"code\": null,\n \"e\": 6518,\n \"s\": 6389,\n \"text\": \"The complete text from an article titled Microsoft Launches Intelligent Cloud Hub To Upskill Students In AI & Cloud Technologies\"\n },\n {\n \"code\": null,\n \"e\": 8534,\n \"s\": 6518,\n \"text\": \"In an attempt to build an AI-ready workforce, Microsoft announced Intelligent Cloud Hub which has been launched to empower the next generation of students with AI-ready skills. Envisioned as a three-year collaborative program, Intelligent Cloud Hub will support around 100 institutions with AI infrastructure, course content and curriculum, developer support, development tools and give students access to cloud and AI services. As part of the program, the Redmond giant which wants to expand its reach and is planning to build a strong developer ecosystem in India with the program will set up the core AI infrastructure and IoT Hub for the selected campuses. The company will provide AI development tools and Azure AI services such as Microsoft Cognitive Services, Bot Services and Azure Machine Learning.According to Manish Prakash, Country General Manager-PS, Health and Education, Microsoft India, said, \\\"With AI being the defining technology of our time, it is transforming lives and industry and the jobs of tomorrow will require a different skillset. This will require more collaborations and training and working with AI. That’s why it has become more critical than ever for educational institutions to integrate new cloud and AI technologies. The program is an attempt to ramp up the institutional set-up and build capabilities among the educators to educate the workforce of tomorrow.\\\" The program aims to build up the cognitive skills and in-depth understanding of developing intelligent cloud connected solutions for applications across industry. Earlier in April this year, the company announced Microsoft Professional Program In AI as a learning track open to the public. The program was developed to provide job ready skills to programmers who wanted to hone their skills in AI and data science with a series of online courses which featured hands-on labs and expert instructors as well. This program also included developer-focused AI school that provided a bunch of assets to help build AI skills.\"\n },\n {\n \"code\": null,\n \"e\": 8566,\n \"s\": 8534,\n \"text\": \"(source: analyticsindiamag.com)\"\n },\n {\n \"code\": null,\n \"e\": 8618,\n \"s\": 8566,\n \"text\": \"and the summarized text with 2 lines as an input is\"\n },\n {\n \"code\": null,\n \"e\": 9269,\n \"s\": 8618,\n \"text\": \"Envisioned as a three-year collaborative program, Intelligent Cloud Hub will support around 100 institutions with AI infrastructure, course content and curriculum, developer support, development tools and give students access to cloud and AI services. The company will provide AI development tools and Azure AI services such as Microsoft Cognitive Services, Bot Services and Azure Machine Learning. According to Manish Prakash, Country General Manager-PS, Health and Education, Microsoft India, said, \\\"With AI being the defining technology of our time, it is transforming lives and industry and the jobs of tomorrow will require a different skillset.\"\n },\n {\n \"code\": null,\n \"e\": 9393,\n \"s\": 9269,\n \"text\": \"As you can see, it does a pretty good job. You can further customized it to reduce to number to character instead of lines.\"\n },\n {\n \"code\": null,\n \"e\": 9657,\n \"s\": 9393,\n \"text\": \"It is important to understand that we have used textrank as an approach to rank the sentences. TextRank does not rely on any previous training data and can work with any arbitrary piece of text. TextRank is a general purpose graph-based ranking algorithm for NLP.\"\n },\n {\n \"code\": null,\n \"e\": 9849,\n \"s\": 9657,\n \"text\": \"There are much-advanced techniques available for text summarization. If you are new to it, you can start with an interesting research paper named Text Summarization Techniques: A Brief Survey\"\n },\n {\n \"code\": null,\n \"e\": 10042,\n \"s\": 9849,\n \"text\": \"Survey of the State of the Art in Natural Language Generation: Core tasks, applications and evaluation is a much more detailed research paper which you can go through for better understanding.\"\n },\n {\n \"code\": null,\n \"e\": 10273,\n \"s\": 10042,\n \"text\": \"Hope this would have given you a brief overview of text summarization and sample demonstration of code to summarize the text. You can start with the above research papers for advance knowledge and approaches to solve this problem.\"\n },\n {\n \"code\": null,\n \"e\": 10362,\n \"s\": 10273,\n \"text\": \"The code shown here is available on my GitHub. You can download and play around with it.\"\n }\n]"}}},{"rowIdx":446,"cells":{"title":{"kind":"string","value":"How to Convert Decimal to Binary?"},"text":{"kind":"string","value":"Decimal number is most familiar number system to the general public. It is base 10 which has only 10 symbols − 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. Whereas Binary number is most familiar number system to the digital systems, networking, and computer professionals. It is base 2 which has only 2 symbols: 0 and 1, these digits can be represented by off and on respectively.\nThere are various direct or indirect methods to convert a decimal number into binary number. In an indirect method, you need to convert a decimal number into other number system (e.g., octal or hexadecimal), then you can convert into binary number by converting each digit into binary number.\nExample − Convert decimal number 125 into binary number.\nFirst convert it into octal or hexadecimal number,\n= (125)10\n= (1x82+7x81+5x80)10\nor (7x161+13x160)10\nBecause base of octal and hexadecimal are 8 and 16 respectively.\n= (175)8\nor (7D)16\nThen convert it into binary number by converting each digit.\n= (001 111 101)2\nor (0111 1101)2\n= (01111101)2\nHowever, there are two direct methods are available for converting a decimal number into binary number: Performing Short Division by Two with Remainder (for integer part), Performing Short Multiplication by Two with result (For fractional part) and Descending Powers of Two and Subtraction. These are explained as following below.\nThis is a straightforward method which involve dividing the number to be converted. Let decimal number is N then divide this number from 2 because base of binary number system is 2. Note down the value of remainder, which will be either 0 or 1. Again divide remaining decimal number till it became 0 and note every remainder of every step. Then write remainders from bottom to up (or in reverse order), which will be equivalent binary number of given decimal number. This is procedure for converting an integer decimal number, algorithm is given below.\nTake decimal number as dividend.\nTake decimal number as dividend.\nDivide this number by 2 (2 is base of binary so divisor here).\nDivide this number by 2 (2 is base of binary so divisor here).\nStore the remainder in an array (it will be either 0 or 1 because of divisor 2).\nStore the remainder in an array (it will be either 0 or 1 because of divisor 2).\nRepeat the above two steps until the number is greater than zero.\nRepeat the above two steps until the number is greater than zero.\nPrint the array in reverse order (which will be equivalent binary number of given decimal number).\nPrint the array in reverse order (which will be equivalent binary number of given decimal number).\nNote that dividend (here given decimal number) is the number being divided, the divisor (here base of binary, i.e., 2) in the number by which the dividend is divided, and quotient (remaining divided decimal number) is the result of the division.\nExample − Convert decimal number 112 into binary number.\nSince given number is decimal integer number, so by using above algorithm performing short division by 2 with remainder.\nNow, write remainder from bottom to up (in reverse order), this will be 1110000 which is equivalent binary number of decimal integer 112.\nBut above method can not convert fraction part of a mixed (a number with integer and fraction part) decimal number. For decimal fractional part, the method is explained as following below.\nLet decimal fractional part is M then multiply this number from 2 because base of binary number system is 2. Note down the value of integer part, which will be either 0 or 1. Again multiply remaining decimal fractional number till it became 0 and note every integer part of result of every step. Then write noted results of integer part, which will be equivalent fraction binary number of given decimal number. This is procedure for converting an fractional decimal number, algorithm is given below.\nTake decimal number as multiplicand.\nTake decimal number as multiplicand.\nMultiple this number by 2 (2 is base of binary so multiplier here).\nMultiple this number by 2 (2 is base of binary so multiplier here).\nStore the value of integer part of result in an array (it will be either 0 or 1 because of multiplier 2).\nStore the value of integer part of result in an array (it will be either 0 or 1 because of multiplier 2).\nRepeat the above two steps until the number became zero.\nRepeat the above two steps until the number became zero.\nPrint the array (which will be equivalent fractional binary number of given decimal fractional number).\nPrint the array (which will be equivalent fractional binary number of given decimal fractional number).\nNote that a multiplicand (here decimal fractional number) is that to be multiplied by multiplier (here base of 2, i.e., 2)\nExample − Convert decimal fractional number 0.8125 into binary number.\nSince given number is decimal fractional number, so by using above algorithm performing short multiplication by 2 with integer part.\nNow, write these resultant integer part, this will be 0.11010 which is equivalent binary fractional number of decimal fractional 0.8125.\nThis method is gussing binary number of a decimal number. You need to draw a table of power of 2, then take given decimal number and subtract it from maximum possible power of 2 that does not return resultant number negative. Then put 1 into that box of this power in the table. Repeat these steps till number is greater than zero. Put a 0 in all other empty boxes and take the output which will be equivalent binary number of given decimal number. For integer part, The algorithm is explained as following below.\nStart by making a chart.\nStart by making a chart.\nLook for the greatest power of 2.\nLook for the greatest power of 2.\nMove to the next lower power of two.\nMove to the next lower power of two.\nSubtract each successive number that can fit, and mark it with a 1.\nSubtract each successive number that can fit, and mark it with a 1.\nContinue until you reach the end of your chart.\nContinue until you reach the end of your chart.\nWrite out the binary answer.\nWrite out the binary answer.\nExample − Convert decimal number 205 into binary number.\nTake table of power of 2,\nSubtract given number 205 from maximum possible power of 2,\n= 205 - 128 = 77\nPut 1 in box of 128 (= 27), then again subtract remaining number 77 from maximum possible power of 2,\n= 77 - 64 =13\nPut 1 in box of 64 (= 26), then repeat above steps,\n= 13 - 8 =5\n= 5 - 4 =1\n= 1 - 1 =0\nAnd put a 0 in remaining boxes. Therefore equivalent binary number will be 11001101 of given 205 decimal number."},"parsed":{"kind":"list like","value":[{"code":null,"e":1431,"s":1062,"text":"Decimal number is most familiar number system to the general public. It is base 10 which has only 10 symbols − 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. Whereas Binary number is most familiar number system to the digital systems, networking, and computer professionals. It is base 2 which has only 2 symbols: 0 and 1, these digits can be represented by off and on respectively."},{"code":null,"e":1724,"s":1431,"text":"There are various direct or indirect methods to convert a decimal number into binary number. In an indirect method, you need to convert a decimal number into other number system (e.g., octal or hexadecimal), then you can convert into binary number by converting each digit into binary number."},{"code":null,"e":1781,"s":1724,"text":"Example − Convert decimal number 125 into binary number."},{"code":null,"e":2075,"s":1781,"text":"First convert it into octal or hexadecimal number,\n= (125)10\n= (1x82+7x81+5x80)10\nor (7x161+13x160)10\nBecause base of octal and hexadecimal are 8 and 16 respectively.\n= (175)8\nor (7D)16\nThen convert it into binary number by converting each digit.\n= (001 111 101)2\nor (0111 1101)2\n= (01111101)2"},{"code":null,"e":2406,"s":2075,"text":"However, there are two direct methods are available for converting a decimal number into binary number: Performing Short Division by Two with Remainder (for integer part), Performing Short Multiplication by Two with result (For fractional part) and Descending Powers of Two and Subtraction. These are explained as following below."},{"code":null,"e":2959,"s":2406,"text":"This is a straightforward method which involve dividing the number to be converted. Let decimal number is N then divide this number from 2 because base of binary number system is 2. Note down the value of remainder, which will be either 0 or 1. Again divide remaining decimal number till it became 0 and note every remainder of every step. Then write remainders from bottom to up (or in reverse order), which will be equivalent binary number of given decimal number. This is procedure for converting an integer decimal number, algorithm is given below."},{"code":null,"e":2992,"s":2959,"text":"Take decimal number as dividend."},{"code":null,"e":3025,"s":2992,"text":"Take decimal number as dividend."},{"code":null,"e":3088,"s":3025,"text":"Divide this number by 2 (2 is base of binary so divisor here)."},{"code":null,"e":3151,"s":3088,"text":"Divide this number by 2 (2 is base of binary so divisor here)."},{"code":null,"e":3232,"s":3151,"text":"Store the remainder in an array (it will be either 0 or 1 because of divisor 2)."},{"code":null,"e":3313,"s":3232,"text":"Store the remainder in an array (it will be either 0 or 1 because of divisor 2)."},{"code":null,"e":3379,"s":3313,"text":"Repeat the above two steps until the number is greater than zero."},{"code":null,"e":3445,"s":3379,"text":"Repeat the above two steps until the number is greater than zero."},{"code":null,"e":3544,"s":3445,"text":"Print the array in reverse order (which will be equivalent binary number of given decimal number)."},{"code":null,"e":3643,"s":3544,"text":"Print the array in reverse order (which will be equivalent binary number of given decimal number)."},{"code":null,"e":3889,"s":3643,"text":"Note that dividend (here given decimal number) is the number being divided, the divisor (here base of binary, i.e., 2) in the number by which the dividend is divided, and quotient (remaining divided decimal number) is the result of the division."},{"code":null,"e":3946,"s":3889,"text":"Example − Convert decimal number 112 into binary number."},{"code":null,"e":4067,"s":3946,"text":"Since given number is decimal integer number, so by using above algorithm performing short division by 2 with remainder."},{"code":null,"e":4205,"s":4067,"text":"Now, write remainder from bottom to up (in reverse order), this will be 1110000 which is equivalent binary number of decimal integer 112."},{"code":null,"e":4394,"s":4205,"text":"But above method can not convert fraction part of a mixed (a number with integer and fraction part) decimal number. For decimal fractional part, the method is explained as following below."},{"code":null,"e":4894,"s":4394,"text":"Let decimal fractional part is M then multiply this number from 2 because base of binary number system is 2. Note down the value of integer part, which will be either 0 or 1. Again multiply remaining decimal fractional number till it became 0 and note every integer part of result of every step. Then write noted results of integer part, which will be equivalent fraction binary number of given decimal number. This is procedure for converting an fractional decimal number, algorithm is given below."},{"code":null,"e":4931,"s":4894,"text":"Take decimal number as multiplicand."},{"code":null,"e":4968,"s":4931,"text":"Take decimal number as multiplicand."},{"code":null,"e":5036,"s":4968,"text":"Multiple this number by 2 (2 is base of binary so multiplier here)."},{"code":null,"e":5104,"s":5036,"text":"Multiple this number by 2 (2 is base of binary so multiplier here)."},{"code":null,"e":5210,"s":5104,"text":"Store the value of integer part of result in an array (it will be either 0 or 1 because of multiplier 2)."},{"code":null,"e":5316,"s":5210,"text":"Store the value of integer part of result in an array (it will be either 0 or 1 because of multiplier 2)."},{"code":null,"e":5373,"s":5316,"text":"Repeat the above two steps until the number became zero."},{"code":null,"e":5430,"s":5373,"text":"Repeat the above two steps until the number became zero."},{"code":null,"e":5534,"s":5430,"text":"Print the array (which will be equivalent fractional binary number of given decimal fractional number)."},{"code":null,"e":5638,"s":5534,"text":"Print the array (which will be equivalent fractional binary number of given decimal fractional number)."},{"code":null,"e":5761,"s":5638,"text":"Note that a multiplicand (here decimal fractional number) is that to be multiplied by multiplier (here base of 2, i.e., 2)"},{"code":null,"e":5832,"s":5761,"text":"Example − Convert decimal fractional number 0.8125 into binary number."},{"code":null,"e":5965,"s":5832,"text":"Since given number is decimal fractional number, so by using above algorithm performing short multiplication by 2 with integer part."},{"code":null,"e":6102,"s":5965,"text":"Now, write these resultant integer part, this will be 0.11010 which is equivalent binary fractional number of decimal fractional 0.8125."},{"code":null,"e":6616,"s":6102,"text":"This method is gussing binary number of a decimal number. You need to draw a table of power of 2, then take given decimal number and subtract it from maximum possible power of 2 that does not return resultant number negative. Then put 1 into that box of this power in the table. Repeat these steps till number is greater than zero. Put a 0 in all other empty boxes and take the output which will be equivalent binary number of given decimal number. For integer part, The algorithm is explained as following below."},{"code":null,"e":6641,"s":6616,"text":"Start by making a chart."},{"code":null,"e":6666,"s":6641,"text":"Start by making a chart."},{"code":null,"e":6700,"s":6666,"text":"Look for the greatest power of 2."},{"code":null,"e":6734,"s":6700,"text":"Look for the greatest power of 2."},{"code":null,"e":6771,"s":6734,"text":"Move to the next lower power of two."},{"code":null,"e":6808,"s":6771,"text":"Move to the next lower power of two."},{"code":null,"e":6876,"s":6808,"text":"Subtract each successive number that can fit, and mark it with a 1."},{"code":null,"e":6944,"s":6876,"text":"Subtract each successive number that can fit, and mark it with a 1."},{"code":null,"e":6992,"s":6944,"text":"Continue until you reach the end of your chart."},{"code":null,"e":7040,"s":6992,"text":"Continue until you reach the end of your chart."},{"code":null,"e":7069,"s":7040,"text":"Write out the binary answer."},{"code":null,"e":7098,"s":7069,"text":"Write out the binary answer."},{"code":null,"e":7155,"s":7098,"text":"Example − Convert decimal number 205 into binary number."},{"code":null,"e":7181,"s":7155,"text":"Take table of power of 2,"},{"code":null,"e":7573,"s":7181,"text":"Subtract given number 205 from maximum possible power of 2,\n= 205 - 128 = 77\nPut 1 in box of 128 (= 27), then again subtract remaining number 77 from maximum possible power of 2,\n= 77 - 64 =13\nPut 1 in box of 64 (= 26), then repeat above steps,\n= 13 - 8 =5\n= 5 - 4 =1\n= 1 - 1 =0\nAnd put a 0 in remaining boxes. Therefore equivalent binary number will be 11001101 of given 205 decimal number."}],"string":"[\n {\n \"code\": null,\n \"e\": 1431,\n \"s\": 1062,\n \"text\": \"Decimal number is most familiar number system to the general public. It is base 10 which has only 10 symbols − 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. Whereas Binary number is most familiar number system to the digital systems, networking, and computer professionals. It is base 2 which has only 2 symbols: 0 and 1, these digits can be represented by off and on respectively.\"\n },\n {\n \"code\": null,\n \"e\": 1724,\n \"s\": 1431,\n \"text\": \"There are various direct or indirect methods to convert a decimal number into binary number. In an indirect method, you need to convert a decimal number into other number system (e.g., octal or hexadecimal), then you can convert into binary number by converting each digit into binary number.\"\n },\n {\n \"code\": null,\n \"e\": 1781,\n \"s\": 1724,\n \"text\": \"Example − Convert decimal number 125 into binary number.\"\n },\n {\n \"code\": null,\n \"e\": 2075,\n \"s\": 1781,\n \"text\": \"First convert it into octal or hexadecimal number,\\n= (125)10\\n= (1x82+7x81+5x80)10\\nor (7x161+13x160)10\\nBecause base of octal and hexadecimal are 8 and 16 respectively.\\n= (175)8\\nor (7D)16\\nThen convert it into binary number by converting each digit.\\n= (001 111 101)2\\nor (0111 1101)2\\n= (01111101)2\"\n },\n {\n \"code\": null,\n \"e\": 2406,\n \"s\": 2075,\n \"text\": \"However, there are two direct methods are available for converting a decimal number into binary number: Performing Short Division by Two with Remainder (for integer part), Performing Short Multiplication by Two with result (For fractional part) and Descending Powers of Two and Subtraction. These are explained as following below.\"\n },\n {\n \"code\": null,\n \"e\": 2959,\n \"s\": 2406,\n \"text\": \"This is a straightforward method which involve dividing the number to be converted. Let decimal number is N then divide this number from 2 because base of binary number system is 2. Note down the value of remainder, which will be either 0 or 1. Again divide remaining decimal number till it became 0 and note every remainder of every step. Then write remainders from bottom to up (or in reverse order), which will be equivalent binary number of given decimal number. This is procedure for converting an integer decimal number, algorithm is given below.\"\n },\n {\n \"code\": null,\n \"e\": 2992,\n \"s\": 2959,\n \"text\": \"Take decimal number as dividend.\"\n },\n {\n \"code\": null,\n \"e\": 3025,\n \"s\": 2992,\n \"text\": \"Take decimal number as dividend.\"\n },\n {\n \"code\": null,\n \"e\": 3088,\n \"s\": 3025,\n \"text\": \"Divide this number by 2 (2 is base of binary so divisor here).\"\n },\n {\n \"code\": null,\n \"e\": 3151,\n \"s\": 3088,\n \"text\": \"Divide this number by 2 (2 is base of binary so divisor here).\"\n },\n {\n \"code\": null,\n \"e\": 3232,\n \"s\": 3151,\n \"text\": \"Store the remainder in an array (it will be either 0 or 1 because of divisor 2).\"\n },\n {\n \"code\": null,\n \"e\": 3313,\n \"s\": 3232,\n \"text\": \"Store the remainder in an array (it will be either 0 or 1 because of divisor 2).\"\n },\n {\n \"code\": null,\n \"e\": 3379,\n \"s\": 3313,\n \"text\": \"Repeat the above two steps until the number is greater than zero.\"\n },\n {\n \"code\": null,\n \"e\": 3445,\n \"s\": 3379,\n \"text\": \"Repeat the above two steps until the number is greater than zero.\"\n },\n {\n \"code\": null,\n \"e\": 3544,\n \"s\": 3445,\n \"text\": \"Print the array in reverse order (which will be equivalent binary number of given decimal number).\"\n },\n {\n \"code\": null,\n \"e\": 3643,\n \"s\": 3544,\n \"text\": \"Print the array in reverse order (which will be equivalent binary number of given decimal number).\"\n },\n {\n \"code\": null,\n \"e\": 3889,\n \"s\": 3643,\n \"text\": \"Note that dividend (here given decimal number) is the number being divided, the divisor (here base of binary, i.e., 2) in the number by which the dividend is divided, and quotient (remaining divided decimal number) is the result of the division.\"\n },\n {\n \"code\": null,\n \"e\": 3946,\n \"s\": 3889,\n \"text\": \"Example − Convert decimal number 112 into binary number.\"\n },\n {\n \"code\": null,\n \"e\": 4067,\n \"s\": 3946,\n \"text\": \"Since given number is decimal integer number, so by using above algorithm performing short division by 2 with remainder.\"\n },\n {\n \"code\": null,\n \"e\": 4205,\n \"s\": 4067,\n \"text\": \"Now, write remainder from bottom to up (in reverse order), this will be 1110000 which is equivalent binary number of decimal integer 112.\"\n },\n {\n \"code\": null,\n \"e\": 4394,\n \"s\": 4205,\n \"text\": \"But above method can not convert fraction part of a mixed (a number with integer and fraction part) decimal number. For decimal fractional part, the method is explained as following below.\"\n },\n {\n \"code\": null,\n \"e\": 4894,\n \"s\": 4394,\n \"text\": \"Let decimal fractional part is M then multiply this number from 2 because base of binary number system is 2. Note down the value of integer part, which will be either 0 or 1. Again multiply remaining decimal fractional number till it became 0 and note every integer part of result of every step. Then write noted results of integer part, which will be equivalent fraction binary number of given decimal number. This is procedure for converting an fractional decimal number, algorithm is given below.\"\n },\n {\n \"code\": null,\n \"e\": 4931,\n \"s\": 4894,\n \"text\": \"Take decimal number as multiplicand.\"\n },\n {\n \"code\": null,\n \"e\": 4968,\n \"s\": 4931,\n \"text\": \"Take decimal number as multiplicand.\"\n },\n {\n \"code\": null,\n \"e\": 5036,\n \"s\": 4968,\n \"text\": \"Multiple this number by 2 (2 is base of binary so multiplier here).\"\n },\n {\n \"code\": null,\n \"e\": 5104,\n \"s\": 5036,\n \"text\": \"Multiple this number by 2 (2 is base of binary so multiplier here).\"\n },\n {\n \"code\": null,\n \"e\": 5210,\n \"s\": 5104,\n \"text\": \"Store the value of integer part of result in an array (it will be either 0 or 1 because of multiplier 2).\"\n },\n {\n \"code\": null,\n \"e\": 5316,\n \"s\": 5210,\n \"text\": \"Store the value of integer part of result in an array (it will be either 0 or 1 because of multiplier 2).\"\n },\n {\n \"code\": null,\n \"e\": 5373,\n \"s\": 5316,\n \"text\": \"Repeat the above two steps until the number became zero.\"\n },\n {\n \"code\": null,\n \"e\": 5430,\n \"s\": 5373,\n \"text\": \"Repeat the above two steps until the number became zero.\"\n },\n {\n \"code\": null,\n \"e\": 5534,\n \"s\": 5430,\n \"text\": \"Print the array (which will be equivalent fractional binary number of given decimal fractional number).\"\n },\n {\n \"code\": null,\n \"e\": 5638,\n \"s\": 5534,\n \"text\": \"Print the array (which will be equivalent fractional binary number of given decimal fractional number).\"\n },\n {\n \"code\": null,\n \"e\": 5761,\n \"s\": 5638,\n \"text\": \"Note that a multiplicand (here decimal fractional number) is that to be multiplied by multiplier (here base of 2, i.e., 2)\"\n },\n {\n \"code\": null,\n \"e\": 5832,\n \"s\": 5761,\n \"text\": \"Example − Convert decimal fractional number 0.8125 into binary number.\"\n },\n {\n \"code\": null,\n \"e\": 5965,\n \"s\": 5832,\n \"text\": \"Since given number is decimal fractional number, so by using above algorithm performing short multiplication by 2 with integer part.\"\n },\n {\n \"code\": null,\n \"e\": 6102,\n \"s\": 5965,\n \"text\": \"Now, write these resultant integer part, this will be 0.11010 which is equivalent binary fractional number of decimal fractional 0.8125.\"\n },\n {\n \"code\": null,\n \"e\": 6616,\n \"s\": 6102,\n \"text\": \"This method is gussing binary number of a decimal number. You need to draw a table of power of 2, then take given decimal number and subtract it from maximum possible power of 2 that does not return resultant number negative. Then put 1 into that box of this power in the table. Repeat these steps till number is greater than zero. Put a 0 in all other empty boxes and take the output which will be equivalent binary number of given decimal number. For integer part, The algorithm is explained as following below.\"\n },\n {\n \"code\": null,\n \"e\": 6641,\n \"s\": 6616,\n \"text\": \"Start by making a chart.\"\n },\n {\n \"code\": null,\n \"e\": 6666,\n \"s\": 6641,\n \"text\": \"Start by making a chart.\"\n },\n {\n \"code\": null,\n \"e\": 6700,\n \"s\": 6666,\n \"text\": \"Look for the greatest power of 2.\"\n },\n {\n \"code\": null,\n \"e\": 6734,\n \"s\": 6700,\n \"text\": \"Look for the greatest power of 2.\"\n },\n {\n \"code\": null,\n \"e\": 6771,\n \"s\": 6734,\n \"text\": \"Move to the next lower power of two.\"\n },\n {\n \"code\": null,\n \"e\": 6808,\n \"s\": 6771,\n \"text\": \"Move to the next lower power of two.\"\n },\n {\n \"code\": null,\n \"e\": 6876,\n \"s\": 6808,\n \"text\": \"Subtract each successive number that can fit, and mark it with a 1.\"\n },\n {\n \"code\": null,\n \"e\": 6944,\n \"s\": 6876,\n \"text\": \"Subtract each successive number that can fit, and mark it with a 1.\"\n },\n {\n \"code\": null,\n \"e\": 6992,\n \"s\": 6944,\n \"text\": \"Continue until you reach the end of your chart.\"\n },\n {\n \"code\": null,\n \"e\": 7040,\n \"s\": 6992,\n \"text\": \"Continue until you reach the end of your chart.\"\n },\n {\n \"code\": null,\n \"e\": 7069,\n \"s\": 7040,\n \"text\": \"Write out the binary answer.\"\n },\n {\n \"code\": null,\n \"e\": 7098,\n \"s\": 7069,\n \"text\": \"Write out the binary answer.\"\n },\n {\n \"code\": null,\n \"e\": 7155,\n \"s\": 7098,\n \"text\": \"Example − Convert decimal number 205 into binary number.\"\n },\n {\n \"code\": null,\n \"e\": 7181,\n \"s\": 7155,\n \"text\": \"Take table of power of 2,\"\n },\n {\n \"code\": null,\n \"e\": 7573,\n \"s\": 7181,\n \"text\": \"Subtract given number 205 from maximum possible power of 2,\\n= 205 - 128 = 77\\nPut 1 in box of 128 (= 27), then again subtract remaining number 77 from maximum possible power of 2,\\n= 77 - 64 =13\\nPut 1 in box of 64 (= 26), then repeat above steps,\\n= 13 - 8 =5\\n= 5 - 4 =1\\n= 1 - 1 =0\\nAnd put a 0 in remaining boxes. Therefore equivalent binary number will be 11001101 of given 205 decimal number.\"\n }\n]"}}},{"rowIdx":447,"cells":{"title":{"kind":"string","value":"Basic Text Summarization in Python | by Graham Harrison | Towards Data Science"},"text":{"kind":"string","value":"Text summarization is a sub-set of text mining and natural language processing that aims to take long corpus of text and transform them into a summary that can be easily and quickly read and understood without losing the meaning of the original text.\nIn particular text summarisation “tokenizes” words (i.e. converts them into data) and then assesses the importance of each by looking at relative frequency and other factors. The word importance scores can then be aggregated back into values for sentences with the most important sentences bubbling up to the top of the summary.\nIf you would like a more in-depth exploration of the principles, this article is a great place to start — https://towardsdatascience.com/a-quick-introduction-to-text-summarization-in-machine-learning-3d27ccf18a9f\nThe objective of this article is to produce a basic interactive text summarization utility to demonstrate the principles and to provide a way of generating basic summaries for complex reports.\nThe summarization will have been successful if the summaries impart the majority of the meaning of the source report and can be read and understood in a fraction of the time.\nTo start with we will need to import the libraries that will be used ...\nThe building blocks for our text summarization utility handle the leg-work of allowing the user to browse the local file system to select a file to summarize.\nopenfile() handles showing the File | Open dialog box, selecting a file, and returning the full path of the selected file.\nNext getText takes the path, opens the file and reads the text contained in the file into a str. The code provided can read from .txt or .docx files.\nThe main work is done in a single line of code by calling the gensim.summarization.summarize function. The same effect can be achieved by using the nltk natural language toolkit but it would be more involved and it would require a bit more low level work.\nThe summarise function provides the implementation and it follows 3 basic steps involved in text summarization -\nPre-process and prepare the text.Perform the text summarization process.Post-process and tidy the result.\nPre-process and prepare the text.\nPerform the text summarization process.\nPost-process and tidy the result.\nThere will be many serious, industry-strength text processing engines that involve complex and comprehensive implementations of these 3 steps but this serves as a good example and it does provide summarization which can be quite useful as we will see.\nThe last few helper functions are -\nprintmd which formats and prints text that includes markup to give us a nicely formatted heading.\nopenLocalFileAndSummarize which calls the functions we have defined above to select a file and summarize the contents.\non_button_clicked which handles the button click event to add interactivity to the Notebook and to enable several files to be selected and summarised sequentially.\nIn order to test the text summarization I collected the text from two public web sites which have published freely available reports on the topics of online reporting and marketing.\nThe two web sites used to provide the test data are -\nhttps://www.sustainability-reports.com/unleashing-the-power-of-online-reporting/\nhttps://www.mckinsey.com/business-functions/marketing-and-sales/our-insights/were-all-marketers-now\nLastly a single line of code creates a button that can be clicked repeatedly to select a .txt or a .docx from the local disk which will then be transformed into a 300 word summary which is printed out below.\nWhen the button is clicked a File | Open dialog box is displayed to select a file-\nOnce the file has been selected gensim.summarization.summarize does the work and the output is formatted in the cell output -\nExecutive Summary for Unleashing the Power of Online Reporting.txt\nUnleashing the Power of Online Reporting Source: Sustainable Brands, 15 February 2018 Confronted with an ever-growing demand for transparency and materiality, companies need to find an adequate format to publish both financial and pre-financial information to their stakeholders in an effective way.In the real world, they are confronted with a multitude of information sources different in name, type and content, like Annual Report, CSR Report, Financial Statement, Sustainability Report, Annual Review, Corporate Citizenship Report, or Integrated Report.Online integrated reporting to the rescue Research from Message Group among Europe’s 800 largest companies shows that between 2015 and 2017 the number of businesses publishing financial and extra-financial information in one single integrated report increased by 34 percent, while the number of companies publishing separate sustainability and annual reports decreased by 30 percent.Unlike stand-alone annual or sustainability reports, online integrated reporting formats put an organization’s financial performance, business strategy and governance into the social, environmental and economic context within which it operates.Instead of directing readers from a webpage to separate PDF reports and resources located in different online places, Core & More provides all the relevant information on a single multi-layered website.Moreover, it is flexible enough to integrate multiple reporting frameworks, accounting standards and concepts, such as the International Financial Reporting Standard (IFRS) in combination with GRI, , the TCFD recommendations, or the SDGs. On top of all this flexibility, a digital reporting format is highly interactive and customizable, allowing the reader to create charts or compile selected content into personal PDF or printed reports.Turning reporting into a powerful communications tool In view of growing demand for ESG disclosure, the related surge in sustainability reporting, and a complex reporting landscape companies are challenged to find a disclosure format for both financial and extra-financial information that has a measurable value for their key stakeholders.\nText summarization can be a complex and involved process of pre-processing, summarization and post-processing and a real-world application that could summarize complex reports without losing the meaning of the original text would have commercial value.\nHowever, in this article we have explored the basic concepts and quickly built a simple text summarization tool that can be used to open .txt or .docx files and then summarise the contents into 300 words based on evaluating the most popular sentences.\nThe test on two public reports proved that the basic text summarization process works and provided an example of what the summarization output looks like.\nThe full source code can be found here -\ngithub.com\nIf you enjoyed reading this article, why not check out my other articles at https://grahamharrison-86487.medium.com/?\nAlso, I would love to hear from you to get your thoughts on this piece, any of my other articles or anything else related to data science and data analytics.\nIf you would like to get in touch to discuss any of these topics please look me up on LinkedIn — https://www.linkedin.com/in/grahamharrison1 or feel free to e-mail me at GHarrison@lincolncollege.ac.uk."},"parsed":{"kind":"list like","value":[{"code":null,"e":423,"s":172,"text":"Text summarization is a sub-set of text mining and natural language processing that aims to take long corpus of text and transform them into a summary that can be easily and quickly read and understood without losing the meaning of the original text."},{"code":null,"e":752,"s":423,"text":"In particular text summarisation “tokenizes” words (i.e. converts them into data) and then assesses the importance of each by looking at relative frequency and other factors. The word importance scores can then be aggregated back into values for sentences with the most important sentences bubbling up to the top of the summary."},{"code":null,"e":965,"s":752,"text":"If you would like a more in-depth exploration of the principles, this article is a great place to start — https://towardsdatascience.com/a-quick-introduction-to-text-summarization-in-machine-learning-3d27ccf18a9f"},{"code":null,"e":1158,"s":965,"text":"The objective of this article is to produce a basic interactive text summarization utility to demonstrate the principles and to provide a way of generating basic summaries for complex reports."},{"code":null,"e":1333,"s":1158,"text":"The summarization will have been successful if the summaries impart the majority of the meaning of the source report and can be read and understood in a fraction of the time."},{"code":null,"e":1406,"s":1333,"text":"To start with we will need to import the libraries that will be used ..."},{"code":null,"e":1565,"s":1406,"text":"The building blocks for our text summarization utility handle the leg-work of allowing the user to browse the local file system to select a file to summarize."},{"code":null,"e":1688,"s":1565,"text":"openfile() handles showing the File | Open dialog box, selecting a file, and returning the full path of the selected file."},{"code":null,"e":1838,"s":1688,"text":"Next getText takes the path, opens the file and reads the text contained in the file into a str. The code provided can read from .txt or .docx files."},{"code":null,"e":2094,"s":1838,"text":"The main work is done in a single line of code by calling the gensim.summarization.summarize function. The same effect can be achieved by using the nltk natural language toolkit but it would be more involved and it would require a bit more low level work."},{"code":null,"e":2207,"s":2094,"text":"The summarise function provides the implementation and it follows 3 basic steps involved in text summarization -"},{"code":null,"e":2313,"s":2207,"text":"Pre-process and prepare the text.Perform the text summarization process.Post-process and tidy the result."},{"code":null,"e":2347,"s":2313,"text":"Pre-process and prepare the text."},{"code":null,"e":2387,"s":2347,"text":"Perform the text summarization process."},{"code":null,"e":2421,"s":2387,"text":"Post-process and tidy the result."},{"code":null,"e":2673,"s":2421,"text":"There will be many serious, industry-strength text processing engines that involve complex and comprehensive implementations of these 3 steps but this serves as a good example and it does provide summarization which can be quite useful as we will see."},{"code":null,"e":2709,"s":2673,"text":"The last few helper functions are -"},{"code":null,"e":2807,"s":2709,"text":"printmd which formats and prints text that includes markup to give us a nicely formatted heading."},{"code":null,"e":2926,"s":2807,"text":"openLocalFileAndSummarize which calls the functions we have defined above to select a file and summarize the contents."},{"code":null,"e":3090,"s":2926,"text":"on_button_clicked which handles the button click event to add interactivity to the Notebook and to enable several files to be selected and summarised sequentially."},{"code":null,"e":3272,"s":3090,"text":"In order to test the text summarization I collected the text from two public web sites which have published freely available reports on the topics of online reporting and marketing."},{"code":null,"e":3326,"s":3272,"text":"The two web sites used to provide the test data are -"},{"code":null,"e":3407,"s":3326,"text":"https://www.sustainability-reports.com/unleashing-the-power-of-online-reporting/"},{"code":null,"e":3507,"s":3407,"text":"https://www.mckinsey.com/business-functions/marketing-and-sales/our-insights/were-all-marketers-now"},{"code":null,"e":3715,"s":3507,"text":"Lastly a single line of code creates a button that can be clicked repeatedly to select a .txt or a .docx from the local disk which will then be transformed into a 300 word summary which is printed out below."},{"code":null,"e":3798,"s":3715,"text":"When the button is clicked a File | Open dialog box is displayed to select a file-"},{"code":null,"e":3924,"s":3798,"text":"Once the file has been selected gensim.summarization.summarize does the work and the output is formatted in the cell output -"},{"code":null,"e":3991,"s":3924,"text":"Executive Summary for Unleashing the Power of Online Reporting.txt"},{"code":null,"e":6162,"s":3991,"text":"Unleashing the Power of Online Reporting Source: Sustainable Brands, 15 February 2018 Confronted with an ever-growing demand for transparency and materiality, companies need to find an adequate format to publish both financial and pre-financial information to their stakeholders in an effective way.In the real world, they are confronted with a multitude of information sources different in name, type and content, like Annual Report, CSR Report, Financial Statement, Sustainability Report, Annual Review, Corporate Citizenship Report, or Integrated Report.Online integrated reporting to the rescue Research from Message Group among Europe’s 800 largest companies shows that between 2015 and 2017 the number of businesses publishing financial and extra-financial information in one single integrated report increased by 34 percent, while the number of companies publishing separate sustainability and annual reports decreased by 30 percent.Unlike stand-alone annual or sustainability reports, online integrated reporting formats put an organization’s financial performance, business strategy and governance into the social, environmental and economic context within which it operates.Instead of directing readers from a webpage to separate PDF reports and resources located in different online places, Core & More provides all the relevant information on a single multi-layered website.Moreover, it is flexible enough to integrate multiple reporting frameworks, accounting standards and concepts, such as the International Financial Reporting Standard (IFRS) in combination with GRI, , the TCFD recommendations, or the SDGs. On top of all this flexibility, a digital reporting format is highly interactive and customizable, allowing the reader to create charts or compile selected content into personal PDF or printed reports.Turning reporting into a powerful communications tool In view of growing demand for ESG disclosure, the related surge in sustainability reporting, and a complex reporting landscape companies are challenged to find a disclosure format for both financial and extra-financial information that has a measurable value for their key stakeholders."},{"code":null,"e":6415,"s":6162,"text":"Text summarization can be a complex and involved process of pre-processing, summarization and post-processing and a real-world application that could summarize complex reports without losing the meaning of the original text would have commercial value."},{"code":null,"e":6667,"s":6415,"text":"However, in this article we have explored the basic concepts and quickly built a simple text summarization tool that can be used to open .txt or .docx files and then summarise the contents into 300 words based on evaluating the most popular sentences."},{"code":null,"e":6822,"s":6667,"text":"The test on two public reports proved that the basic text summarization process works and provided an example of what the summarization output looks like."},{"code":null,"e":6863,"s":6822,"text":"The full source code can be found here -"},{"code":null,"e":6874,"s":6863,"text":"github.com"},{"code":null,"e":6992,"s":6874,"text":"If you enjoyed reading this article, why not check out my other articles at https://grahamharrison-86487.medium.com/?"},{"code":null,"e":7150,"s":6992,"text":"Also, I would love to hear from you to get your thoughts on this piece, any of my other articles or anything else related to data science and data analytics."}],"string":"[\n {\n \"code\": null,\n \"e\": 423,\n \"s\": 172,\n \"text\": \"Text summarization is a sub-set of text mining and natural language processing that aims to take long corpus of text and transform them into a summary that can be easily and quickly read and understood without losing the meaning of the original text.\"\n },\n {\n \"code\": null,\n \"e\": 752,\n \"s\": 423,\n \"text\": \"In particular text summarisation “tokenizes” words (i.e. converts them into data) and then assesses the importance of each by looking at relative frequency and other factors. The word importance scores can then be aggregated back into values for sentences with the most important sentences bubbling up to the top of the summary.\"\n },\n {\n \"code\": null,\n \"e\": 965,\n \"s\": 752,\n \"text\": \"If you would like a more in-depth exploration of the principles, this article is a great place to start — https://towardsdatascience.com/a-quick-introduction-to-text-summarization-in-machine-learning-3d27ccf18a9f\"\n },\n {\n \"code\": null,\n \"e\": 1158,\n \"s\": 965,\n \"text\": \"The objective of this article is to produce a basic interactive text summarization utility to demonstrate the principles and to provide a way of generating basic summaries for complex reports.\"\n },\n {\n \"code\": null,\n \"e\": 1333,\n \"s\": 1158,\n \"text\": \"The summarization will have been successful if the summaries impart the majority of the meaning of the source report and can be read and understood in a fraction of the time.\"\n },\n {\n \"code\": null,\n \"e\": 1406,\n \"s\": 1333,\n \"text\": \"To start with we will need to import the libraries that will be used ...\"\n },\n {\n \"code\": null,\n \"e\": 1565,\n \"s\": 1406,\n \"text\": \"The building blocks for our text summarization utility handle the leg-work of allowing the user to browse the local file system to select a file to summarize.\"\n },\n {\n \"code\": null,\n \"e\": 1688,\n \"s\": 1565,\n \"text\": \"openfile() handles showing the File | Open dialog box, selecting a file, and returning the full path of the selected file.\"\n },\n {\n \"code\": null,\n \"e\": 1838,\n \"s\": 1688,\n \"text\": \"Next getText takes the path, opens the file and reads the text contained in the file into a str. The code provided can read from .txt or .docx files.\"\n },\n {\n \"code\": null,\n \"e\": 2094,\n \"s\": 1838,\n \"text\": \"The main work is done in a single line of code by calling the gensim.summarization.summarize function. The same effect can be achieved by using the nltk natural language toolkit but it would be more involved and it would require a bit more low level work.\"\n },\n {\n \"code\": null,\n \"e\": 2207,\n \"s\": 2094,\n \"text\": \"The summarise function provides the implementation and it follows 3 basic steps involved in text summarization -\"\n },\n {\n \"code\": null,\n \"e\": 2313,\n \"s\": 2207,\n \"text\": \"Pre-process and prepare the text.Perform the text summarization process.Post-process and tidy the result.\"\n },\n {\n \"code\": null,\n \"e\": 2347,\n \"s\": 2313,\n \"text\": \"Pre-process and prepare the text.\"\n },\n {\n \"code\": null,\n \"e\": 2387,\n \"s\": 2347,\n \"text\": \"Perform the text summarization process.\"\n },\n {\n \"code\": null,\n \"e\": 2421,\n \"s\": 2387,\n \"text\": \"Post-process and tidy the result.\"\n },\n {\n \"code\": null,\n \"e\": 2673,\n \"s\": 2421,\n \"text\": \"There will be many serious, industry-strength text processing engines that involve complex and comprehensive implementations of these 3 steps but this serves as a good example and it does provide summarization which can be quite useful as we will see.\"\n },\n {\n \"code\": null,\n \"e\": 2709,\n \"s\": 2673,\n \"text\": \"The last few helper functions are -\"\n },\n {\n \"code\": null,\n \"e\": 2807,\n \"s\": 2709,\n \"text\": \"printmd which formats and prints text that includes markup to give us a nicely formatted heading.\"\n },\n {\n \"code\": null,\n \"e\": 2926,\n \"s\": 2807,\n \"text\": \"openLocalFileAndSummarize which calls the functions we have defined above to select a file and summarize the contents.\"\n },\n {\n \"code\": null,\n \"e\": 3090,\n \"s\": 2926,\n \"text\": \"on_button_clicked which handles the button click event to add interactivity to the Notebook and to enable several files to be selected and summarised sequentially.\"\n },\n {\n \"code\": null,\n \"e\": 3272,\n \"s\": 3090,\n \"text\": \"In order to test the text summarization I collected the text from two public web sites which have published freely available reports on the topics of online reporting and marketing.\"\n },\n {\n \"code\": null,\n \"e\": 3326,\n \"s\": 3272,\n \"text\": \"The two web sites used to provide the test data are -\"\n },\n {\n \"code\": null,\n \"e\": 3407,\n \"s\": 3326,\n \"text\": \"https://www.sustainability-reports.com/unleashing-the-power-of-online-reporting/\"\n },\n {\n \"code\": null,\n \"e\": 3507,\n \"s\": 3407,\n \"text\": \"https://www.mckinsey.com/business-functions/marketing-and-sales/our-insights/were-all-marketers-now\"\n },\n {\n \"code\": null,\n \"e\": 3715,\n \"s\": 3507,\n \"text\": \"Lastly a single line of code creates a button that can be clicked repeatedly to select a .txt or a .docx from the local disk which will then be transformed into a 300 word summary which is printed out below.\"\n },\n {\n \"code\": null,\n \"e\": 3798,\n \"s\": 3715,\n \"text\": \"When the button is clicked a File | Open dialog box is displayed to select a file-\"\n },\n {\n \"code\": null,\n \"e\": 3924,\n \"s\": 3798,\n \"text\": \"Once the file has been selected gensim.summarization.summarize does the work and the output is formatted in the cell output -\"\n },\n {\n \"code\": null,\n \"e\": 3991,\n \"s\": 3924,\n \"text\": \"Executive Summary for Unleashing the Power of Online Reporting.txt\"\n },\n {\n \"code\": null,\n \"e\": 6162,\n \"s\": 3991,\n \"text\": \"Unleashing the Power of Online Reporting Source: Sustainable Brands, 15 February 2018 Confronted with an ever-growing demand for transparency and materiality, companies need to find an adequate format to publish both financial and pre-financial information to their stakeholders in an effective way.In the real world, they are confronted with a multitude of information sources different in name, type and content, like Annual Report, CSR Report, Financial Statement, Sustainability Report, Annual Review, Corporate Citizenship Report, or Integrated Report.Online integrated reporting to the rescue Research from Message Group among Europe’s 800 largest companies shows that between 2015 and 2017 the number of businesses publishing financial and extra-financial information in one single integrated report increased by 34 percent, while the number of companies publishing separate sustainability and annual reports decreased by 30 percent.Unlike stand-alone annual or sustainability reports, online integrated reporting formats put an organization’s financial performance, business strategy and governance into the social, environmental and economic context within which it operates.Instead of directing readers from a webpage to separate PDF reports and resources located in different online places, Core & More provides all the relevant information on a single multi-layered website.Moreover, it is flexible enough to integrate multiple reporting frameworks, accounting standards and concepts, such as the International Financial Reporting Standard (IFRS) in combination with GRI, , the TCFD recommendations, or the SDGs. On top of all this flexibility, a digital reporting format is highly interactive and customizable, allowing the reader to create charts or compile selected content into personal PDF or printed reports.Turning reporting into a powerful communications tool In view of growing demand for ESG disclosure, the related surge in sustainability reporting, and a complex reporting landscape companies are challenged to find a disclosure format for both financial and extra-financial information that has a measurable value for their key stakeholders.\"\n },\n {\n \"code\": null,\n \"e\": 6415,\n \"s\": 6162,\n \"text\": \"Text summarization can be a complex and involved process of pre-processing, summarization and post-processing and a real-world application that could summarize complex reports without losing the meaning of the original text would have commercial value.\"\n },\n {\n \"code\": null,\n \"e\": 6667,\n \"s\": 6415,\n \"text\": \"However, in this article we have explored the basic concepts and quickly built a simple text summarization tool that can be used to open .txt or .docx files and then summarise the contents into 300 words based on evaluating the most popular sentences.\"\n },\n {\n \"code\": null,\n \"e\": 6822,\n \"s\": 6667,\n \"text\": \"The test on two public reports proved that the basic text summarization process works and provided an example of what the summarization output looks like.\"\n },\n {\n \"code\": null,\n \"e\": 6863,\n \"s\": 6822,\n \"text\": \"The full source code can be found here -\"\n },\n {\n \"code\": null,\n \"e\": 6874,\n \"s\": 6863,\n \"text\": \"github.com\"\n },\n {\n \"code\": null,\n \"e\": 6992,\n \"s\": 6874,\n \"text\": \"If you enjoyed reading this article, why not check out my other articles at https://grahamharrison-86487.medium.com/?\"\n },\n {\n \"code\": null,\n \"e\": 7150,\n \"s\": 6992,\n \"text\": \"Also, I would love to hear from you to get your thoughts on this piece, any of my other articles or anything else related to data science and data analytics.\"\n }\n]"}}},{"rowIdx":448,"cells":{"title":{"kind":"string","value":"Java SAX Parser - Modify XML Document"},"text":{"kind":"string","value":"Here is the input XML file that we need to modify by appending Pass at the end of tag.\n\n\n \n dinkar\n kad\n dinkar\n 85\n \n \n \n Vaneet\n Gupta\n vinni\n 95\n \n \n \n jasvir\n singn\n jazz\n 90\n \n\npackage com.tutorialspoint.xml;\n\nimport java.io.*;\nimport org.xml.sax.*;\nimport javax.xml.parsers.*;\nimport org.xml.sax.helpers.DefaultHandler;\n\npublic class SAXModifyDemo extends DefaultHandler {\n static String displayText[] = new String[1000];\n static int numberLines = 0;\n static String indentation = \"\";\n\n public static void main(String args[]) {\n\n try {\n File inputFile = new File(\"input.txt\");\n SAXParserFactory factory = \n SAXParserFactory.newInstance();\n SAXModifyDemo obj = new SAXModifyDemo();\n obj.childLoop(inputFile);\n FileWriter filewriter = new FileWriter(\"newfile.xml\");\n \n for(int loopIndex = 0; loopIndex < numberLines; loopIndex++) {\n filewriter.write(displayText[loopIndex].toCharArray());\n filewriter.write('\\n');\n System.out.println(displayText[loopIndex].toString());\n }\n filewriter.close();\n }\n catch (Exception e) {\n e.printStackTrace(System.err);\n }\n }\n\n public void childLoop(File input) {\n DefaultHandler handler = this;\n SAXParserFactory factory = SAXParserFactory.newInstance();\n \n try {\n SAXParser saxParser = factory.newSAXParser();\n saxParser.parse(input, handler);\n } catch (Throwable t) {}\n }\n\n public void startDocument() {\n displayText[numberLines] = indentation;\n displayText[numberLines] += \"\";\n numberLines++;\n }\n\n public void processingInstruction(String target, String data) {\n displayText[numberLines] = indentation;\n displayText[numberLines] += \" 0) {\n displayText[numberLines] += ' ';\n displayText[numberLines] += data;\n }\n displayText[numberLines] += \"?>\";\n numberLines++;\n }\n\n public void startElement(String uri, String localName, String qualifiedName,\n Attributes attributes) {\n\n displayText[numberLines] = indentation;\n\n indentation += \" \";\n\n displayText[numberLines] += '<';\n displayText[numberLines] += qualifiedName;\n \n if (attributes != null) {\n int numberAttributes = attributes.getLength();\n\n for (int loopIndex = 0; loopIndex < numberAttributes; loopIndex++) {\n displayText[numberLines] += ' ';\n displayText[numberLines] += attributes.getQName(loopIndex);\n displayText[numberLines] += \"=\\\"\";\n displayText[numberLines] += attributes.getValue(loopIndex);\n displayText[numberLines] += '\"';\n }\n }\n displayText[numberLines] += '>';\n numberLines++;\n }\n\n public void characters(char characters[], int start, int length) {\n String characterData = (new String(characters, start, length)).trim();\n \n if(characterData.indexOf(\"\\n\") < 0 && characterData.length() > 0) {\n displayText[numberLines] = indentation;\n displayText[numberLines] += characterData;\n numberLines++;\n }\n }\n\n public void endElement(String uri, String localName, String qualifiedName) {\n indentation = indentation.substring(0, indentation.length() - 4) ;\n displayText[numberLines] = indentation;\n displayText[numberLines] += \"';\n numberLines++;\n\n if (qualifiedName.equals(\"marks\")) {\n startElement(\"\", \"Result\", \"Result\", null);\n characters(\"Pass\".toCharArray(), 0, \"Pass\".length());\n endElement(\"\", \"Result\", \"Result\");\n }\n }\n}\nThis would produce the following result −\n\n\n \n \n dinkar\n \n \n kad\n \n \n dinkar\n \n \n 85\n \n \n Pass\n \n \n \n \n Vaneet\n \n \n Gupta\n \n \n vinni\n \n \n 95\n \n \n Pass\n \n \n \n \n jasvir\n \n \n singn\n \n \n jazz\n \n \n 90\n \n \n Pass\n \n \n\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":2436,"s":2323,"text":"Here is the input XML file that we need to modify by appending Pass at the end of tag."},{"code":null,"e":2987,"s":2436,"text":"\n\n \n dinkar\n kad\n dinkar\n 85\n \n \n \n Vaneet\n Gupta\n vinni\n 95\n \n \n \n jasvir\n singn\n jazz\n 90\n \n"},{"code":null,"e":6681,"s":2987,"text":"package com.tutorialspoint.xml;\n\nimport java.io.*;\nimport org.xml.sax.*;\nimport javax.xml.parsers.*;\nimport org.xml.sax.helpers.DefaultHandler;\n\npublic class SAXModifyDemo extends DefaultHandler {\n static String displayText[] = new String[1000];\n static int numberLines = 0;\n static String indentation = \"\";\n\n public static void main(String args[]) {\n\n try {\n File inputFile = new File(\"input.txt\");\n SAXParserFactory factory = \n SAXParserFactory.newInstance();\n SAXModifyDemo obj = new SAXModifyDemo();\n obj.childLoop(inputFile);\n FileWriter filewriter = new FileWriter(\"newfile.xml\");\n \n for(int loopIndex = 0; loopIndex < numberLines; loopIndex++) {\n filewriter.write(displayText[loopIndex].toCharArray());\n filewriter.write('\\n');\n System.out.println(displayText[loopIndex].toString());\n }\n filewriter.close();\n }\n catch (Exception e) {\n e.printStackTrace(System.err);\n }\n }\n\n public void childLoop(File input) {\n DefaultHandler handler = this;\n SAXParserFactory factory = SAXParserFactory.newInstance();\n \n try {\n SAXParser saxParser = factory.newSAXParser();\n saxParser.parse(input, handler);\n } catch (Throwable t) {}\n }\n\n public void startDocument() {\n displayText[numberLines] = indentation;\n displayText[numberLines] += \"\";\n numberLines++;\n }\n\n public void processingInstruction(String target, String data) {\n displayText[numberLines] = indentation;\n displayText[numberLines] += \" 0) {\n displayText[numberLines] += ' ';\n displayText[numberLines] += data;\n }\n displayText[numberLines] += \"?>\";\n numberLines++;\n }\n\n public void startElement(String uri, String localName, String qualifiedName,\n Attributes attributes) {\n\n displayText[numberLines] = indentation;\n\n indentation += \" \";\n\n displayText[numberLines] += '<';\n displayText[numberLines] += qualifiedName;\n \n if (attributes != null) {\n int numberAttributes = attributes.getLength();\n\n for (int loopIndex = 0; loopIndex < numberAttributes; loopIndex++) {\n displayText[numberLines] += ' ';\n displayText[numberLines] += attributes.getQName(loopIndex);\n displayText[numberLines] += \"=\\\"\";\n displayText[numberLines] += attributes.getValue(loopIndex);\n displayText[numberLines] += '\"';\n }\n }\n displayText[numberLines] += '>';\n numberLines++;\n }\n\n public void characters(char characters[], int start, int length) {\n String characterData = (new String(characters, start, length)).trim();\n \n if(characterData.indexOf(\"\\n\") < 0 && characterData.length() > 0) {\n displayText[numberLines] = indentation;\n displayText[numberLines] += characterData;\n numberLines++;\n }\n }\n\n public void endElement(String uri, String localName, String qualifiedName) {\n indentation = indentation.substring(0, indentation.length() - 4) ;\n displayText[numberLines] = indentation;\n displayText[numberLines] += \"';\n numberLines++;\n\n if (qualifiedName.equals(\"marks\")) {\n startElement(\"\", \"Result\", \"Result\", null);\n characters(\"Pass\".toCharArray(), 0, \"Pass\".length());\n endElement(\"\", \"Result\", \"Result\");\n }\n }\n}"},{"code":null,"e":6723,"s":6681,"text":"This would produce the following result −"},{"code":null,"e":7625,"s":6723,"text":"\n\n \n \n dinkar\n \n \n kad\n \n \n dinkar\n \n \n 85\n \n \n Pass\n \n \n \n \n Vaneet\n \n \n Gupta\n \n \n vinni\n \n \n 95\n \n \n Pass\n \n \n \n \n jasvir\n \n \n singn\n \n \n jazz\n \n \n 90\n \n \n Pass\n \n \n\n"},{"code":null,"e":7658,"s":7625,"text":"\n 16 Lectures \n 2 hours \n"},{"code":null,"e":7674,"s":7658,"text":" Malhar Lathkar"},{"code":null,"e":7707,"s":7674,"text":"\n 19 Lectures \n 5 hours \n"},{"code":null,"e":7723,"s":7707,"text":" Malhar Lathkar"},{"code":null,"e":7758,"s":7723,"text":"\n 25 Lectures \n 2.5 hours \n"},{"code":null,"e":7772,"s":7758,"text":" Anadi Sharma"},{"code":null,"e":7806,"s":7772,"text":"\n 126 Lectures \n 7 hours \n"},{"code":null,"e":7820,"s":7806,"text":" Tushar Kale"},{"code":null,"e":7857,"s":7820,"text":"\n 119 Lectures \n 17.5 hours \n"},{"code":null,"e":7872,"s":7857,"text":" Monica Mittal"},{"code":null,"e":7905,"s":7872,"text":"\n 76 Lectures \n 7 hours \n"},{"code":null,"e":7924,"s":7905,"text":" Arnab Chakraborty"},{"code":null,"e":7931,"s":7924,"text":" Print"},{"code":null,"e":7942,"s":7931,"text":" Add Notes"}],"string":"[\n {\n \"code\": null,\n \"e\": 2436,\n \"s\": 2323,\n \"text\": \"Here is the input XML file that we need to modify by appending Pass at the end of tag.\"\n },\n {\n \"code\": null,\n \"e\": 2987,\n \"s\": 2436,\n \"text\": \"\\n\\n \\n dinkar\\n kad\\n dinkar\\n 85\\n \\n \\n \\n Vaneet\\n Gupta\\n vinni\\n 95\\n \\n \\n \\n jasvir\\n singn\\n jazz\\n 90\\n \\n\"\n },\n {\n \"code\": null,\n \"e\": 6681,\n \"s\": 2987,\n \"text\": \"package com.tutorialspoint.xml;\\n\\nimport java.io.*;\\nimport org.xml.sax.*;\\nimport javax.xml.parsers.*;\\nimport org.xml.sax.helpers.DefaultHandler;\\n\\npublic class SAXModifyDemo extends DefaultHandler {\\n static String displayText[] = new String[1000];\\n static int numberLines = 0;\\n static String indentation = \\\"\\\";\\n\\n public static void main(String args[]) {\\n\\n try {\\n File inputFile = new File(\\\"input.txt\\\");\\n SAXParserFactory factory = \\n SAXParserFactory.newInstance();\\n SAXModifyDemo obj = new SAXModifyDemo();\\n obj.childLoop(inputFile);\\n FileWriter filewriter = new FileWriter(\\\"newfile.xml\\\");\\n \\n for(int loopIndex = 0; loopIndex < numberLines; loopIndex++) {\\n filewriter.write(displayText[loopIndex].toCharArray());\\n filewriter.write('\\\\n');\\n System.out.println(displayText[loopIndex].toString());\\n }\\n filewriter.close();\\n }\\n catch (Exception e) {\\n e.printStackTrace(System.err);\\n }\\n }\\n\\n public void childLoop(File input) {\\n DefaultHandler handler = this;\\n SAXParserFactory factory = SAXParserFactory.newInstance();\\n \\n try {\\n SAXParser saxParser = factory.newSAXParser();\\n saxParser.parse(input, handler);\\n } catch (Throwable t) {}\\n }\\n\\n public void startDocument() {\\n displayText[numberLines] = indentation;\\n displayText[numberLines] += \\\"\\\";\\n numberLines++;\\n }\\n\\n public void processingInstruction(String target, String data) {\\n displayText[numberLines] = indentation;\\n displayText[numberLines] += \\\" 0) {\\n displayText[numberLines] += ' ';\\n displayText[numberLines] += data;\\n }\\n displayText[numberLines] += \\\"?>\\\";\\n numberLines++;\\n }\\n\\n public void startElement(String uri, String localName, String qualifiedName,\\n Attributes attributes) {\\n\\n displayText[numberLines] = indentation;\\n\\n indentation += \\\" \\\";\\n\\n displayText[numberLines] += '<';\\n displayText[numberLines] += qualifiedName;\\n \\n if (attributes != null) {\\n int numberAttributes = attributes.getLength();\\n\\n for (int loopIndex = 0; loopIndex < numberAttributes; loopIndex++) {\\n displayText[numberLines] += ' ';\\n displayText[numberLines] += attributes.getQName(loopIndex);\\n displayText[numberLines] += \\\"=\\\\\\\"\\\";\\n displayText[numberLines] += attributes.getValue(loopIndex);\\n displayText[numberLines] += '\\\"';\\n }\\n }\\n displayText[numberLines] += '>';\\n numberLines++;\\n }\\n\\n public void characters(char characters[], int start, int length) {\\n String characterData = (new String(characters, start, length)).trim();\\n \\n if(characterData.indexOf(\\\"\\\\n\\\") < 0 && characterData.length() > 0) {\\n displayText[numberLines] = indentation;\\n displayText[numberLines] += characterData;\\n numberLines++;\\n }\\n }\\n\\n public void endElement(String uri, String localName, String qualifiedName) {\\n indentation = indentation.substring(0, indentation.length() - 4) ;\\n displayText[numberLines] = indentation;\\n displayText[numberLines] += \\\"';\\n numberLines++;\\n\\n if (qualifiedName.equals(\\\"marks\\\")) {\\n startElement(\\\"\\\", \\\"Result\\\", \\\"Result\\\", null);\\n characters(\\\"Pass\\\".toCharArray(), 0, \\\"Pass\\\".length());\\n endElement(\\\"\\\", \\\"Result\\\", \\\"Result\\\");\\n }\\n }\\n}\"\n },\n {\n \"code\": null,\n \"e\": 6723,\n \"s\": 6681,\n \"text\": \"This would produce the following result −\"\n },\n {\n \"code\": null,\n \"e\": 7625,\n \"s\": 6723,\n \"text\": \"\\n\\n \\n \\n dinkar\\n \\n \\n kad\\n \\n \\n dinkar\\n \\n \\n 85\\n \\n \\n Pass\\n \\n \\n \\n \\n Vaneet\\n \\n \\n Gupta\\n \\n \\n vinni\\n \\n \\n 95\\n \\n \\n Pass\\n \\n \\n \\n \\n jasvir\\n \\n \\n singn\\n \\n \\n jazz\\n \\n \\n 90\\n \\n \\n Pass\\n \\n \\n\\n\"\n },\n {\n \"code\": null,\n \"e\": 7658,\n \"s\": 7625,\n \"text\": \"\\n 16 Lectures \\n 2 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 7674,\n \"s\": 7658,\n \"text\": \" Malhar Lathkar\"\n },\n {\n \"code\": null,\n \"e\": 7707,\n \"s\": 7674,\n \"text\": \"\\n 19 Lectures \\n 5 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 7723,\n \"s\": 7707,\n \"text\": \" Malhar Lathkar\"\n },\n {\n \"code\": null,\n \"e\": 7758,\n \"s\": 7723,\n \"text\": \"\\n 25 Lectures \\n 2.5 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 7772,\n \"s\": 7758,\n \"text\": \" Anadi Sharma\"\n },\n {\n \"code\": null,\n \"e\": 7806,\n \"s\": 7772,\n \"text\": \"\\n 126 Lectures \\n 7 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 7820,\n \"s\": 7806,\n \"text\": \" Tushar Kale\"\n },\n {\n \"code\": null,\n \"e\": 7857,\n \"s\": 7820,\n \"text\": \"\\n 119 Lectures \\n 17.5 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 7872,\n \"s\": 7857,\n \"text\": \" Monica Mittal\"\n },\n {\n \"code\": null,\n \"e\": 7905,\n \"s\": 7872,\n \"text\": \"\\n 76 Lectures \\n 7 hours \\n\"\n },\n {\n \"code\": null,\n \"e\": 7924,\n \"s\": 7905,\n \"text\": \" Arnab Chakraborty\"\n },\n {\n \"code\": null,\n \"e\": 7931,\n \"s\": 7924,\n \"text\": \" Print\"\n },\n {\n \"code\": null,\n \"e\": 7942,\n \"s\": 7931,\n \"text\": \" Add Notes\"\n }\n]"}}},{"rowIdx":449,"cells":{"title":{"kind":"string","value":"BufferedReader mark() method in Java with Examples - GeeksforGeeks"},"text":{"kind":"string","value":"05 Jun, 2020\nThe mark() method of BufferedReader class in Java is used to mark the current position in the buffer reader stream. The reset() method of the same BufferedReader class is also called subsequently, after the mark() method is called. The reset() method fixes the position at the last marked position so that same byte can be read again.\nSyntax:\npublic void mark(int readAheadLimit) \n throws IOException\n\nOverrides: It overrides the mark() method of Reader class.\nParameters: This method accepts readAheadLimit of Integer type which represents the maximum limit of bytes that can be read before the mark position becomes invalid.\nReturn value: This method does not return any value.\nExceptions: This method can throw two types of exceptions.\nIllegalArgumentException – This exception is thrown if the passed parameter readAheadLimit is less than zero.\nIOException – This exception is thrown if an I/O error occurs.\nBelow programs illustrate mark() method in BufferedReader class in IO package.Program 1: Assume the existence of the file “c:/demo.txt”.\n// Java program to illustrate// BufferedReader mark() method import java.io.*; public class GFG { public static void main(String[] args) { // Read the stream 'demo.txt' // for containing text \"GEEKS\" FileReader fileReader = new FileReader( \"c:/demo.txt\"); // Convert fileReader to // bufferedReader BufferedReader buffReader = new BufferedReader( fileReader); // Read and print characters // one by one System.out.println( \"Char : \" + (char)buffReader.read()); System.out.println( \"Char : \" + (char)buffReader.read()); System.out.println( \"Char : \" + (char)buffReader.read()); // Mark is set on the stream buffReader.mark(0); System.out.println( \"Char : \" + (char)buffReader.read()); // Reset() is invoked buffReader.reset(); // Read and print characters System.out.println( \"Char : \" + (char)buffReader.read()); System.out.println( \"Char : \" + (char)buffReader.read()); }}\nChar : G\nChar : E\nChar : E\nChar : K\nChar : K\nChar : S\n\nProgram 2: Assume the existence of the file “c:/demo.txt”.\n// Java program to illustrate// BufferedReader mark() method import java.io.*;public class GFG { public static void main(String[] args) { // Read the stream 'demo.txt' // containing text \"GEEKSFORGEEKS\" FileReader fileReader = new FileReader( \"c:/demo.txt\"); // Convert fileReader to // bufferedReader BufferedReader buffReader = new BufferedReader( fileReader); // Read and print characters // one by one System.out.println( \"Char : \" + (char)buffReader.read()); System.out.println( \"Char : \" + (char)buffReader.read()); System.out.println( \"Char : \" + (char)buffReader.read()); System.out.println( \"Char : \" + (char)buffReader.read()); // Mark is set on the stream buffReader.mark(0); System.out.println( \"Char : \" + (char)buffReader.read()); // Reset() is invoked buffReader.reset(); // read and print characters System.out.println( \"Char : \" + (char)buffReader.read()); System.out.println( \"Char : \" + (char)buffReader.read()); System.out.println( \"Char : \" + (char)buffReader.read()); System.out.println( \"Char : \" + (char)buffReader.read()); }}\nChar : G\nChar : E\nChar : E\nChar : K\nChar : S\nChar : S\nChar : F\nChar : O\nChar : R\n\nReferences:https://docs.oracle.com/javase/10/docs/api/java/io/BufferedReader.html#mark(int)\nJava-Functions\nJava-IO package\nJava\nJava\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nInitialize an ArrayList in Java\nObject Oriented Programming (OOPs) Concept in Java\nHashMap in Java with Examples\nInterfaces in Java\nArrayList in Java\nHow to iterate any Map in Java\nMultidimensional Arrays in Java\nStack Class in Java\nSingleton Class in Java\nSet in Java"},"parsed":{"kind":"list like","value":[{"code":null,"e":24480,"s":24452,"text":"\n05 Jun, 2020"},{"code":null,"e":24815,"s":24480,"text":"The mark() method of BufferedReader class in Java is used to mark the current position in the buffer reader stream. The reset() method of the same BufferedReader class is also called subsequently, after the mark() method is called. The reset() method fixes the position at the last marked position so that same byte can be read again."},{"code":null,"e":24823,"s":24815,"text":"Syntax:"},{"code":null,"e":24900,"s":24823,"text":"public void mark(int readAheadLimit) \n throws IOException\n"},{"code":null,"e":24959,"s":24900,"text":"Overrides: It overrides the mark() method of Reader class."},{"code":null,"e":25125,"s":24959,"text":"Parameters: This method accepts readAheadLimit of Integer type which represents the maximum limit of bytes that can be read before the mark position becomes invalid."},{"code":null,"e":25178,"s":25125,"text":"Return value: This method does not return any value."},{"code":null,"e":25237,"s":25178,"text":"Exceptions: This method can throw two types of exceptions."},{"code":null,"e":25347,"s":25237,"text":"IllegalArgumentException – This exception is thrown if the passed parameter readAheadLimit is less than zero."},{"code":null,"e":25410,"s":25347,"text":"IOException – This exception is thrown if an I/O error occurs."},{"code":null,"e":25547,"s":25410,"text":"Below programs illustrate mark() method in BufferedReader class in IO package.Program 1: Assume the existence of the file “c:/demo.txt”."},{"code":"// Java program to illustrate// BufferedReader mark() method import java.io.*; public class GFG { public static void main(String[] args) { // Read the stream 'demo.txt' // for containing text \"GEEKS\" FileReader fileReader = new FileReader( \"c:/demo.txt\"); // Convert fileReader to // bufferedReader BufferedReader buffReader = new BufferedReader( fileReader); // Read and print characters // one by one System.out.println( \"Char : \" + (char)buffReader.read()); System.out.println( \"Char : \" + (char)buffReader.read()); System.out.println( \"Char : \" + (char)buffReader.read()); // Mark is set on the stream buffReader.mark(0); System.out.println( \"Char : \" + (char)buffReader.read()); // Reset() is invoked buffReader.reset(); // Read and print characters System.out.println( \"Char : \" + (char)buffReader.read()); System.out.println( \"Char : \" + (char)buffReader.read()); }}","e":26763,"s":25547,"text":null},{"code":null,"e":26818,"s":26763,"text":"Char : G\nChar : E\nChar : E\nChar : K\nChar : K\nChar : S\n"},{"code":null,"e":26877,"s":26818,"text":"Program 2: Assume the existence of the file “c:/demo.txt”."},{"code":"// Java program to illustrate// BufferedReader mark() method import java.io.*;public class GFG { public static void main(String[] args) { // Read the stream 'demo.txt' // containing text \"GEEKSFORGEEKS\" FileReader fileReader = new FileReader( \"c:/demo.txt\"); // Convert fileReader to // bufferedReader BufferedReader buffReader = new BufferedReader( fileReader); // Read and print characters // one by one System.out.println( \"Char : \" + (char)buffReader.read()); System.out.println( \"Char : \" + (char)buffReader.read()); System.out.println( \"Char : \" + (char)buffReader.read()); System.out.println( \"Char : \" + (char)buffReader.read()); // Mark is set on the stream buffReader.mark(0); System.out.println( \"Char : \" + (char)buffReader.read()); // Reset() is invoked buffReader.reset(); // read and print characters System.out.println( \"Char : \" + (char)buffReader.read()); System.out.println( \"Char : \" + (char)buffReader.read()); System.out.println( \"Char : \" + (char)buffReader.read()); System.out.println( \"Char : \" + (char)buffReader.read()); }}","e":28356,"s":26877,"text":null},{"code":null,"e":28438,"s":28356,"text":"Char : G\nChar : E\nChar : E\nChar : K\nChar : S\nChar : S\nChar : F\nChar : O\nChar : R\n"},{"code":null,"e":28530,"s":28438,"text":"References:https://docs.oracle.com/javase/10/docs/api/java/io/BufferedReader.html#mark(int)"},{"code":null,"e":28545,"s":28530,"text":"Java-Functions"},{"code":null,"e":28561,"s":28545,"text":"Java-IO package"},{"code":null,"e":28566,"s":28561,"text":"Java"},{"code":null,"e":28571,"s":28566,"text":"Java"},{"code":null,"e":28669,"s":28571,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":28701,"s":28669,"text":"Initialize an ArrayList in Java"},{"code":null,"e":28752,"s":28701,"text":"Object Oriented Programming (OOPs) Concept in Java"},{"code":null,"e":28782,"s":28752,"text":"HashMap in Java with Examples"},{"code":null,"e":28801,"s":28782,"text":"Interfaces in Java"},{"code":null,"e":28819,"s":28801,"text":"ArrayList in Java"},{"code":null,"e":28850,"s":28819,"text":"How to iterate any Map in Java"},{"code":null,"e":28882,"s":28850,"text":"Multidimensional Arrays in Java"},{"code":null,"e":28902,"s":28882,"text":"Stack Class in Java"},{"code":null,"e":28926,"s":28902,"text":"Singleton Class in Java"}],"string":"[\n {\n \"code\": null,\n \"e\": 24480,\n \"s\": 24452,\n \"text\": \"\\n05 Jun, 2020\"\n },\n {\n \"code\": null,\n \"e\": 24815,\n \"s\": 24480,\n \"text\": \"The mark() method of BufferedReader class in Java is used to mark the current position in the buffer reader stream. The reset() method of the same BufferedReader class is also called subsequently, after the mark() method is called. The reset() method fixes the position at the last marked position so that same byte can be read again.\"\n },\n {\n \"code\": null,\n \"e\": 24823,\n \"s\": 24815,\n \"text\": \"Syntax:\"\n },\n {\n \"code\": null,\n \"e\": 24900,\n \"s\": 24823,\n \"text\": \"public void mark(int readAheadLimit) \\n throws IOException\\n\"\n },\n {\n \"code\": null,\n \"e\": 24959,\n \"s\": 24900,\n \"text\": \"Overrides: It overrides the mark() method of Reader class.\"\n },\n {\n \"code\": null,\n \"e\": 25125,\n \"s\": 24959,\n \"text\": \"Parameters: This method accepts readAheadLimit of Integer type which represents the maximum limit of bytes that can be read before the mark position becomes invalid.\"\n },\n {\n \"code\": null,\n \"e\": 25178,\n \"s\": 25125,\n \"text\": \"Return value: This method does not return any value.\"\n },\n {\n \"code\": null,\n \"e\": 25237,\n \"s\": 25178,\n \"text\": \"Exceptions: This method can throw two types of exceptions.\"\n },\n {\n \"code\": null,\n \"e\": 25347,\n \"s\": 25237,\n \"text\": \"IllegalArgumentException – This exception is thrown if the passed parameter readAheadLimit is less than zero.\"\n },\n {\n \"code\": null,\n \"e\": 25410,\n \"s\": 25347,\n \"text\": \"IOException – This exception is thrown if an I/O error occurs.\"\n },\n {\n \"code\": null,\n \"e\": 25547,\n \"s\": 25410,\n \"text\": \"Below programs illustrate mark() method in BufferedReader class in IO package.Program 1: Assume the existence of the file “c:/demo.txt”.\"\n },\n {\n \"code\": \"// Java program to illustrate// BufferedReader mark() method import java.io.*; public class GFG { public static void main(String[] args) { // Read the stream 'demo.txt' // for containing text \\\"GEEKS\\\" FileReader fileReader = new FileReader( \\\"c:/demo.txt\\\"); // Convert fileReader to // bufferedReader BufferedReader buffReader = new BufferedReader( fileReader); // Read and print characters // one by one System.out.println( \\\"Char : \\\" + (char)buffReader.read()); System.out.println( \\\"Char : \\\" + (char)buffReader.read()); System.out.println( \\\"Char : \\\" + (char)buffReader.read()); // Mark is set on the stream buffReader.mark(0); System.out.println( \\\"Char : \\\" + (char)buffReader.read()); // Reset() is invoked buffReader.reset(); // Read and print characters System.out.println( \\\"Char : \\\" + (char)buffReader.read()); System.out.println( \\\"Char : \\\" + (char)buffReader.read()); }}\",\n \"e\": 26763,\n \"s\": 25547,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 26818,\n \"s\": 26763,\n \"text\": \"Char : G\\nChar : E\\nChar : E\\nChar : K\\nChar : K\\nChar : S\\n\"\n },\n {\n \"code\": null,\n \"e\": 26877,\n \"s\": 26818,\n \"text\": \"Program 2: Assume the existence of the file “c:/demo.txt”.\"\n },\n {\n \"code\": \"// Java program to illustrate// BufferedReader mark() method import java.io.*;public class GFG { public static void main(String[] args) { // Read the stream 'demo.txt' // containing text \\\"GEEKSFORGEEKS\\\" FileReader fileReader = new FileReader( \\\"c:/demo.txt\\\"); // Convert fileReader to // bufferedReader BufferedReader buffReader = new BufferedReader( fileReader); // Read and print characters // one by one System.out.println( \\\"Char : \\\" + (char)buffReader.read()); System.out.println( \\\"Char : \\\" + (char)buffReader.read()); System.out.println( \\\"Char : \\\" + (char)buffReader.read()); System.out.println( \\\"Char : \\\" + (char)buffReader.read()); // Mark is set on the stream buffReader.mark(0); System.out.println( \\\"Char : \\\" + (char)buffReader.read()); // Reset() is invoked buffReader.reset(); // read and print characters System.out.println( \\\"Char : \\\" + (char)buffReader.read()); System.out.println( \\\"Char : \\\" + (char)buffReader.read()); System.out.println( \\\"Char : \\\" + (char)buffReader.read()); System.out.println( \\\"Char : \\\" + (char)buffReader.read()); }}\",\n \"e\": 28356,\n \"s\": 26877,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 28438,\n \"s\": 28356,\n \"text\": \"Char : G\\nChar : E\\nChar : E\\nChar : K\\nChar : S\\nChar : S\\nChar : F\\nChar : O\\nChar : R\\n\"\n },\n {\n \"code\": null,\n \"e\": 28530,\n \"s\": 28438,\n \"text\": \"References:https://docs.oracle.com/javase/10/docs/api/java/io/BufferedReader.html#mark(int)\"\n },\n {\n \"code\": null,\n \"e\": 28545,\n \"s\": 28530,\n \"text\": \"Java-Functions\"\n },\n {\n \"code\": null,\n \"e\": 28561,\n \"s\": 28545,\n \"text\": \"Java-IO package\"\n },\n {\n \"code\": null,\n \"e\": 28566,\n \"s\": 28561,\n \"text\": \"Java\"\n },\n {\n \"code\": null,\n \"e\": 28571,\n \"s\": 28566,\n \"text\": \"Java\"\n },\n {\n \"code\": null,\n \"e\": 28669,\n \"s\": 28571,\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\": 28701,\n \"s\": 28669,\n \"text\": \"Initialize an ArrayList in Java\"\n },\n {\n \"code\": null,\n \"e\": 28752,\n \"s\": 28701,\n \"text\": \"Object Oriented Programming (OOPs) Concept in Java\"\n },\n {\n \"code\": null,\n \"e\": 28782,\n \"s\": 28752,\n \"text\": \"HashMap in Java with Examples\"\n },\n {\n \"code\": null,\n \"e\": 28801,\n \"s\": 28782,\n \"text\": \"Interfaces in Java\"\n },\n {\n \"code\": null,\n \"e\": 28819,\n \"s\": 28801,\n \"text\": \"ArrayList in Java\"\n },\n {\n \"code\": null,\n \"e\": 28850,\n \"s\": 28819,\n \"text\": \"How to iterate any Map in Java\"\n },\n {\n \"code\": null,\n \"e\": 28882,\n \"s\": 28850,\n \"text\": \"Multidimensional Arrays in Java\"\n },\n {\n \"code\": null,\n \"e\": 28902,\n \"s\": 28882,\n \"text\": \"Stack Class in Java\"\n },\n {\n \"code\": null,\n \"e\": 28926,\n \"s\": 28902,\n \"text\": \"Singleton Class in Java\"\n }\n]"}}},{"rowIdx":450,"cells":{"title":{"kind":"string","value":"Average of Levels in Binary Tree in C++"},"text":{"kind":"string","value":"Suppose we have a non-empty binary tree; we have to find the average value of the nodes on each level in the return the average values as an array.\nSo, if the input is like\nthen the output will be [3, 14.5, 11].\nTo solve this, we will follow these steps −\nDefine an array result\nDefine an array result\nDefine one queue q\nDefine one queue q\ninsert root into q\ninsert root into q\nwhile (not q is empty), do −n := size of qDefine an array tempwhile n is non-zero, do −t := first element of qinsert value of t into tempdelete element from qif left of t is not null, then −insert left of t into qif right of t is not null, then −insert right of t into q(decrease n by 1)if size of temp is same as 1, then −insert temp[0] at the end of resultotherwise when size of temp > 1, then −sum := 0for initialize i := 0, when i < size of temp, update (increase i by 1), do −sum := sum + temp[i]insert (sum / size of temp) at the end of result\nwhile (not q is empty), do −\nn := size of q\nn := size of q\nDefine an array temp\nDefine an array temp\nwhile n is non-zero, do −t := first element of qinsert value of t into tempdelete element from qif left of t is not null, then −insert left of t into qif right of t is not null, then −insert right of t into q(decrease n by 1)\nwhile n is non-zero, do −\nt := first element of q\nt := first element of q\ninsert value of t into temp\ninsert value of t into temp\ndelete element from q\ndelete element from q\nif left of t is not null, then −insert left of t into q\nif left of t is not null, then −\ninsert left of t into q\ninsert left of t into q\nif right of t is not null, then −insert right of t into q\nif right of t is not null, then −\ninsert right of t into q\ninsert right of t into q\n(decrease n by 1)\n(decrease n by 1)\nif size of temp is same as 1, then −insert temp[0] at the end of result\nif size of temp is same as 1, then −\ninsert temp[0] at the end of result\ninsert temp[0] at the end of result\notherwise when size of temp > 1, then −sum := 0for initialize i := 0, when i < size of temp, update (increase i by 1), do −sum := sum + temp[i]insert (sum / size of temp) at the end of result\notherwise when size of temp > 1, then −\nsum := 0\nsum := 0\nfor initialize i := 0, when i < size of temp, update (increase i by 1), do −sum := sum + temp[i]\nfor initialize i := 0, when i < size of temp, update (increase i by 1), do −\nsum := sum + temp[i]\nsum := sum + temp[i]\ninsert (sum / size of temp) at the end of result\ninsert (sum / size of temp) at the end of result\nreturn result\nreturn result\nLet us see the following implementation to get a better understanding −\n Live Demo\n#include \nusing namespace std;\nvoid print_vector(vector v){\n cout << \"[\";\n for(int i = 0; i q;\n q.push(*root);\n while(q.size()){\n TreeNode *temp = q.front();\n q.pop();\n if(!temp->left){\n if(val != NULL)\n temp->left = new TreeNode(val);\n else\n temp->left = new TreeNode(0);\n return;\n }\n else{\n q.push(temp->left);\n }\n if(!temp->right){\n if(val != NULL)\n temp->right = new TreeNode(val);\n else\n temp->right = new TreeNode(0);\n return;\n }\n else{\n q.push(temp->right);\n }\n }\n}\nTreeNode *make_tree(vector v){\n TreeNode *root = new TreeNode(v[0]);\n for(int i = 1; i averageOfLevels(TreeNode *root){\n vector result;\n queue q;\n q.push(root);\n while (!q.empty()) {\n int n = q.size();\n vector temp;\n while (n) {\n TreeNode* t = q.front();\n temp.push_back(t->val);\n q.pop();\n if (t->left && t->left->val != 0)\n q.push(t->left);\n if (t->right && t->right->val != 0)\n q.push(t->right);\n n--;\n }\n if (temp.size() == 1)\n result.push_back(temp[0]);\n else if (temp.size() > 1) {\n double sum = 0;\n for (int i = 0; i < temp.size(); i++) {\n sum += temp[i];\n }\n result.push_back(sum / temp.size());\n }\n }\n return result;\n }\n};\nmain(){\n Solution ob;\n vector v = {3,9,20,NULL,NULL,15,7};\n TreeNode *root = make_tree(v);\n print_vector(ob.averageOfLevels(root));\n}\n{3,9,20,NULL,NULL,15,7}\n[3, 14.5, 11, ]"},"parsed":{"kind":"list like","value":[{"code":null,"e":1210,"s":1062,"text":"Suppose we have a non-empty binary tree; we have to find the average value of the nodes on each level in the return the average values as an array."},{"code":null,"e":1235,"s":1210,"text":"So, if the input is like"},{"code":null,"e":1274,"s":1235,"text":"then the output will be [3, 14.5, 11]."},{"code":null,"e":1318,"s":1274,"text":"To solve this, we will follow these steps −"},{"code":null,"e":1341,"s":1318,"text":"Define an array result"},{"code":null,"e":1364,"s":1341,"text":"Define an array result"},{"code":null,"e":1383,"s":1364,"text":"Define one queue q"},{"code":null,"e":1402,"s":1383,"text":"Define one queue q"},{"code":null,"e":1421,"s":1402,"text":"insert root into q"},{"code":null,"e":1440,"s":1421,"text":"insert root into q"},{"code":null,"e":1990,"s":1440,"text":"while (not q is empty), do −n := size of qDefine an array tempwhile n is non-zero, do −t := first element of qinsert value of t into tempdelete element from qif left of t is not null, then −insert left of t into qif right of t is not null, then −insert right of t into q(decrease n by 1)if size of temp is same as 1, then −insert temp[0] at the end of resultotherwise when size of temp > 1, then −sum := 0for initialize i := 0, when i < size of temp, update (increase i by 1), do −sum := sum + temp[i]insert (sum / size of temp) at the end of result"},{"code":null,"e":2019,"s":1990,"text":"while (not q is empty), do −"},{"code":null,"e":2034,"s":2019,"text":"n := size of q"},{"code":null,"e":2049,"s":2034,"text":"n := size of q"},{"code":null,"e":2070,"s":2049,"text":"Define an array temp"},{"code":null,"e":2091,"s":2070,"text":"Define an array temp"},{"code":null,"e":2317,"s":2091,"text":"while n is non-zero, do −t := first element of qinsert value of t into tempdelete element from qif left of t is not null, then −insert left of t into qif right of t is not null, then −insert right of t into q(decrease n by 1)"},{"code":null,"e":2343,"s":2317,"text":"while n is non-zero, do −"},{"code":null,"e":2367,"s":2343,"text":"t := first element of q"},{"code":null,"e":2391,"s":2367,"text":"t := first element of q"},{"code":null,"e":2419,"s":2391,"text":"insert value of t into temp"},{"code":null,"e":2447,"s":2419,"text":"insert value of t into temp"},{"code":null,"e":2469,"s":2447,"text":"delete element from q"},{"code":null,"e":2491,"s":2469,"text":"delete element from q"},{"code":null,"e":2547,"s":2491,"text":"if left of t is not null, then −insert left of t into q"},{"code":null,"e":2580,"s":2547,"text":"if left of t is not null, then −"},{"code":null,"e":2604,"s":2580,"text":"insert left of t into q"},{"code":null,"e":2628,"s":2604,"text":"insert left of t into q"},{"code":null,"e":2686,"s":2628,"text":"if right of t is not null, then −insert right of t into q"},{"code":null,"e":2720,"s":2686,"text":"if right of t is not null, then −"},{"code":null,"e":2745,"s":2720,"text":"insert right of t into q"},{"code":null,"e":2770,"s":2745,"text":"insert right of t into q"},{"code":null,"e":2788,"s":2770,"text":"(decrease n by 1)"},{"code":null,"e":2806,"s":2788,"text":"(decrease n by 1)"},{"code":null,"e":2878,"s":2806,"text":"if size of temp is same as 1, then −insert temp[0] at the end of result"},{"code":null,"e":2915,"s":2878,"text":"if size of temp is same as 1, then −"},{"code":null,"e":2951,"s":2915,"text":"insert temp[0] at the end of result"},{"code":null,"e":2987,"s":2951,"text":"insert temp[0] at the end of result"},{"code":null,"e":3179,"s":2987,"text":"otherwise when size of temp > 1, then −sum := 0for initialize i := 0, when i < size of temp, update (increase i by 1), do −sum := sum + temp[i]insert (sum / size of temp) at the end of result"},{"code":null,"e":3219,"s":3179,"text":"otherwise when size of temp > 1, then −"},{"code":null,"e":3228,"s":3219,"text":"sum := 0"},{"code":null,"e":3237,"s":3228,"text":"sum := 0"},{"code":null,"e":3334,"s":3237,"text":"for initialize i := 0, when i < size of temp, update (increase i by 1), do −sum := sum + temp[i]"},{"code":null,"e":3411,"s":3334,"text":"for initialize i := 0, when i < size of temp, update (increase i by 1), do −"},{"code":null,"e":3432,"s":3411,"text":"sum := sum + temp[i]"},{"code":null,"e":3453,"s":3432,"text":"sum := sum + temp[i]"},{"code":null,"e":3502,"s":3453,"text":"insert (sum / size of temp) at the end of result"},{"code":null,"e":3551,"s":3502,"text":"insert (sum / size of temp) at the end of result"},{"code":null,"e":3565,"s":3551,"text":"return result"},{"code":null,"e":3579,"s":3565,"text":"return result"},{"code":null,"e":3651,"s":3579,"text":"Let us see the following implementation to get a better understanding −"},{"code":null,"e":3662,"s":3651,"text":" Live Demo"},{"code":null,"e":5805,"s":3662,"text":"#include \nusing namespace std;\nvoid print_vector(vector v){\n cout << \"[\";\n for(int i = 0; i q;\n q.push(*root);\n while(q.size()){\n TreeNode *temp = q.front();\n q.pop();\n if(!temp->left){\n if(val != NULL)\n temp->left = new TreeNode(val);\n else\n temp->left = new TreeNode(0);\n return;\n }\n else{\n q.push(temp->left);\n }\n if(!temp->right){\n if(val != NULL)\n temp->right = new TreeNode(val);\n else\n temp->right = new TreeNode(0);\n return;\n }\n else{\n q.push(temp->right);\n }\n }\n}\nTreeNode *make_tree(vector v){\n TreeNode *root = new TreeNode(v[0]);\n for(int i = 1; i averageOfLevels(TreeNode *root){\n vector result;\n queue q;\n q.push(root);\n while (!q.empty()) {\n int n = q.size();\n vector temp;\n while (n) {\n TreeNode* t = q.front();\n temp.push_back(t->val);\n q.pop();\n if (t->left && t->left->val != 0)\n q.push(t->left);\n if (t->right && t->right->val != 0)\n q.push(t->right);\n n--;\n }\n if (temp.size() == 1)\n result.push_back(temp[0]);\n else if (temp.size() > 1) {\n double sum = 0;\n for (int i = 0; i < temp.size(); i++) {\n sum += temp[i];\n }\n result.push_back(sum / temp.size());\n }\n }\n return result;\n }\n};\nmain(){\n Solution ob;\n vector v = {3,9,20,NULL,NULL,15,7};\n TreeNode *root = make_tree(v);\n print_vector(ob.averageOfLevels(root));\n}"},{"code":null,"e":5829,"s":5805,"text":"{3,9,20,NULL,NULL,15,7}"},{"code":null,"e":5845,"s":5829,"text":"[3, 14.5, 11, ]"}],"string":"[\n {\n \"code\": null,\n \"e\": 1210,\n \"s\": 1062,\n \"text\": \"Suppose we have a non-empty binary tree; we have to find the average value of the nodes on each level in the return the average values as an array.\"\n },\n {\n \"code\": null,\n \"e\": 1235,\n \"s\": 1210,\n \"text\": \"So, if the input is like\"\n },\n {\n \"code\": null,\n \"e\": 1274,\n \"s\": 1235,\n \"text\": \"then the output will be [3, 14.5, 11].\"\n },\n {\n \"code\": null,\n \"e\": 1318,\n \"s\": 1274,\n \"text\": \"To solve this, we will follow these steps −\"\n },\n {\n \"code\": null,\n \"e\": 1341,\n \"s\": 1318,\n \"text\": \"Define an array result\"\n },\n {\n \"code\": null,\n \"e\": 1364,\n \"s\": 1341,\n \"text\": \"Define an array result\"\n },\n {\n \"code\": null,\n \"e\": 1383,\n \"s\": 1364,\n \"text\": \"Define one queue q\"\n },\n {\n \"code\": null,\n \"e\": 1402,\n \"s\": 1383,\n \"text\": \"Define one queue q\"\n },\n {\n \"code\": null,\n \"e\": 1421,\n \"s\": 1402,\n \"text\": \"insert root into q\"\n },\n {\n \"code\": null,\n \"e\": 1440,\n \"s\": 1421,\n \"text\": \"insert root into q\"\n },\n {\n \"code\": null,\n \"e\": 1990,\n \"s\": 1440,\n \"text\": \"while (not q is empty), do −n := size of qDefine an array tempwhile n is non-zero, do −t := first element of qinsert value of t into tempdelete element from qif left of t is not null, then −insert left of t into qif right of t is not null, then −insert right of t into q(decrease n by 1)if size of temp is same as 1, then −insert temp[0] at the end of resultotherwise when size of temp > 1, then −sum := 0for initialize i := 0, when i < size of temp, update (increase i by 1), do −sum := sum + temp[i]insert (sum / size of temp) at the end of result\"\n },\n {\n \"code\": null,\n \"e\": 2019,\n \"s\": 1990,\n \"text\": \"while (not q is empty), do −\"\n },\n {\n \"code\": null,\n \"e\": 2034,\n \"s\": 2019,\n \"text\": \"n := size of q\"\n },\n {\n \"code\": null,\n \"e\": 2049,\n \"s\": 2034,\n \"text\": \"n := size of q\"\n },\n {\n \"code\": null,\n \"e\": 2070,\n \"s\": 2049,\n \"text\": \"Define an array temp\"\n },\n {\n \"code\": null,\n \"e\": 2091,\n \"s\": 2070,\n \"text\": \"Define an array temp\"\n },\n {\n \"code\": null,\n \"e\": 2317,\n \"s\": 2091,\n \"text\": \"while n is non-zero, do −t := first element of qinsert value of t into tempdelete element from qif left of t is not null, then −insert left of t into qif right of t is not null, then −insert right of t into q(decrease n by 1)\"\n },\n {\n \"code\": null,\n \"e\": 2343,\n \"s\": 2317,\n \"text\": \"while n is non-zero, do −\"\n },\n {\n \"code\": null,\n \"e\": 2367,\n \"s\": 2343,\n \"text\": \"t := first element of q\"\n },\n {\n \"code\": null,\n \"e\": 2391,\n \"s\": 2367,\n \"text\": \"t := first element of q\"\n },\n {\n \"code\": null,\n \"e\": 2419,\n \"s\": 2391,\n \"text\": \"insert value of t into temp\"\n },\n {\n \"code\": null,\n \"e\": 2447,\n \"s\": 2419,\n \"text\": \"insert value of t into temp\"\n },\n {\n \"code\": null,\n \"e\": 2469,\n \"s\": 2447,\n \"text\": \"delete element from q\"\n },\n {\n \"code\": null,\n \"e\": 2491,\n \"s\": 2469,\n \"text\": \"delete element from q\"\n },\n {\n \"code\": null,\n \"e\": 2547,\n \"s\": 2491,\n \"text\": \"if left of t is not null, then −insert left of t into q\"\n },\n {\n \"code\": null,\n \"e\": 2580,\n \"s\": 2547,\n \"text\": \"if left of t is not null, then −\"\n },\n {\n \"code\": null,\n \"e\": 2604,\n \"s\": 2580,\n \"text\": \"insert left of t into q\"\n },\n {\n \"code\": null,\n \"e\": 2628,\n \"s\": 2604,\n \"text\": \"insert left of t into q\"\n },\n {\n \"code\": null,\n \"e\": 2686,\n \"s\": 2628,\n \"text\": \"if right of t is not null, then −insert right of t into q\"\n },\n {\n \"code\": null,\n \"e\": 2720,\n \"s\": 2686,\n \"text\": \"if right of t is not null, then −\"\n },\n {\n \"code\": null,\n \"e\": 2745,\n \"s\": 2720,\n \"text\": \"insert right of t into q\"\n },\n {\n \"code\": null,\n \"e\": 2770,\n \"s\": 2745,\n \"text\": \"insert right of t into q\"\n },\n {\n \"code\": null,\n \"e\": 2788,\n \"s\": 2770,\n \"text\": \"(decrease n by 1)\"\n },\n {\n \"code\": null,\n \"e\": 2806,\n \"s\": 2788,\n \"text\": \"(decrease n by 1)\"\n },\n {\n \"code\": null,\n \"e\": 2878,\n \"s\": 2806,\n \"text\": \"if size of temp is same as 1, then −insert temp[0] at the end of result\"\n },\n {\n \"code\": null,\n \"e\": 2915,\n \"s\": 2878,\n \"text\": \"if size of temp is same as 1, then −\"\n },\n {\n \"code\": null,\n \"e\": 2951,\n \"s\": 2915,\n \"text\": \"insert temp[0] at the end of result\"\n },\n {\n \"code\": null,\n \"e\": 2987,\n \"s\": 2951,\n \"text\": \"insert temp[0] at the end of result\"\n },\n {\n \"code\": null,\n \"e\": 3179,\n \"s\": 2987,\n \"text\": \"otherwise when size of temp > 1, then −sum := 0for initialize i := 0, when i < size of temp, update (increase i by 1), do −sum := sum + temp[i]insert (sum / size of temp) at the end of result\"\n },\n {\n \"code\": null,\n \"e\": 3219,\n \"s\": 3179,\n \"text\": \"otherwise when size of temp > 1, then −\"\n },\n {\n \"code\": null,\n \"e\": 3228,\n \"s\": 3219,\n \"text\": \"sum := 0\"\n },\n {\n \"code\": null,\n \"e\": 3237,\n \"s\": 3228,\n \"text\": \"sum := 0\"\n },\n {\n \"code\": null,\n \"e\": 3334,\n \"s\": 3237,\n \"text\": \"for initialize i := 0, when i < size of temp, update (increase i by 1), do −sum := sum + temp[i]\"\n },\n {\n \"code\": null,\n \"e\": 3411,\n \"s\": 3334,\n \"text\": \"for initialize i := 0, when i < size of temp, update (increase i by 1), do −\"\n },\n {\n \"code\": null,\n \"e\": 3432,\n \"s\": 3411,\n \"text\": \"sum := sum + temp[i]\"\n },\n {\n \"code\": null,\n \"e\": 3453,\n \"s\": 3432,\n \"text\": \"sum := sum + temp[i]\"\n },\n {\n \"code\": null,\n \"e\": 3502,\n \"s\": 3453,\n \"text\": \"insert (sum / size of temp) at the end of result\"\n },\n {\n \"code\": null,\n \"e\": 3551,\n \"s\": 3502,\n \"text\": \"insert (sum / size of temp) at the end of result\"\n },\n {\n \"code\": null,\n \"e\": 3565,\n \"s\": 3551,\n \"text\": \"return result\"\n },\n {\n \"code\": null,\n \"e\": 3579,\n \"s\": 3565,\n \"text\": \"return result\"\n },\n {\n \"code\": null,\n \"e\": 3651,\n \"s\": 3579,\n \"text\": \"Let us see the following implementation to get a better understanding −\"\n },\n {\n \"code\": null,\n \"e\": 3662,\n \"s\": 3651,\n \"text\": \" Live Demo\"\n },\n {\n \"code\": null,\n \"e\": 5805,\n \"s\": 3662,\n \"text\": \"#include \\nusing namespace std;\\nvoid print_vector(vector v){\\n cout << \\\"[\\\";\\n for(int i = 0; i q;\\n q.push(*root);\\n while(q.size()){\\n TreeNode *temp = q.front();\\n q.pop();\\n if(!temp->left){\\n if(val != NULL)\\n temp->left = new TreeNode(val);\\n else\\n temp->left = new TreeNode(0);\\n return;\\n }\\n else{\\n q.push(temp->left);\\n }\\n if(!temp->right){\\n if(val != NULL)\\n temp->right = new TreeNode(val);\\n else\\n temp->right = new TreeNode(0);\\n return;\\n }\\n else{\\n q.push(temp->right);\\n }\\n }\\n}\\nTreeNode *make_tree(vector v){\\n TreeNode *root = new TreeNode(v[0]);\\n for(int i = 1; i averageOfLevels(TreeNode *root){\\n vector result;\\n queue q;\\n q.push(root);\\n while (!q.empty()) {\\n int n = q.size();\\n vector temp;\\n while (n) {\\n TreeNode* t = q.front();\\n temp.push_back(t->val);\\n q.pop();\\n if (t->left && t->left->val != 0)\\n q.push(t->left);\\n if (t->right && t->right->val != 0)\\n q.push(t->right);\\n n--;\\n }\\n if (temp.size() == 1)\\n result.push_back(temp[0]);\\n else if (temp.size() > 1) {\\n double sum = 0;\\n for (int i = 0; i < temp.size(); i++) {\\n sum += temp[i];\\n }\\n result.push_back(sum / temp.size());\\n }\\n }\\n return result;\\n }\\n};\\nmain(){\\n Solution ob;\\n vector v = {3,9,20,NULL,NULL,15,7};\\n TreeNode *root = make_tree(v);\\n print_vector(ob.averageOfLevels(root));\\n}\"\n },\n {\n \"code\": null,\n \"e\": 5829,\n \"s\": 5805,\n \"text\": \"{3,9,20,NULL,NULL,15,7}\"\n },\n {\n \"code\": null,\n \"e\": 5845,\n \"s\": 5829,\n \"text\": \"[3, 14.5, 11, ]\"\n }\n]"}}},{"rowIdx":451,"cells":{"title":{"kind":"string","value":"Length of the smallest substring which contains all vowels - GeeksforGeeks"},"text":{"kind":"string","value":"08 Jun, 2021\nGiven string str consisting of only lowercase English alphabets, the task is to find the substring of the smallest length which contains all the vowels. If no such substring is found, print -1.\nExample: \nInput: str = “babeivoucu” Output: 7 Explanation: Smallest substring which contains each vowel atleast once is “abeivou” of length 7.\nInput: str = “abcdef” Output: -1 Explanation: No such substring is found. \nTwo Pointer Approach: \nStore the frequencies of each vowel and the indices at which the vowels are present.\nIf all the vowels are not present, straightaway print -1.\nTake two pointers i and j at the first and last indices containing a vowel.\nIf the frequencies of vowel at ith and jth index exceed 1, decrease the count of that vowel and shift i and j to the right and left respectively to the next index containing a vowel.\nIf the frequencies of vowel at ith or jth index is equal to 1, set flag1 or flag2 respectively and continue.\nOnce both flag1 and flag2 are set, the length of the substring cannot be further minimized. The distance between the current indices pointed by the two pointers denotes the result.\nThe below code is the implementation of the above approach: \nC++\nJava\nPython3\nC#\nJavascript\n// C++ Program to find the// length of the smallest// substring of which// contains all vowels #include using namespace std; int findMinLength(string s){ int n = s.size(); // Map to store the // frequency of vowels map counts; // Store the indices // which contains // the vowels vector indices; for (int i = 0; i < n; i++) { if (s[i] == 'a' || s[i] == 'e' || s[i] == 'o' || s[i] == 'i' || s[i] == 'u') { counts[s[i]]++; indices.push_back(i); } } // If all vowels are not // present in the string if (counts.size() < 5) return -1; int flag1 = 0, flag2 = 0; int i = 0; int j = indices.size() - 1; while ((j - i) >= 4) { // If the frequency of the // vowel at i-th index // exceeds 1 if (!flag1 && counts[s[indices[i]]] > 1) { // Decrease the frequency // of that vowel counts[s[indices[i]]]--; // Move to the left i++; } // Otherwise set flag1 else flag1 = 1; // If the frequency of the // vowel at j-th index // exceeds 1 if (!flag2 && counts[s[indices[j]]] > 1) { // Decrease the frequency // of that vowel counts[s[indices[j]]]--; // Move to the right j--; } // Otherwise set flag2 else flag2 = 1; // If both flag1 and flag2 // are set, break out of the // loop as the substring // length cannot be minimized if (flag1 && flag2) break; } // Return the length of the substring return (indices[j] - indices[i] + 1);} int main(){ string s = \"aaeebbeaccaaoiuooooooooiuu\"; cout << findMinLength(s); return 0;}\n// Java program to find the length of// the smallest substring of which// contains all vowelsimport java.util.*;class GFG{ public static int findMinLength(String s){ int n = s.length(); // Map to store the // frequency of vowels HashMap counts = new HashMap<>(); // Store the indices // which contains // the vowels Vector indices = new Vector(); for(int i = 0; i < n; i++) { if (s.charAt(i) == 'a' || s.charAt(i) == 'e' || s.charAt(i) == 'o' || s.charAt(i) == 'i' || s.charAt(i) == 'u') { if (counts.containsKey(s.charAt(i))) { counts.replace(s.charAt(i), counts.get(s.charAt(i)) + 1); } else { counts.put(s.charAt(i), 1); } indices.add(i); } } // If all vowels are not // present in the string if (counts.size() < 5) return -1; int flag1 = 0, flag2 = 0; int i = 0; int j = indices.size() - 1; while ((j - i) >= 4) { // If the frequency of the // vowel at i-th index // exceeds 1 if (flag1 == 0 && counts.get(s.charAt( indices.get(i))) > 1) { // Decrease the frequency // of that vowel counts.replace(s.charAt(indices.get(i)), counts.get(s.charAt(indices.get(i))) - 1); // Move to the left i++; } // Otherwise set flag1 else flag1 = 1; // If the frequency of the // vowel at j-th index // exceeds 1 if (flag2 == 0 && counts.get(s.charAt( indices.get(j))) > 1) { // Decrease the frequency // of that vowel counts.replace(s.charAt(indices.get(j)), counts.get(s.charAt(indices.get(j))) - 1); // Move to the right j--; } // Otherwise set flag2 else flag2 = 1; // If both flag1 and flag2 // are set, break out of the // loop as the substring // length cannot be minimized if (flag1 == 1 && flag2 == 1) break; } // Return the length of the substring return (indices.get(j) - indices.get(i) + 1);} // Driver Codepublic static void main(String[] args){ String s = \"aaeebbeaccaaoiuooooooooiuu\"; System.out.print(findMinLength(s));}} // This code is contributed by divyeshrabadiya07\n# Python3 program to find the# length of the smallest# substring of which# contains all vowelsfrom collections import defaultdict def findMinLength(s): n = len(s) # Map to store the # frequency of vowels counts = defaultdict(int) # Store the indices # which contains # the vowels indices = [] for i in range(n): if (s[i] == 'a' or s[i] == 'e' or s[i] == 'o' or s[i] == 'i' or s[i] == 'u'): counts[s[i]] += 1 indices.append(i) # If all vowels are not # present in the string if len(counts) < 5: return -1 flag1 = 0 flag2 = 0 i = 0 j = len(indices) - 1 while (j - i) >= 4: # If the frequency of the # vowel at i-th index # exceeds 1 if (~flag1 and counts[s[indices[i]]] > 1): # Decrease the frequency # of that vowel counts[s[indices[i]]] -= 1 # Move to the left i += 1 # Otherwise set flag1 else: flag1 = 1 # If the frequency of the # vowel at j-th index # exceeds 1 if (~flag2 and counts[s[indices[j]]] > 1): # Decrease the frequency # of that vowel counts[s[indices[j]]] -= 1 # Move to the right j -= 1 # Otherwise set flag2 else: flag2 = 1 # If both flag1 and flag2 # are set, break out of the # loop as the substring # length cannot be minimized if (flag1 and flag2): break # Return the length of the substring return (indices[j] - indices[i] + 1) # Driver Codes = \"aaeebbeaccaaoiuooooooooiuu\"print(findMinLength(s)) # This code is contributed by# divyamohan123\n// C# program to find the length of// the smallest substring of which// contains all vowelsusing System;using System.Collections.Generic;class GFG{ public static int findMinLength(String s){ int n = s.Length; int i = 0; // Map to store the // frequency of vowels Dictionary counts = new Dictionary(); // Store the indices // which contains // the vowels List indices = new List(); for(i = 0; i < n; i++) { if (s[i] == 'a' || s[i] == 'e' || s[i] == 'o' || s[i] == 'i' || s[i] == 'u') { if (counts.ContainsKey(s[i])) { counts[s[i]] = counts[s[i]] + 1; } else { counts.Add(s[i], 1); } indices.Add(i); } } // If all vowels are not // present in the string if (counts.Count < 5) return -1; int flag1 = 0, flag2 = 0; i = 0; int j = indices.Count - 1; while ((j - i) >= 4) { // If the frequency of the // vowel at i-th index // exceeds 1 if (flag1 == 0 && counts[s[indices[i]]] > 1) { // Decrease the frequency // of that vowel counts[s[indices[i]]]= counts[s[indices[i]]] - 1; // Move to the left i++; } // Otherwise set flag1 else flag1 = 1; // If the frequency of the // vowel at j-th index // exceeds 1 if (flag2 == 0 && counts[s[indices[j]]] > 1) { // Decrease the frequency // of that vowel counts[s[indices[j]]] = counts[s[indices[j]]] - 1; // Move to the right j--; } // Otherwise set flag2 else flag2 = 1; // If both flag1 and flag2 // are set, break out of the // loop as the substring // length cannot be minimized if (flag1 == 1 && flag2 == 1) break; } // Return the length of the substring return (indices[j] - indices[i] + 1);} // Driver Codepublic static void Main(String[] args){ String s = \"aaeebbeaccaaoiuooooooooiuu\"; Console.Write(findMinLength(s));}} // This code is contributed by shikhasingrajput\n\n9\n \nTime Complexity: O(N) Auxiliary Space: O(N)\nSliding Window Approach: \nMaintain an array count to store the frequency of each vowel.\nMaintain a start variable to store the starting index of the current substring.\nIterate over the string and do the following: Increase the frequency of the character if it is a vowel.Move start as right as possible based on the condition that either the character at the start is not a vowel or it is a vowel with a frequency greater than 1 which means that it has appeared previously.Once the start is moved as far as possible, check if all vowels are present in the substring between start and the current index.Whenever the above condition satisfies, update the minimum length of such substring obtained\nIncrease the frequency of the character if it is a vowel.\nMove start as right as possible based on the condition that either the character at the start is not a vowel or it is a vowel with a frequency greater than 1 which means that it has appeared previously.\nOnce the start is moved as far as possible, check if all vowels are present in the substring between start and the current index.\nWhenever the above condition satisfies, update the minimum length of such substring obtained\nPrint the minimum length of substring obtained or print -1 if no such substring is obtained\nThe below code implements the above approach: \nC++\nJava\nPython3\nC#\nJavascript\n// C++ Program to find the// length of the smallest// substring of which// contains all vowels #include using namespace std; // Function to return the// index for respective// vowels to increase their countint get_index(char ch){ if (ch == 'a') return 0; else if (ch == 'e') return 1; else if (ch == 'i') return 2; else if (ch == 'o') return 3; else if (ch == 'u') return 4; // Returns -1 for consonants else return -1;} // Function to find the minimum lengthint findMinLength(string s){ int n = s.size(); int ans = n + 1; // Store the starting index // of the current substring int start = 0; // Store the frequencies of vowels int count[5] = { 0 }; for (int x = 0; x < n; x++) { int idx = get_index(s[x]); // If the current character // is a vowel if (idx != -1) { // Increase its count count[idx]++; } // Move start as much // right as possible int idx_start = get_index(s[start]); while (idx_start == -1 || count[idx_start] > 1) { if (idx_start != -1) { count[idx_start]--; } start++; if (start < n) idx_start = get_index(s[start]); } // Condition for valid substring if (count[0] > 0 && count[1] > 0 && count[2] > 0 && count[3] > 0 && count[4] > 0) { ans = min(ans, x - start + 1); } } if (ans == n + 1) return -1; return ans;} // Driver codeint main(){ string s = \"aaeebbeaccaaoiuooooooooiuu\"; cout << findMinLength(s); return 0;}\n// Java program to find the length// of the smallest subString of// which contains all vowelsimport java.util.*; class GFG{ // Function to return the// index for respective// vowels to increase their countstatic int get_index(char ch){ if (ch == 'a') return 0; else if (ch == 'e') return 1; else if (ch == 'i') return 2; else if (ch == 'o') return 3; else if (ch == 'u') return 4; // Returns -1 for consonants else return -1;} // Function to find the minimum lengthstatic int findMinLength(String s){ int n = s.length(); int ans = n + 1; // Store the starting index // of the current subString int start = 0; // Store the frequencies of vowels int count[] = new int[5]; for(int x = 0; x < n; x++) { int idx = get_index(s.charAt(x)); // If the current character // is a vowel if (idx != -1) { // Increase its count count[idx]++; } // Move start as much // right as possible int idx_start = get_index(s.charAt(start)); while (idx_start == -1 || count[idx_start] > 1) { if (idx_start != -1) { count[idx_start]--; } start++; if (start < n) idx_start = get_index(s.charAt(start)); } // Condition for valid subString if (count[0] > 0 && count[1] > 0 && count[2] > 0 && count[3] > 0 && count[4] > 0) { ans = Math.min(ans, x - start + 1); } } if (ans == n + 1) return -1; return ans;} // Driver codepublic static void main(String[] args){ String s = \"aaeebbeaccaaoiuooooooooiuu\"; System.out.print(findMinLength(s));}} // This code is contributed by 29AjayKumar\n# Python3 Program to find the# length of the smallest# substring of which# contains all vowels # Function to return the# index for respective# vowels to increase their countdef get_index(ch): if (ch == 'a'): return 0 elif (ch == 'e'): return 1 elif (ch == 'i'): return 2 elif (ch == 'o'): return 3 elif (ch == 'u'): return 4 # Returns -1 for consonants else: return -1 # Function to find the minimum lengthdef findMinLength(s): n = len(s) ans = n + 1 # Store the starting index # of the current substring start = 0 # Store the frequencies # of vowels count = [0] * 5 for x in range (n): idx = get_index(s[x]) # If the current character # is a vowel if (idx != -1): # Increase its count count[idx] += 1 # Move start as much # right as possible idx_start = get_index(s[start]) while (idx_start == -1 or count[idx_start] > 1): if (idx_start != -1): count[idx_start] -= 1 start += 1 if (start < n): idx_start = get_index(s[start]) # Condition for valid substring if (count[0] > 0 and count[1] > 0 and count[2] > 0 and count[3] > 0 and count[4] > 0): ans = min(ans, x - start + 1) if (ans == n + 1): return -1 return ans # Driver codeif __name__ == \"__main__\": s = \"aaeebbeaccaaoiuooooooooiuu\" print(findMinLength(s)) # This code is contributed by Chitranayal\n// C# program to find the length// of the smallest subString of// which contains all vowelsusing System;class GFG{ // Function to return the// index for respective// vowels to increase their countstatic int get_index(char ch){ if (ch == 'a') return 0; else if (ch == 'e') return 1; else if (ch == 'i') return 2; else if (ch == 'o') return 3; else if (ch == 'u') return 4; // Returns -1 for consonants else return -1;} // Function to find the minimum lengthstatic int findMinLength(String s){ int n = s.Length; int ans = n + 1; // Store the starting index // of the current subString int start = 0; // Store the frequencies of vowels int []count = new int[5]; for(int x = 0; x < n; x++) { int idx = get_index(s[x]); // If the current character // is a vowel if (idx != -1) { // Increase its count count[idx]++; } // Move start as much // right as possible int idx_start = get_index(s[start]); while (idx_start == -1 || count[idx_start] > 1) { if (idx_start != -1) { count[idx_start]--; } start++; if (start < n) idx_start = get_index(s[start]); } // Condition for valid subString if (count[0] > 0 && count[1] > 0 && count[2] > 0 && count[3] > 0 && count[4] > 0) { ans = Math.Min(ans, x - start + 1); } } if (ans == n + 1) return -1; return ans;} // Driver codepublic static void Main(String[] args){ String s = \"aaeebbeaccaaoiuooooooooiuu\"; Console.Write(findMinLength(s));}} // This code is contributed by sapnasingh4991\n\n9\n \nTime Complexity: O(N) \ndivyamohan123\n29AjayKumar\nsapnasingh4991\nnidhi_biet\nukasp\ndivyeshrabadiya07\nshikhasingrajput\nrutvik_56\navanitrachhadiya2155\nsliding-window\nsubstring\ntwo-pointer-algorithm\nvowel-consonant\nCompetitive Programming\nHash\nStrings\nWrite From Home\nsliding-window\ntwo-pointer-algorithm\nHash\nStrings\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nMultistage Graph (Shortest Path)\nBreadth First Traversal ( BFS ) on a 2D array\nShortest path in a directed graph by Dijkstra’s algorithm\n5 Best Books for Competitive Programming\nCheck whether bitwise AND of a number with any subset of an array is zero or not\nGiven an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)\nInternal Working of HashMap in Java\nCount pairs with given sum\nHashing | Set 1 (Introduction)\nHashing | Set 3 (Open Addressing)"},"parsed":{"kind":"list like","value":[{"code":null,"e":26357,"s":26329,"text":"\n08 Jun, 2021"},{"code":null,"e":26551,"s":26357,"text":"Given string str consisting of only lowercase English alphabets, the task is to find the substring of the smallest length which contains all the vowels. If no such substring is found, print -1."},{"code":null,"e":26562,"s":26551,"text":"Example: "},{"code":null,"e":26695,"s":26562,"text":"Input: str = “babeivoucu” Output: 7 Explanation: Smallest substring which contains each vowel atleast once is “abeivou” of length 7."},{"code":null,"e":26770,"s":26695,"text":"Input: str = “abcdef” Output: -1 Explanation: No such substring is found. "},{"code":null,"e":26794,"s":26770,"text":"Two Pointer Approach: "},{"code":null,"e":26879,"s":26794,"text":"Store the frequencies of each vowel and the indices at which the vowels are present."},{"code":null,"e":26937,"s":26879,"text":"If all the vowels are not present, straightaway print -1."},{"code":null,"e":27013,"s":26937,"text":"Take two pointers i and j at the first and last indices containing a vowel."},{"code":null,"e":27196,"s":27013,"text":"If the frequencies of vowel at ith and jth index exceed 1, decrease the count of that vowel and shift i and j to the right and left respectively to the next index containing a vowel."},{"code":null,"e":27305,"s":27196,"text":"If the frequencies of vowel at ith or jth index is equal to 1, set flag1 or flag2 respectively and continue."},{"code":null,"e":27486,"s":27305,"text":"Once both flag1 and flag2 are set, the length of the substring cannot be further minimized. The distance between the current indices pointed by the two pointers denotes the result."},{"code":null,"e":27547,"s":27486,"text":"The below code is the implementation of the above approach: "},{"code":null,"e":27551,"s":27547,"text":"C++"},{"code":null,"e":27556,"s":27551,"text":"Java"},{"code":null,"e":27564,"s":27556,"text":"Python3"},{"code":null,"e":27567,"s":27564,"text":"C#"},{"code":null,"e":27578,"s":27567,"text":"Javascript"},{"code":"// C++ Program to find the// length of the smallest// substring of which// contains all vowels #include using namespace std; int findMinLength(string s){ int n = s.size(); // Map to store the // frequency of vowels map counts; // Store the indices // which contains // the vowels vector indices; for (int i = 0; i < n; i++) { if (s[i] == 'a' || s[i] == 'e' || s[i] == 'o' || s[i] == 'i' || s[i] == 'u') { counts[s[i]]++; indices.push_back(i); } } // If all vowels are not // present in the string if (counts.size() < 5) return -1; int flag1 = 0, flag2 = 0; int i = 0; int j = indices.size() - 1; while ((j - i) >= 4) { // If the frequency of the // vowel at i-th index // exceeds 1 if (!flag1 && counts[s[indices[i]]] > 1) { // Decrease the frequency // of that vowel counts[s[indices[i]]]--; // Move to the left i++; } // Otherwise set flag1 else flag1 = 1; // If the frequency of the // vowel at j-th index // exceeds 1 if (!flag2 && counts[s[indices[j]]] > 1) { // Decrease the frequency // of that vowel counts[s[indices[j]]]--; // Move to the right j--; } // Otherwise set flag2 else flag2 = 1; // If both flag1 and flag2 // are set, break out of the // loop as the substring // length cannot be minimized if (flag1 && flag2) break; } // Return the length of the substring return (indices[j] - indices[i] + 1);} int main(){ string s = \"aaeebbeaccaaoiuooooooooiuu\"; cout << findMinLength(s); return 0;}","e":29478,"s":27578,"text":null},{"code":"// Java program to find the length of// the smallest substring of which// contains all vowelsimport java.util.*;class GFG{ public static int findMinLength(String s){ int n = s.length(); // Map to store the // frequency of vowels HashMap counts = new HashMap<>(); // Store the indices // which contains // the vowels Vector indices = new Vector(); for(int i = 0; i < n; i++) { if (s.charAt(i) == 'a' || s.charAt(i) == 'e' || s.charAt(i) == 'o' || s.charAt(i) == 'i' || s.charAt(i) == 'u') { if (counts.containsKey(s.charAt(i))) { counts.replace(s.charAt(i), counts.get(s.charAt(i)) + 1); } else { counts.put(s.charAt(i), 1); } indices.add(i); } } // If all vowels are not // present in the string if (counts.size() < 5) return -1; int flag1 = 0, flag2 = 0; int i = 0; int j = indices.size() - 1; while ((j - i) >= 4) { // If the frequency of the // vowel at i-th index // exceeds 1 if (flag1 == 0 && counts.get(s.charAt( indices.get(i))) > 1) { // Decrease the frequency // of that vowel counts.replace(s.charAt(indices.get(i)), counts.get(s.charAt(indices.get(i))) - 1); // Move to the left i++; } // Otherwise set flag1 else flag1 = 1; // If the frequency of the // vowel at j-th index // exceeds 1 if (flag2 == 0 && counts.get(s.charAt( indices.get(j))) > 1) { // Decrease the frequency // of that vowel counts.replace(s.charAt(indices.get(j)), counts.get(s.charAt(indices.get(j))) - 1); // Move to the right j--; } // Otherwise set flag2 else flag2 = 1; // If both flag1 and flag2 // are set, break out of the // loop as the substring // length cannot be minimized if (flag1 == 1 && flag2 == 1) break; } // Return the length of the substring return (indices.get(j) - indices.get(i) + 1);} // Driver Codepublic static void main(String[] args){ String s = \"aaeebbeaccaaoiuooooooooiuu\"; System.out.print(findMinLength(s));}} // This code is contributed by divyeshrabadiya07","e":32131,"s":29478,"text":null},{"code":"# Python3 program to find the# length of the smallest# substring of which# contains all vowelsfrom collections import defaultdict def findMinLength(s): n = len(s) # Map to store the # frequency of vowels counts = defaultdict(int) # Store the indices # which contains # the vowels indices = [] for i in range(n): if (s[i] == 'a' or s[i] == 'e' or s[i] == 'o' or s[i] == 'i' or s[i] == 'u'): counts[s[i]] += 1 indices.append(i) # If all vowels are not # present in the string if len(counts) < 5: return -1 flag1 = 0 flag2 = 0 i = 0 j = len(indices) - 1 while (j - i) >= 4: # If the frequency of the # vowel at i-th index # exceeds 1 if (~flag1 and counts[s[indices[i]]] > 1): # Decrease the frequency # of that vowel counts[s[indices[i]]] -= 1 # Move to the left i += 1 # Otherwise set flag1 else: flag1 = 1 # If the frequency of the # vowel at j-th index # exceeds 1 if (~flag2 and counts[s[indices[j]]] > 1): # Decrease the frequency # of that vowel counts[s[indices[j]]] -= 1 # Move to the right j -= 1 # Otherwise set flag2 else: flag2 = 1 # If both flag1 and flag2 # are set, break out of the # loop as the substring # length cannot be minimized if (flag1 and flag2): break # Return the length of the substring return (indices[j] - indices[i] + 1) # Driver Codes = \"aaeebbeaccaaoiuooooooooiuu\"print(findMinLength(s)) # This code is contributed by# divyamohan123","e":33936,"s":32131,"text":null},{"code":"// C# program to find the length of// the smallest substring of which// contains all vowelsusing System;using System.Collections.Generic;class GFG{ public static int findMinLength(String s){ int n = s.Length; int i = 0; // Map to store the // frequency of vowels Dictionary counts = new Dictionary(); // Store the indices // which contains // the vowels List indices = new List(); for(i = 0; i < n; i++) { if (s[i] == 'a' || s[i] == 'e' || s[i] == 'o' || s[i] == 'i' || s[i] == 'u') { if (counts.ContainsKey(s[i])) { counts[s[i]] = counts[s[i]] + 1; } else { counts.Add(s[i], 1); } indices.Add(i); } } // If all vowels are not // present in the string if (counts.Count < 5) return -1; int flag1 = 0, flag2 = 0; i = 0; int j = indices.Count - 1; while ((j - i) >= 4) { // If the frequency of the // vowel at i-th index // exceeds 1 if (flag1 == 0 && counts[s[indices[i]]] > 1) { // Decrease the frequency // of that vowel counts[s[indices[i]]]= counts[s[indices[i]]] - 1; // Move to the left i++; } // Otherwise set flag1 else flag1 = 1; // If the frequency of the // vowel at j-th index // exceeds 1 if (flag2 == 0 && counts[s[indices[j]]] > 1) { // Decrease the frequency // of that vowel counts[s[indices[j]]] = counts[s[indices[j]]] - 1; // Move to the right j--; } // Otherwise set flag2 else flag2 = 1; // If both flag1 and flag2 // are set, break out of the // loop as the substring // length cannot be minimized if (flag1 == 1 && flag2 == 1) break; } // Return the length of the substring return (indices[j] - indices[i] + 1);} // Driver Codepublic static void Main(String[] args){ String s = \"aaeebbeaccaaoiuooooooooiuu\"; Console.Write(findMinLength(s));}} // This code is contributed by shikhasingrajput","e":36033,"s":33936,"text":null},{"code":"","e":38220,"s":36033,"text":null},{"code":null,"e":38222,"s":38220,"text":"9"},{"code":null,"e":38268,"s":38224,"text":"Time Complexity: O(N) Auxiliary Space: O(N)"},{"code":null,"e":38295,"s":38268,"text":"Sliding Window Approach: "},{"code":null,"e":38357,"s":38295,"text":"Maintain an array count to store the frequency of each vowel."},{"code":null,"e":38437,"s":38357,"text":"Maintain a start variable to store the starting index of the current substring."},{"code":null,"e":38964,"s":38437,"text":"Iterate over the string and do the following: Increase the frequency of the character if it is a vowel.Move start as right as possible based on the condition that either the character at the start is not a vowel or it is a vowel with a frequency greater than 1 which means that it has appeared previously.Once the start is moved as far as possible, check if all vowels are present in the substring between start and the current index.Whenever the above condition satisfies, update the minimum length of such substring obtained"},{"code":null,"e":39022,"s":38964,"text":"Increase the frequency of the character if it is a vowel."},{"code":null,"e":39225,"s":39022,"text":"Move start as right as possible based on the condition that either the character at the start is not a vowel or it is a vowel with a frequency greater than 1 which means that it has appeared previously."},{"code":null,"e":39355,"s":39225,"text":"Once the start is moved as far as possible, check if all vowels are present in the substring between start and the current index."},{"code":null,"e":39448,"s":39355,"text":"Whenever the above condition satisfies, update the minimum length of such substring obtained"},{"code":null,"e":39540,"s":39448,"text":"Print the minimum length of substring obtained or print -1 if no such substring is obtained"},{"code":null,"e":39587,"s":39540,"text":"The below code implements the above approach: "},{"code":null,"e":39591,"s":39587,"text":"C++"},{"code":null,"e":39596,"s":39591,"text":"Java"},{"code":null,"e":39604,"s":39596,"text":"Python3"},{"code":null,"e":39607,"s":39604,"text":"C#"},{"code":null,"e":39618,"s":39607,"text":"Javascript"},{"code":"// C++ Program to find the// length of the smallest// substring of which// contains all vowels #include using namespace std; // Function to return the// index for respective// vowels to increase their countint get_index(char ch){ if (ch == 'a') return 0; else if (ch == 'e') return 1; else if (ch == 'i') return 2; else if (ch == 'o') return 3; else if (ch == 'u') return 4; // Returns -1 for consonants else return -1;} // Function to find the minimum lengthint findMinLength(string s){ int n = s.size(); int ans = n + 1; // Store the starting index // of the current substring int start = 0; // Store the frequencies of vowels int count[5] = { 0 }; for (int x = 0; x < n; x++) { int idx = get_index(s[x]); // If the current character // is a vowel if (idx != -1) { // Increase its count count[idx]++; } // Move start as much // right as possible int idx_start = get_index(s[start]); while (idx_start == -1 || count[idx_start] > 1) { if (idx_start != -1) { count[idx_start]--; } start++; if (start < n) idx_start = get_index(s[start]); } // Condition for valid substring if (count[0] > 0 && count[1] > 0 && count[2] > 0 && count[3] > 0 && count[4] > 0) { ans = min(ans, x - start + 1); } } if (ans == n + 1) return -1; return ans;} // Driver codeint main(){ string s = \"aaeebbeaccaaoiuooooooooiuu\"; cout << findMinLength(s); return 0;}","e":41362,"s":39618,"text":null},{"code":"// Java program to find the length// of the smallest subString of// which contains all vowelsimport java.util.*; class GFG{ // Function to return the// index for respective// vowels to increase their countstatic int get_index(char ch){ if (ch == 'a') return 0; else if (ch == 'e') return 1; else if (ch == 'i') return 2; else if (ch == 'o') return 3; else if (ch == 'u') return 4; // Returns -1 for consonants else return -1;} // Function to find the minimum lengthstatic int findMinLength(String s){ int n = s.length(); int ans = n + 1; // Store the starting index // of the current subString int start = 0; // Store the frequencies of vowels int count[] = new int[5]; for(int x = 0; x < n; x++) { int idx = get_index(s.charAt(x)); // If the current character // is a vowel if (idx != -1) { // Increase its count count[idx]++; } // Move start as much // right as possible int idx_start = get_index(s.charAt(start)); while (idx_start == -1 || count[idx_start] > 1) { if (idx_start != -1) { count[idx_start]--; } start++; if (start < n) idx_start = get_index(s.charAt(start)); } // Condition for valid subString if (count[0] > 0 && count[1] > 0 && count[2] > 0 && count[3] > 0 && count[4] > 0) { ans = Math.min(ans, x - start + 1); } } if (ans == n + 1) return -1; return ans;} // Driver codepublic static void main(String[] args){ String s = \"aaeebbeaccaaoiuooooooooiuu\"; System.out.print(findMinLength(s));}} // This code is contributed by 29AjayKumar","e":43218,"s":41362,"text":null},{"code":"# Python3 Program to find the# length of the smallest# substring of which# contains all vowels # Function to return the# index for respective# vowels to increase their countdef get_index(ch): if (ch == 'a'): return 0 elif (ch == 'e'): return 1 elif (ch == 'i'): return 2 elif (ch == 'o'): return 3 elif (ch == 'u'): return 4 # Returns -1 for consonants else: return -1 # Function to find the minimum lengthdef findMinLength(s): n = len(s) ans = n + 1 # Store the starting index # of the current substring start = 0 # Store the frequencies # of vowels count = [0] * 5 for x in range (n): idx = get_index(s[x]) # If the current character # is a vowel if (idx != -1): # Increase its count count[idx] += 1 # Move start as much # right as possible idx_start = get_index(s[start]) while (idx_start == -1 or count[idx_start] > 1): if (idx_start != -1): count[idx_start] -= 1 start += 1 if (start < n): idx_start = get_index(s[start]) # Condition for valid substring if (count[0] > 0 and count[1] > 0 and count[2] > 0 and count[3] > 0 and count[4] > 0): ans = min(ans, x - start + 1) if (ans == n + 1): return -1 return ans # Driver codeif __name__ == \"__main__\": s = \"aaeebbeaccaaoiuooooooooiuu\" print(findMinLength(s)) # This code is contributed by Chitranayal","e":44813,"s":43218,"text":null},{"code":"// C# program to find the length// of the smallest subString of// which contains all vowelsusing System;class GFG{ // Function to return the// index for respective// vowels to increase their countstatic int get_index(char ch){ if (ch == 'a') return 0; else if (ch == 'e') return 1; else if (ch == 'i') return 2; else if (ch == 'o') return 3; else if (ch == 'u') return 4; // Returns -1 for consonants else return -1;} // Function to find the minimum lengthstatic int findMinLength(String s){ int n = s.Length; int ans = n + 1; // Store the starting index // of the current subString int start = 0; // Store the frequencies of vowels int []count = new int[5]; for(int x = 0; x < n; x++) { int idx = get_index(s[x]); // If the current character // is a vowel if (idx != -1) { // Increase its count count[idx]++; } // Move start as much // right as possible int idx_start = get_index(s[start]); while (idx_start == -1 || count[idx_start] > 1) { if (idx_start != -1) { count[idx_start]--; } start++; if (start < n) idx_start = get_index(s[start]); } // Condition for valid subString if (count[0] > 0 && count[1] > 0 && count[2] > 0 && count[3] > 0 && count[4] > 0) { ans = Math.Min(ans, x - start + 1); } } if (ans == n + 1) return -1; return ans;} // Driver codepublic static void Main(String[] args){ String s = \"aaeebbeaccaaoiuooooooooiuu\"; Console.Write(findMinLength(s));}} // This code is contributed by sapnasingh4991","e":46691,"s":44813,"text":null},{"code":"","e":48526,"s":46691,"text":null},{"code":null,"e":48528,"s":48526,"text":"9"},{"code":null,"e":48553,"s":48530,"text":"Time Complexity: O(N) "},{"code":null,"e":48567,"s":48553,"text":"divyamohan123"},{"code":null,"e":48579,"s":48567,"text":"29AjayKumar"},{"code":null,"e":48594,"s":48579,"text":"sapnasingh4991"},{"code":null,"e":48605,"s":48594,"text":"nidhi_biet"},{"code":null,"e":48611,"s":48605,"text":"ukasp"},{"code":null,"e":48629,"s":48611,"text":"divyeshrabadiya07"},{"code":null,"e":48646,"s":48629,"text":"shikhasingrajput"},{"code":null,"e":48656,"s":48646,"text":"rutvik_56"},{"code":null,"e":48677,"s":48656,"text":"avanitrachhadiya2155"},{"code":null,"e":48692,"s":48677,"text":"sliding-window"},{"code":null,"e":48702,"s":48692,"text":"substring"},{"code":null,"e":48724,"s":48702,"text":"two-pointer-algorithm"},{"code":null,"e":48740,"s":48724,"text":"vowel-consonant"},{"code":null,"e":48764,"s":48740,"text":"Competitive Programming"},{"code":null,"e":48769,"s":48764,"text":"Hash"},{"code":null,"e":48777,"s":48769,"text":"Strings"},{"code":null,"e":48793,"s":48777,"text":"Write From Home"},{"code":null,"e":48808,"s":48793,"text":"sliding-window"},{"code":null,"e":48830,"s":48808,"text":"two-pointer-algorithm"},{"code":null,"e":48835,"s":48830,"text":"Hash"},{"code":null,"e":48843,"s":48835,"text":"Strings"},{"code":null,"e":48941,"s":48843,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":48974,"s":48941,"text":"Multistage Graph (Shortest Path)"},{"code":null,"e":49020,"s":48974,"text":"Breadth First Traversal ( BFS ) on a 2D array"},{"code":null,"e":49078,"s":49020,"text":"Shortest path in a directed graph by Dijkstra’s algorithm"},{"code":null,"e":49119,"s":49078,"text":"5 Best Books for Competitive Programming"},{"code":null,"e":49200,"s":49119,"text":"Check whether bitwise AND of a number with any subset of an array is zero or not"},{"code":null,"e":49285,"s":49200,"text":"Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"},{"code":null,"e":49321,"s":49285,"text":"Internal Working of HashMap in Java"},{"code":null,"e":49348,"s":49321,"text":"Count pairs with given sum"},{"code":null,"e":49379,"s":49348,"text":"Hashing | Set 1 (Introduction)"}],"string":"[\n {\n \"code\": null,\n \"e\": 26357,\n \"s\": 26329,\n \"text\": \"\\n08 Jun, 2021\"\n },\n {\n \"code\": null,\n \"e\": 26551,\n \"s\": 26357,\n \"text\": \"Given string str consisting of only lowercase English alphabets, the task is to find the substring of the smallest length which contains all the vowels. If no such substring is found, print -1.\"\n },\n {\n \"code\": null,\n \"e\": 26562,\n \"s\": 26551,\n \"text\": \"Example: \"\n },\n {\n \"code\": null,\n \"e\": 26695,\n \"s\": 26562,\n \"text\": \"Input: str = “babeivoucu” Output: 7 Explanation: Smallest substring which contains each vowel atleast once is “abeivou” of length 7.\"\n },\n {\n \"code\": null,\n \"e\": 26770,\n \"s\": 26695,\n \"text\": \"Input: str = “abcdef” Output: -1 Explanation: No such substring is found. \"\n },\n {\n \"code\": null,\n \"e\": 26794,\n \"s\": 26770,\n \"text\": \"Two Pointer Approach: \"\n },\n {\n \"code\": null,\n \"e\": 26879,\n \"s\": 26794,\n \"text\": \"Store the frequencies of each vowel and the indices at which the vowels are present.\"\n },\n {\n \"code\": null,\n \"e\": 26937,\n \"s\": 26879,\n \"text\": \"If all the vowels are not present, straightaway print -1.\"\n },\n {\n \"code\": null,\n \"e\": 27013,\n \"s\": 26937,\n \"text\": \"Take two pointers i and j at the first and last indices containing a vowel.\"\n },\n {\n \"code\": null,\n \"e\": 27196,\n \"s\": 27013,\n \"text\": \"If the frequencies of vowel at ith and jth index exceed 1, decrease the count of that vowel and shift i and j to the right and left respectively to the next index containing a vowel.\"\n },\n {\n \"code\": null,\n \"e\": 27305,\n \"s\": 27196,\n \"text\": \"If the frequencies of vowel at ith or jth index is equal to 1, set flag1 or flag2 respectively and continue.\"\n },\n {\n \"code\": null,\n \"e\": 27486,\n \"s\": 27305,\n \"text\": \"Once both flag1 and flag2 are set, the length of the substring cannot be further minimized. The distance between the current indices pointed by the two pointers denotes the result.\"\n },\n {\n \"code\": null,\n \"e\": 27547,\n \"s\": 27486,\n \"text\": \"The below code is the implementation of the above approach: \"\n },\n {\n \"code\": null,\n \"e\": 27551,\n \"s\": 27547,\n \"text\": \"C++\"\n },\n {\n \"code\": null,\n \"e\": 27556,\n \"s\": 27551,\n \"text\": \"Java\"\n },\n {\n \"code\": null,\n \"e\": 27564,\n \"s\": 27556,\n \"text\": \"Python3\"\n },\n {\n \"code\": null,\n \"e\": 27567,\n \"s\": 27564,\n \"text\": \"C#\"\n },\n {\n \"code\": null,\n \"e\": 27578,\n \"s\": 27567,\n \"text\": \"Javascript\"\n },\n {\n \"code\": \"// C++ Program to find the// length of the smallest// substring of which// contains all vowels #include using namespace std; int findMinLength(string s){ int n = s.size(); // Map to store the // frequency of vowels map counts; // Store the indices // which contains // the vowels vector indices; for (int i = 0; i < n; i++) { if (s[i] == 'a' || s[i] == 'e' || s[i] == 'o' || s[i] == 'i' || s[i] == 'u') { counts[s[i]]++; indices.push_back(i); } } // If all vowels are not // present in the string if (counts.size() < 5) return -1; int flag1 = 0, flag2 = 0; int i = 0; int j = indices.size() - 1; while ((j - i) >= 4) { // If the frequency of the // vowel at i-th index // exceeds 1 if (!flag1 && counts[s[indices[i]]] > 1) { // Decrease the frequency // of that vowel counts[s[indices[i]]]--; // Move to the left i++; } // Otherwise set flag1 else flag1 = 1; // If the frequency of the // vowel at j-th index // exceeds 1 if (!flag2 && counts[s[indices[j]]] > 1) { // Decrease the frequency // of that vowel counts[s[indices[j]]]--; // Move to the right j--; } // Otherwise set flag2 else flag2 = 1; // If both flag1 and flag2 // are set, break out of the // loop as the substring // length cannot be minimized if (flag1 && flag2) break; } // Return the length of the substring return (indices[j] - indices[i] + 1);} int main(){ string s = \\\"aaeebbeaccaaoiuooooooooiuu\\\"; cout << findMinLength(s); return 0;}\",\n \"e\": 29478,\n \"s\": 27578,\n \"text\": null\n },\n {\n \"code\": \"// Java program to find the length of// the smallest substring of which// contains all vowelsimport java.util.*;class GFG{ public static int findMinLength(String s){ int n = s.length(); // Map to store the // frequency of vowels HashMap counts = new HashMap<>(); // Store the indices // which contains // the vowels Vector indices = new Vector(); for(int i = 0; i < n; i++) { if (s.charAt(i) == 'a' || s.charAt(i) == 'e' || s.charAt(i) == 'o' || s.charAt(i) == 'i' || s.charAt(i) == 'u') { if (counts.containsKey(s.charAt(i))) { counts.replace(s.charAt(i), counts.get(s.charAt(i)) + 1); } else { counts.put(s.charAt(i), 1); } indices.add(i); } } // If all vowels are not // present in the string if (counts.size() < 5) return -1; int flag1 = 0, flag2 = 0; int i = 0; int j = indices.size() - 1; while ((j - i) >= 4) { // If the frequency of the // vowel at i-th index // exceeds 1 if (flag1 == 0 && counts.get(s.charAt( indices.get(i))) > 1) { // Decrease the frequency // of that vowel counts.replace(s.charAt(indices.get(i)), counts.get(s.charAt(indices.get(i))) - 1); // Move to the left i++; } // Otherwise set flag1 else flag1 = 1; // If the frequency of the // vowel at j-th index // exceeds 1 if (flag2 == 0 && counts.get(s.charAt( indices.get(j))) > 1) { // Decrease the frequency // of that vowel counts.replace(s.charAt(indices.get(j)), counts.get(s.charAt(indices.get(j))) - 1); // Move to the right j--; } // Otherwise set flag2 else flag2 = 1; // If both flag1 and flag2 // are set, break out of the // loop as the substring // length cannot be minimized if (flag1 == 1 && flag2 == 1) break; } // Return the length of the substring return (indices.get(j) - indices.get(i) + 1);} // Driver Codepublic static void main(String[] args){ String s = \\\"aaeebbeaccaaoiuooooooooiuu\\\"; System.out.print(findMinLength(s));}} // This code is contributed by divyeshrabadiya07\",\n \"e\": 32131,\n \"s\": 29478,\n \"text\": null\n },\n {\n \"code\": \"# Python3 program to find the# length of the smallest# substring of which# contains all vowelsfrom collections import defaultdict def findMinLength(s): n = len(s) # Map to store the # frequency of vowels counts = defaultdict(int) # Store the indices # which contains # the vowels indices = [] for i in range(n): if (s[i] == 'a' or s[i] == 'e' or s[i] == 'o' or s[i] == 'i' or s[i] == 'u'): counts[s[i]] += 1 indices.append(i) # If all vowels are not # present in the string if len(counts) < 5: return -1 flag1 = 0 flag2 = 0 i = 0 j = len(indices) - 1 while (j - i) >= 4: # If the frequency of the # vowel at i-th index # exceeds 1 if (~flag1 and counts[s[indices[i]]] > 1): # Decrease the frequency # of that vowel counts[s[indices[i]]] -= 1 # Move to the left i += 1 # Otherwise set flag1 else: flag1 = 1 # If the frequency of the # vowel at j-th index # exceeds 1 if (~flag2 and counts[s[indices[j]]] > 1): # Decrease the frequency # of that vowel counts[s[indices[j]]] -= 1 # Move to the right j -= 1 # Otherwise set flag2 else: flag2 = 1 # If both flag1 and flag2 # are set, break out of the # loop as the substring # length cannot be minimized if (flag1 and flag2): break # Return the length of the substring return (indices[j] - indices[i] + 1) # Driver Codes = \\\"aaeebbeaccaaoiuooooooooiuu\\\"print(findMinLength(s)) # This code is contributed by# divyamohan123\",\n \"e\": 33936,\n \"s\": 32131,\n \"text\": null\n },\n {\n \"code\": \"// C# program to find the length of// the smallest substring of which// contains all vowelsusing System;using System.Collections.Generic;class GFG{ public static int findMinLength(String s){ int n = s.Length; int i = 0; // Map to store the // frequency of vowels Dictionary counts = new Dictionary(); // Store the indices // which contains // the vowels List indices = new List(); for(i = 0; i < n; i++) { if (s[i] == 'a' || s[i] == 'e' || s[i] == 'o' || s[i] == 'i' || s[i] == 'u') { if (counts.ContainsKey(s[i])) { counts[s[i]] = counts[s[i]] + 1; } else { counts.Add(s[i], 1); } indices.Add(i); } } // If all vowels are not // present in the string if (counts.Count < 5) return -1; int flag1 = 0, flag2 = 0; i = 0; int j = indices.Count - 1; while ((j - i) >= 4) { // If the frequency of the // vowel at i-th index // exceeds 1 if (flag1 == 0 && counts[s[indices[i]]] > 1) { // Decrease the frequency // of that vowel counts[s[indices[i]]]= counts[s[indices[i]]] - 1; // Move to the left i++; } // Otherwise set flag1 else flag1 = 1; // If the frequency of the // vowel at j-th index // exceeds 1 if (flag2 == 0 && counts[s[indices[j]]] > 1) { // Decrease the frequency // of that vowel counts[s[indices[j]]] = counts[s[indices[j]]] - 1; // Move to the right j--; } // Otherwise set flag2 else flag2 = 1; // If both flag1 and flag2 // are set, break out of the // loop as the substring // length cannot be minimized if (flag1 == 1 && flag2 == 1) break; } // Return the length of the substring return (indices[j] - indices[i] + 1);} // Driver Codepublic static void Main(String[] args){ String s = \\\"aaeebbeaccaaoiuooooooooiuu\\\"; Console.Write(findMinLength(s));}} // This code is contributed by shikhasingrajput\",\n \"e\": 36033,\n \"s\": 33936,\n \"text\": null\n },\n {\n \"code\": \"\",\n \"e\": 38220,\n \"s\": 36033,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 38222,\n \"s\": 38220,\n \"text\": \"9\"\n },\n {\n \"code\": null,\n \"e\": 38268,\n \"s\": 38224,\n \"text\": \"Time Complexity: O(N) Auxiliary Space: O(N)\"\n },\n {\n \"code\": null,\n \"e\": 38295,\n \"s\": 38268,\n \"text\": \"Sliding Window Approach: \"\n },\n {\n \"code\": null,\n \"e\": 38357,\n \"s\": 38295,\n \"text\": \"Maintain an array count to store the frequency of each vowel.\"\n },\n {\n \"code\": null,\n \"e\": 38437,\n \"s\": 38357,\n \"text\": \"Maintain a start variable to store the starting index of the current substring.\"\n },\n {\n \"code\": null,\n \"e\": 38964,\n \"s\": 38437,\n \"text\": \"Iterate over the string and do the following: Increase the frequency of the character if it is a vowel.Move start as right as possible based on the condition that either the character at the start is not a vowel or it is a vowel with a frequency greater than 1 which means that it has appeared previously.Once the start is moved as far as possible, check if all vowels are present in the substring between start and the current index.Whenever the above condition satisfies, update the minimum length of such substring obtained\"\n },\n {\n \"code\": null,\n \"e\": 39022,\n \"s\": 38964,\n \"text\": \"Increase the frequency of the character if it is a vowel.\"\n },\n {\n \"code\": null,\n \"e\": 39225,\n \"s\": 39022,\n \"text\": \"Move start as right as possible based on the condition that either the character at the start is not a vowel or it is a vowel with a frequency greater than 1 which means that it has appeared previously.\"\n },\n {\n \"code\": null,\n \"e\": 39355,\n \"s\": 39225,\n \"text\": \"Once the start is moved as far as possible, check if all vowels are present in the substring between start and the current index.\"\n },\n {\n \"code\": null,\n \"e\": 39448,\n \"s\": 39355,\n \"text\": \"Whenever the above condition satisfies, update the minimum length of such substring obtained\"\n },\n {\n \"code\": null,\n \"e\": 39540,\n \"s\": 39448,\n \"text\": \"Print the minimum length of substring obtained or print -1 if no such substring is obtained\"\n },\n {\n \"code\": null,\n \"e\": 39587,\n \"s\": 39540,\n \"text\": \"The below code implements the above approach: \"\n },\n {\n \"code\": null,\n \"e\": 39591,\n \"s\": 39587,\n \"text\": \"C++\"\n },\n {\n \"code\": null,\n \"e\": 39596,\n \"s\": 39591,\n \"text\": \"Java\"\n },\n {\n \"code\": null,\n \"e\": 39604,\n \"s\": 39596,\n \"text\": \"Python3\"\n },\n {\n \"code\": null,\n \"e\": 39607,\n \"s\": 39604,\n \"text\": \"C#\"\n },\n {\n \"code\": null,\n \"e\": 39618,\n \"s\": 39607,\n \"text\": \"Javascript\"\n },\n {\n \"code\": \"// C++ Program to find the// length of the smallest// substring of which// contains all vowels #include using namespace std; // Function to return the// index for respective// vowels to increase their countint get_index(char ch){ if (ch == 'a') return 0; else if (ch == 'e') return 1; else if (ch == 'i') return 2; else if (ch == 'o') return 3; else if (ch == 'u') return 4; // Returns -1 for consonants else return -1;} // Function to find the minimum lengthint findMinLength(string s){ int n = s.size(); int ans = n + 1; // Store the starting index // of the current substring int start = 0; // Store the frequencies of vowels int count[5] = { 0 }; for (int x = 0; x < n; x++) { int idx = get_index(s[x]); // If the current character // is a vowel if (idx != -1) { // Increase its count count[idx]++; } // Move start as much // right as possible int idx_start = get_index(s[start]); while (idx_start == -1 || count[idx_start] > 1) { if (idx_start != -1) { count[idx_start]--; } start++; if (start < n) idx_start = get_index(s[start]); } // Condition for valid substring if (count[0] > 0 && count[1] > 0 && count[2] > 0 && count[3] > 0 && count[4] > 0) { ans = min(ans, x - start + 1); } } if (ans == n + 1) return -1; return ans;} // Driver codeint main(){ string s = \\\"aaeebbeaccaaoiuooooooooiuu\\\"; cout << findMinLength(s); return 0;}\",\n \"e\": 41362,\n \"s\": 39618,\n \"text\": null\n },\n {\n \"code\": \"// Java program to find the length// of the smallest subString of// which contains all vowelsimport java.util.*; class GFG{ // Function to return the// index for respective// vowels to increase their countstatic int get_index(char ch){ if (ch == 'a') return 0; else if (ch == 'e') return 1; else if (ch == 'i') return 2; else if (ch == 'o') return 3; else if (ch == 'u') return 4; // Returns -1 for consonants else return -1;} // Function to find the minimum lengthstatic int findMinLength(String s){ int n = s.length(); int ans = n + 1; // Store the starting index // of the current subString int start = 0; // Store the frequencies of vowels int count[] = new int[5]; for(int x = 0; x < n; x++) { int idx = get_index(s.charAt(x)); // If the current character // is a vowel if (idx != -1) { // Increase its count count[idx]++; } // Move start as much // right as possible int idx_start = get_index(s.charAt(start)); while (idx_start == -1 || count[idx_start] > 1) { if (idx_start != -1) { count[idx_start]--; } start++; if (start < n) idx_start = get_index(s.charAt(start)); } // Condition for valid subString if (count[0] > 0 && count[1] > 0 && count[2] > 0 && count[3] > 0 && count[4] > 0) { ans = Math.min(ans, x - start + 1); } } if (ans == n + 1) return -1; return ans;} // Driver codepublic static void main(String[] args){ String s = \\\"aaeebbeaccaaoiuooooooooiuu\\\"; System.out.print(findMinLength(s));}} // This code is contributed by 29AjayKumar\",\n \"e\": 43218,\n \"s\": 41362,\n \"text\": null\n },\n {\n \"code\": \"# Python3 Program to find the# length of the smallest# substring of which# contains all vowels # Function to return the# index for respective# vowels to increase their countdef get_index(ch): if (ch == 'a'): return 0 elif (ch == 'e'): return 1 elif (ch == 'i'): return 2 elif (ch == 'o'): return 3 elif (ch == 'u'): return 4 # Returns -1 for consonants else: return -1 # Function to find the minimum lengthdef findMinLength(s): n = len(s) ans = n + 1 # Store the starting index # of the current substring start = 0 # Store the frequencies # of vowels count = [0] * 5 for x in range (n): idx = get_index(s[x]) # If the current character # is a vowel if (idx != -1): # Increase its count count[idx] += 1 # Move start as much # right as possible idx_start = get_index(s[start]) while (idx_start == -1 or count[idx_start] > 1): if (idx_start != -1): count[idx_start] -= 1 start += 1 if (start < n): idx_start = get_index(s[start]) # Condition for valid substring if (count[0] > 0 and count[1] > 0 and count[2] > 0 and count[3] > 0 and count[4] > 0): ans = min(ans, x - start + 1) if (ans == n + 1): return -1 return ans # Driver codeif __name__ == \\\"__main__\\\": s = \\\"aaeebbeaccaaoiuooooooooiuu\\\" print(findMinLength(s)) # This code is contributed by Chitranayal\",\n \"e\": 44813,\n \"s\": 43218,\n \"text\": null\n },\n {\n \"code\": \"// C# program to find the length// of the smallest subString of// which contains all vowelsusing System;class GFG{ // Function to return the// index for respective// vowels to increase their countstatic int get_index(char ch){ if (ch == 'a') return 0; else if (ch == 'e') return 1; else if (ch == 'i') return 2; else if (ch == 'o') return 3; else if (ch == 'u') return 4; // Returns -1 for consonants else return -1;} // Function to find the minimum lengthstatic int findMinLength(String s){ int n = s.Length; int ans = n + 1; // Store the starting index // of the current subString int start = 0; // Store the frequencies of vowels int []count = new int[5]; for(int x = 0; x < n; x++) { int idx = get_index(s[x]); // If the current character // is a vowel if (idx != -1) { // Increase its count count[idx]++; } // Move start as much // right as possible int idx_start = get_index(s[start]); while (idx_start == -1 || count[idx_start] > 1) { if (idx_start != -1) { count[idx_start]--; } start++; if (start < n) idx_start = get_index(s[start]); } // Condition for valid subString if (count[0] > 0 && count[1] > 0 && count[2] > 0 && count[3] > 0 && count[4] > 0) { ans = Math.Min(ans, x - start + 1); } } if (ans == n + 1) return -1; return ans;} // Driver codepublic static void Main(String[] args){ String s = \\\"aaeebbeaccaaoiuooooooooiuu\\\"; Console.Write(findMinLength(s));}} // This code is contributed by sapnasingh4991\",\n \"e\": 46691,\n \"s\": 44813,\n \"text\": null\n },\n {\n \"code\": \"\",\n \"e\": 48526,\n \"s\": 46691,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 48528,\n \"s\": 48526,\n \"text\": \"9\"\n },\n {\n \"code\": null,\n \"e\": 48553,\n \"s\": 48530,\n \"text\": \"Time Complexity: O(N) \"\n },\n {\n \"code\": null,\n \"e\": 48567,\n \"s\": 48553,\n \"text\": \"divyamohan123\"\n },\n {\n \"code\": null,\n \"e\": 48579,\n \"s\": 48567,\n \"text\": \"29AjayKumar\"\n },\n {\n \"code\": null,\n \"e\": 48594,\n \"s\": 48579,\n \"text\": \"sapnasingh4991\"\n },\n {\n \"code\": null,\n \"e\": 48605,\n \"s\": 48594,\n \"text\": \"nidhi_biet\"\n },\n {\n \"code\": null,\n \"e\": 48611,\n \"s\": 48605,\n \"text\": \"ukasp\"\n },\n {\n \"code\": null,\n \"e\": 48629,\n \"s\": 48611,\n \"text\": \"divyeshrabadiya07\"\n },\n {\n \"code\": null,\n \"e\": 48646,\n \"s\": 48629,\n \"text\": \"shikhasingrajput\"\n },\n {\n \"code\": null,\n \"e\": 48656,\n \"s\": 48646,\n \"text\": \"rutvik_56\"\n },\n {\n \"code\": null,\n \"e\": 48677,\n \"s\": 48656,\n \"text\": \"avanitrachhadiya2155\"\n },\n {\n \"code\": null,\n \"e\": 48692,\n \"s\": 48677,\n \"text\": \"sliding-window\"\n },\n {\n \"code\": null,\n \"e\": 48702,\n \"s\": 48692,\n \"text\": \"substring\"\n },\n {\n \"code\": null,\n \"e\": 48724,\n \"s\": 48702,\n \"text\": \"two-pointer-algorithm\"\n },\n {\n \"code\": null,\n \"e\": 48740,\n \"s\": 48724,\n \"text\": \"vowel-consonant\"\n },\n {\n \"code\": null,\n \"e\": 48764,\n \"s\": 48740,\n \"text\": \"Competitive Programming\"\n },\n {\n \"code\": null,\n \"e\": 48769,\n \"s\": 48764,\n \"text\": \"Hash\"\n },\n {\n \"code\": null,\n \"e\": 48777,\n \"s\": 48769,\n \"text\": \"Strings\"\n },\n {\n \"code\": null,\n \"e\": 48793,\n \"s\": 48777,\n \"text\": \"Write From Home\"\n },\n {\n \"code\": null,\n \"e\": 48808,\n \"s\": 48793,\n \"text\": \"sliding-window\"\n },\n {\n \"code\": null,\n \"e\": 48830,\n \"s\": 48808,\n \"text\": \"two-pointer-algorithm\"\n },\n {\n \"code\": null,\n \"e\": 48835,\n \"s\": 48830,\n \"text\": \"Hash\"\n },\n {\n \"code\": null,\n \"e\": 48843,\n \"s\": 48835,\n \"text\": \"Strings\"\n },\n {\n \"code\": null,\n \"e\": 48941,\n \"s\": 48843,\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\": 48974,\n \"s\": 48941,\n \"text\": \"Multistage Graph (Shortest Path)\"\n },\n {\n \"code\": null,\n \"e\": 49020,\n \"s\": 48974,\n \"text\": \"Breadth First Traversal ( BFS ) on a 2D array\"\n },\n {\n \"code\": null,\n \"e\": 49078,\n \"s\": 49020,\n \"text\": \"Shortest path in a directed graph by Dijkstra’s algorithm\"\n },\n {\n \"code\": null,\n \"e\": 49119,\n \"s\": 49078,\n \"text\": \"5 Best Books for Competitive Programming\"\n },\n {\n \"code\": null,\n \"e\": 49200,\n \"s\": 49119,\n \"text\": \"Check whether bitwise AND of a number with any subset of an array is zero or not\"\n },\n {\n \"code\": null,\n \"e\": 49285,\n \"s\": 49200,\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\": 49321,\n \"s\": 49285,\n \"text\": \"Internal Working of HashMap in Java\"\n },\n {\n \"code\": null,\n \"e\": 49348,\n \"s\": 49321,\n \"text\": \"Count pairs with given sum\"\n },\n {\n \"code\": null,\n \"e\": 49379,\n \"s\": 49348,\n \"text\": \"Hashing | Set 1 (Introduction)\"\n }\n]"}}},{"rowIdx":452,"cells":{"title":{"kind":"string","value":"Introducing LOB Locators - GeeksforGeeks"},"text":{"kind":"string","value":"28 Jun, 2019\nLarge object (LOB) locators let you reference a LOB in Transact-SQL statements rather than referencing the LOB itself as the size of a text can be unitext, or image LOB can be many megabytes. Using a LOB locator in Transact-SQL statements helps to reduce network traffic between the client and SAP ASE and also reduces the amount of memory which would be needed by the client to process the LOB. SAP ASE or Sybase ASE help client applications to send and receive locators as host variables and parameter markers.\nA LOB locator will remain valid for the duration of the transaction in which it was created. SAP ASE performs validation which invalidates the locator whenever the transaction commits or is rolled back.\nDatatypes used in LOB Locators:LOB locators use three different datatypes:\ntext_locator: for text LOBs.\nunitext_locator: for unitext LOBs.\nimage_locator: for image LOBs.\nDeclaring a local variable for the LOB Locator: One can declare local variables for the locator datatypes.For example:\ndeclare @v1 text_locator\n\nBecause LOBs and locators are stored only in memory, you cannot use locator datatypes as column datatypes for user tables or views, or in constraints or defaults.\nCreating a LOB Locator: One can create a LOB locator explicitly or implicitly.\nIn general, when LOB locator is used in a Transact-SQL statement, locators are implicitly converted to the LOB they reference. That is, whenever a LOB locator is passed to a Transact-SQL function, the function operates on the LOB that is referenced by the locator.\nAny changes you make to the LOB referenced by the locator are not reflected in the source LOB in the database—unless you explicitly save them. Similarly, if any changes you make to the LOB stored in the database will be not reflected in the LOB referenced by the locator.\nA LOB instance has both a locator and a value. The LOB locator is referred to where the LOB value is physically stored. The LOB value is termed as the data stored in the LOB.\nWhenever you use a LOB in an operation such as passing a LOB as a parameter, you are actually passing a LOB locator. For most of the part, you can work with a LOB instance in your application without being concerned with the semantics of LOB locators. There is no need to de-reference LOB locators because it is required with pointers in some programming languages.\nThere are still some issues regarding the semantics of LOB locators and how LOB values are stored that you should be aware of.\nTemporary LOBs\nYou can also create temporary LOBs, that are like local variables, to assist the use of database LOBs. Temporary LOBs are not associated with any table, they are only accessible by their creator, have locators (which is how they are accessed), and are deleted when a session ends.\nThere is no support for temporary BFILES. Temporary LOBs are only permitted to be input variables (IN values) in the WHERE clauses of INSERT, UPDATE, or DELETE statements. They are also permitted as values inserted by an INSERT statement, or a value in the SET clause of an UPDATE statement. Temporary LOBs have no transactional support from the database server, which means that you cannot do COMMITS or ROLLBACKs on them.\nTemporary LOB locators can span transactions. They also are deleted when the server abnormally terminates, and when an error is returned from a database SQL operation.\nLOB Locators in Your ApplicationTo use a LOB locator in Pro*C/C++ application, we have to include the oci.h header file and have to declare a pointer to the type OCIBlobLocator for BLOBs, OCIClobLocator for CLOBs and NCLOBs, or OCIBFileLocator for BFILEs.\nFor an NCLOB, you can either\nUse the clause ‘CHARACTER SET IS NCHAR_CS’ in Pro*C/C++ declaration,\nOr, you must have already used an NLS_CHAR precompiler option on the command line or in a configuration file to set the NLS_NCHAR environment variable.\nOracle-LOB\nDBMS\nDBMS\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nSQL Interview Questions\nIntroduction of B-Tree\nDifference between Clustered and Non-clustered index\nData Preprocessing in Data Mining\nIntroduction of ER Model\nIntroduction of DBMS (Database Management System) | Set 1\nDifference between DDL and DML in DBMS\nSQL | Views\nSQL | GROUP BY\nDifference between Primary Key and Foreign Key"},"parsed":{"kind":"list like","value":[{"code":null,"e":25067,"s":25039,"text":"\n28 Jun, 2019"},{"code":null,"e":25580,"s":25067,"text":"Large object (LOB) locators let you reference a LOB in Transact-SQL statements rather than referencing the LOB itself as the size of a text can be unitext, or image LOB can be many megabytes. Using a LOB locator in Transact-SQL statements helps to reduce network traffic between the client and SAP ASE and also reduces the amount of memory which would be needed by the client to process the LOB. SAP ASE or Sybase ASE help client applications to send and receive locators as host variables and parameter markers."},{"code":null,"e":25783,"s":25580,"text":"A LOB locator will remain valid for the duration of the transaction in which it was created. SAP ASE performs validation which invalidates the locator whenever the transaction commits or is rolled back."},{"code":null,"e":25858,"s":25783,"text":"Datatypes used in LOB Locators:LOB locators use three different datatypes:"},{"code":null,"e":25887,"s":25858,"text":"text_locator: for text LOBs."},{"code":null,"e":25922,"s":25887,"text":"unitext_locator: for unitext LOBs."},{"code":null,"e":25953,"s":25922,"text":"image_locator: for image LOBs."},{"code":null,"e":26072,"s":25953,"text":"Declaring a local variable for the LOB Locator: One can declare local variables for the locator datatypes.For example:"},{"code":null,"e":26098,"s":26072,"text":"declare @v1 text_locator\n"},{"code":null,"e":26261,"s":26098,"text":"Because LOBs and locators are stored only in memory, you cannot use locator datatypes as column datatypes for user tables or views, or in constraints or defaults."},{"code":null,"e":26340,"s":26261,"text":"Creating a LOB Locator: One can create a LOB locator explicitly or implicitly."},{"code":null,"e":26605,"s":26340,"text":"In general, when LOB locator is used in a Transact-SQL statement, locators are implicitly converted to the LOB they reference. That is, whenever a LOB locator is passed to a Transact-SQL function, the function operates on the LOB that is referenced by the locator."},{"code":null,"e":26877,"s":26605,"text":"Any changes you make to the LOB referenced by the locator are not reflected in the source LOB in the database—unless you explicitly save them. Similarly, if any changes you make to the LOB stored in the database will be not reflected in the LOB referenced by the locator."},{"code":null,"e":27052,"s":26877,"text":"A LOB instance has both a locator and a value. The LOB locator is referred to where the LOB value is physically stored. The LOB value is termed as the data stored in the LOB."},{"code":null,"e":27418,"s":27052,"text":"Whenever you use a LOB in an operation such as passing a LOB as a parameter, you are actually passing a LOB locator. For most of the part, you can work with a LOB instance in your application without being concerned with the semantics of LOB locators. There is no need to de-reference LOB locators because it is required with pointers in some programming languages."},{"code":null,"e":27545,"s":27418,"text":"There are still some issues regarding the semantics of LOB locators and how LOB values are stored that you should be aware of."},{"code":null,"e":27560,"s":27545,"text":"Temporary LOBs"},{"code":null,"e":27841,"s":27560,"text":"You can also create temporary LOBs, that are like local variables, to assist the use of database LOBs. Temporary LOBs are not associated with any table, they are only accessible by their creator, have locators (which is how they are accessed), and are deleted when a session ends."},{"code":null,"e":28265,"s":27841,"text":"There is no support for temporary BFILES. Temporary LOBs are only permitted to be input variables (IN values) in the WHERE clauses of INSERT, UPDATE, or DELETE statements. They are also permitted as values inserted by an INSERT statement, or a value in the SET clause of an UPDATE statement. Temporary LOBs have no transactional support from the database server, which means that you cannot do COMMITS or ROLLBACKs on them."},{"code":null,"e":28433,"s":28265,"text":"Temporary LOB locators can span transactions. They also are deleted when the server abnormally terminates, and when an error is returned from a database SQL operation."},{"code":null,"e":28689,"s":28433,"text":"LOB Locators in Your ApplicationTo use a LOB locator in Pro*C/C++ application, we have to include the oci.h header file and have to declare a pointer to the type OCIBlobLocator for BLOBs, OCIClobLocator for CLOBs and NCLOBs, or OCIBFileLocator for BFILEs."},{"code":null,"e":28718,"s":28689,"text":"For an NCLOB, you can either"},{"code":null,"e":28787,"s":28718,"text":"Use the clause ‘CHARACTER SET IS NCHAR_CS’ in Pro*C/C++ declaration,"},{"code":null,"e":28939,"s":28787,"text":"Or, you must have already used an NLS_CHAR precompiler option on the command line or in a configuration file to set the NLS_NCHAR environment variable."},{"code":null,"e":28950,"s":28939,"text":"Oracle-LOB"},{"code":null,"e":28955,"s":28950,"text":"DBMS"},{"code":null,"e":28960,"s":28955,"text":"DBMS"},{"code":null,"e":29058,"s":28960,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":29082,"s":29058,"text":"SQL Interview Questions"},{"code":null,"e":29105,"s":29082,"text":"Introduction of B-Tree"},{"code":null,"e":29158,"s":29105,"text":"Difference between Clustered and Non-clustered index"},{"code":null,"e":29192,"s":29158,"text":"Data Preprocessing in Data Mining"},{"code":null,"e":29217,"s":29192,"text":"Introduction of ER Model"},{"code":null,"e":29275,"s":29217,"text":"Introduction of DBMS (Database Management System) | Set 1"},{"code":null,"e":29314,"s":29275,"text":"Difference between DDL and DML in DBMS"},{"code":null,"e":29326,"s":29314,"text":"SQL | Views"},{"code":null,"e":29341,"s":29326,"text":"SQL | GROUP BY"}],"string":"[\n {\n \"code\": null,\n \"e\": 25067,\n \"s\": 25039,\n \"text\": \"\\n28 Jun, 2019\"\n },\n {\n \"code\": null,\n \"e\": 25580,\n \"s\": 25067,\n \"text\": \"Large object (LOB) locators let you reference a LOB in Transact-SQL statements rather than referencing the LOB itself as the size of a text can be unitext, or image LOB can be many megabytes. Using a LOB locator in Transact-SQL statements helps to reduce network traffic between the client and SAP ASE and also reduces the amount of memory which would be needed by the client to process the LOB. SAP ASE or Sybase ASE help client applications to send and receive locators as host variables and parameter markers.\"\n },\n {\n \"code\": null,\n \"e\": 25783,\n \"s\": 25580,\n \"text\": \"A LOB locator will remain valid for the duration of the transaction in which it was created. SAP ASE performs validation which invalidates the locator whenever the transaction commits or is rolled back.\"\n },\n {\n \"code\": null,\n \"e\": 25858,\n \"s\": 25783,\n \"text\": \"Datatypes used in LOB Locators:LOB locators use three different datatypes:\"\n },\n {\n \"code\": null,\n \"e\": 25887,\n \"s\": 25858,\n \"text\": \"text_locator: for text LOBs.\"\n },\n {\n \"code\": null,\n \"e\": 25922,\n \"s\": 25887,\n \"text\": \"unitext_locator: for unitext LOBs.\"\n },\n {\n \"code\": null,\n \"e\": 25953,\n \"s\": 25922,\n \"text\": \"image_locator: for image LOBs.\"\n },\n {\n \"code\": null,\n \"e\": 26072,\n \"s\": 25953,\n \"text\": \"Declaring a local variable for the LOB Locator: One can declare local variables for the locator datatypes.For example:\"\n },\n {\n \"code\": null,\n \"e\": 26098,\n \"s\": 26072,\n \"text\": \"declare @v1 text_locator\\n\"\n },\n {\n \"code\": null,\n \"e\": 26261,\n \"s\": 26098,\n \"text\": \"Because LOBs and locators are stored only in memory, you cannot use locator datatypes as column datatypes for user tables or views, or in constraints or defaults.\"\n },\n {\n \"code\": null,\n \"e\": 26340,\n \"s\": 26261,\n \"text\": \"Creating a LOB Locator: One can create a LOB locator explicitly or implicitly.\"\n },\n {\n \"code\": null,\n \"e\": 26605,\n \"s\": 26340,\n \"text\": \"In general, when LOB locator is used in a Transact-SQL statement, locators are implicitly converted to the LOB they reference. That is, whenever a LOB locator is passed to a Transact-SQL function, the function operates on the LOB that is referenced by the locator.\"\n },\n {\n \"code\": null,\n \"e\": 26877,\n \"s\": 26605,\n \"text\": \"Any changes you make to the LOB referenced by the locator are not reflected in the source LOB in the database—unless you explicitly save them. Similarly, if any changes you make to the LOB stored in the database will be not reflected in the LOB referenced by the locator.\"\n },\n {\n \"code\": null,\n \"e\": 27052,\n \"s\": 26877,\n \"text\": \"A LOB instance has both a locator and a value. The LOB locator is referred to where the LOB value is physically stored. The LOB value is termed as the data stored in the LOB.\"\n },\n {\n \"code\": null,\n \"e\": 27418,\n \"s\": 27052,\n \"text\": \"Whenever you use a LOB in an operation such as passing a LOB as a parameter, you are actually passing a LOB locator. For most of the part, you can work with a LOB instance in your application without being concerned with the semantics of LOB locators. There is no need to de-reference LOB locators because it is required with pointers in some programming languages.\"\n },\n {\n \"code\": null,\n \"e\": 27545,\n \"s\": 27418,\n \"text\": \"There are still some issues regarding the semantics of LOB locators and how LOB values are stored that you should be aware of.\"\n },\n {\n \"code\": null,\n \"e\": 27560,\n \"s\": 27545,\n \"text\": \"Temporary LOBs\"\n },\n {\n \"code\": null,\n \"e\": 27841,\n \"s\": 27560,\n \"text\": \"You can also create temporary LOBs, that are like local variables, to assist the use of database LOBs. Temporary LOBs are not associated with any table, they are only accessible by their creator, have locators (which is how they are accessed), and are deleted when a session ends.\"\n },\n {\n \"code\": null,\n \"e\": 28265,\n \"s\": 27841,\n \"text\": \"There is no support for temporary BFILES. Temporary LOBs are only permitted to be input variables (IN values) in the WHERE clauses of INSERT, UPDATE, or DELETE statements. They are also permitted as values inserted by an INSERT statement, or a value in the SET clause of an UPDATE statement. Temporary LOBs have no transactional support from the database server, which means that you cannot do COMMITS or ROLLBACKs on them.\"\n },\n {\n \"code\": null,\n \"e\": 28433,\n \"s\": 28265,\n \"text\": \"Temporary LOB locators can span transactions. They also are deleted when the server abnormally terminates, and when an error is returned from a database SQL operation.\"\n },\n {\n \"code\": null,\n \"e\": 28689,\n \"s\": 28433,\n \"text\": \"LOB Locators in Your ApplicationTo use a LOB locator in Pro*C/C++ application, we have to include the oci.h header file and have to declare a pointer to the type OCIBlobLocator for BLOBs, OCIClobLocator for CLOBs and NCLOBs, or OCIBFileLocator for BFILEs.\"\n },\n {\n \"code\": null,\n \"e\": 28718,\n \"s\": 28689,\n \"text\": \"For an NCLOB, you can either\"\n },\n {\n \"code\": null,\n \"e\": 28787,\n \"s\": 28718,\n \"text\": \"Use the clause ‘CHARACTER SET IS NCHAR_CS’ in Pro*C/C++ declaration,\"\n },\n {\n \"code\": null,\n \"e\": 28939,\n \"s\": 28787,\n \"text\": \"Or, you must have already used an NLS_CHAR precompiler option on the command line or in a configuration file to set the NLS_NCHAR environment variable.\"\n },\n {\n \"code\": null,\n \"e\": 28950,\n \"s\": 28939,\n \"text\": \"Oracle-LOB\"\n },\n {\n \"code\": null,\n \"e\": 28955,\n \"s\": 28950,\n \"text\": \"DBMS\"\n },\n {\n \"code\": null,\n \"e\": 28960,\n \"s\": 28955,\n \"text\": \"DBMS\"\n },\n {\n \"code\": null,\n \"e\": 29058,\n \"s\": 28960,\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\": 29082,\n \"s\": 29058,\n \"text\": \"SQL Interview Questions\"\n },\n {\n \"code\": null,\n \"e\": 29105,\n \"s\": 29082,\n \"text\": \"Introduction of B-Tree\"\n },\n {\n \"code\": null,\n \"e\": 29158,\n \"s\": 29105,\n \"text\": \"Difference between Clustered and Non-clustered index\"\n },\n {\n \"code\": null,\n \"e\": 29192,\n \"s\": 29158,\n \"text\": \"Data Preprocessing in Data Mining\"\n },\n {\n \"code\": null,\n \"e\": 29217,\n \"s\": 29192,\n \"text\": \"Introduction of ER Model\"\n },\n {\n \"code\": null,\n \"e\": 29275,\n \"s\": 29217,\n \"text\": \"Introduction of DBMS (Database Management System) | Set 1\"\n },\n {\n \"code\": null,\n \"e\": 29314,\n \"s\": 29275,\n \"text\": \"Difference between DDL and DML in DBMS\"\n },\n {\n \"code\": null,\n \"e\": 29326,\n \"s\": 29314,\n \"text\": \"SQL | Views\"\n },\n {\n \"code\": null,\n \"e\": 29341,\n \"s\": 29326,\n \"text\": \"SQL | GROUP BY\"\n }\n]"}}},{"rowIdx":453,"cells":{"title":{"kind":"string","value":"Analysis of Algorithms | Set 3 (Asymptotic Notations) - GeeksforGeeks"},"text":{"kind":"string","value":"12 Nov, 2021\nWe have discussed Asymptotic Analysis, and Worst, Average, and Best Cases of Algorithms. The main idea of asymptotic analysis is to have a measure of the efficiency of algorithms that don’t depend on machine-specific constants and don’t require algorithms to be implemented and time taken by programs to be compared. Asymptotic notations are mathematical tools to represent the time complexity of algorithms for asymptotic analysis. The following 3 asymptotic notations are mostly used to represent the time complexity of algorithms. \n \n1) Θ Notation: The theta notation bounds a function from above and below, so it defines exact asymptotic behavior. A simple way to get the Theta notation of an expression is to drop low-order terms and ignore leading constants. For example, consider the following expression. 3n3 + 6n2 + 6000 = Θ(n3) Dropping lower order terms is always fine because there will always be a number(n) after which Θ(n3) has higher values than Θ(n2) irrespective of the constants involved. For a given function g(n), we denote Θ(g(n)) is following set of functions. \nΘ(g(n)) = {f(n): there exist positive constants c1, c2 and n0 such \n that 0 <= c1*g(n) <= f(n) <= c2*g(n) for all n >= n0}\nThe above definition means, if f(n) is theta of g(n), then the value f(n) is always between c1*g(n) and c2*g(n) for large values of n (n >= n0). The definition of theta also requires that f(n) must be non-negative for values of n greater than n0. \n \n2) Big O Notation: The Big O notation defines an upper bound of an algorithm, it bounds a function only from above. For example, consider the case of Insertion Sort. It takes linear time in the best case and quadratic time in the worst case. We can safely say that the time complexity of Insertion sort is O(n^2). Note that O(n^2) also covers linear time. If we use Θ notation to represent time complexity of Insertion sort, we have to use two statements for best and worst cases: 1. The worst-case time complexity of Insertion Sort is Θ(n^2). 2. The best case time complexity of Insertion Sort is Θ(n). \nThe Big O notation is useful when we only have an upper bound on the time complexity of an algorithm. Many times we easily find an upper bound by simply looking at the algorithm. \nO(g(n)) = { f(n): there exist positive constants c and \n n0 such that 0 <= f(n) <= c*g(n) for \n all n >= n0}\n \n3) Ω Notation: Just as Big O notation provides an asymptotic upper bound on a function, Ω notation provides an asymptotic lower bound. Ω Notation can be useful when we have a lower bound on the time complexity of an algorithm. As discussed in the previous post, the best case performance of an algorithm is generally not useful, the Omega notation is the least used notation among all three. \nFor a given function g(n), we denote by Ω(g(n)) the set of functions. \nΩ (g(n)) = {f(n): there exist positive constants c and\n n0 such that 0 <= c*g(n) <= f(n) for\n all n >= n0}.\nLet us consider the same Insertion sort example here. The time complexity of Insertion Sort can be written as Ω(n), but it is not very useful information about insertion sort, as we are generally interested in worst-case and sometimes in the average case. \nProperties of Asymptotic Notations : As we have gone through the definition of these three notations let’s now discuss some important properties of those notations. \n1. General Properties : \n If f(n) is O(g(n)) then a*f(n) is also O(g(n)) ; where a is a constant. \n Example: f(n) = 2n2+5 is O(n2) then 7*f(n) = 7(2n2+5) = 14n2+35 is also O(n2) .\n Similarly, this property satisfies both Θ and Ω notation. \n We can say If f(n) is Θ(g(n)) then a*f(n) is also Θ(g(n)) ; where a is a constant. If f(n) is Ω (g(n)) then a*f(n) is also Ω (g(n)) ; where a is a constant.\n2. Transitive Properties : \n If f(n) is O(g(n)) and g(n) is O(h(n)) then f(n) = O(h(n)) .\n Example: if f(n) = n, g(n) = n2 and h(n)=n3 n is O(n2) and n2 is O(n3) then n is O(n3)\n Similarly, this property satisfies both Θ and Ω notation.\n We can say If f(n) is Θ(g(n)) and g(n) is Θ(h(n)) then f(n) = Θ(h(n)) . If f(n) is Ω (g(n)) and g(n) is Ω (h(n)) then f(n) = Ω (h(n))\n3. Reflexive Properties : \n Reflexive properties are always easy to understand after transitive.\n If f(n) is given then f(n) is O(f(n)). Since MAXIMUM VALUE OF f(n) will be f(n) ITSELF !\n Hence x = f(n) and y = O(f(n) tie themselves in reflexive relation always.\n Example: f(n) = n2 ; O(n2) i.e O(f(n))\n Similarly, this property satisfies both Θ and Ω notation.\n We can say that:\n If f(n) is given then f(n) is Θ(f(n)).\n If f(n) is given then f(n) is Ω (f(n)).\n4. Symmetric Properties : \n If f(n) is Θ(g(n)) then g(n) is Θ(f(n)) . \n Example: f(n) = n2 and g(n) = n2 then f(n) = Θ(n2) and g(n) = Θ(n2) \n This property only satisfies for Θ notation.\n5. Transpose Symmetric Properties : \n If f(n) is O(g(n)) then g(n) is Ω (f(n)). \n Example: f(n) = n , g(n) = n2 then n is O(n2) and n2 is Ω (n) \nThis property only satisfies O and Ω notations.\n6. Some More Properties : \n 1.) If f(n) = O(g(n)) and f(n) = Ω(g(n)) then f(n) = Θ(g(n))\n 2.) If f(n) = O(g(n)) and d(n)=O(e(n)) then f(n) + d(n) = O( max( g(n), e(n) )) Example: f(n) = n i.e O(n) d(n) = n2 i.e O(n2) then f(n) + d(n) = n + n2 i.e O(n2)\n 3.) If f(n)=O(g(n)) and d(n)=O(e(n)) then f(n) * d(n) = O( g(n) * e(n) ) Example: f(n) = n i.e O(n) d(n) = n2 i.e O(n2) then f(n) * d(n) = n * n2 = n3 i.e O(n3)\n_______________________________________________________________________________\nExercise: Which of the following statements is/are valid? 1. Time Complexity of QuickSort is Θ(n^2) 2. Time Complexity of QuickSort is O(n^2) 3. For any two functions f(n) and g(n), we have f(n) = Θ(g(n)) if and only if f(n) = O(g(n)) and f(n) = Ω(g(n)). 4. Time complexity of all computer algorithms can be written as Ω(1) \n Important Links :\nThere are two more notations called little o and little omega. Little o provides a strict upper bound (equality condition is removed from Big O) and little omega provides strict lower bound (equality condition removed from big omega)\nAnalysis of Algorithms | Set 4 (Analysis of Loops)\nRecent Articles on analysis of algorithm.\nReferences:Lec 1 | MIT (Introduction to Algorithms)\nThis article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.\nOmkarJai\nAmiyaRanjanRout\nkaustubh765\nskmodi20bce2835\n23603vaibhav2021\nAnalysis\nArticles\nWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nUnderstanding Time Complexity with Simple Examples\nTime Complexity and Space Complexity\nPractice Questions on Time Complexity Analysis\nComplexity of different operations in Binary tree, Binary Search Tree and AVL tree\nTime Complexity of building a heap\nTree Traversals (Inorder, Preorder and Postorder)\nSQL | Join (Inner, Left, Right and Full Joins)\nfind command in Linux with examples\nHow to write a Pseudo Code?\nSQL Interview Questions"},"parsed":{"kind":"list like","value":[{"code":null,"e":35839,"s":35811,"text":"\n12 Nov, 2021"},{"code":null,"e":36374,"s":35839,"text":"We have discussed Asymptotic Analysis, and Worst, Average, and Best Cases of Algorithms. The main idea of asymptotic analysis is to have a measure of the efficiency of algorithms that don’t depend on machine-specific constants and don’t require algorithms to be implemented and time taken by programs to be compared. Asymptotic notations are mathematical tools to represent the time complexity of algorithms for asymptotic analysis. The following 3 asymptotic notations are mostly used to represent the time complexity of algorithms. "},{"code":null,"e":36925,"s":36376,"text":"1) Θ Notation: The theta notation bounds a function from above and below, so it defines exact asymptotic behavior. A simple way to get the Theta notation of an expression is to drop low-order terms and ignore leading constants. For example, consider the following expression. 3n3 + 6n2 + 6000 = Θ(n3) Dropping lower order terms is always fine because there will always be a number(n) after which Θ(n3) has higher values than Θ(n2) irrespective of the constants involved. For a given function g(n), we denote Θ(g(n)) is following set of functions. "},{"code":null,"e":37064,"s":36925,"text":"Θ(g(n)) = {f(n): there exist positive constants c1, c2 and n0 such \n that 0 <= c1*g(n) <= f(n) <= c2*g(n) for all n >= n0}"},{"code":null,"e":37312,"s":37064,"text":"The above definition means, if f(n) is theta of g(n), then the value f(n) is always between c1*g(n) and c2*g(n) for large values of n (n >= n0). The definition of theta also requires that f(n) must be non-negative for values of n greater than n0. "},{"code":null,"e":37919,"s":37314,"text":"2) Big O Notation: The Big O notation defines an upper bound of an algorithm, it bounds a function only from above. For example, consider the case of Insertion Sort. It takes linear time in the best case and quadratic time in the worst case. We can safely say that the time complexity of Insertion sort is O(n^2). Note that O(n^2) also covers linear time. If we use Θ notation to represent time complexity of Insertion sort, we have to use two statements for best and worst cases: 1. The worst-case time complexity of Insertion Sort is Θ(n^2). 2. The best case time complexity of Insertion Sort is Θ(n). "},{"code":null,"e":38100,"s":37919,"text":"The Big O notation is useful when we only have an upper bound on the time complexity of an algorithm. Many times we easily find an upper bound by simply looking at the algorithm. "},{"code":null,"e":38243,"s":38100,"text":"O(g(n)) = { f(n): there exist positive constants c and \n n0 such that 0 <= f(n) <= c*g(n) for \n all n >= n0}"},{"code":null,"e":38638,"s":38245,"text":"3) Ω Notation: Just as Big O notation provides an asymptotic upper bound on a function, Ω notation provides an asymptotic lower bound. Ω Notation can be useful when we have a lower bound on the time complexity of an algorithm. As discussed in the previous post, the best case performance of an algorithm is generally not useful, the Omega notation is the least used notation among all three. "},{"code":null,"e":38710,"s":38638,"text":"For a given function g(n), we denote by Ω(g(n)) the set of functions. "},{"code":null,"e":38852,"s":38710,"text":"Ω (g(n)) = {f(n): there exist positive constants c and\n n0 such that 0 <= c*g(n) <= f(n) for\n all n >= n0}."},{"code":null,"e":39109,"s":38852,"text":"Let us consider the same Insertion sort example here. The time complexity of Insertion Sort can be written as Ω(n), but it is not very useful information about insertion sort, as we are generally interested in worst-case and sometimes in the average case. "},{"code":null,"e":39275,"s":39109,"text":"Properties of Asymptotic Notations : As we have gone through the definition of these three notations let’s now discuss some important properties of those notations. "},{"code":null,"e":39300,"s":39275,"text":"1. General Properties : "},{"code":null,"e":39378,"s":39300,"text":" If f(n) is O(g(n)) then a*f(n) is also O(g(n)) ; where a is a constant. "},{"code":null,"e":39468,"s":39378,"text":" Example: f(n) = 2n2+5 is O(n2) then 7*f(n) = 7(2n2+5) = 14n2+35 is also O(n2) ."},{"code":null,"e":39533,"s":39468,"text":" Similarly, this property satisfies both Θ and Ω notation. "},{"code":null,"e":39705,"s":39533,"text":" We can say If f(n) is Θ(g(n)) then a*f(n) is also Θ(g(n)) ; where a is a constant. If f(n) is Ω (g(n)) then a*f(n) is also Ω (g(n)) ; where a is a constant."},{"code":null,"e":39733,"s":39705,"text":"2. Transitive Properties : "},{"code":null,"e":39798,"s":39733,"text":" If f(n) is O(g(n)) and g(n) is O(h(n)) then f(n) = O(h(n)) ."},{"code":null,"e":39895,"s":39798,"text":" Example: if f(n) = n, g(n) = n2 and h(n)=n3 n is O(n2) and n2 is O(n3) then n is O(n3)"},{"code":null,"e":39956,"s":39895,"text":" Similarly, this property satisfies both Θ and Ω notation."},{"code":null,"e":40097,"s":39956,"text":" We can say If f(n) is Θ(g(n)) and g(n) is Θ(h(n)) then f(n) = Θ(h(n)) . If f(n) is Ω (g(n)) and g(n) is Ω (h(n)) then f(n) = Ω (h(n))"},{"code":null,"e":40124,"s":40097,"text":"3. Reflexive Properties : "},{"code":null,"e":40199,"s":40124,"text":" Reflexive properties are always easy to understand after transitive."},{"code":null,"e":40294,"s":40199,"text":" If f(n) is given then f(n) is O(f(n)). Since MAXIMUM VALUE OF f(n) will be f(n) ITSELF !"},{"code":null,"e":40375,"s":40294,"text":" Hence x = f(n) and y = O(f(n) tie themselves in reflexive relation always."},{"code":null,"e":40420,"s":40375,"text":" Example: f(n) = n2 ; O(n2) i.e O(f(n))"},{"code":null,"e":40484,"s":40420,"text":" Similarly, this property satisfies both Θ and Ω notation."},{"code":null,"e":40507,"s":40484,"text":" We can say that:"},{"code":null,"e":40552,"s":40507,"text":" If f(n) is given then f(n) is Θ(f(n))."},{"code":null,"e":40598,"s":40552,"text":" If f(n) is given then f(n) is Ω (f(n))."},{"code":null,"e":40626,"s":40598,"text":"4. Symmetric Properties : "},{"code":null,"e":40676,"s":40626,"text":" If f(n) is Θ(g(n)) then g(n) is Θ(f(n)) . "},{"code":null,"e":40758,"s":40676,"text":" Example: f(n) = n2 and g(n) = n2 then f(n) = Θ(n2) and g(n) = Θ(n2) "},{"code":null,"e":40809,"s":40758,"text":" This property only satisfies for Θ notation."},{"code":null,"e":40847,"s":40809,"text":"5. Transpose Symmetric Properties : "},{"code":null,"e":40897,"s":40847,"text":" If f(n) is O(g(n)) then g(n) is Ω (f(n)). "},{"code":null,"e":40972,"s":40897,"text":" Example: f(n) = n , g(n) = n2 then n is O(n2) and n2 is Ω (n) "},{"code":null,"e":41020,"s":40972,"text":"This property only satisfies O and Ω notations."},{"code":null,"e":41047,"s":41020,"text":"6. Some More Properties : "},{"code":null,"e":41113,"s":41047,"text":" 1.) If f(n) = O(g(n)) and f(n) = Ω(g(n)) then f(n) = Θ(g(n))"},{"code":null,"e":41351,"s":41113,"text":" 2.) If f(n) = O(g(n)) and d(n)=O(e(n)) then f(n) + d(n) = O( max( g(n), e(n) )) Example: f(n) = n i.e O(n) d(n) = n2 i.e O(n2) then f(n) + d(n) = n + n2 i.e O(n2)"},{"code":null,"e":41573,"s":41351,"text":" 3.) If f(n)=O(g(n)) and d(n)=O(e(n)) then f(n) * d(n) = O( g(n) * e(n) ) Example: f(n) = n i.e O(n) d(n) = n2 i.e O(n2) then f(n) * d(n) = n * n2 = n3 i.e O(n3)"},{"code":null,"e":41653,"s":41573,"text":"_______________________________________________________________________________"},{"code":null,"e":41978,"s":41653,"text":"Exercise: Which of the following statements is/are valid? 1. Time Complexity of QuickSort is Θ(n^2) 2. Time Complexity of QuickSort is O(n^2) 3. For any two functions f(n) and g(n), we have f(n) = Θ(g(n)) if and only if f(n) = O(g(n)) and f(n) = Ω(g(n)). 4. Time complexity of all computer algorithms can be written as Ω(1) "},{"code":null,"e":41997,"s":41978,"text":" Important Links :"},{"code":null,"e":42231,"s":41997,"text":"There are two more notations called little o and little omega. Little o provides a strict upper bound (equality condition is removed from Big O) and little omega provides strict lower bound (equality condition removed from big omega)"},{"code":null,"e":42282,"s":42231,"text":"Analysis of Algorithms | Set 4 (Analysis of Loops)"},{"code":null,"e":42324,"s":42282,"text":"Recent Articles on analysis of algorithm."},{"code":null,"e":42376,"s":42324,"text":"References:Lec 1 | MIT (Introduction to Algorithms)"},{"code":null,"e":42545,"s":42376,"text":"This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."},{"code":null,"e":42554,"s":42545,"text":"OmkarJai"},{"code":null,"e":42570,"s":42554,"text":"AmiyaRanjanRout"},{"code":null,"e":42582,"s":42570,"text":"kaustubh765"},{"code":null,"e":42598,"s":42582,"text":"skmodi20bce2835"},{"code":null,"e":42615,"s":42598,"text":"23603vaibhav2021"},{"code":null,"e":42624,"s":42615,"text":"Analysis"},{"code":null,"e":42633,"s":42624,"text":"Articles"},{"code":null,"e":42731,"s":42633,"text":"Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."},{"code":null,"e":42782,"s":42731,"text":"Understanding Time Complexity with Simple Examples"},{"code":null,"e":42819,"s":42782,"text":"Time Complexity and Space Complexity"},{"code":null,"e":42866,"s":42819,"text":"Practice Questions on Time Complexity Analysis"},{"code":null,"e":42949,"s":42866,"text":"Complexity of different operations in Binary tree, Binary Search Tree and AVL tree"},{"code":null,"e":42984,"s":42949,"text":"Time Complexity of building a heap"},{"code":null,"e":43034,"s":42984,"text":"Tree Traversals (Inorder, Preorder and Postorder)"},{"code":null,"e":43081,"s":43034,"text":"SQL | Join (Inner, Left, Right and Full Joins)"},{"code":null,"e":43117,"s":43081,"text":"find command in Linux with examples"},{"code":null,"e":43145,"s":43117,"text":"How to write a Pseudo Code?"}],"string":"[\n {\n \"code\": null,\n \"e\": 35839,\n \"s\": 35811,\n \"text\": \"\\n12 Nov, 2021\"\n },\n {\n \"code\": null,\n \"e\": 36374,\n \"s\": 35839,\n \"text\": \"We have discussed Asymptotic Analysis, and Worst, Average, and Best Cases of Algorithms. The main idea of asymptotic analysis is to have a measure of the efficiency of algorithms that don’t depend on machine-specific constants and don’t require algorithms to be implemented and time taken by programs to be compared. Asymptotic notations are mathematical tools to represent the time complexity of algorithms for asymptotic analysis. The following 3 asymptotic notations are mostly used to represent the time complexity of algorithms. \"\n },\n {\n \"code\": null,\n \"e\": 36925,\n \"s\": 36376,\n \"text\": \"1) Θ Notation: The theta notation bounds a function from above and below, so it defines exact asymptotic behavior. A simple way to get the Theta notation of an expression is to drop low-order terms and ignore leading constants. For example, consider the following expression. 3n3 + 6n2 + 6000 = Θ(n3) Dropping lower order terms is always fine because there will always be a number(n) after which Θ(n3) has higher values than Θ(n2) irrespective of the constants involved. For a given function g(n), we denote Θ(g(n)) is following set of functions. \"\n },\n {\n \"code\": null,\n \"e\": 37064,\n \"s\": 36925,\n \"text\": \"Θ(g(n)) = {f(n): there exist positive constants c1, c2 and n0 such \\n that 0 <= c1*g(n) <= f(n) <= c2*g(n) for all n >= n0}\"\n },\n {\n \"code\": null,\n \"e\": 37312,\n \"s\": 37064,\n \"text\": \"The above definition means, if f(n) is theta of g(n), then the value f(n) is always between c1*g(n) and c2*g(n) for large values of n (n >= n0). The definition of theta also requires that f(n) must be non-negative for values of n greater than n0. \"\n },\n {\n \"code\": null,\n \"e\": 37919,\n \"s\": 37314,\n \"text\": \"2) Big O Notation: The Big O notation defines an upper bound of an algorithm, it bounds a function only from above. For example, consider the case of Insertion Sort. It takes linear time in the best case and quadratic time in the worst case. We can safely say that the time complexity of Insertion sort is O(n^2). Note that O(n^2) also covers linear time. If we use Θ notation to represent time complexity of Insertion sort, we have to use two statements for best and worst cases: 1. The worst-case time complexity of Insertion Sort is Θ(n^2). 2. The best case time complexity of Insertion Sort is Θ(n). \"\n },\n {\n \"code\": null,\n \"e\": 38100,\n \"s\": 37919,\n \"text\": \"The Big O notation is useful when we only have an upper bound on the time complexity of an algorithm. Many times we easily find an upper bound by simply looking at the algorithm. \"\n },\n {\n \"code\": null,\n \"e\": 38243,\n \"s\": 38100,\n \"text\": \"O(g(n)) = { f(n): there exist positive constants c and \\n n0 such that 0 <= f(n) <= c*g(n) for \\n all n >= n0}\"\n },\n {\n \"code\": null,\n \"e\": 38638,\n \"s\": 38245,\n \"text\": \"3) Ω Notation: Just as Big O notation provides an asymptotic upper bound on a function, Ω notation provides an asymptotic lower bound. Ω Notation can be useful when we have a lower bound on the time complexity of an algorithm. As discussed in the previous post, the best case performance of an algorithm is generally not useful, the Omega notation is the least used notation among all three. \"\n },\n {\n \"code\": null,\n \"e\": 38710,\n \"s\": 38638,\n \"text\": \"For a given function g(n), we denote by Ω(g(n)) the set of functions. \"\n },\n {\n \"code\": null,\n \"e\": 38852,\n \"s\": 38710,\n \"text\": \"Ω (g(n)) = {f(n): there exist positive constants c and\\n n0 such that 0 <= c*g(n) <= f(n) for\\n all n >= n0}.\"\n },\n {\n \"code\": null,\n \"e\": 39109,\n \"s\": 38852,\n \"text\": \"Let us consider the same Insertion sort example here. The time complexity of Insertion Sort can be written as Ω(n), but it is not very useful information about insertion sort, as we are generally interested in worst-case and sometimes in the average case. \"\n },\n {\n \"code\": null,\n \"e\": 39275,\n \"s\": 39109,\n \"text\": \"Properties of Asymptotic Notations : As we have gone through the definition of these three notations let’s now discuss some important properties of those notations. \"\n },\n {\n \"code\": null,\n \"e\": 39300,\n \"s\": 39275,\n \"text\": \"1. General Properties : \"\n },\n {\n \"code\": null,\n \"e\": 39378,\n \"s\": 39300,\n \"text\": \" If f(n) is O(g(n)) then a*f(n) is also O(g(n)) ; where a is a constant. \"\n },\n {\n \"code\": null,\n \"e\": 39468,\n \"s\": 39378,\n \"text\": \" Example: f(n) = 2n2+5 is O(n2) then 7*f(n) = 7(2n2+5) = 14n2+35 is also O(n2) .\"\n },\n {\n \"code\": null,\n \"e\": 39533,\n \"s\": 39468,\n \"text\": \" Similarly, this property satisfies both Θ and Ω notation. \"\n },\n {\n \"code\": null,\n \"e\": 39705,\n \"s\": 39533,\n \"text\": \" We can say If f(n) is Θ(g(n)) then a*f(n) is also Θ(g(n)) ; where a is a constant. If f(n) is Ω (g(n)) then a*f(n) is also Ω (g(n)) ; where a is a constant.\"\n },\n {\n \"code\": null,\n \"e\": 39733,\n \"s\": 39705,\n \"text\": \"2. Transitive Properties : \"\n },\n {\n \"code\": null,\n \"e\": 39798,\n \"s\": 39733,\n \"text\": \" If f(n) is O(g(n)) and g(n) is O(h(n)) then f(n) = O(h(n)) .\"\n },\n {\n \"code\": null,\n \"e\": 39895,\n \"s\": 39798,\n \"text\": \" Example: if f(n) = n, g(n) = n2 and h(n)=n3 n is O(n2) and n2 is O(n3) then n is O(n3)\"\n },\n {\n \"code\": null,\n \"e\": 39956,\n \"s\": 39895,\n \"text\": \" Similarly, this property satisfies both Θ and Ω notation.\"\n },\n {\n \"code\": null,\n \"e\": 40097,\n \"s\": 39956,\n \"text\": \" We can say If f(n) is Θ(g(n)) and g(n) is Θ(h(n)) then f(n) = Θ(h(n)) . If f(n) is Ω (g(n)) and g(n) is Ω (h(n)) then f(n) = Ω (h(n))\"\n },\n {\n \"code\": null,\n \"e\": 40124,\n \"s\": 40097,\n \"text\": \"3. Reflexive Properties : \"\n },\n {\n \"code\": null,\n \"e\": 40199,\n \"s\": 40124,\n \"text\": \" Reflexive properties are always easy to understand after transitive.\"\n },\n {\n \"code\": null,\n \"e\": 40294,\n \"s\": 40199,\n \"text\": \" If f(n) is given then f(n) is O(f(n)). Since MAXIMUM VALUE OF f(n) will be f(n) ITSELF !\"\n },\n {\n \"code\": null,\n \"e\": 40375,\n \"s\": 40294,\n \"text\": \" Hence x = f(n) and y = O(f(n) tie themselves in reflexive relation always.\"\n },\n {\n \"code\": null,\n \"e\": 40420,\n \"s\": 40375,\n \"text\": \" Example: f(n) = n2 ; O(n2) i.e O(f(n))\"\n },\n {\n \"code\": null,\n \"e\": 40484,\n \"s\": 40420,\n \"text\": \" Similarly, this property satisfies both Θ and Ω notation.\"\n },\n {\n \"code\": null,\n \"e\": 40507,\n \"s\": 40484,\n \"text\": \" We can say that:\"\n },\n {\n \"code\": null,\n \"e\": 40552,\n \"s\": 40507,\n \"text\": \" If f(n) is given then f(n) is Θ(f(n)).\"\n },\n {\n \"code\": null,\n \"e\": 40598,\n \"s\": 40552,\n \"text\": \" If f(n) is given then f(n) is Ω (f(n)).\"\n },\n {\n \"code\": null,\n \"e\": 40626,\n \"s\": 40598,\n \"text\": \"4. Symmetric Properties : \"\n },\n {\n \"code\": null,\n \"e\": 40676,\n \"s\": 40626,\n \"text\": \" If f(n) is Θ(g(n)) then g(n) is Θ(f(n)) . \"\n },\n {\n \"code\": null,\n \"e\": 40758,\n \"s\": 40676,\n \"text\": \" Example: f(n) = n2 and g(n) = n2 then f(n) = Θ(n2) and g(n) = Θ(n2) \"\n },\n {\n \"code\": null,\n \"e\": 40809,\n \"s\": 40758,\n \"text\": \" This property only satisfies for Θ notation.\"\n },\n {\n \"code\": null,\n \"e\": 40847,\n \"s\": 40809,\n \"text\": \"5. Transpose Symmetric Properties : \"\n },\n {\n \"code\": null,\n \"e\": 40897,\n \"s\": 40847,\n \"text\": \" If f(n) is O(g(n)) then g(n) is Ω (f(n)). \"\n },\n {\n \"code\": null,\n \"e\": 40972,\n \"s\": 40897,\n \"text\": \" Example: f(n) = n , g(n) = n2 then n is O(n2) and n2 is Ω (n) \"\n },\n {\n \"code\": null,\n \"e\": 41020,\n \"s\": 40972,\n \"text\": \"This property only satisfies O and Ω notations.\"\n },\n {\n \"code\": null,\n \"e\": 41047,\n \"s\": 41020,\n \"text\": \"6. Some More Properties : \"\n },\n {\n \"code\": null,\n \"e\": 41113,\n \"s\": 41047,\n \"text\": \" 1.) If f(n) = O(g(n)) and f(n) = Ω(g(n)) then f(n) = Θ(g(n))\"\n },\n {\n \"code\": null,\n \"e\": 41351,\n \"s\": 41113,\n \"text\": \" 2.) If f(n) = O(g(n)) and d(n)=O(e(n)) then f(n) + d(n) = O( max( g(n), e(n) )) Example: f(n) = n i.e O(n) d(n) = n2 i.e O(n2) then f(n) + d(n) = n + n2 i.e O(n2)\"\n },\n {\n \"code\": null,\n \"e\": 41573,\n \"s\": 41351,\n \"text\": \" 3.) If f(n)=O(g(n)) and d(n)=O(e(n)) then f(n) * d(n) = O( g(n) * e(n) ) Example: f(n) = n i.e O(n) d(n) = n2 i.e O(n2) then f(n) * d(n) = n * n2 = n3 i.e O(n3)\"\n },\n {\n \"code\": null,\n \"e\": 41653,\n \"s\": 41573,\n \"text\": \"_______________________________________________________________________________\"\n },\n {\n \"code\": null,\n \"e\": 41978,\n \"s\": 41653,\n \"text\": \"Exercise: Which of the following statements is/are valid? 1. Time Complexity of QuickSort is Θ(n^2) 2. Time Complexity of QuickSort is O(n^2) 3. For any two functions f(n) and g(n), we have f(n) = Θ(g(n)) if and only if f(n) = O(g(n)) and f(n) = Ω(g(n)). 4. Time complexity of all computer algorithms can be written as Ω(1) \"\n },\n {\n \"code\": null,\n \"e\": 41997,\n \"s\": 41978,\n \"text\": \" Important Links :\"\n },\n {\n \"code\": null,\n \"e\": 42231,\n \"s\": 41997,\n \"text\": \"There are two more notations called little o and little omega. Little o provides a strict upper bound (equality condition is removed from Big O) and little omega provides strict lower bound (equality condition removed from big omega)\"\n },\n {\n \"code\": null,\n \"e\": 42282,\n \"s\": 42231,\n \"text\": \"Analysis of Algorithms | Set 4 (Analysis of Loops)\"\n },\n {\n \"code\": null,\n \"e\": 42324,\n \"s\": 42282,\n \"text\": \"Recent Articles on analysis of algorithm.\"\n },\n {\n \"code\": null,\n \"e\": 42376,\n \"s\": 42324,\n \"text\": \"References:Lec 1 | MIT (Introduction to Algorithms)\"\n },\n {\n \"code\": null,\n \"e\": 42545,\n \"s\": 42376,\n \"text\": \"This article is contributed by Abhay Rathi. 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\": 42554,\n \"s\": 42545,\n \"text\": \"OmkarJai\"\n },\n {\n \"code\": null,\n \"e\": 42570,\n \"s\": 42554,\n \"text\": \"AmiyaRanjanRout\"\n },\n {\n \"code\": null,\n \"e\": 42582,\n \"s\": 42570,\n \"text\": \"kaustubh765\"\n },\n {\n \"code\": null,\n \"e\": 42598,\n \"s\": 42582,\n \"text\": \"skmodi20bce2835\"\n },\n {\n \"code\": null,\n \"e\": 42615,\n \"s\": 42598,\n \"text\": \"23603vaibhav2021\"\n },\n {\n \"code\": null,\n \"e\": 42624,\n \"s\": 42615,\n \"text\": \"Analysis\"\n },\n {\n \"code\": null,\n \"e\": 42633,\n \"s\": 42624,\n \"text\": \"Articles\"\n },\n {\n \"code\": null,\n \"e\": 42731,\n \"s\": 42633,\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\": 42782,\n \"s\": 42731,\n \"text\": \"Understanding Time Complexity with Simple Examples\"\n },\n {\n \"code\": null,\n \"e\": 42819,\n \"s\": 42782,\n \"text\": \"Time Complexity and Space Complexity\"\n },\n {\n \"code\": null,\n \"e\": 42866,\n \"s\": 42819,\n \"text\": \"Practice Questions on Time Complexity Analysis\"\n },\n {\n \"code\": null,\n \"e\": 42949,\n \"s\": 42866,\n \"text\": \"Complexity of different operations in Binary tree, Binary Search Tree and AVL tree\"\n },\n {\n \"code\": null,\n \"e\": 42984,\n \"s\": 42949,\n \"text\": \"Time Complexity of building a heap\"\n },\n {\n \"code\": null,\n \"e\": 43034,\n \"s\": 42984,\n \"text\": \"Tree Traversals (Inorder, Preorder and Postorder)\"\n },\n {\n \"code\": null,\n \"e\": 43081,\n \"s\": 43034,\n \"text\": \"SQL | Join (Inner, Left, Right and Full Joins)\"\n },\n {\n \"code\": null,\n \"e\": 43117,\n \"s\": 43081,\n \"text\": \"find command in Linux with examples\"\n },\n {\n \"code\": null,\n \"e\": 43145,\n \"s\": 43117,\n \"text\": \"How to write a Pseudo Code?\"\n }\n]"}}},{"rowIdx":454,"cells":{"title":{"kind":"string","value":"HTML | \nOutput:\nSupported Browsers: The browsers supported by HTML ","e":27087,"s":26608,"text":null},{"code":null,"e":27095,"s":27087,"text":"Output:"},{"code":null,"e":27195,"s":27095,"text":"Supported Browsers: The browsers supported by HTML \",\n \"e\": 27087,\n \"s\": 26608,\n \"text\": null\n },\n {\n \"code\": null,\n \"e\": 27095,\n \"s\": 27087,\n \"text\": \"Output:\"\n },\n {\n \"code\": null,\n \"e\": 27195,\n \"s\": 27095,\n \"text\": \"Supported Browsers: The browsers supported by HTML