{ // 获取包含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 !== 'PDF TO Markdown' && linkText !== 'PDF TO Markdown' ) { link.textContent = 'PDF TO 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 !== 'Voice Cloning' ) { link.textContent = 'Voice Cloning'; link.href = 'https://vibevoice.info/'; 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, 'PDF TO 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 }); }); } })(); \n\n\nHe probado a poner onclick=\"window.open(this.href)\" después del enlace, pero ello no ha solucionado el problema. Sé que el problema no es del enlace en sí ya que, de poner target=\"_blank\" sí se abre. El problema es que de esta manera se abre en otra pestaña y a mi me gustaría que lo hiciera en la misma. ¿Qué puedo hacer para que el link se abra y lo haga en la misma pestaña?\n\nA:\n\nAgrégale el protocolo http:// al enlace.\n\n\n \n \n \n\n \n

Abre

\n YT\n \n\n\nHay que agregarle el protocolo http o https porque sin él, la URL estaba funcionando como una URL relativa, adjuntando la cadena www.youtube.com a la URL que tenga el navegador, de tal modo que si estamos en http://localhost el resultado del click nos estaba redirigiendo a http://localhost/www.youtube.com\nAgregándole el protocolo si nos lleva directamente a http://www.youtube.com\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29114,"cells":{"text":{"kind":"string","value":"Q:\n\nUpdate Query With If Exists\n\nI am trying to write a query that will update my table #master12.cg when it is null. So here are my steps needed:\n\n1) Check if #master12.uid exists in #check1.dasboot and if it does, then update #master12.cg with that value\n 2) Check if #master12.uid exists in #check.uid and if it does update #master12.cg with the value in #check2.redbluegreen\n 3) If #master12.uid does not exist in either table then just leave #master12.uid as null\n\nI have tried this query\nUpdate #master12\nSet [cg] = case \n when exists (Select [dasboot] FROM [#check1] WHERE [#master]. [uid] = [#check1].[uid])\n when not exists (Select [redbluegreen] FROM [#check2] WHERE [#master12].[uid] = [#check2].[uid]\n else [#master12].[cg]\n end\nWHERE [#master12].[cg] IS NULL\n\nHowever this query presents an error of:\n\nMsg 156, Level 15, State 1, Line 4\n Incorrect syntax near the keyword 'when'.\n Msg 156, Level 15, State 1, Line 5\n Incorrect syntax near the keyword 'else'.\n\nHow should I write this update statement so that the checks listed above are performed and my table is updated accordingly?\n\nA:\n\nSQLServer case when statement doesn't work like that. You need a condition, and then a result. Your query only has a condition.\nYou could rewrite your query like that :\nUpdate #master12\nSet [cg] = [dasboot] \nfrom #master12 m\njoin [#check1] c1 on m.[uid] = c1.[uid]\nWHERE m.[cg] IS NULL\n\nUpdate #master12\nSet [cg] = [redbluegreen] \nfrom #master12 m\njoin [#check2] c2 on m.[uid] = c2.[uid]\nWHERE m.[cg] IS NULL\n\nOr maybe in a single one like :\nUpdate #master12\nSet [cg] = isnull([dasboot], [redbluegreen])\nfrom #master12 m\nleft join [#check1] c1 on m.[uid] = c1.[uid]\nleft join [#check2] c2 on m.[uid] = c2.[uid]\nWHERE m.[cg] IS NULL\n\nBut it will also depend on what you want when you have a uid value present in both tables #check1 and #check2 and which value you want to be used for the update.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29115,"cells":{"text":{"kind":"string","value":"Q:\n\nnot able to display footer using TOM and javascript in mozila\n\nHow to diplay footer like this in mozilla?\n\n\n\n
\n\n\n\nA:\n\nTry \noRow = oTFoot.insertRow(-1);\noCell = oRow.insertCell(-1)\n\nThe index argument is not optional for insertRow() and insertCell():\n\nIf index is -1 or equal to the number\n of rows, the row is appended as the\n last row. If index is omitted or\n greater than the number of rows, an\n error will result.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29116,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to avoid downloading schema file from internet during spring initialization\n\nI have a web app running on a production server which does not allow public internet access. The initialization fails with error like \n2010-02-18 15:21:33,150 **WARN** [SimpleSaxErrorHandler.java:47] Ignored XML validation warning\norg.xml.sax.SAXParseException: schema_reference.4: Failed to read schema document 'https://jax-ws.dev.java.net/spring/servlet.xsd', because 1) could not find the document; 2) the document could not be\n read; 3) the root element of the document is not .\n at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)\n ...\n\n2010-02-18 15:21:33,154 **ERROR** [ContextLoader.java:215] Context initialization failed\norg.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 9 in XML document from ServletContext resource [/WEB-INF/app.xml] is invalid; nested exception is org.xml.sax.SAXPar\nseException: cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'wss:binding'.\n at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:389)\n\nIt seems the 1st WARN indicates the app failed to download the schema file, which caused the 2nd ERROR.\nMy questions are:\n\nI feel it is reasonable that I should be able to run an app w/o having to have internet access. how can I ask the xml parser to use a local schema file instead of a copy downloaded from the internet. I know XML catalog has the capability. I am using tomcat and spring. Is there a way to configure XML catalog? Are there other mechanisms that can achieve the same purpose?\nIf I cannot redirect the parser to use a local schema file. Can I disable the xml schema validation? Again, I would like to just configure the behavior without touching the code.\n\nA:\n\nPut the schemas you need in your classpath, and then use a resolver to use it. \n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29117,"cells":{"text":{"kind":"string","value":"Q:\n\nWhy isn't the Microsoft Public License compatible with the GPL?\n\nAccording to this GNU Project page, regarding Microsoft Public License (Ms-PL):\n\nThis is a free software license; it has a copyleft that is not strong, but incompatible with the GNU GPL.\n\nThey do not explain why it is incompatible. I cannot find any satisfactory answers nor explanations via Google.\n\nA:\n\nAs far as I can see, the incompatibility between GPL and Ms-PL stems from the fact that the Ms-PL does not seem to allow sub-licensing or dual-licensing.\nAs the GPL requires that all code in a GPL-licensed product is covered by the GPL and the Ms-PL seems to require code that is Ms-PL licensed to remain covered by the Ms-PL and only the Ms-PL, this makes it impossible to have code covered by these two licenses in one product, thus rendering the licenses incompatible.\n\nMy understanding of the incompatibility comes from this quote from the Ms-PL license (emphasis mine):\n\n(D) If you distribute any portion of the software in source code\n form, you may do so only under this license by including a\n complete copy of this license with your distribution. [...]\n\nA:\n\nI am not a lawyer, and this is not legal advice. If you want a definitive answer, consult an attorney.\nI cannot find any potential incompatibility with the GPL v3 (as I understand it) except perhaps §3(D), which disallows relicensing under a license that does not impose compatible requirements. The GPL also disallows relicensing under a license that is less permissive, as the FSF defines it.\nYou should email the FSF about this, to get their take, as I can't find their reasoning published on the GNU or FSF websites.\n\nA:\n\nIn general, the GPL states that you can use non-GPL licensed code in your GPL-licensed product provided that the non-GPL license does not impose more restrictions than the GPL. In other words, you can freely use 3-clause-BSD-licensed code in your GPL project. This doesn't change the license of the BSD-licensed code - the GPL is viral only to code that uses GPL-licensed code, not to code that is used by GPL-licensed code (that would be unreasonable and in general impossible). On the other hand, the 4-clause-BSD license contains an additional clause about advertising, which doesn't exist in the GPL, and so is incompatible.\nI see two candidates for the offending clauses in the Ms-PL. One is 3c, which requires the preservation of not only copyright notices (that's pretty much universal across licenses), but also patent, trademark and attribution notices. The other is the second part of 3d, which imposes a restriction on the compiled form of the code that is not there in this form in the GPL. But IANAL, so I'm not sure about this.\nNote also that the Ms-PL contains a patent provision similar to that of the Apache License, which makes it incompatible with the GPLv2, but not the GPLv3 (which added similar wording of its own). See the description on GNU's website: http://www.gnu.org/licenses/license-list.html#apache2\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29118,"cells":{"text":{"kind":"string","value":"Q:\n\nRouting rules for MVC 2 in ASP.Net (c#)\n\nHow can I add a routing rule that takes this URL\nhttp://localhost:57334/Blog/index.aspx?Id=23\nand converts to this:\nhttp://localhost:57334/Blog/Id/23/blog\n\nA:\n\nRouting rules typically interprets the urls you give and maps them to resources meant to handle those requests. Your url suggests you are using webforms and not asp.net mvc.\nWhat i think you need is URL rewriting... you could check out \nthis link\nHope this helps\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29119,"cells":{"text":{"kind":"string","value":"Q:\n\nC++17 std::optional in G++?\n\ncppreference.com - std::optional identifies std::optional as being available \"since C++17\". C++ Standards Support in GCC - C++1z Language Features Lists c++17 features. I do not see std::optional in the list. Were is std::optional documented for G++?\n#include \n#include \n#include \n\n// optional can be used as the return type of a factory that may fail\nstd::optional create(bool b) {\n if(b)\n return \"Godzilla\";\n else\n return {};\n}\n\nint main()\n{\n std::cout << \"create(false) returned \"\n << create(false).value_or(\"empty\") << '\\n';\n\n // optional-returning factory functions are usable as conditions of while and if\n if(auto str = create(true)) {\n std::cout << \"create(true) returned \" << *str << '\\n';\n }\n}\n\nA:\n\nYou need to follow the \"library implementation\" link\nhttps://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html#status.iso.201z\nit is described under Library Fundamentals V1 TS Components (Table 1.5).\nThat's because std::optional is a library feature, not a language feature, as mentioned in one of the comments.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29120,"cells":{"text":{"kind":"string","value":"Q:\n\nWindows 10 BSOD due to HID\n\nLog Name: System\nSource: Microsoft-Windows-DriverFrameworks-UserMode\nDate: 28/11/2018 16:34:44\nEvent ID: 10111\nTask Category: User-mode Driver problems.\nLevel: Critical\nKeywords: \nUser: SYSTEM\nComputer: DESKTOP-3JS743D\nDescription:\nThe device HID-compliant headset (location (unknown)) is offline due to a user-mode driver crash. Windows will attempt to restart the device 5 more times. Please contact the device manufacturer for more information about this problem.\nEvent Xml:\n\n \n \n 10111\n 1\n 1\n 64\n 0\n 0x2000000000000000\n \n 1122\n \n \n System\n DESKTOP-3JS743D\n \n \n \n \n {714af0f3-18c1-4dd0-8385-17569f8faac6}\n HID-compliant headset\n (unknown)\n HID\\VID_0951&amp;PID_16A4&amp;MI_03&amp;COL02\\7&amp;1C94FA2&amp;0&amp;0001\n 5\n \n \n\n\nCan anyone help me with this crash? I dont really understand how I can fix this. The driver files it refers to are c:\\Windows\\system32\\DRIVERS\\UMDF\\HidTelephony.dll and C:\\Windows\\system32\\drivers\\WudfRD.sys\nAll drivers are up to date. Headset is the HyperX Cloud.\n\nA:\n\nThe issue was entirely unrelated to Drivers and ended up being bad CPU voltage settings.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29121,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to add markers on OpenLayers 3 giving coordinates\n\nI need to add a marker on my map when I call the method addMarker(long, lat).\nThe only example I have found is this one in the OpenLayers example list, but it adds only one marker in a specific place.\nI need to be able to call my method anytime I need and pass the coordinates (the general idea is to have a simple menu where the user can type the long and lat and click a submit button and the marker is drawn on the map).\nIn the example, if I got it right, they created a feature and its style, then created a layer to draw the icon and initialized the map using that layer.\nvar iconFeature = new ol.Feature({\n geometry: new ol.geom.Point(ol.proj.transform([-72.0704, 46.678], 'EPSG:4326', 'EPSG:3857')),\n name: 'Null Island',\n population: 4000,\n rainfall: 500\n});\n\nvar iconStyle = new ol.style.Style({\n image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({\n anchor: [0.5, 46],\n anchorXUnits: 'fraction',\n anchorYUnits: 'pixels',\n opacity: 0.75,\n src: 'data/icon.png'\n }))\n});\n\niconFeature.setStyle(iconStyle);\n\nvar vectorSource = new ol.source.Vector({\n features: [iconFeature]\n});\n\nvar vectorLayer = new ol.layer.Vector({\n source: vectorSource\n});\n\nvar map = new ol.Map({\n layers: [new ol.layer.Tile({ source: new ol.source.OSM() }), vectorLayer],\n target: document.getElementById('map'),\n view: new ol.View2D({\n center: [0, 0],\n zoom: 3\n })\n});\n\nI believe I can create an array of features, something like that(an example I saw here):\nvar iconFeatures=[];\n\nvar iconFeature = new ol.Feature({\n geometry: new ol.geom.Point(ol.proj.transform([-72.0704, 46.678], 'EPSG:4326', \n 'EPSG:3857')),\n name: 'Null Island',\n population: 4000,\n rainfall: 500\n});\n\nvar iconFeature1 = new ol.Feature({\n geometry: new ol.geom.Point(ol.proj.transform([-73.1234, 45.678], 'EPSG:4326', \n 'EPSG:3857')),\n name: 'Null Island Two',\n population: 4001,\n rainfall: 501\n});\n\niconFeatures.push(iconFeature);\niconFeatures.push(iconFeature1);\n\nHere is my method so far:\nclass map{\n private markerFeatures = [];\n\n //receive an array of coordinates\n public addMarkers(markers: Array): void { \n for (var i in markers) {\n var markFeature = new ol.Feature({\n geometry: new ol.geom.Point(ol.proj.transform([markers[i].long, markers[i].lat], 'EPSG:4326', \n 'EPSG:3857')),\n name: 'Null Island',\n population: 4000,\n rainfall: 500\n });\n\n this.markerFeatures.push(markFeature);\n } \n }\n} \n\nBut nothing happened when I did that.\nObs: I created the map, the layer and called the method.\nI'm using OL v3.7\n\nA:\n\nAssuming you have a layer containing a vector source, you just need to add one more step to your addMarkers function:\nmyVectorSource.addFeatures(markerFeatures);\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29122,"cells":{"text":{"kind":"string","value":"Q:\n\nSet windows form properties values from separated class\n\nI have a windows forms application i have too many forms, \ni want to set all of them same properties at once, any help please\n\nA:\n\nYou can use PropertyBinding, and the value is save on Settings from application.\nI make one example:\nIn Properties window, select Application Settings, PropertyBinding:\n\nAnd select whats property you want, if exists the setting select, or create new:\n\nAfter, you can change the value on Settings window, and all forms with setting, will be changed:\n\nResult:\n\nValues are save in the .config file:\n\n \n \n LightBlue\n \n \n\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29123,"cells":{"text":{"kind":"string","value":"Q:\n\nWhat Android methods are called when battery dies?\n\nWhen the battery on my Android device dies what methods in the Activity and Fragment classes (if any) are called during the \"Powering Off\" stage of the device?\nAlso, if a user is currently looking at a screen in my app and they hold the power button and choose switch off, do the events called/not called coincide with when the battery is depleted and shuts down automatically?\nOnPause?\nOnStop?\nOnDestroy?\nOnDetach?\nBonus:\nWill I have enough time to save a small amount of data to a web server?\nTo clarify \"dies\" when the device's battery is 'completely' dead, accepts no more input and a message box/loading screen pops up on the screen stating \"Powering Off\". Shortly there after the device switches off.\nI just need enough time to save a forms state before the phone switches off, I have a strategy to clean the saved data should the phone not switch off, but I want to get as close to the phone switching off as possible (any more than a minute is pointless really).\n\nA:\n\nonDestroy is called on everything when the battery reaches 0.5%\nEDIT: There is no specified time that you have to do anything in the shutdown process resulting from low/dead battery, that would be dependent on the specific phone battery and not the system, so you may have enough time to save data to a web server on some phones but not others. Experimentally, I have only been able to write a short line to a file I was already writing to before onDestroy was called and nothing more.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29124,"cells":{"text":{"kind":"string","value":"Q:\n\nQuery to group distinct values and show sum of array values in mongodb\n\nI wanted to group by cart.name and find the sum of cart.qty in mongodb. Below is sample document\n{\n \"_id\" : ObjectId(\"581323379ae5e607645cb485\"),\n \"cust\" : {\n \"name\" : \"Customer 1\",\n \"dob\" : \"09/04/1989\",\n \"mob\" : 999999999,\n \"loc\" : \"Karimangalam\",\n \"aadhar\" : {\n\n }\n },\n \"cart\" : [\n {\n \"name\" : \"Casual Shirt\",\n \"qty\" : 1,\n \"mrp\" : 585,\n \"discperc\" : 10,\n \"fit\" : null,\n \"size\" : \"L\"\n },\n {\n \"name\" : \"Casual Shirt\",\n \"qty\" : 1,\n \"mrp\" : 500,\n \"discperc\" : 0,\n \"fit\" : null,\n \"size\" : \"L\"\n },\n {\n \"name\" : \"Cotton Pant\",\n \"qty\" : 1,\n \"mrp\" : 850,\n \"discperc\" : 0,\n \"fit\" : null,\n \"size\" : \"34\"\n },\n {\n \"name\" : \"Cotton Pant\",\n \"qty\" : 1,\n \"mrp\" : 1051,\n \"discperc\" : 10,\n \"fit\" : null,\n \"size\" : \"34\"\n }\n ],\n \"summary\" : {\n \"bill\" : 2822.4,\n \"qty\" : 4,\n \"mrp\" : 2986,\n \"received\" : \"2800\",\n \"balance\" : -22.40000000000009\n },\n \"createdAt\" : ISODate(\"2016-10-28T10:06:47.367Z\"),\n \"updatedAt\" : ISODate(\"2016-10-28T10:06:47.367Z\")\n}\n\nThere are many document like this. I want the output as below distinct product name (cart.name) and its total qty\n{Casual Shirt , 30},\n{Cotton Pant , 10},\n{T-Shirt , 15},\n{Lower , 12}\n\nHere is my query trying to group by cart.name and sum qty\ndb.order.aggregate( [ \n{ $unwind: \"$cart\" }, \n{ $group: { \n _id: \"$cart.name\",\n totalQTY: { $sum:\"$cart.qty\"},\n count: { $sum: 1 }\n } \n} \n] )\n\nbut it displays wrong totalQty values for each product name. I checked manually.\nPlease give me the correct query.\n\nA:\n\n> db.collection.aggregate([\n... { $unwind: \"$cart\" },\n... { $group: { \"_id\": \"$cart.name\", totalQTY: { $sum: \"$cart.qty\" }, count: { $sum: 1 } } }\n... ])\n\nI get the following result: \n{ \"_id\" : \"Cotton Pant\", \"totalQTY\" : 2, \"count\" : 2 }\n{ \"_id\" : \"Casual Shirt\", \"totalQTY\" : 11, \"count\" : 2 }\n\nI'm not sure what you're looking for, it looks like your aggregation pipeline is correct. (Note I changed the Casual Shirt Quantity to be 10 and 1 respectively)\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29125,"cells":{"text":{"kind":"string","value":"Q:\n\nfusion-tables, help needed with getting latest data from a table and inserting it in maps code\n\nHi all trying to find the code to pull the latest co-ordinates from a google fusion table and insert it into the code below as the origin. (var origin1)\nGOOGLE Fusion table setup;\n {\n \"kind\": \"fusiontables#columnList\",\n \"totalItems\": 15,\n \"items\": [\n {\n \"kind\": \"fusiontables#column\",\n \"columnId\": 0,\n \"name\": \"description\",\n \"type\": \"STRING\"\n },\n {\n \"kind\": \"fusiontables#column\",\n \"columnId\": 1,\n \"name\": \"kind\",\n \"type\": \"STRING\"\n },\n {\n \"kind\": \"fusiontables#column\",\n \"columnId\": 2,\n \"name\": \"name\",\n \"type\": \"STRING\"\n },\n {\n \"kind\": \"fusiontables#column\",\n \"columnId\": 3,\n \"name\": \"placeId\",\n \"type\": \"STRING\"\n },\n {\n \"kind\": \"fusiontables#column\",\n \"columnId\": 4,\n \"name\": \"info1\",\n \"type\": \"STRING\"\n },\n {\n \"kind\": \"fusiontables#column\",\n \"columnId\": 5,\n \"name\": \"info2\",\n \"type\": \"STRING\"\n },\n {\n \"kind\": \"fusiontables#column\",\n \"columnId\": 6,\n \"name\": \"info3\",\n \"type\": \"STRING\"\n },\n {\n \"kind\": \"fusiontables#column\",\n \"columnId\": 7,\n \"name\": \"info4\",\n \"type\": \"STRING\"\n },\n {\n \"kind\": \"fusiontables#column\",\n \"columnId\": 8,\n \"name\": \"accuracy\",\n \"type\": \"NUMBER\"\n },\n {\n \"kind\": \"fusiontables#column\",\n \"columnId\": 9,\n \"name\": \"speed\",\n \"type\": \"NUMBER\"\n },\n {\n \"kind\": \"fusiontables#column\",\n \"columnId\": 10,\n \"name\": \"heading\",\n \"type\": \"NUMBER\"\n },\n {\n \"kind\": \"fusiontables#column\",\n \"columnId\": 11,\n \"name\": \"altitude\",\n \"type\": \"NUMBER\"\n },\n {\n \"kind\": \"fusiontables#column\",\n \"columnId\": 12,\n \"name\": \"altitudeAccuracy\",\n \"type\": \"NUMBER\"\n },\n {\n \"kind\": \"fusiontables#column\",\n \"columnId\": 13,\n \"name\": \"timestamp\",\n \"type\": \"NUMBER\"\n },\n {\n \"kind\": \"fusiontables#column\",\n \"columnId\": 14,\n \"name\": \"geometry\",\n \"type\": \"LOCATION\"\n }\n ]\n }\n\nand here is some of the data it keeps, i am trying to get the \"LATEST\" geometry coordinates and add that my map, to provide realtime updates.\n{\n \"kind\": \"fusiontables#sqlresponse\",\n \"columns\": [\n \"description\",\n \"kind\",\n \"name\",\n \"placeId\",\n \"info1\",\n \"info2\",\n \"info3\",\n \"info4\",\n \"accuracy\",\n \"speed\",\n \"heading\",\n \"altitude\",\n \"altitudeAccuracy\",\n \"timestamp\",\n \"geometry\"\n ],\n \"rows\": [\n [\n \"\",\n \"\",\n \"Location at Mon 14/05/2012 13:42:58\",\n \"\",\n \"resourceasstring\",\n \"\",\n \"\",\n \"\",\n \"65\",\n NaN,\n NaN,\n NaN,\n NaN,\n 1.336966978085E12,\n {\n \"geometry\": {\n \"type\": \"Point\",\n \"coordinates\": [\n 144.9339931215855,\n -37.83169408321385,\n 0.0\n ]\n }\n }\n ],\n [\n \"\",\n \"\",\n \"Location at Mon 14/05/2012 19:20:11\",\n \"\",\n \"resourceasstring\",\n \"\",\n \"\",\n \"\",\n \"1414\",\n NaN,\n NaN,\n NaN,\n NaN,\n 1.336987211753E12,\n {\n \"geometry\": {\n \"type\": \"Point\",\n \"coordinates\": [\n 145.2516605102396,\n -37.92732182161065,\n 0.0\n ]\n }\n }\n ],\n [\n \"\",\n \"\",\n \"Location at Mon 14/05/2012 19:40:12\",\n \"\",\n \"resourceasstring\",\n \"\",\n \"\",\n \"\",\n \"1414\",\n NaN,\n NaN,\n NaN,\n NaN,\n 1.336988412041E12,\n {\n \"geometry\": {\n \"type\": \"Point\",\n \"coordinates\": [\n 145.3447657261889,\n -37.91152087158031,\n 0.0\n ]\n }\n }\n ],\n [\n \"\",\n \"\",\n \"Location at Tue 15/05/2012 09:41:57\",\n \"\",\n \"resourceasstring\",\n \"\",\n \"\",\n \"\",\n \"65\",\n NaN,\n NaN,\n NaN,\n NaN,\n 1.337038917553E12,\n {\n \"geometry\": {\n \"type\": \"Point\",\n \"coordinates\": [\n 144.9339498133275,\n -37.8317148043096,\n 0.0\n ]\n }\n }\n ],\n\nThis is the html/java code that display's the map;\n \n \n \n Google Maps API v3 Example: Distance Matrix\n \n\n \n\n \n \n \n \n
\n
\n    This will automatically calculate distances on load and then will re-load every minute. hahaha...\n    Really need to work out how to pull data from a fusion table as well.\n          
\n

\n
\n
\n
\n \n \n\nthx\nmatt.\n\nA:\n\nProof of concept:\nhttp://www.geocodezip.com/v3_GoogleEx_FusionTables_latestData.html\nUses the FusionTables API v1.0 to query the table for the data; creates a native Google Maps API v3 marker for the \"latest\" location (the one with the greatest value in the timestamp column).\nNote that if you have lots of markers or only markers you may want to modify the approach.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29126,"cells":{"text":{"kind":"string","value":"Q:\n\nGCC's extended version of asm\n\nI never thought I'd be posting an assembly question. :-) \nIn GCC, there is an extended version of the asm function. This function can take four parameters: assembly-code, output-list, input-list and overwrite-list. \nMy question is, are the registers in the overwrite-list zeroed out? What happens to the values that were previously in there (from other code executing). \nUpdate: In considering my answers thus far (thank you!), I want to add that though a register is listed in the clobber-list, it (in my instance) is being used in a pop (popl) command. There is no other reference.\n\nA:\n\nNo, they are not zeroed out. The purpose of the overwrite list (more commonly called the clobber list) is to inform GCC that, as a result of the asm instructions the register(s) listed in the clobber list will be modified, and so the compiler should preserve any which are currently live.\nFor example, on x86 the cpuid instruction returns information in four parts using four fixed registers: %eax, %ebx, %ecx and %edx, based on the input value of %eax. If we were only interested in the result in %eax and %ebx, then we might (naively) write:\nint input_res1 = 0; // also used for first part of result \nint res2;\n__asm__(\"cpuid\" : \"+a\"(input_res1), \"=b\"(res2) ); \n\nThis would get the first and second parts of the result in C variables input_res1 and res2; however if GCC was using %ecx and %edx to hold other data; they would be overwritten by the cpuid instruction without gcc knowing. To prevent this; we use the clobber list:\nint input_res1 = 0; // also used for first part of result \nint res2;\n__asm__(\"cpuid\" : \"+a\"(input_res1), \"=b\"(res2)\n : : \"%ecx\", \"%edx\" );\n\nAs we have told GCC that %ecx and %edx will be overwritten by this asm call, it can handle the situation correctly - either by not using %ecx or %edx, or by saving their values to the stack before the asm function and restoring after. \nUpdate:\nWith regards to your second question (why you are seeing a register listed in the clobber list for a popl instruction) - assuming your asm looks something like:\n__asm__(\"popl %eax\" : : : \"%eax\" );\n\nThen the code here is popping an item off the stack, however it doesn't care about the actual value - it's probably just keeping the stack balanced, or the value isn't needed in this code path. By writing this way, as opposed to:\nint trash // don't ever use this.\n__asm__(\"popl %0\" : \"=r\"(trash));\n\nYou don't have to explicitly create a temporary variable to hold the unwanted value. Admittedly in this case there isn't a huge difference between the two, but the version with the clobber makes it clear that you don't care about the value from the stack.\n\nA:\n\nIf by \"zeroed out\" you mean \"the values in the registers are replaced with 0's to prevent me from knowing what some other function was doing\" then no, the registers are not zeroed out before use. But it shouldn't matter because you're telling GCC you plan to store information there, not that you want to read information that's currently there.\nYou give this information to GCC so that (reading the documentation) \"you need not guess which registers or memory locations will contain the data you want to use\" when you're finished with the assembly code (eg., you don't have to remember if the data will be in the stack register, or some other register).\nGCC needs a lot of help for assembly code because \"The compiler ... does not parse the assembler instruction template and does not know what it means or even whether it is valid assembler input. The extended asm feature is most often used for machine instructions the compiler itself does not know exist.\"\nUpdate\nGCC is designed as a multi-pass compiler. Many of the passes are in fact entirely different programs. A set of programs forming \"the compiler\" translate your source from C, C++, Ada, Java, etc. into assembly code. Then a separate program (gas, for GNU Assembler) takes that assembly code and turns it into a binary (and then ld and collect2 do more things to the binary). Assembly blocks exist to pass text directly to gas, and the clobber-list (and input list) exist so that the compiler can do whatever set up is needed to pass information between the C, C++, Ada, Java, etc. side of things and the gas side of things, and to guarantee that any important information currently in registers can be protected from the assembly block by copying it to memory before the assembly block runs (and copying back from memory afterward).\nThe alternative would be to save and restore every register for every assembly code block. On a RISC machine with a large number of registers that could get expensive (the Itanium has 128 general registers, another 128 floating point registers and 64 1-bit registers, for instance).\nIt's been a while since I've written any assembly code. And I have much more experience using GCC's named registers feature than doing things with specific registers. So, looking at an example:\n#include \n\nlong foo(long l)\n{\n long result;\n asm (\n \"movl %[l], %[reg];\"\n \"incl %[reg];\"\n : [reg] \"=r\" (result)\n : [l] \"r\" (l)\n );\n return result;\n}\n\nint main(int argc, char** argv)\n{\n printf(\"%ld\\n\", foo(5L));\n}\n\nI have asked for an output register, which I will call reg inside the assembly code, and that GCC will automatically copy to the result variable on completion. There is no need to give this variable different names in C code vs assembly code; I only did it to show that it is possible. Whichever physical register GCC decides to use -- whether it's %%eax, %%ebx, %%ecx, etc. -- GCC will take care of copying any important data from that register into memory when I enter the assembly block so that I have full use of that register until the end of the assembly block.\nI have also asked for an input register, which I will call l both in C and in assembly. GCC promises that whatever physical register it decides to give me will have the value currently in the C variable l when I enter the assembly block. GCC will also do any needed recordkeeping to protect any data that happens to be in that register before I enter the assembly block.\nWhat if I add a line to the assembly code? Say:\n\"addl %[reg], %%ecx;\"\n\nSince the compiler part of GCC doesn't check the assembly code it won't have protected the data in %%ecx. If I'm lucky, %%ecx may happen to be one of the registers GCC decided to use for %[reg] or %[l]. If I'm not lucky, I will have \"mysteriously\" changed a value in some other part of my program.\n\nA:\n\nI suspect the overwrite list is just to give GCC a hint not to store anything of value in these registers across the ASM call; since GCC doesn't analyze what ASM you're giving it, and certain instructions have side-effects that touch other registers not explicitly named in the code, this is the way to tell GCC about it. \n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29127,"cells":{"text":{"kind":"string","value":"Q:\n\nWhat was the Democrats' counter to REDMAP?\n\nFor the 2010 elections, Republicans created the Redistricting Majority Project (REDMAP) with the plan of flipping state legislative chambers to take control of the redistricting process. Did the Democrats have a similar organization, and if so what was it called?\n(Note: I don't consider the DSLC an equivalent group, as the Republicans also had the RSLC in 2010 but that never seems to get mentioned in analysis.)\n\nA:\n\nThe DSLC has launched Advantage 2020, which seeks to be an answer to REDMAP, which will also be launching REDMAP 2020. \nMore info: http://www.dlcc.org/advantage-2020 \n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29128,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to prevent pcre(C library) to continue matching when it failed in one string?\n\nIf I have a string and a pattern: \nchar src[]=\"\\\"http://www.aaa.cn\\\"\\\"www.bbb.com\\\"\"; \nchar pattern[] = \"\\\"http:\\/\\/.*\\.com\\\"\"; \n\nThen it returns \"http://www.aaa.cn\\\"\\\"www.bbb.com\" to me (it failed but continue matching next characters).\nI just want some like \"http://www.aaa.com\", \"http://www.bbb.com\", not like that combined string.\nCan someone help me out? Should I change my pattern or add some arguments to pcre_compile() and pcre_exec() functions?\n\nA:\n\nTry this.\nchar pattern[] = \"\\\"http://[^\\\"]*\\\"\";\n\nBetter yet, don't parse HTML (or fragments thereof or XML) with regexen.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29129,"cells":{"text":{"kind":"string","value":"Q:\n\nIn graph's axis, can we say \"somewhere between year1 and year2\"?\n\nHere is a graph I get somewhere in the internet for illustration:\n\nCan I say\n\nSomewhere between 2006 and 2010, first three lines raise significantly\n\n...?\nIf we mention about lines, I think using somewhere is not wrong. But if we using the legends directly, can I use somewhere or I have to use some times?\nI find that we can use somewhere down the road and some times down the road at the same time.\n\nA:\n\nAs you are referring to a graph, where the lines are physically drawn on a piece of paper (or on a computer screen or whatever), there is clearly a \"where\", the place on the graph where the lines begin going up. So \"somewhere between 2006 and 2010\" is perfectly acceptable and is literally accurate. There is a place on the graph between the place marked 2006 and the place marked 2010, etc.\nIf you were just talking of this trend generally, without reference to a graph, it would be more correct to say \"some time between\". But people often do say \"somewhere between\" in that context. Perhaps they are thinking of a graph or perhaps their language is just getting a little sloppy.\nBTW \"first three lines\" requires an article. It should be \"THE first three lines\". And we don't say that a trend \"raises\", we say that it \"rises\". So the sentence should be, \"Somewhere between 2006 and 2010, the first three lines rise significantly.\"\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29130,"cells":{"text":{"kind":"string","value":"Q:\n\nWhy is “de” used in “il n'y a pas de bus direct”?\n\nI would need help in order not to mix up de and le or un\n(What article can I use to refer to a thing correctly?)\nI came across this sentence \n\nIl n'y a pas de bus direct?\n\nBut I couldn't understand why le wasn't used (or for that matter un, if you don't want to refer to a particular bus). \nY avoir doesn't seem to be in this list of verbs that are succeeded by «de» here http://french.about.com/od/grammar/a/preposition_de_3.htm\n\nA:\n\nThere are some situations, and negative sentences are one of them, where de is used instead of des (which is in this context the plural of un, there may be several direct busses).\n\nIl y a des bus directs.\nIl n'y a pas de bus directs.\n\n(Note the plural for directs in both sentences).\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29131,"cells":{"text":{"kind":"string","value":"Q:\n\nHow could i change the Text of an label by a function?\n\nI have a Label on my Windows Forms, and I want to change the Text of it by a Button2_Click, but only if an another Button clicked before.\nExample Code:\nbool var1 = false;\n//the Label Example\nlabel1.Text = \"Noooh!\";\n\nprivate void Button2_Click(object sender, EventArgs e)\n{\n function1(label1.Text);\n}\n\nprivate void Button1_Click(object sender, EventArgs e)\n{\n var1 = true;\n}\n\nprivate void function1(string Text)\n{\n if (var1)\n {\n Text = \"Yeaaah!\";\n }\n}\n\nIt should work like this, you need to click on the button1 first, after this you should click button2 by this the function1 should be activated and change the label1 Text to \"Yeaaah!\". The Code is executed in Visual Studio but the label1 Text doesn't change, don't know why.\n\nA:\n\nChange function's (techically, we call it method, not function) design, pass Control (e.g. label1), not its Text:\nprivate void Button2_Click(object sender, EventArgs e)\n{\n // we modify control...\n function1(label1);\n}\n\nprivate void function1(Control ctrl)\n{\n if (var1)\n {\n // ... control's Text to be exact\n ctrl.Text = \"Yeaaah!\";\n }\n}\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29132,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to write an if statement that's always true without using any variables and operators?\n\nHow to write an if condition without using variables and operators? The condition should always be true.\nif(condition)\n{\n executable statements;\n}\n\nA:\n\nJust use any non-zero number to fill the condition in if statement\n\nExamples:\nif(1), if(2), .....so on\nsimilarly\nif(-1), if(-2), .....so on\n\nThese would be held true for all cases except if(0)\nReason: You can fill the condition with any value except 0. The reason for this is that generally in C, \n\n0 is returned by a false condition\n\nand so if you enter a 0, C skips the if block terating the condition to be false.\nso your code would be:\nif(1) //I just considered 1\n{\n executable statements;\n}\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29133,"cells":{"text":{"kind":"string","value":"Q:\n\nWhat ASP.NET MVC 3 CMS Provides Multi-language support?\n\nWhat Content Management Systems are built in ASP.NET MVC, are preferably open-source, and provide multi-language support?\n\nA:\n\nI asked a similar question around CMS choice some time ago: Edit in Place CMS Suggestions\nHaving tried several I would say that Umbraco CMS is the way to go - Umbraco 5 (currently in pre-production) is written on MVC 3\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29134,"cells":{"text":{"kind":"string","value":"Q:\n\nAllow Tabbing in a contentEditable div with execCommand\n\nI am making an application where I need for a contentEditable div to be allowed to have tabs in it. I have already figured out that it is really not possible to have to work correctly. So is there a way that on keyDown it adds the HTML code for a tab, which is\n&#09;\n\nWhat I have so far is this\ndocument.getElementById('codeline').contentEditable='true';\ndocument.getElementById('codeline').onkeydown=function(e){\n if(e.keyCode==9){\n e.preventDefault();\n //document.getElementById('codeline').contentWindow.document.execCommand(\"InsertHTML\",false,\"&#09;\"); \n //Thought this would work but it doesn't\n }\n}\n\nIf anybody knows if there is a way to do this, or if that is the way and I am simply doing it wrong, please tell me! Thanks!\n\nA:\n\nThe HTML spec specifies that a TAB char should be treated as a single white space except for when it's contained inside a
 element. \nThe code that you posted above does work and it does insert a TAB char but it's just displayed by the browser as a white space. If you can put your entire editable content in a 
 tag then your tabs will show up. \nIf you only want to use the tabs to indent content, you can also look into \nexecCommand('indent', false, null)\n\nA:\n\nFor future readers, perhaps a simpler solution is to just use the 'pre' white-space style. original post here.\nwhite-space: pre;\n\n"},"meta":{"kind":"string","value":"{\n  \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29135,"cells":{"text":{"kind":"string","value":"Q:\n\nRegular expression to transform 1.2.3 to 1.02.03\n\ni'm really not good with regular expressions and i need one to transform \"1.2.3\" to \"1.02.03\" in a way that first part stays always as it was and second and third one will transform 2 to 02, 7 to 07 and so on but if there is 10, 15, 17 and so on  it will leave it as it is. I want to use it in msbuild.\nsamples:\n2.5.7  -> 2.05.07\n2.10.9 -> 2.10.09\n1.7.18 -> 1.07.18\n\nThanks.\n\nA:\n\n/\\.(\\d)(?=\\D|$)/g  =>  .0$1\n\nWorks with any number of dots :)\nEdit: when look-ahead isn't supported but word boundaries are, you can use\n/\\.(\\d)\\b/g  =>  .0$1\n\n... or just because it's simpler :)\n\n"},"meta":{"kind":"string","value":"{\n  \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29136,"cells":{"text":{"kind":"string","value":"Q:\n\nchmod 4755 (rwsr-xr-x) gives (rwxrwxrwx)\n\nI want to get the permissions of a program, call_shellcode (which calls shellcode), to be set to -rwsr-xr-x. When I run: \nsudo chmod 4755 call_shellcode\n\nthe permissions for some reason is still set at -rwxrwxrwx\n\nI am trying to get the root shell, but when I execute the program I get a normal shell. I am using Ubuntu 16.04 (32-bit) in VirtualBox\n\nA:\n\nYou are running gcc as root for some strange reason, but then you run the chmod as your regular user. You don't have [permission to change the rights of call_shellcode since you compiled it as root, and therefore the permissions remain unchanged. \nDon't compile as root! Don't do anything as root unless you have to. \n\n"},"meta":{"kind":"string","value":"{\n  \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29137,"cells":{"text":{"kind":"string","value":"Q:\n\nPaper status changed from under review to Awaiting Decision\n\nI submitted my manuscript to a journal from 1 month ago in scholar one. The status changed to admin check to under review after one week. Now, it shows Awaiting Decision.  \nDoes this mean that the paper has passed the editorial check and the external reviewer completed?\n\nA:\n\nIf it has been \"under review\" for some time, then yes - the external reviewers are done. If you didn't see \"under review\", then the editor is making a decision without consulting reviewers, which is usually a bad sign.\n\n"},"meta":{"kind":"string","value":"{\n  \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29138,"cells":{"text":{"kind":"string","value":"Q:\n\nORDER BY with IF...ELSE SQL Server 2008 r2\n\nI've got a very basic problem that I'm trying to solve (basic to me, anyway), but I'm having trouble understanding why one bit of code works standalone, but when you wrap it in an IF statement, it doesn't.\nThis works just fine:\nSELECT DISTINCT H.FB FROM I_HSE H WHERE H.AC IN (@AC) ORDER BY H.FB\n\nHowever, when I try to make use of it in an IF statement:\nIF @FILTERBY = '2'\n  BEGIN\n    (SELECT DISTINCT H.FB FROM I_HSE H WHERE H.AC IN (@AC) ORDER BY H.FB)\n  END\n\nI get the error \"Incorrect syntax near the keyword 'ORDER'\nI've done some searching, but I can't seem to figure out why this doesn't work.  Is there another way to order the returned result set?\n\nA:\n\nTake the parenthesis off\nLike so:\nIF @FILTERBY = '2'\n  BEGIN\n    SELECT DISTINCT H.FB FROM I_HSE H WHERE H.AC IN (@AC) ORDER BY H.FB\n  END\n\n"},"meta":{"kind":"string","value":"{\n  \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29139,"cells":{"text":{"kind":"string","value":"Q:\n\noverwrite hdfs directory Sqoop import\n\nIs it possible to overwrite HDFS directory automatically instead of overwriting it every time manually while Sqoop import? \n(Do we have any option like \"--overwrite\" like we have for hive import \"--hive-overwrite\")\n\nA:\n\nUse --delete-target-dir \n​It will delete  provided in command before writing data to this directory. \n\nA:\n\nUse this: --delete-target-dir\nThis will work for overwriting the hdfs directory using sqoop syntax:\n$ sqoop import --connect jdbc:mysql://localhost/dbname --username username -P --table tablename --delete-target-dir --target-dir '/targetdirectorypath' -m 1\n\nE.g:\n$ sqoop import --connect jdbc:mysql://localhost/abc --username root -P --table empsqooptargetdel --delete-target-dir --target-dir '/tmp/sqooptargetdirdelete' -m 1\n\nThis command will refresh the corresponding hdfs directory or hive table data with updated/fresh data, every time this command is run.\n\n"},"meta":{"kind":"string","value":"{\n  \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29140,"cells":{"text":{"kind":"string","value":"Q:\n\nAssume $G$ is abelian. Prove that $p$ divides $|Z(G)|$.\n\nLet $G$ be a group and let $p$ be a positive prime number. Suppose $|G| = p^\nn$. for some positive integer $n$.\nI know to be abelian you have to be commutative, where $ab=ba$ and $a,b \\in$ a group. And we have that the center:  $Z(G) = \\{z ∈ G : ∀g \\in G, zg = gz\\}$. Its looks so easy to connect but I am not sure how to connect.\n\nA:\n\nSince $G$ is abelian, $G=Z(G)$, so it's obvious.\nBut I want to tell you that even if $G$ is not abelian the theorem also holds.\nIt follows from the Class Equation.\n\n"},"meta":{"kind":"string","value":"{\n  \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29141,"cells":{"text":{"kind":"string","value":"Q:\n\nWhy does the `describe` function display floats using scientific notation?\n\nData in a .csv file looks like this:\n\nBut when I am using function describe it shows me numbers in scientific notation?\nHow can I format them within describe function?\n\nA:\n\nYou can try following as mentioned in similar issue:\npd.set_option('float_format',lambda x: \"%.6f\" % x)\n\nFrom the document:\ndisplay.float_format : callable\n    The callable should accept a floating point number and return\n    a string with the desired format of the number. This is used\n    in some places like SeriesFormatter.\n    See formats.format.EngFormatter for an example.\n    [default: None] [currently: None]\n\n"},"meta":{"kind":"string","value":"{\n  \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29142,"cells":{"text":{"kind":"string","value":"Q:\n\nRunning bazel build with an aspect on test targets does not yield test output jars\n\nrunning bazel build //... \\\n--aspects some-aspect.bzl%some_aspect \\\n--output_groups=some_new_output,default\n does not create test jars outputs. \non the other hand running bazel test does create the test jar outputs:\nbazel test //... \\\n--aspects some-aspect.bzl%some_aspect \\\n--output_groups=some_new_output,default\n\nHow come?\nThis question was updated to reflect use of aspects:\nThe original question:\n\nrunning bazel build //... does not add test code to output jar. \non the other hand bazel test //... builds the test code but also\n  runs it.\nIs there a way in bazel to build the test code without running the\n  tests?\n\nA:\n\nI had a mistake in the values I gave the --output_groups flag.\nIt should have been --output_groups=+some_new_output,+default\nThe default can even be omitted:\n--output_groups=+some_new_output\nThis flag is not documented at all. There is an open issue on this in bazel github repo.\n\n"},"meta":{"kind":"string","value":"{\n  \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29143,"cells":{"text":{"kind":"string","value":"Q:\n\nSolving Boolean equations\n\n@Artes suggested this code to me to solve this system of equations:\n'x[a_, b_] := Boole[a >= b] \ny[a_, c_] := Boole[a >= c]\nz[b_, c_] := Boole[b >= c]\nSolve[ a == x[a, b] + y[a, c] && b == x[a, b] + z[b, c] && \n       c == y[a, c] + z[b, c], {a, b, c}]'\n\nWhat's the fastest way to get to the solution of x[a_, b_], which should be a parameter now.\nA problem which arised while coding the above was, that this code\n H[1, x_, y_] := 1 /; 10 - x - y >= p[B2] - y && 10 - x - y >= 0\nH[1, x_, y_] := 1 /; 6 - x > p[B2] - y && 6 - x >= 0\nH[1, x_, y_] := 0.5 /; 4 - x == p[B2] - y && 4 - x >= 0\nH[1, x_, y_] := 0 /; others\n\ndoesn't work for me. \nP[q_, w_] := 1 /; q > w  \nP[q_, w_] := 0 /; others  \nP[q_, w_] := 0.5 /; q == w \n\nThis code on the other hand works fine. So i suppose that \"others\" in the case of multiple conditions doesn't work any longer. Is there a solution?\n\nA:\n\nLet's define the following functions:\nx[a_, b_] := Boole[a >= b] \ny[a_, c_] := Boole[a >= c]\nz[b_, c_] := Boole[b >= c]\n\nIn fact we need only one function but for clarity of dealing with variables we have used three definitions, \nthen we rewrite the given system \nSolve[ a == x[a, b] + y[a, c] && b == x[a, b] + z[b, c] && \n       c == y[a, c] + z[b, c], {a, b, c}]\n\n{{a -> 0, b -> 1, c -> 1}, {a -> 2, b -> 2, c -> 2}}\n\nalternatively\nReduce[ a == x[a, b] + y[a, c] && b == x[a, b] + z[b, c] && \n        c == y[a, c] + z[b, c], {a, b, c}]\n\n(a == 0 && b == 1 && c == 1) || (a == 2 && b == 2 && c == 2)\n\n"},"meta":{"kind":"string","value":"{\n  \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29144,"cells":{"text":{"kind":"string","value":"Q:\n\n\"The fact of its being\" Grammar\n\n\"The fact of its being so rare a flower ought to have made it easier to trace the source of this particular specimen, but in practice it was an impossible task.\" \n\nI just found this sentence reading a book and it sounds weird to me. I understand the meaning, but I've never seen or studied this structure in English before. I did some research on the Internet but I could find nothing. Could anyone  explain the grammar? Could you please provide more examples with the same structure?  \n\nA:\n\nThat sentence sounds fine to me as an English speaker.\nA verb ending in -ing can function as a noun (usually called a 'gerund'). Example: 'His being late inconvenienced us all'\nNot the most common way to express it, but grammatically valid nonetheless. 'His' (and 'its' in your example) are adjectives modifying the gerund.\nAdding 'the fact of' is a tad redundant but also grammatically okay. It's just a prepositional phrase with the object 'its being'.\n\nso rare a flower\n\nThis is a construction in English that takes the form 'So [adjective] a [noun]'. The more colloquial way to express it would be 'such a [adjective] [noun]'.\nNeither of these constructions are very common in spoken English, or in plain writing.\n\n"},"meta":{"kind":"string","value":"{\n  \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29145,"cells":{"text":{"kind":"string","value":"Q:\n\nUse a type generated at runtime\n\nI've several classes which I'd like to select and instantiate at run time. For example:\npublic class MyClassA{ \n  public int property1 {get; set;}\n  public string property2 {get; set;}\n}\n\npublic class MyClassB{ \n  public int property1 {get; set;}\n  public string property3 {get; set;}\n}\n\nLet's say, MyClassB was selected at runtime: \nType t = Type.GetType(\"MyNamespace.MyClassB\");\nObject myType = Activator.CreateInstance(t);\n\nNow, i'd like to use myType as a type to pass to other classes/methods like this.\nmyType myDeserializedObject = JsonConvert.DeserializeObject(MyJsonString);\n\nCode never compiles throwing \"myType is a variable but is used like a type\" error.\nIs there any way or workaround to convert the activated instance to a type? Let me know if there is any other approach I should look into.\nThanks!\n\nA:\n\nYou cant pass in a variable Type as a generic. Instead use\nvar myDeserializedObject = JsonConvert.DeserializeObject(MyJsonString, t);\n\n"},"meta":{"kind":"string","value":"{\n  \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29146,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to measure the performance of a domain adaptation /Transfer learning technique?\n\nGiven that the performance you achieve depends on how far the target from the source domain is, how can you judge the performance of an algorithm?\n\nA:\n\nYou can measure the divergence between the source and target domain using KL-Divergence (there are some ways to estimate k-l divergence e.g. depdended on k-nn algorithm). Then you can check if there is a correlation between the divergence and the accuracy of the models considering a few cases of source-target pairs of datasets. You can compare several algorithms of Transfer Learning/Domain Adaptation using the same source-target datasets.\n\n"},"meta":{"kind":"string","value":"{\n  \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29147,"cells":{"text":{"kind":"string","value":"Q:\n\nCheckout maven project from SCM: disconnect and merge\n\nWhenever checking out Maven project from svn server in Eclipse, it creates a new folder like maven.xxxxxxxxxxxx under the target workspace. After specific time, it disconnected from SVN server.\nMy question is when the new checkout process is started again:- \nCan the next checking-out process merge to one of the existing folder maven.xxxxxxxxxxxx?\nAny input would be appreciated!!\n\nA:\n\nNo, not directly. This happens if something stops the import step. While I can not tell you wat exactly went wrong in your case, I can tell you how to solve it:\nRename the maven.xxxxxfolder in your workspace to the real project name.\nThe select File -> Import... -> Existing Maven Project and choose the project folder. The project will appear in your workspace as maven project.\nDepending on your eclipse configuration and plugins environment, you might also need to right-click on your new project and select Team -> Share... -> SVN (if there is a long list of options under Team, it is already correctly identifed as SVN project).\nUpdate\nIf your maven.xxxx folder is empty, than you seem to have connection problems. Split the checkout and the import part:\n\nSwitch to the \"SVN Repository Exploring\" perspective, create the repository (if not already there). Can you browse the repository? If not, you have a connection problem (proxy?).\nRight click your SVN project and select -> Checkout... \nSelect Check out as project in the workspace\nThis checks out the project as simple resource project\nnow back in the java perspective you can either delete the project and do an \"Import existing Maven Project\" or convert the project to a maven project using right-click -> Configure -> Convert to Maven project (exact command may vary with your m2e version).\n\nIf everything elese fails, try to checkout your project using TortoiseSVN (on Windows) or the commandline and doing \"import -> existing maven project\" afterwards.\n\n"},"meta":{"kind":"string","value":"{\n  \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29148,"cells":{"text":{"kind":"string","value":"Q:\n\nhow to call a module file in header file in opencart 2.0.1.1\n\nI have a module of facebook login. \nBut it could be add in content top or content bottom I want to add it in header for users. \nCould someone can tell me how to call a module named facebook_login.tpl as \n  in header.tpl file in Opencart 2.0.1.1.\n\nA:\n\nYou will call controller in header.php file. for eg. if you want to call controller of facebook_login.php file so you need to write code in header.php like : \n$data['facebook_login'] = $this->load->controller('common/facebook_login');\n\nand in header.tpl file you need to write code like :\n\n\nmaybe it will be helpful\nThanks\n\n"},"meta":{"kind":"string","value":"{\n  \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29149,"cells":{"text":{"kind":"string","value":"Q:\n\nCode generation for Java JVM / .NET CLR\n\nI am doing a compilers discipline at college and we must generate code for our invented language to any platform we want to. I think the simplest case is generating code for the Java JVM or .NET CLR. Any suggestion which one to choose, and which APIs out there can help me on this task? I already have all the semantic analysis done, just need to generate code for a given program.\nThank you\n\nA:\n\nFrom what I know, on higher level, two VMs are actually quite similar: both are classic stack-based machines, with largely high-level operations (e.g. virtual method dispatch is an opcode). That said, CLR lets you get down to the metal if you want, as it has raw data pointers with arithmetic, raw function pointers, unions etc. It also has proper tailcalls. So, if the implementation of language needs any of the above (e.g. Scheme spec mandates tailcalls), or if it is significantly advantaged by having those features, then you would probably want to go the CLR way.\nThe other advantage there is that you get a stock API to emit bytecode there - System.Reflection.Emit - even though it is somewhat limited for full-fledged compiler scenarios, it is still generally enough for a simple compiler.\nWith JVM, two main advantages you get are better portability, and the fact that bytecode itself is arguably simpler (because of less features).\n\n"},"meta":{"kind":"string","value":"{\n  \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29150,"cells":{"text":{"kind":"string","value":"Q:\n\nUnable to Reach a Value..... ReactJS\n\nI am currently having trouble accessing a value within a function. \nHere is my code:\ndistanceBool = (event) => {\n    console.dir(event);\n\n    let address = [\"Toronto, ON, CA\"];\n\n    let destination = [\"Vancouver\"];\n\n    let location = this;\n\n    let service = new window.google.maps.DistanceMatrixService();\n    new Promise((resolve)=>{\n      resolve(\n        service.getDistanceMatrix({\n        origins: [\"Waterloo ON\"],\n        destinations: destination,\n        travelMode: 'DRIVING',\n        avoidHighways: false,\n        avoidTolls: false\n      }, function(response, status){\n       if (status == 'OK') {\n         var origins = response.originAddresses;\n         var destinations = response.destinationAddresses;\n\n         for (var i = 0; i < origins.length; i++) {\n           var results = response.rows[i].elements;\n           for (var j = 0; j < results.length; j++) {\n             var element = results[j];\n             var distance = element.distance.text;\n             var duration = element.duration.text;\n             var from = origins[i];\n             var to = destinations[j];\n\n             location.distFinal = distance;\n\n             location.setState({\n               dist: distance\n             })\n\n           }\n         }\n\n       }\n     })\n\n      )\n    }).then((res)=>{\n      // console.log(res)\n      // console.dir(location);\n      console.dir(location);\n      console.dir(location.distFinal);\n      // console.log(\"hello\")\n    })\n\n}\n\nI am trying to access the distance so I did console.dir(location.distFinal) but it gave me an undefined value. \nHowever, when I did console.dir(location), it gave me the object with distFinal as a value.... \nThis is what I mean: \n\nLine 132 is the console.dir(location) and line 133 is console.dir(location.distFinal)\nPlease! I just want to be able to extract the distance!\n\nA:\n\nYour top-level promise resolves immediately - you probably want to resolve only once the asynchronous code inside finishes.\nnew Promise((resolve)=>{\n  service.getDistanceMatrix({\n    origins: [\"Waterloo ON\"],\n    destinations: destination,\n    travelMode: 'DRIVING',\n    avoidHighways: false,\n    avoidTolls: false\n  }, function(response, status){\n    if (status !== 'OK') return;\n    var origins = response.originAddresses;\n    var destinations = response.destinationAddresses;\n\n    for (var i = 0; i < origins.length; i++) {\n      var results = response.rows[i].elements;\n      for (var j = 0; j < results.length; j++) {\n        var element = results[j];\n        var distance = element.distance.text;\n        var duration = element.duration.text;\n        var from = origins[i];\n        var to = destinations[j];\n\n        location.distFinal = distance;\n        location.setState({\n          dist: distance\n        })\n      }\n    }\n    // all the looping is done:\n    resolve();\n  })\n}).then((res)=>{\n  // console.log(res)\n  // console.dir(location);\n  console.dir(location);\n  console.dir(location.distFinal);\n  // console.log(\"hello\")\n})\n\n"},"meta":{"kind":"string","value":"{\n  \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29151,"cells":{"text":{"kind":"string","value":"Q:\n\nReplacing a specified line in File\n\nI want to search for a item and then replace it's quantity. Is it possible to do it to a file?\nExample of text file:\napples\n10.2\nbanana\n20.5\noranges\n10\n\nSo when I input \"banana\" I want to be able to update the 20.5 to a different number.\n\nA:\n\nsince you haven't posted what you have done so far I can only give you pointers ;\n    # open the file -> check out python's open() function and the different modes , w+ opens the file for both writing ad reading\n     .... file_handle = open(\"yourtextfile\", \"w+\")\n    # check out readlines() function , it gives you back a list of lines , in the order of from the first line to the last\n  ..... the_lines = file_handle.readlines()\n  # remove newline '\\n' from every element in the list\n ..... new_list = [elem.strip() for elem in the_lines]\n    # look for existence of 'banana' in the new_list and going by the structure of the file you just posted edit the value next to the banana i.e 20.5\n.... for item in new_list:\n        if item == \"banana\":\n           index = new_list.index(item) + 1\n           new_list[index] = new_value\n           #add the newlines back\n           new_string = '\\n'.join(new_list)\n           file_handle.write(new_string)\n           file_handle.close()\n           break\n\n"},"meta":{"kind":"string","value":"{\n  \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29152,"cells":{"text":{"kind":"string","value":"Q:\n\nNo database selected, even though explictly stated\n\nI have a query running in a script, and when it's run in mysql workbench it works fine.\nHowever, running the script results in 'no database selected' error in powershell. I've followed the error prompts but you can see in my query I explicitly state the database for each table, i.e. (ambition.ambition_totals).\nIs there another constraint I should add to this?\n$stmt3 = mysqli_prepare($conn2,\n             \"UPDATE ambition.ambition_totals a\n                INNER JOIN \n                (SELECT \n                    c.user AS UserID,\n                    COUNT(*) AS dealers,\n                    ROUND((al.NumberOfDealers / al.NumberOfDealerContacts) * 100 ,2)  AS percent\n                FROM jfi_dealers.contact_events c\n                JOIN jackson_id.users u\n                ON c.user = u.id\n                JOIN jfi_dealers.dealers d\n                ON c.dealer_num = d.dealer_num\n                LEFT JOIN (\n                  SELECT user_id, COUNT(*) AS NumberOfDealerContacts,\n                  SUM(CASE WHEN ( d.next_call_date + INTERVAL 7 DAY) THEN 1 ELSE 0 END) AS NumberOfDealers\n                  FROM jackson_id.attr_list AS al\n                  JOIN jfi_dealers.dealers AS d ON d.csr = al.data\n                  WHERE al.attr_id = 14\n                  GROUP BY user_id) AS al\n                ON al.user_id = c.user\n                GROUP BY UserID) as cu\n                on cu.UserID = a.ext_id \n                SET a.dealers_contacted = cu.dealers,\n                  a.percent_up_to_date = cu.percent;\n                        \") or die(mysqli_error($conn2));\n\nA:\n\nSpecify the database name as the fourth parameter to mysqli_connect()\nHere's an example that assumes you're connecting on localhost:\n$conn2 = mysqli_connect(\"localhost\", \"your_username\", \"your_password\", \"ambition\");\n\nor do mysqli_select_db(\"ambition\") before your mysqli_prepare statement if ambition was not your default database.\n\n"},"meta":{"kind":"string","value":"{\n  \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29153,"cells":{"text":{"kind":"string","value":"Q:\n\nWhat java based CMS can manage existing pages' content?\n\nWe have an existing and running java web application, currently the pages' content is static but the pages are still jsp files, they have look and feel designed specifically.  My customer now wants to use CMS to manage the update of content like news, events with the minimal changes to the jsp code, I tried opencms and haven't found yet it can do that. As much as I know pages are needed to create through opencms ade in opencms world. The layout,look and feel must follow the pattern of opencms , that being said many block contents on pages.Is there any kind of CMS which can match my requirements out of the world?\n\nA:\n\nOpenCms and Magnolia are leading open source java-based CMS. They can do it, but of course there is some effort to it, which depends on the architecture of your current website.\nIf you're only, and really only, using JSPs in your current website, then you can just dump the JSPs into OpenCms, and that's it. Then you have the website within OpenCms, of course not yet editable, and then integrate the editable elements step by step, using structured content elements (XSDs). The process can't be described briefly in an answer here as it's quite complex, it definitely takes a bit of OpenCms experience to do it, as it's harder than building a OpenCms based website from scratch.\nIf your current application uses a framework like Spring, then there are additional steps to it. We've integrated Spring with OpenCms before and it works.\nI assume most java CMS will allow what you need, but it will take a bit of effort in all of them. Additionally, if you're using jars in your current application, you need to check that there are no conflicts between those and those of the OpenCms version you're using.\nAlternatively, you can just create your own small CMS functionality by implementing FCKEditor / CKEditor, if your CMS requirements are very basic.\nPlease provide some more details about your current technology stack / frameworks, etc. Then it's easier to answer in more detail.\nUpdate (2015):\nAs of 2015, I meanwhile moved from OpenCms to Magnolia, and would recommend that very much. Documentation is great an they explicitly have a module for Spring integration named Blossom. https://documentation.magnolia-cms.com/display/DOCS/Blossom+module.\n\n"},"meta":{"kind":"string","value":"{\n  \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29154,"cells":{"text":{"kind":"string","value":"Q:\n\nrecreating whole SQL Server Database with relations\n\ni have used SQL server 2012 and made a huge database with many relations. today i realized using \"NCHAR\" instead on \"NVARCHAR\" adds space on end of strings which i don't like it. is there any way to recreate database with relations. I've tried \"drop and create\" for tables but needs to remove all relations and define them again which is very time consuming.\n\nA:\n\nIt's possible to alter only the affected tables? like this:\nSELECT 'alter table '+s.name+'.'+t.name+\n' alter column '+c.name+' nvarchar('+convert(varchar(11),c.max_length/2)+') go'\nFROM    sys.tables as T\ninner join sys.schemas as s\non T.[schema_id]=s.[schema_id]\ninner join sys.columns as C\non T.[object_id]=C.[object_id]\nand c.system_type_id=239--nchar type\n\n, and before that don't forget to use the same kind of mechanism to generate an update statement to remove extra spaces.\n\n"},"meta":{"kind":"string","value":"{\n  \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29155,"cells":{"text":{"kind":"string","value":"Q:\n\nSyntaxError: illegal character when posting array to data attribute of highcharts\n\nI have a rails app that uses highcharts to display a line graph of 2 currencies. However when I run the app on my browser I keep getting the following error in firebug\nSyntaxError: illegal character\n data: #&lt;Forex::ActiveRecord_Relation:0xc743144&gt;\n\nI can't figure out what's wrong with my javascript code since it does not include the following after data attribute of highcharts\n#&lt \n\nHere is my code:\n
\n\n
\n\nI'm populating my data from a scope defined on forex.rb which is as follows\nscope :dollar, -> { where(:us_dollar != 0) }\nscope :british_pound, -> { where(:british_pound != 0 ) }\n\nI've done according to Santosh's answer:\n<% { \"Dollar\" => Forex.dollar, \"British Pound\" => Forex.british_pound }.each do |name, value| %>\n

<%= name == 'Dollar' ? a=value.pluck(:us_dollar) : b=value.pluck(:british_pound) %>

\n<% end %>\n\nBut this prints out 2 empty arrays while I have 2 values in my table attributes\nus_dollar: 88.27 and british_pound: 149.23\n\nA:\n\nYour scope syntax is wrong\nChange the conditions to \nwhere([\"us_dollar != ?\", 0])\n\nChange the data to\ndata: <%= name == 'Dollar' ? value.pluck(:us_dollar) : value.pluck(:british_pound) %>\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29156,"cells":{"text":{"kind":"string","value":"Q:\n\nsend dynamic table or div content as an email body content\n\nI have a page (somePage.aspx) and I need the content that has been generated as an Email body\n
\n \n \n \n \n \n \n \n <%\n if(edata != null)\n for (int idx=0;idx\n \">\n \n \n \n \n \n <%\n if (idx == edata.Count - 1)\n sendLog();\n }\n %>\n
\n name \n \n ID\n \n initial Stage\n \n current Stage\n
\n <% = row[\"name\"] %>\n \n <%= row[\"UserId\"]%>\n \n <%\n int uidForSrc = Convert.ToInt32(row[\"UserId\"]);\n string src = \"images/SignedOutNoFrame.png\";\n if (UserDidnotSignOutTimeOut(uidForSrc))\n src = \"images/didnotSignOut.png\";\n %>\n \" style=\"width:25px\" />\n \n <% \n string EexcSrc = \"\";\n string inputType =\"hidden\";\n //this updates if needed then returns true= needed update false = isn't need\n if (UpdatedTimeOutOKForUSER(uidForSrc))\n {\n inputType = \"image\";\n excSrc = \"/images/SignedOutNoFrame.png\";\n }\n %>\n \" src=\"<%=EexcSrc %>\" style=\"width:25px\" />\n
\n
\n\ncode for sendLog()\npublic void sendLog()\n{\n mail.aReciver=\"username@gmail.com\";\n mail.bSubject=\"ttest\";\n mail.cBody = DV_UsersInTblTime.InnerHtml;\n mail.HentalSend();\n}\n\nI can't get the value of content to assign mail.cBody with.\nIt's saying something about the value not being a literal etc'.\nThat is the method I'm using in an external class which works fine till this last attempt to add the functionality of page content as a body, how is it possible to achieve the result as needed here?\npublic static class mail\n{\n public static string aReciver, bSubject, cBody;\n public static void HentalSend()\n {\n string SmtpServer = \"smtp.gmail.com\";\n int port = 587;\n string sender = \"Sender@domain.com\";\n string ReCiver = aReciver;\n string Subject = bSubject;\n string Body = cBody;\n string account = \"mail@domain.com\";\n string Pass = \"123456\";\n Send(SmtpServer, port, account, Pass, sender, Receiver, Subject, Body);\n ... //send() is another relevant method to this question, it does rest of mail settings\n }\n}\n\nA:\n\nThis code will get the generated HTML of your dynamic control in to a string variable.\nStringBuilder stringBuilder = new StringBuilder();\nStringWriter writer = new StringWriter(stringBuilder);\nHtmlTextWriter htmlWriter = new HtmlTextWriter(writer);\ntry {\n DV_TimeReportWraper.RenderControl(htmlWriter);\n} catch (HttpException generatedExceptionName) {\n}\n\nstring DV_TimeReportWraper_innerHTML = stringBuilder.ToString();\n\nThen just use DV_TimeReportWraper_innerHTML as the body of your email\nYou might have to create a loop in case this control has children controls. More on that here: http://msdn.microsoft.com/en-us/library/htwek607.aspx#Y472\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29157,"cells":{"text":{"kind":"string","value":"Q:\n\nIs it correct to use citations as nouns for scientific papers, such as dissertations of articles?\n\nWhich of these two is better accepted, or preferred, for scientific papers?\nTHIS\nThe model detaches the calculation of the vertical velocity from the\nequations system, and focuses on the longitudinal velocities instead, leaving the model\nas a 2D equations system. [Mintgen, 2018] provides a description for the properties, characteristics and limitations of SWE in a detailed manner, some of which will be further addressed an extended for a deeper analysis in Section 2.1.\nOR\nThe model detaches the calculation of the vertical velocity from the\nequations system, and focuses on the longitudinal velocities instead, leaving the model\nas a 2D equations system. In his dissertation, Florian Mintgen [Mintgen, 2018] provides a description for the properties, characteristics and limitations of SWE in a detailed manner, some of which will be further addressed an extended for a deeper analysis in Section 2.1.\nOr if you have any other accepted way of doing it, please feel free. Thank you\nReferences\n[Mintgen, 2018] Mintgen, G. F. (2018). Coupling of Shallow and Non-Shallow Flow Solvers An\nOpen Source Framework. Dissertation, Technische Universitaet Muenchen, Muenchen.\n\nA:\n\nThere’s no unique answer to this as citation styles (in text or in bibliography) are somewhat personal or institutional. Some good ways of getting guidance include\n\nGet one or more previous theses on the same topic and follow those models,\nLook up established journals in the field and use their models (if they have a common one).\n\nI personally prefer your second alternative but would then use numbered referencing to avoid name repetition, v.g. “In his dissertation [1], Mintgen ...”\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29158,"cells":{"text":{"kind":"string","value":"Q:\n\nWhy does HashMap's get() compare both the hash value and key in Java?\n\nI was looking at the implementation of HashMap in JDK8. In the get methods, I saw the below line which is used to find the Node that matches with the given key. \nif (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))\n\nWhy is there the need to compare the hash value along with key? Why is the line above not written as:\nif (((k = e.key) == key) || (key != null && key.equals(k)))\n\nIs there any explanation on why it is done this way? Thank you.\n\nA:\n\nWhat seems to be causing your confusion, are two things:\n1. Comparing the hash values is (often very much) faster than comparing keys directly.\n2. In a == operator, the second condition won't be checked if the first is false.\nSo first the hash values are compared, which is fast:\n\nWhen they are not equal, you know the keys aren't equal as well, and you are done.\nWhen they are equal, you don't know if the keys are equal as well, so you must compare keys, which is (relatively) slow.\n\nSince most keys are not equal, most of the time you only compare hashes. Only when keys are equal (or when hashes are equal due to hash collisions) do you compare the keys, which is rare, and thus you have a performance benefit.\n\nA:\n\nThis is an efficient way to check if two values can possibly be equal.\nThe contract for hashcode mandates:\nJavaDocs of Object.hashCode\n\nIf two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. \n\nTherefore, if the hashes are distinct, there is not point in performing further checks.\nAs HashMap requires the hashcodes for the keys anyway for choosing the buckets to put the entries in, the tradeoff is storing an additional int per entry vs. possibly having to compute it repeatedly and having to execute equals for the keys more often. HashMap is more optimized for fast retrieval and insertion, less so for memory efficiency.\n\nSide Note: HashMap relies on keys not being mutated in any way that would change their \"identity\" in terms of equals and hashcode - while this may seem obvious, it is not explicitly mentioned in the JavaDocs for HashMap and has led to questions in the past: Are mutable hashmap keys a dangerous practice? - this is covered by the more general Map contract:\n\nNote: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29159,"cells":{"text":{"kind":"string","value":"Q:\n\nNginx location image\n\nЕсть папка с картинками site.com/upload/image1.png и я не могу добавить правило если по запросу картинки из папки upload нет, то выдать картинку (по умолчанию noimage.png) без изменения url\nПытался так №1:\nlocation /upload/ {\n try_files $uri /1_image_not_found.png;\n}\n\nПытался так №2:\nlocation /upload/ {\n error_page 404 /1_image_not_found.png;\n}\n\nТолку ноль вижу страницу 404\nUPD:\nПолностью конфиг\nUPD2: Изменил\nserver {\nlisten 443 ssl spdy;\nserver_name site.com www.site.com;\nresolver 8.8.8.8;\n\nssl on;\nssl_certificate /etc/nginx/ssl/site.com.crt;\nssl_certificate_key /etc/nginx/ssl/site.com.key;\nssl_session_timeout 5m;\nssl_session_cache shared:SSL:20m;\nssl_stapling on;\nssl_dhparam /etc/nginx/dhparam.pem;\nssl_protocols TLSv1 TLSv1.1 TLSv1.2;\nssl_ciphers HIGH:!aNULL:!MD5:!kEDH;\nssl_prefer_server_ciphers on;\n\nroot /home/site.com/public_html;\nindex index.php index.html index.htm;\n\naccess_log /dev/null;\nerror_log /home/site.com/logs/nginx.error.log;\n\nlocation = /favicon.ico { access_log off; log_not_found off; }\nlocation = /robots.txt { access_log off; log_not_found off; }\n\nlocation ~* \".+\\.(?:ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|rss|css|swf|js|atom|jpe?g|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$\" {\n access_log off;\n log_not_found off;\n expires max;\n}\n\nlocation / {\n try_files $uri $uri/ /index.php;\n}\n\nlocation ~ \\.php$ {\n limit_req zone=one burst=5;\n\n try_files $uri $uri/ =404;\n fastcgi_pass unix:/tmp/site.com;\n fastcgi_index index.php;\n fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;\n include fastcgi_params;\n}\n\nlocation /upload/ {\n try_files $uri /upload/1_image_not_found.png;\n}\n\nlocation ~ /\\. {\n deny all;\n access_log off;\n log_not_found off;\n return 404;\n}}\n\nA:\n\nlocation /upload/ {\n\n try_files $uri /upload/1_image_not_found.png;\n}\n\nUPD: После публикации полной конфигурации.\nNginx обходит location в определенном порядке. Сначала он ищет совпадения среди location заданных строками, в вашем случае максимально близкий это / и /upload/, но дальше nginx ищет среди location заданных регулярными выражениями. В вашем случае это будет строка где вы указываете всю статику, чтобы выключить журналирование добавить кэширование. Именно по этой причине не срабатывает изображение по умолчанию.\nОдин из вариантов решения сделать location /upload/ не строковой, а с помощью регулярных выражений. Например location ~ ^/upload/(.+). \nБолее подробно можно прочитать в инструкции nginx: Как nginx обрабатывает запросы \n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29160,"cells":{"text":{"kind":"string","value":"Q:\n\nIs this writing pattern called an attribution?\n\nI had posted this question under \"academic-writing\" and on there someone believes that it might be called \"attribution\". Can anyone confirm if this is correct or where I can find a reference?\n\nOriginal Question:\n\nI'm curious to know if this style of writing (pattern) has a name. They can sometimes take up almost a full paragraph giving background about a specific person or subject when introducing them into an article.\n\"At the Saturday briefing, Dr. Stephen Hahn, commissioner of the Food and Drug Administration, co-author of the critically acclaimed book \"XYZ\", told us that...\"\n\nA:\n\nIt is indeed an example of attribution.\nThis website lists 4 distinct styles of attribution, and your example is the first kind:\n\nOn the record: All statements are directly quotable and attributable, by name and title, to the person making the statement. This is the most valuable type of attribution.\n\nExample: \"The U.S. has no plans to invade Iran,\" said White House press secretary Jim Smith.\n\nYour statement is simply the reverse. Hope this helps!\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29161,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to update column by a long char in Oracle12c\n\nI want to update an HTML format, but the HTML format is too long to update. Furthermore, there are functions in this HTML format. it seems that Oracle recognized the characters as the replace() function\nUPDATE DS_ADPRODSET_FREETAG\nSET html=''\nWHERE adprodset_id=11111;\n\nthe Oracle asked me to replace the '&gt', but I just want the contents in XXX are characters.\n\nA:\n\nWhat follows & is recognised a substitution variable in IDEs like SQL developer and SQL* Plus\nAdd SET DEFINE OFF before running the query.\nCheckout this link to know more about substitution variable\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29162,"cells":{"text":{"kind":"string","value":"Q:\n\nMYSQL: Get result twice based on if statement\n\ni'm trying to get from each department from the dept table, the number of rich AND poor employees from the employee table.\nSo far I was able to get one of each but can't seem to figure how to get both rich and poor written on two rows for each dept.\nSELECT Depts.Department, IF (Employees.Salary>100000, 'Rich', 'Poor'), \nCOUNT(*) FROM `Employees`, `Depts` \nWHERE Depts.Dept = Employees.Dept \nGROUP BY Depts.Department\n\nthanks for any help\n\nA:\n\nincluding your IF logic in GROUP BY \nSELECT Depts.Department, IF (Employees.Salary>100000, 'Rich', 'Poor'), \nCOUNT(*) FROM `Employees`, `Depts` \nWHERE Depts.Dept = Employees.Dept \nGROUP BY Depts.Department, IF (Employees.Salary>100000, 'Rich', 'Poor')\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29163,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to use the labeling function of Prolog (ECLIPSE program) within the SEND+MORE = MONEY program?\n\nSo I managed to write the SEND + MORE = MONEY program for Prolog and I'm having trouble labeling the results. Any ideas on how to do that? I keep using the labeling function but it still wouldn't work. I'm lost here. \n:- lib(ic).\n\npuzzle(List) :-\n List = [S, E, N, D, M, O, R, Y],\n List :: 0..9,\n diff_list(List),\n 1000*S + 100*E + 10*N + D\n + 1000*M + 100*O + 10*R + E\n $= 10000*M + 1000*O + 100*N + 10*E + Y,\n S $\\= 0, M $\\= 0,\n shallow_backtrack(List).\n\nshallow_backtrack(List) :-\n ( foreach(Var, List) do once(indomain(Var)) ).\n\ndiff_list(List) :-\n ( fromto(List, [X|Tail], Tail, []) do\n ( foreach(Y, Tail), param(X) do\n X $\\= Y\n )\n ).\n\nResults:\n?- puzzle(X).\nX = [9, 5, 6, 7, 1, 0, 8, 2]\nYes (0.00s cpu)\n\nAny help would be appreciated! Thanks!\n\nA:\n\nHere is a variant of your program that uses labeling:\n:- lib(ic).\n\npuzzle(List) :-\n List = [S, E, N, D, M, O, R, Y],\n List :: 0..9,\n alldifferent(List),\n 1000*S + 100*E + 10*N + D\n + 1000*M + 100*O + 10*R + E\n $= 10000*M + 1000*O + 100*N + 10*E + Y,\n S $\\= 0, M $\\= 0,\n labeling(List).\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29164,"cells":{"text":{"kind":"string","value":"Q:\n\nthe fundamental differences of the way to overwrite getattr and setattr\n\nMy hope is to make attributes case-insensitive. But overwriting __getattr__ and __setattr__ are somewhat different, as indicated by the following toy example:\nclass A(object):\n\n x = 10\n\n def __getattr__(self, attribute):\n return getattr(self, attribute.lower())\n\n ## following alternatives don't work ##\n\n# def __getattr__(self, attribute):\n# return self.__getattr__(attribute.lower()) \n\n# def __getattr__(self, attribute):\n# return super().__getattr__(attribute.lower()) \n\n def __setattr__(self, attribute, value):\n return super().__setattr__(attribute.lower(), value)\n\n ## following alternative doesn't work ##\n\n# def __setattr__(self, attribute, value):\n# return setattr(self, attribute.lower(), value)\n\na = A()\nprint(a.x) ## output is 10\na.X = 2\nprint(a.X) ## output is 2\n\nI am confused by two points.\n\nI assume getattr() is a syntactic sugar for __getattr__, but they behave differently.\nWhy does __setattr__ need to call super(), while __getattr__ doesn't?\n\nA:\n\nI assume getattr() is a syntactic sugar for __getattr__, but they behave differently.\n\nThat's because the assumption is incorrect. getattr() goes through the entire attribute lookup process, of which __getattr__ is only a part. \nAttribute lookup first invokes a different hook, namely the __getattribute__ method, which by default performs the familiar search through the instance dict and class hierarchy. __getattr__ will be called only if the attribute hasn't been found by __getattribute__. From the __getattr__ documentation:\n\nCalled when the default attribute access fails with an AttributeError (either __getattribute__() raises an AttributeError because name is not an instance attribute or an attribute in the class tree for self; or __get__() of a name property raises AttributeError).\n\nIn other words, __getattr__ is an extra hook to access attributes that don't exist, and would otherwise raise AttributeError.\nAlso, functions like getattr() or len() are not syntactic sugar for a dunder method. They almost always do more work, with the dunder method a hook for that process to call. Sometimes there are multiple hooks involved, such as here, or when creating an instance of a class by calling the class. Sometimes the connection is fairly direct, such as in len(), but even in the simple cases there are additional checks being made that the hook itself is not responsible for.\n\nWhy does __setattr__ need to call super(), while __getattr__ doesn't?\n\n__getattr__ is an optional hook. There is no default implementation, which is why super().__getattr__() doesn't work. __setattr__ is not optional, so object provides you with a default implementation.\nNote that by using getattr() you created an infinite loop! instance.non_existing will call __getattribute__('non_existing') and then __getattr__('non_existing'), at which point you use getattr(..., 'non_existing') which calls __getattribute__() and then __getattr__, etc.\nIn this case, you should override __getattribute__ instead:\nclass A(object):\n x = 10\n\n def __getattribute__(self, attribute):\n return super().__getattribute__(attribute.lower())\n\n def __setattr__(self, attribute, value):\n return super().__setattr__(attribute.lower(), value)\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29165,"cells":{"text":{"kind":"string","value":"Q:\n\nIIS 7 manager not opening but working\n\nI have windows 7 home premium. I have turned on IIS .Confirmed if its running by typing localhost on my address bar. It show IIS welcome message, showing its working.\nHowever when I try to open IIS manager, nothing happens. I want to deploy my asp.net mvc 3 application on it. How do I solve this issue? \n\nA:\n\nFor me helped focusing on the window via Alt-Tab, then pressing Alt-Space and select Move in the drop-down menu. After that, either drag the mouse or move with keyboard buttons. By the way, works with all windows.\nUpdate for Win 10\nThere is another easier solution for such windows for Win 10. You can pull any available window to the left edge of the screen. Windows will expand the window to half of the screen and prompts you to choose any opened window to fill the second half. Choose the window you can't access and you're good.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29166,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to make method in data access class for parameterized query?\n\nI have created one method in data Access class to select data from database with parameter. I just want to use parameterized query.\nMethod Is :\npublic DataTable executeSelectQuery(String _query, SqlParameter[] sqlParameter)\n {\n SqlCommand myCommand = new SqlCommand();\n DataTable dataTable = new DataTable();\n dataTable = null;\n DataSet ds = new DataSet();\n try\n {\n myCommand.Connection = openConnection();\n myCommand.CommandText = _query;\n myCommand.Parameters.AddRange(sqlParameter);\n myCommand.ExecuteNonQuery();\n myAdapter.SelectCommand = myCommand;\n myAdapter.Fill(ds);\n dataTable = ds.Tables[0];\n }\n catch (SqlException e)\n {\n return null;\n }\n finally\n {\n myCommand.Connection = CloseConnection();\n }\n return dataTable;\n }\n\nbut I can't understand how to use this method to fetch data and how to pass parameter? \nMy query may be \"select password from tblUsers where email=@email\" How to pass @email at business layer?\nHow to make method in data access class for getting Scalar value?\npublic string getpasswrd(string unm)\n {\n con.Open();\n string cpaswrd;\n\n cmd1 = new SqlCommand(\"select password from tbl_login where username='\" + unm + \"'\", con);\n cpaswrd = (String)cmd1.ExecuteScalar();\n con.Close();\n return cpaswrd;\n\n }\n\nA:\n\n SqlParameter param;\n\n cmd1 = new SqlCommand(\"select password from tbl_login where username=@username, con);\n\n param = new SqlParameter(\"@username\", SqlDbType.VarChar);\n param.Direction = ParameterDirection.Input;\n param.Value = unm;\n cmd1.Parameters.Add(param);\n\n cpaswrd = cmd1.ExecuteScalar().ToString();\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29167,"cells":{"text":{"kind":"string","value":"Q:\n\nConfigure pylint for modules within eggs. (VS code)\n\nProject structure\nI have the following folder structure\n|\n|- src\n| |- mypackage\n| | |- __init__.py\n| | |- mymodule.py\n| |- utils.egg\n|- main.py\n\nin mymodule.py file I can import the egg adding it to the sys.path as \nimport sys\nsys.path.append('src/utils.egg')\nimport utils\n\nWhen calling main.py everything works fine (python -m main). \nProblem\nThe problem comes from pylint. First, it shows the following message in mymodule.py file\n\nUnable to import 'utils' pylint(import-error)\n\nif I ask for suggestions (CRTL + Space) when importing I got \nutils.build\n .dist\n .utils\n .setup\n# |- suggestions\n\nAnd from utils.utils I can acces the actual classes / functions in utils module. Of course if I import utils.utils, when executing the main script, an importing error pops up.\n\nHow can I configure my vscode setting in order fix pylint? \nshould I install the egg instead of copy it to the working folder? \nIs my project's folder-structure ok, or it goes against recommended practices?\n\nExtra info\nIn case you wonder the EGG-INFO/SOURCE.txt file looks like\nsetup.py\nutils/__init__.py\nutils/functions.py\nutils.egg-info/PKG-INFO\nutils.egg-info/SOURCES.txt\nutils.egg-info/dependency_links.txt\nutils.egg-info/top_level.txt\nutils/internals/__init__.py\nutils/internals/somemodule.py\nutils/internals/someothermodule.py\n\nAlso, there aren't build nor dist folder in the egg.\n\nA:\n\nThis is an issue with Pylint itself and not the Python extension, so it will come down to however you need to configure Pylint.\nAs for whether you should copy an egg around or install it, you should be installing it into your virtual environment, or at least copying over the appropriate .pth file to make the egg directory work appropriately.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29168,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to get a dynamic elements height in console\n\nStupid question I know but can't seem to get this working. Using Chrome console, I need to get the height of some elements (can do with inspector, but this has become personal) \nconsole.log$('#myDiv').height();\n\nreturns TypeError: Object # has no method 'log$'\nconsole.log $('#myDiv').height();\n\nreturns SyntaxError: Unexpected identifier\nI know this is simple, and Ive looked around but cant see the forrest for the trees at this point.\n\nA:\n\nconsole.log( $('#myDiv').height() )\n\nconsole.log is a function so you need parentheses to call it, passing as argument(s) what you want to output in the console.\nIf typing directly into the console directly, you can omit console.log:\n$('#myDiv').height()\n\nThe console automatically returns the last return value to your screen so you don't have to console.log when using the console.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29169,"cells":{"text":{"kind":"string","value":"Q:\n\nIncorporate string with list entries - alternating\n\nSo SO, i am trying to \"merge\" a string (a) and a list of strings (b):\na = '1234'\nb = ['+', '-', '']\n\nto get the desired output (c):\nc = '1+2-34'\n\nThe characters in the desired output string alternate in terms of origin between string and list. Also, the list will always contain one element less than characters in the string. I was wondering what the fastest way to do this is. \nwhat i have so far is the following:\nc = a[0]\nfor i in range(len(b)):\n c += b[i] + a[1:][i]\nprint(c) # prints -> 1+2-34\n\nBut i kind of feel like there is a better way to do this..\n\nA:\n\nYou can use itertools.zip_longest to zip the two sequences, then keep iterating even after the shorter sequence ran out of characters. If you run out of characters, you'll start getting None back, so just consume the rest of the numerical characters.\n>>> from itertools import chain\n>>> from itertools import zip_longest\n>>> ''.join(i+j if j else i for i,j in zip_longest(a, b))\n'1+2-34'\n\nAs @deceze suggested in the comments, you can also pass a fillvalue argument to zip_longest which will insert empty strings. I'd suggest his method since it's a bit more readable.\n>>> ''.join(i+j for i,j in zip_longest(a, b, fillvalue=''))\n'1+2-34'\n\nA further optimization suggested by @ShadowRanger is to remove the temporary string concatenations (i+j) and replace those with an itertools.chain.from_iterable call instead\n>>> ''.join(chain.from_iterable(zip_longest(a, b, fillvalue='')))\n'1+2-34'\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29170,"cells":{"text":{"kind":"string","value":"Q:\n\nVector graphics in LaTeX\n\nI need to add some vector graphics to my LaTeX files. I would like to end up with good looking wireframes, such as in Hatcher's book \"Algebraic Topology\" (for an example take a look here). Which tools would you recommend? Any help would be appreciated, thanks in advance.\nEDIT: The best thing would be to use an external tool, such as a 3d editor (just a simple one, which lets you easily model a 3d mesh from scratch) and then export the wireframe as a vector image. I don't know if something like this could exist. Tools like tikz or pstricks could do the job, but they are mainly suitable for flat drawings, and require more effort for 3d (drawing something like this could be very tedious).\n\nA:\n\nYou can use tikz or pstricks to draw diagrams from within a LaTeX document. Diagram drawing software capable of creating eps or pdf files (e.g. xfig (free) or Adobe Illustrator) will also yield good results.\nFor examples using TikZ (including 3D), see here.\n\nA:\n\nIpe is another drawing program you may want to consider. It has very nice TeX integration. Inkscape is yet another option; see this.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29171,"cells":{"text":{"kind":"string","value":"Q:\n\nIs there equivalent of WPF OriginalSource event property in Winform and ASP.NET?\n\nFrom:\nhttp://www.wpfwiki.com/WPF%20Q14.12.ashx\n\nThe OriginalSource property of the\n object identifies the original object\n that received/initiated the event. \nConsider a custom control (called\n CustomControl1 in this example) that\n is composed of a TextBlock. When a\n MouseDown event is raised on the\n TextBlock, the OriginalSource property\n will be the TextBlock, but in\n CustomControl1's handler, the Source\n will be changed to the CustomControl1\n object so that other elements along\n the event's route will know that\n CustomControl1 received a MouseDown.\n\nIs there equivalent of WPF OriginalSource event property in Winform and ASP.NET ? If not how to emulate this ?\n\nA:\n\nthe \"sender\" argument which is sent to the event does not comfort your case, since you need another object to determine the container object which raised the event.\nI emulate this by manually firing events either on server-side or on client-side through javascript.\nExample:\nif a Span was inside a Div, on the, let's say, click event of the span, I call the click event on its container the div here. And then, in the event handler, the argument will be the div not the span.\nHope that helps.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29172,"cells":{"text":{"kind":"string","value":"Q:\n\njava.lang.IllegalArgumentException: Comparison method violates its general contract! java.util.Date\n\njava.lang.IllegalArgumentException: Comparison method violates its general contract!\n at java.util.TimSort.mergeLo(TimSort.java:747)\n at java.util.TimSort.mergeAt(TimSort.java:483)\n at java.util.TimSort.mergeCollapse(TimSort.java:410)\n at java.util.TimSort.sort(TimSort.java:214)\n at java.util.TimSort.sort(TimSort.java:173)\n at java.util.Arrays.sort(Arrays.java:659)\n at java.util.Collections.sort(Collections.java:217)\n\nI am sorting a collection based on the following comparator.\npublic static Comparator CMP_TIME_DESC = new Comparator() {\n @Override\n public int compare(MyClass o1, MyClass o2) {\n return o2.getOrderSendTime().compareTo(o1.getOrderSendTime());\n }\n};\n\nThe values are always non-null.\nAnd the getOrderSendTime() object is of the java.util.Date class.\nI understand that this is a transitivity inconsistency, and I would assume a class like this would not have such issues. I searched for open issues, but did not find any on the topic.\nAny ideas?\n\nA:\n\nYour issue is related to this one: Sort algorithm changes in Java 7\nIt happens because the default sort algorithm has changed from MergeSort to TimSort.\nOne workaround is to add -Djava.util.Arrays.useLegacyMergeSort=true to the JVM environment.\nThe best option is to conform to the comparison general contract but I think you didn't provide enough information in your question for this. \n\nA:\n\nI had this same exception, and it happened when I had java.util.Date and java.sql.Timestamp objects in the same list/array when being sorted, running on Java8. (This mix was due to some objects being loaded from database records with the Timestamp data type, and others being created manually, and the objects having only a Date object in them.)\nThe exception also doesn't happen every time you sort the same data set, and it seems that there also have to be at least 32 of these mixed objects in the array for it to occur.\nIf I use the legacy sort algorithm, this also doesn't occur (see how in Ortomala Lokni's answer).\nThis also doesn't happen if you use only java.util.Date objects or only java.sql.Timestamp objects in the array.\nSo, the issue seems to be TimSort combined with the compareTo methods in java.util.Date and java.sql.Timestamp. \nHowever, it didn't pay for me to research why this is happening since it is fixed in Java 9!\nAs a workaround until Java9 is released and we can get our systems updated, we have manually implemented a Comparator that only uses getTime(). This seems to work fine.\nHere is code that can be used to reproduce the issue:\nimport java.sql.Timestamp;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Date;\nimport java.util.List;\nimport org.junit.Test;\n\npublic class TimSortDateAndTimestampTest {\n\n // the same test data with all Dates, all Timestamps, all Strings or all Longs does NOT fail.\n // only fails with mixed Timestamp and Date objects\n @Test\n public void testSortWithTimestampsAndDatesFails() throws Exception {\n List dates = new ArrayList<>();\n dates.add(new Timestamp(1498621254602L));\n dates.add(new Timestamp(1498621254603L));\n dates.add(new Timestamp(1498621254603L));\n dates.add(new Timestamp(1498621254604L));\n dates.add(new Timestamp(1498621254604L));\n dates.add(new Timestamp(1498621254605L));\n dates.add(new Timestamp(1498621254605L));\n dates.add(new Timestamp(1498621254605L));\n dates.add(new Timestamp(1498621254605L));\n dates.add(new Timestamp(1498621254606L));\n dates.add(new Timestamp(1498621254607L));\n dates.add(new Date(1498621254605L));\n dates.add(new Timestamp(1498621254607L));\n dates.add(new Timestamp(1498621254609L));\n dates.add(new Date(1498621254603L));\n dates.add(new Date(1498621254604L));\n dates.add(new Date(1498621254605L));\n dates.add(new Date(1498621254605L));\n dates.add(new Date(1498621254607L));\n dates.add(new Timestamp(1498621254607L));\n dates.add(new Date(1498621254608L));\n dates.add(new Timestamp(1498621254608L));\n dates.add(new Date(1498621254611L));\n dates.add(new Timestamp(1498621254612L));\n dates.add(new Timestamp(1498621254613L));\n dates.add(new Date(1498621254607L));\n dates.add(new Timestamp(1498621254607L));\n dates.add(new Timestamp(1498621254608L));\n dates.add(new Timestamp(1498621254609L));\n dates.add(new Timestamp(1498621254611L));\n dates.add(new Date(1498621254603L));\n dates.add(new Date(1498621254606L));\n\n for (int i = 0; i < 200; i++) {\n Collections.shuffle(dates);\n Collections.sort(dates);\n }\n }\n}\n\nEdit: I have removed the exception expectation so you can SEE it throwing when run.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29173,"cells":{"text":{"kind":"string","value":"Q:\n\nSchnorr identification protocol security proof\n\nI read about security proof of Schnorr identification protocol against impersonation attack. For the sake of comprehensibility let me sum up the protocol: Given group $G$ with generator $g$. Verifier is initialized by prover's public key $g^a$, where the knowledge of secret counterpart is to be proven by prover. The protocol runs as following:\n\nProver generates random $a_t\\in G$ and sends $g^{a_t}$ to verifier\nVerifier responds by sending random $c$ to the prover.\nProver responds by sending $a_z = a_t + c\\,a$\nVerifier checks whether $g^{a_z}\\overset{?}{=}g^{a_t}\\,(g^a)^c$\n\nNow, the idea of the security proof was: Given adversary $\\mathcal{A}$ being able to issue valid $a_z'$ against arbitrary public key $g^{a'}$, we can turn $\\mathcal{A}$ into an efficient $\\mathrm{DLog}\\,_g(g^{a'})$ oracle.\nThe proof assumed we can \"rewind\" the adversary so that it issues 2 different $a_z$'s with respect to a single $a_t$. I didn't understand this assumption. It seems somehow incomplete to me. What if I have non-cooperative adversary? This can't be turned into DLog oracle, since such adversary were indistinguishable from honest prover who knows secret key, thus breaking zero-knowledge protocol property. So is this a complete proof, which I merely didn't get or is the fact that malicious adversary might break the protocol without breaking DLog on $G$ essentially unprovable?\n\nA:\n\nIt is important to understand that the simulator is a non-interactive machine; it does not interact with the prover (or with anybody else). What it can do is mimic (or simulate) a real interaction between the prover and the verifier, by playing the roles of both parties and internally \"sending messages to itself\". But it is not required to mimic the protocol exactly, only to produce an output that is close enough to the output of a real execution of the protocol. This is why it can internally repeat the protocol many times until it obtains a satisfactory output; there is no need for the prover to \"cooperate\", since again the simulator does not interact with the prover.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29174,"cells":{"text":{"kind":"string","value":"Q:\n\nPHP/MySQL - Calculate Total for each Reservation\n\nI've got a Reservation application, and I'd like to calculate the total number of meals needed by reservations date span.\nMy database has fields:\n$name - Person reserving\n$chkin - Check in date (DATE yyyy-mm-dd)\n$chkout - Check out date (DATE yyyy-mm-dd)\n$guests - Number of people in group\n$meal - Eating meals (Yes/No)\n\nSo for each reservation I have:\n// Days of Stay\n$days = (strtotime($chkout) - strtotime($chkin)) / (60 * 60 * 24);\n\nWhat I'm not sure of is how to do the calculation for each reservation in the database.\nMy calculation for each reservation would be something like:\n$days * $guests\n\nI would appreciate advice on this query... I'm trying to give a snapshot of how many meals will be need to be prepared for a given month, weeekend, etc. \nThank you!\n\nA:\n\nYou can use the MYSQL date diff to achieve a count of the days, then this can be multiplied by the number of guests. Finally you will need to select a date range for this search. Below are the basics or the MYSQL needed in order to get these values. This should put you on the right track to achieving what you want.\nSELECT DATEDIFF(a.chkout,a.chkin) * a.guests as meals\nFROM table as a \nWHERE a.chkin > '0000-00-00' AND a.chkout < '0000-00-00\n\nI have tested this with a table of mine and it appears to be working correctly, however, without much data I can only test lightly. If you have any issues, leave a comment and I will try to help further.\nhttp://www.w3schools.com/sql/func_datediff.asp\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29175,"cells":{"text":{"kind":"string","value":"Q:\n\nPandas Combining data in two excel\n\nI have two excel\nExcel 1\nfiles language blank comment code\n15 C++ 66 35 354\n1 C/C++ Header 3 7 4\n\nExcel 2\nfiles language blank comment code\n16 C++ 33 35 354\n1 C/C++ Header 3 7 4\n1 Python 1 1 1\n\nTrying to get combined excel\nfiles language blank comment code\n31 C++ 99 70 708\n2 C/C++ Header 6 14 8\n1 Python 1 1 1\n\nAny tips in pandas\n\nA:\n\nUse concat with aggregate sum by groupby:\ndf = pd.concat([df1, df2]).groupby('language', as_index=False).sum()\nprint (df)\n language files blank comment code\n0 C++ 31 99 70 708\n1 C/C++ Header 2 6 14 8\n2 Python 1 1 1 1\n\nIf order of columns is important add reindex:\ndf=pd.concat([df1, df2]).groupby('language',as_index=False).sum().reindex(columns=df1.columns)\nprint (df)\n files language blank comment code\n0 31 C++ 99 70 708\n1 2 C/C++ Header 6 14 8\n2 1 Python 1 1 1\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29176,"cells":{"text":{"kind":"string","value":"Q:\n\nOn click the template data needs to be rendered in the same page\n\nI am trying to render the data(from the template) like hide(when back button is clicked) and show(when the view button is clicked) on the same HTML page. My code is below:\n

Saved Deals

\n

This includes deals which are in draft

\n

View »{{> saveddeals}}

\n\nA:\n\nYou could use Meteor Sessions, for example:\nif (Meteor.isClient) {\n Template.deals.helpers({\n showSavedDeals: function () {\n return Session.equals('showSavedDeals', true);\n }\n });\n Template.deals.events({\n 'click #viewsaveddeals': function () {\n Session.set('showSavedDeals', true);\n }\n });\n Template.deals.onDestroyed(function () {\n Session.set('showSavedDeals', null);\n });\n}\n\n\n\n\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29177,"cells":{"text":{"kind":"string","value":"Q:\n\nMoving data.table columns to rows based on conditions\n\nI have a large data.table that is set up like this:\nID Line.Rec Line.D.Amount Line.Desc Line1.Record Line1.D.Amount Line1.C.Amount Line2.Rec\n1 1 100 test 2 500 200 3\n2 1 200 testb 2 800 100 3\n3 1 600 testc 2 900 500 NA\n\nEach event/row contains an ID and other static columns such as Eventdate. But, there is a varying amounts of lines (potentially anywhere from 1 to 99). Lines contains varying amounts of columns as well. The lines are not fixed, and some files will have different lines than this one. Therefore, I have to use column names rather than position. \nI would like the data.table to look like this:\nID Record D.Amount C.Amount Description\n1 1 100 0 test\n1 2 500 200\n1 3 0 0 \n2 1 200 testb\n2 2 800 100 \n2 3 0 0 \n3 1 600 0 testc\n3 2 900 500 \n\nThe solution needs to be ensure that any column that matches first part of the name (line., line1., line2.,...line99.) are included in the correct row. The ID line (and EventDate) needs to be included as illustrated to make sure that I can trace which lines belong together.\nAny ideas?\n\nA:\n\nNot really a data.table question. You might want to consider changing the tag. Here is something that should get you started:\nlibrary(data.table)\ndt <- fread(\"ID Line.Rec Line.D.Amount Line.Desc Line1.Record Line1.D.Amount Line1.C.Amount Line2.Rec\n1 1 100 test 2 500 200 3\n2 1 200 testb 2 800 100 3\n3 1 600 testc 2 900 500 NA\")\n#ensure that relevant columns share the same names\nsetnames(dt, gsub(\"Rec$\", \"Record\", names(dt)))\n\n#identify which columns forms a sub dataset\notherCols <- setdiff(names(dt), \"ID\")\ngroupCols <- split(otherCols, sapply(strsplit(otherCols, \"\\\\.\"), `[`, 1))\nnewCols <- sapply(names(groupCols), \n function(x) gsub(paste0(x, \".\"), \"\", groupCols[[x]]))\n\n#take sub columns of original dataset by group \nsubDataLs <- lapply(names(groupCols),\n function(x) setnames(dt[, c(\"ID\", groupCols[[x]]), with=FALSE], \n c(\"ID\", newCols[[x]]))\n)\n\n#rbind sub datasets\noutput <- rbindlist(subDataLs, use.names=TRUE, fill=TRUE)\n\n#format to desired output\ncols <- names(output)[sapply(output, is.numeric)]\noutput[, (cols) := replace(.SD, is.na(.SD), 0), .SDcols=cols]\ncols <- names(output)[sapply(output, is.character)]\noutput[, (cols) := replace(.SD, is.na(.SD), \"\"), .SDcols=cols]\n\noutput:\n ID Record D.Amount Desc C.Amount\n1: 1 1 100 test 0\n2: 2 1 200 testb 0\n3: 3 1 600 testc 0\n4: 1 2 500 200\n5: 2 2 800 100\n6: 3 2 900 500\n7: 1 3 0 0\n8: 2 3 0 0\n9: 3 0 0 0\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29178,"cells":{"text":{"kind":"string","value":"Q:\n\nRemove note about bash that appears when opening the terminal\n\nI tried instaling ROOT by CERN by following steps described by certain people. But although that was unsuccessful, I keep getting the following line when I open a new terminal.\nbash: /home/USER/bin/thisroot.sh: No such file or directory\n\nHow can I remove that?\nEDIT- Please note, for those who have raised the doubts, that I have redacted my true username. And I wrote USER in that place.\n\nA:\n\nThere's probably an alias on your .bashrc or .bash_profile calling that file, so it tries to load it everytime you get a new prompt.\nTry editing them with one of these commands:\ngedit $HOME/.bashrc\ngedit $HOME/.bash_profile\ngedit $HOME/.profile\n\nLook for any line loading 'thisroot.sh' and comment it (write a # character at the begining of those lines). If you see after saving and opening a terminal that all works well, you can go ahead and directly deleting those lines.\nAlso, the way the script is being called sounds wrong, shouldn't it be /home/YOURUSERNAMEHERE/bin/thisroot.sh?\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29179,"cells":{"text":{"kind":"string","value":"Q:\n\nIn programming, when does it make sense to have 2 references to the same object (name ambiguity)\n\nIn programming, the standard practice is to give each object it's own unique name by assigning it's address to only one reference variable.\n\nIf we assign one reference variable to another reference variable, it creates two different names for the same thing. I was asked when doing this would be useful.\n\nWhen would using ambiguous names be useful? The only reason I could see for doing this is if you need to make a copy of an object's value to prevent overwriting.\n\nA:\n\nWhat you describe is not ambiguity, it's aliasing (specifically pointer aliasing).\nYou don't usually do it explicitly, but it can be very useful if you pass a reference/pointer to another method. Then at least two variables (the original one and the parameter) will reference the same object, but for different reasons.\nIf you do it explicitly, then it's usually because two variables take two different roles.\nFor example if you're writing code that traverses a tree, you usually start at the root. So the beginning of your code might look like this:\nTreeNode rootNode = getTreeRootFromSomewhere();\nTreeNode currentNode = rootNode;\nwhile (currentNode != null) {\n ...\n\nIn this case currentNode is obviously an alias for rootNode at this point. Later on we will certainly change what currentNode points to, but the first time you enter the loop they point to the same object.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29180,"cells":{"text":{"kind":"string","value":"Q:\n\nHive SQL Extract string of varying length between two non-alphanumeric characters\n\nI would like to extract strings of varying length located between two repeating underscores in Hive QL. Below I show a sampling of the pattern of the rows. Specifically, I would like to extract the string between the 3rd and 4th underscores. Thanks!\n2016_sadfsa_IL_THIS_xsdaf_asd_eventbyevent_tsaC_NA_300x250 \n2017_thisshopper_MA_THIS_NAT_Leb_ReasonsWhy_HDIMC_NA_300x600\n2017_FordShopper_IL_THESE_NAT_sov_winterEvent_HDIMC_NA_300x600 \n\nJust kept trying and I modified this from previous responses to non-Hive SQL. I am still interested in knowing better ways of doing this. Note that creative_str is the name of the column:\nselect creative_str, ltrim(rtrim(substring(regexp_replace(cast(creative_str as varchar(1000)), '_', repeat(cast(' ' as varchar(1000)),10000)), 30001, 10000))) \nfrom impression_cr\n\nA:\n\nYou should be able to do this with Hive's SPLIT() function. If you're trying to grab the value between the third and fourth underscores, this will do it:\nSELECT SPLIT(\"2016_sadfsa_IL_THIS_xsdaf_asd_eventbyevent_tsaC_NA_300x250\", \"[_]\")[3],\n SPLIT(\"2017_thisshopper_MA_THIS_NAT_Leb_ReasonsWhy_HDIMC_NA_300x600\", \"[_]\")[3],\n SPLIT(\"2017_FordShopper_IL_THESE_NAT_sov_winterEvent_HDIMC_NA_300x600\", \"[_]\")[3]\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29181,"cells":{"text":{"kind":"string","value":"Q:\n\nHow many 3 dB couplers are needed to construct a 16 way fiber optic splitter?\n\nWikipedia says we need 31 couplers. Can't we do it with 8 couplers?\n\nA:\n\nFollow the math in the wiki article: (2^4)-1=15.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29182,"cells":{"text":{"kind":"string","value":"Q:\n\njQuery autocomplete - IE8 issue - this tab has been recovered\n\nI run into a problem with jQuery UI - Autocomplete and IE8.\nI'm using combobox method which you can find on jQuery UI website - here\n\nBasically, it is creating autocomplete input + select menu from select/option list.\nI'm using jQuery 1.6.4 and jQuery UI 1.8.16; both from google server.\nIt is working perfectly on Chrome / FF / Opera, but does not work on IE8.\nOn IE8 - once you select something (after typing), or use dropdown button IE will reload the page. Please not that IE will not crash till you use arrows or try to select something.\n\nres://ieframe.dll/acr_error.htm#, in the URL, in front of the actual path\nor a message this tab has been reloaded; a problem with the page causes IE to close and reopen the page\n\nLive example here\nAny idea what is causing IE to act like that? Any suggestion much appreciated.\n\njQuery code:\n \n\nA:\n\nI'm still trying to work out why IE8 is crashing but it does work for me when you add a jQueryUI theme to the page, for example:\n\n\nEdit: I think I know which line it is crashing on, but I still do not know why! In the jQueryUI code activate: function( event, item ) {\nis the following code which adds style and an attribute to the active item.\nthis.active = item.eq(0)\n .children(\"a\")\n .addClass(\"ui-state-hover\")\n .attr(\"id\", \"ui-active-menuitem\")\n .end();\n\nFor some reason, IE8 crashes here, although for me sometimes does not crash when I remove the .addClass and .attr lines.\nEdit 2: OK, for some reason IE is crashing with your .ui-autocomplete style. If you change overflow:scroll; to overflow:auto; then IE8 does not crash. Alternatively change max-height to just height, which also fixes it. Guess it's a bug in IE either with max-height (maybe IE8 overflow:auto with max-height) or overflow.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29183,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to call instance variable form another class and file\n\nI have a question, I have 4 file app.py, face.py, camera.py and db.py Inside face.py file I have one variable call known_encoding_faces. If I put print code inside my face.py and run the app.py the result will display in my command prompt.\nMy question is how can i use known_encoding_faces variable in my camera.py? My expected result is when i run my app.py and open my webcam the command prompt will show the printed known_encoding_faces output. I believe if this work means this known_encoding_faces variable successfully can be used by camera.py file.\nHere I attach my code. Hope someone can help me regarding on this matter.\napp.py\nfrom flask import Flask, Response, json, render_template\nfrom werkzeug.utils import secure_filename\nfrom flask import request\nfrom os import path, getcwd\nimport time\nfrom face import Face\nfrom db import Database\napp = Flask(__name__)\nimport cv2\nfrom camera import VideoCamera\n\napp.config['file_allowed'] = ['image/png', 'image/jpeg']\napp.config['train_img'] = path.join(getcwd(), 'train_img')\napp.db = Database()\napp.face = Face(app)\n\ndef gen(camera):\n while True:\n frame = camera.get_frame()\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n\\r\\n')\n\n@app.route('/video_feed')\ndef video_feed():\n return Response(gen(VideoCamera()),\n mimetype='multipart/x-mixed-replace; boundary=frame')\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\ndef success_handle(output, status=200, mimetype='application/json'):\n return Response(output, status=status, mimetype=mimetype)\n\nface.py\nimport face_recognition\nfrom os import path\nimport cv2\nimport face_recognition\n\nclass Face:\n def __init__(self, app):\n self.train_img = app.config[\"train_img\"]\n self.db = app.db\n self.faces = []\n self.face_user_keys = {}\n self.known_encoding_faces = [] # faces data for recognition\n self.load_all()\n\n def load_user_by_index_key(self, index_key=0):\n\n key_str = str(index_key)\n\n if key_str in self.face_user_keys:\n return self.face_user_keys[key_str]\n\n return None\n\n def load_train_file_by_name(self,name):\n trained_train_img = path.join(self.train_img, 'trained')\n return path.join(trained_train_img, name)\n\n def load_unknown_file_by_name(self,name):\n unknown_img = path.join(self.train_img, 'unknown')\n return path.join(unknown_img, name)\n\n def load_all(self):\n results = self.db.select('SELECT faces.id, faces.user_id, faces.filename, faces.created FROM faces')\n for row in results:\n\n user_id = row[1]\n filename = row[2]\n\n face = {\n \"id\": row[0],\n \"user_id\": user_id,\n \"filename\": filename,\n \"created\": row[3]\n }\n\n self.faces.append(face)\n\n face_image = face_recognition.load_image_file(self.load_train_file_by_name(filename))\n face_image_encoding = face_recognition.face_encodings(face_image)[0]\n index_key = len(self.known_encoding_faces)\n self.known_encoding_faces.append(face_image_encoding)\n index_key_string = str(index_key)\n self.face_user_keys['{0}'.format(index_key_string)] = user_id\n\n def recognize(self,unknown_filename):\n unknown_image = face_recognition.load_image_file(self.load_unknown_file_by_name(unknown_filename))\n unknown_encoding_image = face_recognition.face_encodings(unknown_image)[0]\n\n results = face_recognition.compare_faces(self.known_encoding_faces, unknown_encoding_image);\n\n print(\"results\", results)\n\n index_key = 0\n for matched in results:\n\n if matched:\n # so we found this user with index key and find him\n user_id = self.load_user_by_index_key(index_key)\n\n return user_id\n\n index_key = index_key + 1\n return None\n\ncamera.py\nimport face_recognition\nfrom os import path\nimport cv2\nfrom db import Database\nfrom face import Face\n\nclass VideoCamera(object):\n def __init__(self):\n # Using OpenCV to capture from device 0. If you have trouble capturing\n # from a webcam, comment the line below out and use a video file\n # instead.\n self.video = cv2.VideoCapture(0)\n # If you decide to use video.mp4, you must have this file in the folder\n # as the main.py.\n # self.video = cv2.VideoCapture('video.mp4')\n\n def __del__(self):\n self.video.release()\n\n def get_frame(self):\n success, image = self.video.read()\n # We are using Motion JPEG, but OpenCV defaults to capture raw images,\n # so we must encode it into JPEG in order to correctly display the\n # video stream.\n ret, jpeg = cv2.imencode('.jpg', image)\n return jpeg.tobytes()\n\nA:\n\nknown_encoding_faces is a member of a Face object. That means it does not exist on its own - as evidence, note you only reference self.known_encoding_faces rather than just known_encoding_faces. You need to initialize some Face object, and than you can use it. Further more, it looks like you would need to call load_all on said object to properly initialize it. The minimal thing you need is some thing like:\nfrom face import Face\n\naface = Face(app) #You would need an app here\naface.load_all()\nknown_encoding_faces = aface.known_encoding_faces\n\nIf you are expecting this to exist irrespective of an objects creation, you need to rethink your design, and take it out of your class.\nIf you are expecting this to be called from the main script, you can demand this variable to initialize your camera:\nVideoCamera(app.face.known_encoding_faces) #Called from main script\n\nand in camera.py:\nclass VideoCamera(object):\n def __init__(self,known_face_encodings):\n self.known_encoding_faces = known_face_encodings\n self.video = cv2.VideoCapture(0)\n\nand in this class you can now use self.known_encoding_faces.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29184,"cells":{"text":{"kind":"string","value":"Q:\n\nMatPlotLib dynamic time axis\n\nI've been researching for a bit and haven't found the solution I'm looking for.\nIs there a method to creating a dynamic x-axis with matplotlib? I have a graph with a data stream being plotted, and I would like to have the x-axis display elapsed time (currently is static 0-100, while the rest of the graph updating to my data stream). \nEach tick would ideally be .5 seconds apart, with the latest 10s displaying. The program will be running 24/7, so I could have it set to actual time instead of stopwatch time. I've only been finding static datetime axis in my research.\nI can provide code if necessary, but doesn't seem necessary for this question.\n\nA:\n\nSince I don't know what you are streaming, I wrote a generic example and it may help you solving your problem.\nfrom pylab import *\nimport matplotlib.animation as animation\n\nclass Monitor(object):\n \"\"\" This is supposed to be the class that will capture the data from\n whatever you are doing.\n \"\"\" \n def __init__(self,N):\n self._t = linspace(0,100,N)\n self._data = self._t*0\n\n def captureNewDataPoint(self):\n \"\"\" The function that should be modified to capture the data\n according to your needs\n \"\"\" \n return 2.0*rand()-1.0\n\n def updataData(self):\n while True:\n self._data[:] = roll(self._data,-1)\n self._data[-1] = self.captureNewDataPoint()\n yield self._data\n\nclass StreamingDisplay(object):\n\n def __init__(self):\n self._fig = figure()\n self._ax = self._fig.add_subplot(111)\n\n def set_labels(self,xlabel,ylabel):\n self._ax.set_xlabel(xlabel)\n self._ax.set_ylabel(ylabel)\n\n def set_lims(self,xlim,ylim):\n self._ax.set_xlim(xlim)\n self._ax.set_ylim(ylim)\n\n def plot(self,monitor):\n self._line, = (self._ax.plot(monitor._t,monitor._data))\n\n def update(self,data):\n self._line.set_ydata(data)\n return self._line\n\n# Main\nif __name__ == '__main__':\n m = Monitor(100)\n sd = StreamingDisplay()\n sd.plot(m)\n sd.set_lims((0,100),(-1,1))\n\n ani = animation.FuncAnimation(sd._fig, sd.update, m.updataData, interval=500) # interval is in ms\n plt.show()\n\nHope it helps\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29185,"cells":{"text":{"kind":"string","value":"Q:\n\nFind a variable from a variable value in C\n\nI am trying to make a game similar to chess. I want the user to type in what position of the piece they want to move is, then were they want to move it... ( on an 8x8 grid - A1 through to H8)\nI cant workout a simple way to find a variable from what the user has typed in. The code I currently have is:\nvoid main() {\n\n printf(\"Enter Piece to Move: \");\n scanf(\"%s\",&move); \n\n printf(\"\\n\\nWhere would you like to move %s?:\",move);\n scanf(\"%s\",&to);\n\n [...]\n\nWhat i also have is a variable list of all the location of pieces. What I would like to happen is, if the user was to enter A1 for the piece to move. I want the value of variable named A1 to be used. This is so I can have the current position of the piece and also what is in the place...\nHope this makes scene and someone can help :)\n\nA:\n\nTake a look at the concept of arrays. If you have a 2-dimensional array, you just need to convert the letter 'A' to a number and use it as in index in the array.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29186,"cells":{"text":{"kind":"string","value":"Q:\n\nConfusion Matrix to get precsion,recall, f1score\n\nI have a dataframe df. I have performed decisionTree classification algorithm on the dataframe. The two columns are label and features when algorithm is performed. The model is called dtc. How can I create a confusion matrix in pyspark?\ndtc = DecisionTreeClassifier(featuresCol = 'features', labelCol = 'label')\ndtcModel = dtc.fit(train)\npredictions = dtcModel.transform(test)\n\nfrom pyspark.mllib.linalg import Vectors\nfrom pyspark.mllib.regression import LabeledPoint\nfrom pyspark.mllib.evaluation import MulticlassMetrics\n\npreds = df.select(['label', 'features']) \\\n .df.map(lambda line: (line[1], line[0]))\nmetrics = MulticlassMetrics(preds)\n\n # Confusion Matrix\nprint(metrics.confusionMatrix().toArray())```\n\nA:\n\nYou need to cast to an rdd and map to tuple before calling metrics.confusionMatrix().toArray().\nFrom the official documentation,\n\nclass pyspark.mllib.evaluation.MulticlassMetrics(predictionAndLabels)[source]\nEvaluator for multiclass classification.\nParameters: predictionAndLabels – an RDD of (prediction, label) pairs.\n\nHere is an example to guide you.\nML part\nimport pyspark.sql.functions as F\nfrom pyspark.ml.feature import VectorAssembler\nfrom pyspark.ml.classification import DecisionTreeClassifier\nfrom pyspark.mllib.evaluation import MulticlassMetrics\nfrom pyspark.sql.types import FloatType\n#Note the differences between ml and mllib, they are two different libraries.\n\n#create a sample data frame\ndata = [(1.54,3.45,2.56,0),(9.39,8.31,1.34,0),(1.25,3.31,9.87,1),(9.35,5.67,2.49,2),\\\n (1.23,4.67,8.91,1),(3.56,9.08,7.45,2),(6.43,2.23,1.19,1),(7.89,5.32,9.08,2)]\n\ncols = ('a','b','c','d')\n\ndf = spark.createDataFrame(data, cols)\n\nassembler = VectorAssembler(inputCols=['a','b','c'], outputCol='features')\n\ndf_features = assembler.transform(df)\n\n#df.show()\n\ntrain_data, test_data = df_features.randomSplit([0.6,0.4])\n\ndtc = DecisionTreeClassifier(featuresCol='features',labelCol='d')\n\ndtcModel = dtc.fit(train_data)\n\npredictions = dtcModel.transform(test_data)\n\nEvaluation part\n#important: need to cast to float type, and order by prediction, else it won't work\npreds_and_labels = predictions.select(['predictions','d']).withColumn('label', F.col('d').cast(FloatType())).orderBy('prediction')\n\n#select only prediction and label columns\npreds_and_labels = preds_and_labels.select(['prediction','label'])\n\nmetrics = MultiClassMetrics(preds_and_labels.rdd.map(tuple))\n\n#print(metrics.ConfusionMatrix().toArray())\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29187,"cells":{"text":{"kind":"string","value":"Q:\n\nJar file not running on mac\n\nI have made a runnable java file on eclipse on my windows 64 bit computer using jre and jdk 8. The runnable file opens on my windows computer and on my desktop windows computer. When i email the jar file over to my mac, the jar file does not work and it gives the error the java jar file \"snoman3.jar\" could not be launched. I ran it through the terminal and still gives the same error. I have jre 8 on my mac yet it is still not running. There are many duplicates of this question but i could not find a solution that worked for me, may somebody please tell me possible solutions for this? PS I am running OS X yosemite on my mac. \nThe following is the error I am getting. PS I am using the libGDX graphics library.\n java -jar snoman3.jar\nException in thread \"main\" java.lang.reflect.InvocationTargetException\n at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n at java.lang.reflect.Method.invoke(Method.java:483)\n at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)\nCaused by: java.lang.UnsatisfiedLinkError: Can't load library: /var/folders/88/wtc6dz2d5tvdr3qnzb3pq69w0000gn/T/libgdxasma/75260a42/liblwjgl.dylib\n at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1817)\n at java.lang.Runtime.load0(Runtime.java:809)\n at java.lang.System.load(System.java:1083)\n at org.lwjgl.Sys$1.run(Sys.java:70)\n at java.security.AccessController.doPrivileged(Native Method)\n at org.lwjgl.Sys.doLoadLibrary(Sys.java:66)\n at org.lwjgl.Sys.loadLibrary(Sys.java:95)\n at org.lwjgl.Sys.(Sys.java:112)\n at org.lwjgl.openal.AL.(AL.java:59)\n at com.badlogic.gdx.backends.openal.OpenALAudio.(OpenALAudio.java:70)\n at com.badlogic.gdx.backends.lwjgl.LwjglApplication.(LwjglApplication.java:81)\n at com.badlogic.gdx.backends.lwjgl.LwjglApplication.(LwjglApplication.java:63)\n at com.rarster.snowman.Main.main(Main.java:15)\n ... 5 more\n\nA:\n\nLooks like you are getting a NullPointerException behind the scenes. InvocationTargetException is just a wrapper for an exception that's thrown within a dynamic invocation.\nIf I saw your code, I could have helped you more. \n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29188,"cells":{"text":{"kind":"string","value":"Q:\n\nOpenshift RHC setup throws error\n\nAfter successfully installing rhc, when I try to \nrhc setup\n\nand I get the following console output:\n\nAnyone any idea why this happens?\n\nA:\n\nOkay so after further investigation how I fixed this was:\nrhc ssh *my_app_name*\n\nafter which I ran\ntail_all\n\nThis gave me a pretty extensive error log generated by the openshift server. \nSilly error - turned out it was just a missing dependency from the package.json file :)\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29189,"cells":{"text":{"kind":"string","value":"Q:\n\njqplot and width\n\nI am having some trouble with the width of the ticks on the xaxis. It seems that they are auto adjusted to fill the width of the div - what if I want to override that?\nRegards,\nJacob\n\nA:\n\nI had the same problem but could not find anything useful in the docs. I solved it by changing the width of the div dynamically, based on the data array size, before drawing the graph.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29190,"cells":{"text":{"kind":"string","value":"Q:\n\nSwift - Is there a way to differentiate between a field not being present or a field being nil/null when decoding an optional Codable value\n\nThe Necessary Functionality\nI'm in the process of modifying a system to save a queue of currently unsent API requests to UserDefaults to be re-sent when the user's connection allows.\nAs some patch requests require the ability to send an actual NULL value to the API (and not just ignore out the field if its a nil optional), this means I need the ability to encode and decode nil/NULL values from defaults for certain fields.\nThe Issue\nI have the encoding side down, and can happily encode requests to either send NULL fields to the server or encode them to Defaults. However, my issue is that when it comes to decoding saved unsent requests, I can't find a way to differentiate between an actual Nil value and the field just not being there.\nI am currently using decodeIfPresent to decode my fields (all of the fields for these requests are optional), which returns nil if the field is empty OR if the field is set to Nil/NULL. Obviously this doesn't work for my fields that can explicitly be set to Nil, as there is no way for me to differentiate between the two cases.\nQuestion\nIs there any decode methodology I could implement that would allow for differentiating between a field not being there and a field actually being set to nil?\n\nA:\n\nThere is no way , but you can add another info to know that\nstruct Root : Codable {\n\n let code : Int?\n let codeExists:Bool?\n\n init(from decoder: Decoder) throws {\n let values = try decoder.container(keyedBy: CodingKeys.self) \n code = try values.decodeIfPresent(Int.self, forKey: .code)\n codeExists = values.contains(.code)\n\n }\n}\n\nAccording to docs decodeIfPresent\n\nThis method returns nil if the container does not have a value associated with key, or if the value is null. The difference between these states can be distinguished with a contains(_:) call.\n\nSo decoding\nlet str = \"\"\"\n{\n \"code\" : 12\n}\n\"\"\"\n\ngives\n\nRoot(code: Optional(12), codeExists: Optional(true))\n\n&&\nThis\nlet str = \"\"\"\n{\n \"code\" : null\n}\n\"\"\"\n\ngives\n\nRoot(code: nil, codeExists: Optional(true))\n\nand this\nlet str = \"\"\"\n{\n\n}\n\"\"\"\n\ngives\n\nRoot(code: nil, codeExists: Optional(false))\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29191,"cells":{"text":{"kind":"string","value":"Q:\n\nmat-autocomplete: Need to Reset the List of Options After a Selection is Made\n\nI have a mat-autocomplete component with the options wired up to be populated from a service call as the user types (partial search):\n\n\r\n {{ option }}\r\n\n\nIn my TS code, I am setting the options array to be an empty array at the end of the processing I do when a user selects a value:\n\n resetFetchedOptions() {\r\n this.options = [];\r\n}\n\nThis works in that the code is called, and that this.options is set to an empty array. The problem is that when the user tries to type another value in the field, the previous options are still there. If they type, the options get cleared out, and the new options based on the partial search are populated, so I think this is a rendering problem, but I'm a bit new to Angular Material, so I'm not sure if this is the wrong approach or I'm missing a step.\nThanks!\n\nA:\n\nAre you using reactive forms? I made a similar thing like this (based on this article);\nhtml\n\n \n \n \n \n {{result.description}}\n \n \n {{searchHint()}}\n\n\nTypescript\nngOnInit() {\n this.formControl\n .valueChanges\n .pipe(\n debounceTime(300),\n tap(() => this.isSearching = true),\n switchMap(value => this.someService.searchStuff(this.getSearchString(value as any))\n .pipe(\n finalize(() => this.isSearching = false),\n )\n )\n )\n .subscribe(result => this.filteredResult = result);\n\n this.formControl.valueChanges.subscribe(value => this.setValue(value));\n}\n\n// Need to handle both the search string and a selected full type\nprivate setValue(value: string | ResultType) : void {\n if (typeof value === \"string\")\n this.selectedValue = null;\n else\n this.selectedValue = value;\n}\n\nprivate getSearchString(value: string | ResultType) {\n if (typeof value === \"string\")\n return value;\n else\n return value.description;\n}\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29192,"cells":{"text":{"kind":"string","value":"Q:\n\nHow do I install required gcc and libc6-dev files on 20.04?\n\nI am trying to build software from source (specifically, Asymptote 2.66).\nThis worked fine on Ubuntu 18.04.\nBut a number of the files the make file needs, such as:\n\nbyteswap-16.h and libio.h in /usr/include/x86-64-linux-gnu/bits/\nlimits.h in /usr/lib/gcc/x86-64-linux-gnu/7/include-fixed\n\nare simply not present in Ubuntu 20.04. Well, not present in the expected locations. They can be found in /snap/gnome-3-34-1804.\nEvery bit of help online says to install build-essentials, libc6-dev, and linux-libc-dev.\nBut all of these are installed. Other than manually copying needed files one by one, is there a way to get all the necessary files to build from source?\n\nA:\n\nAt first - the Asymptote 2.62 is contained in the official repository, so you can start getting its build-dependencies by enabling source code repositories in Software & Updates (software-properties-gtk) and by using the following command:\nsudo apt-get build-dep asymptote\n\nAnd then compile the source code:\ncd ~/Downloads\nwget https://github.com/vectorgraphics/asymptote/archive/2.66.tar.gz\ntar -xf 2.66.tar.gz\ncd asymptote-2.66\n./autogen.sh\n./configure\nmake\nsudo make install\n\nand then run the application with asy command.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29193,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to share models between different MVC websites?\n\nI have 2 seperate areas for my ASP.NET MVC 3 website - Admin (Intranet website) and Client (Internet website).\nThe Model (business and data access layer) will be used by both websites. The websites will be hosted on seperate servers. So, the folder will not be shared.\nSo, I am planning to create the DLL of the Model and put the DLL in the Bin Folder of both website and use it.\nI hope this will keep my UI neat and less code as well.\nNow, my doubts are:\n\nDo I need to create a Class Library project to create the DLL of the Model or do I need to use and MVC web application project to create the DLL?\nWhere should I put the web config? Hope I need in both Model and also in UI?\n\nA:\n\nDo I need to create a Class Library project to create the DLL of the Model\n\nYes, a separate class library shared between the 2 web applications is the best approach.\n\nDo I need to use and MVC web application project to create the DLL (looking for the best approach)? \n\nNo, the ASP.NET MVC could contain only the views. Do not reference and reuse a web application for common logic in other applications.\n\nWhere should I put the web config?\n\nEach ASP.NET MVC web application should have its own web.config.\n\nA:\n\nYes, your abstracted business logic should be in a separate class library project. You can then reference this project from web apps in the same solution or compile it and reference it as a DLL. Your web.config file(s) will still live in your web project(s).\nTo add settings for your class library in your web project, use configuration sections:\n\n \n
\n \n\n\n \n \n SettingValue\n \n \n\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29194,"cells":{"text":{"kind":"string","value":"Q:\n\nRegular Expression To Validate Email Address\n\nI'm trying to create a regular expression to check to see if a valid email address has been entered. There is something wrong with my regular expression. Here is the source code I'm using: \nif (!Pattern.matches(\"^[\\\\w-\\\\+]+(\\\\.[\\\\w]+)*@[\\\\w-]+(\\\\.[\\\\w]+)*(\\\\.[a-z]{2,})$\", s)) {\n et.setError(\"Enter a valid Email Address\");\n}\n\nWhat am I doing wrong?\n\nA:\n\nThis did the trick: \n([\\\\w-+]+(?:\\\\.[\\\\w-+]+)*@(?:[\\\\w-]+\\\\.)+[a-zA-Z]{2,7})\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29195,"cells":{"text":{"kind":"string","value":"Q:\n\ncomponent lookup exception with org.apache.maven.repository.RepositorySystem in Maven plugin testing\n\nI'm trying to use maven-plugin-testing-harness version 2.1 with the following test case:\npublic class FooTest extends AbstractMojoTestCase {\n @Override\n protected void setUp() throws Exception {\n super.setUp();\n }\n public void testSomething() throws Exception {\n // todo\n }\n}\n\nThe test fails at the setUp() call:\norg.codehaus.plexus.component.repository.exception.ComponentLookupException: java.util.NoSuchElementException\n role: org.apache.maven.repository.RepositorySystem\nroleHint: \n at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:257)\n at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:245)\n at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:239)\n at org.codehaus.plexus.PlexusTestCase.lookup(PlexusTestCase.java:206)\n at org.apache.maven.plugin.testing.AbstractMojoTestCase.setUp(AbstractMojoTestCase.java:118)\n at foo.FooTest.setUp(FooTest.java:54)\n\nThese dependencies I have in the pom.xml:\n \n org.apache.maven\n maven-plugin-api\n 3.0.5\n \n \n org.apache.maven\n maven-model\n 3.0.5\n \n \n org.apache.maven\n maven-core\n 3.0.5\n \n \n org.apache.maven.plugin-testing\n maven-plugin-testing-harness\n 2.1\n test\n \n\nAny ideas?\n\nA:\n\nRecently I faced the same exception. After a bit researching I found that maven-compat plugin solves the problem:\n\n org.apache.maven\n maven-compat\n 3.0.5\n test\n\n\nA:\n\nLeaving this here for anyone who runs into this problem in the future:\nsmoke's answer does work, but make sure the versions of the dependencies included in yegor256's in the original question match. Adding org.apache.maven:maven-compat did not work for me until I had changed those 4 dependencies to also have version 3.0.5.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29196,"cells":{"text":{"kind":"string","value":"Q:\n\nMinecraft crashes after launching with buildcraft\n\nI just installed Minecraft 1.6.2 and then installed forge. The game launches Forge and the Timber mod but when I attempted to add the Buildcraft mod, the game just crashes. The Mojang screen appears and then the game closes. I don't know what is happening. There isn't and error report or anything, the game just closes.\n\nA:\n\nYou've been tricked\nThe latest BuildCraft (version 3.7.2) from the official download site is for Minecraft 1.5.2. It will not work for Minecraft 1.6.2.\nEither you downloaded it from a scam/malware site that lied about being compatible with 1.6.2 (scam mod sites are very common, since it's easy to prey on people hoping for mods compatible with the latest Minecraft version), or someone well-meaning simply didn't understand compatibility and was wrong when they told you it would work with 1.6.2.\nThere is no fix. You'll have to either downgrade to Minecraft 1.5.2 and use that to play BuildCraft, or wait for BuildCraft to update to Minecraft 1.6.x.\nAlways download mods from reputable sources you trust!\nNever find mods by Googling. Either find the mod on the author's site or from Minecraftforums.net pinned mod list thread. Anywhere else is either illegally redistributing the real mod or is offering a fake mod that might be malware.\nEven if it's the real mod, they often provide inaccurate or misleading compatibility information to boost downloads and their advertising income, leaving you with a mod that simply doesn't work while they get paid for your misfortune.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29197,"cells":{"text":{"kind":"string","value":"Q:\n\nUnable to get the text field value in typescript using angular\n\nI have two type of Request that I need to fetch from the Angular UI page and pass it into app.component.ts file so that I can call my REST client through HTML page.\nRequest 1:\nEnd Point: (GET call)\n http://localhost:8081/api/products?productId=7e1308ba2b9af\n\nI just created a text field in the app.component.html file as like below:\n
\n \n
\n
\n \n
\n\nOutput:\n\nI have written the below code and ensured it works as expected by using the hard-coded value.\napp.component.ts:\n ngOnInit():void{\n\n this.http.get('http://localhost:8081/api/products?productId=7e1308ba2b9af').subscribe(data =>{ \n\n console.log(data);\n });\n }\n\nThe above code return data array with proper response. But the above productId value is hard-coded (7e1308ba2b9af). And I just want to get that value from HTML text box when user click the submit button and pass it to query param and run the above request.\nRequest 2:\nI have to get the below format json file from text box and pass it as JSON request body to the below end point URL.\nEnd Point: (PUT call)\n https://localhost:8081/api/updateRecord\n\nRequest JSON:\n{\n \"productId\":234242882,\n \"purchaseDate\" : \"2019-12-20\",\n \"status\": \"dispatched\"\n}\n\nI just want to create a text field and get the above json file if user click submit button and invoke the above end point.\nI'm very new to the Angular and not sure how to implement this. I just googled but I didn't understand the way they resolved. It would be much appreciated if someone explain me the things and guide me to resolve this. \n\nA:\n\nUse [(ngModel)] to bind an input to a variable:\n
\n \n
\n\nUse (click) to bind a button to a function:\n
\n \n
\n\nIn the controller:\nngOnInit():void { \n this.http.get('http://localhost:8081/api/products?productId=7e1308ba2b9af').subscribe(data =>{ \n console.log(data);\n });\n}\n\ngetById():void {\n const base:string = \"http://localhost:8081/api/products\"; \n const url:string = `${base}?productId=${this.productId}`;\n this.http.get(url).subscribe(data =>{ \n console.log(data);\n }); \n}\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29198,"cells":{"text":{"kind":"string","value":"Q:\n\nReview queues always empty\n\nI am not able to review any post although I have enough reputation (more than 1400) on my Stack Overflow account.\nHowever, the review queues always show zero contents.\nUp until now I've only reviewed one item. Is something broken?\n\nA:\n\nAt your current reputation, you can only see the \"Late Answers\" and \"First Posts\" (I believe). These queues are often empty and, even when they're not, a large group of users constantly patrols the queues and will snatch up the opportunity to review.\nOnce your reputation increases, you'll gain access to some queues that typically have a handful of items in them at any one point. Once you reach 3k, you can drown in all the close reviews you can handle...\n\n(Minimal reputation artfully added in red)\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29199,"cells":{"text":{"kind":"string","value":"Q:\n\nCan I calculate tension in a preloaded string by superposition when the string is deformed?\n\nI am trying to calculate the tension in a string with preloaded tension after a force is applied to the string as in the diagram below. The string would be under tension prior to the force $F$ being applied. The force should deform the string by an amount determined by Young's modulus and the other physical properties of the string. However, this does not account for all tension in the string. If we call the preloaded tension $T$, when the string is straight, can I simply add the tension caused by the deformation to the initial tension in the string?\nMy attempt to solve for the tension (call it $T'$) after the force $F$ is applied begins by calculating the change in length of the string. The length before bending is $$\\sqrt{L^2+h^2}$$ and the length after bending is $$x+\\sqrt{(L-x)^2+h^2}$$ Therefore, the change in length is calculated as $$x+\\sqrt{(L-x)^2+h^2}-\\sqrt{L^2+h^2}$$ and the strain can be calculated as $$\\epsilon=\\frac{x+\\sqrt{(L-x)^2+h^2}-\\sqrt{L^2+h^2}}{\\sqrt{L^2+h^2}}=\\frac{x+\\sqrt{(L-x)^2+h^2}}{\\sqrt{L^2+h^2}}-1$$ Calling the tension induced by deformation $T_d$ and the cross-sectional area of the string $A$, stress is calculated as $$\\sigma=T_d/A$$ Given that Young's modulus is $$Y=\\frac{\\sigma}{\\epsilon} \\therefore \\sigma = Y\\cdot \\epsilon$$ we can substitute and rearrange to get $$T_d=Y\\cdot A\\cdot \\left(\\frac{x+\\sqrt{(L-x)^2+h^2}}{\\sqrt{L^2+h^2}}-1\\right)$$ Firstly, is this a even valid calculation given the angle $\\theta$? I'm not very confident about it, but it's the best I can come up with. Secondly, given the increase in tension due to the change in overall length, is it valid to simply add this amount to the preloaded tension in the string. I'm mostly concerned with the tension in the section of the string labeled $x$, but would be interested in knowing the tension in both sections if possible.\n\nA:\n\nWell, if I understood the system correctly, pushing the string down to the given configuration will make the tension on both the parts of the string equal. This follows from a choice of point without friction, as you can easily find examples of.\nHaving established that, calculating the tension on an ideal string needs us to find the strain on the spring. Strain is $$\\epsilon = \\frac{\\Delta{L}}{L_0}$$ where $L_0$ is the length of the unstrained spring (i.e. without force).\nThis makes the calculations trivial: You first calculate $L_0$ from the first configuration with tension $T$, then use this length to find the final strain and tension $T'$.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":291,"numItemsPerPage":100,"numTotalItems":29950,"offset":29100,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NzkyNjE2OCwic3ViIjoiL2RhdGFzZXRzL3N1b2x5ZXIvcGlsZV9zdGFja2V4Y2hhbmdlIiwiZXhwIjoxNzU3OTI5NzY4LCJpc3MiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvIn0.vH3uft7V8FeS3XHw2fwOdZifN-Td2FkuKTD3XJIIj2Cw6BToP_Yeu6QHriCY3XtLJATd1pSPUTbdzMq6nKTpAg","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
text
stringlengths
175
47.7k
meta
dict
Q: Compatibility between a gRPC server in Go and a client in Python I want to know about the compatibility about a gRPC service in Go and a client in Python. For instance if the service is implemented in Go, it will have signatures like this: ... func (s *routeGuideServer) GetFeature(ctx context.Context, point *pb.Point) (*pb.Feature, error) { ... } ... func (s *routeGuideServer) ListFeatures(rect *pb.Rectangle, stream pb.RouteGuide_ListFeaturesServer) error { ... } ... func (s *routeGuideServer) RecordRoute(stream pb.RouteGuide_RecordRouteServer) error { ... } ... func (s *routeGuideServer) RouteChat(stream pb.RouteGuide_RouteChatServer) error { ... } Note how error objects are returned. Now, if I have to implement the client in Python it will be something like this: feature = stub.GetFeature(point) for received_route_note in stub.RouteChat(sent_route_note_iterator): What happens to the error field that is returned by the Go service implementation? If there is an error from the server side how can it be handled in the Python client? A: gRPC provides error handling that fits the language being used. As you noted, in a Go server you return an error: func (s *routeGuideServer) RouteChat(stream pb.RouteGuide_RouteChatServer) error { for { in, err := stream.Recv() if err == io.EOF { return nil } if err != nil { return err } ... In a Python client, you execute the API call in a try statement (contrived example, since the official documentation doesn't demonstrate this): while True: try: received_route_note = stub.RouteChat(sent_route_note_iterator) except grpc.Error as e: print(e.details()) break Conversely, in a Python server, you set the context and, optionally, raise an exception: example from the Python Generated Code Reference: def TellFortune(self, request, context): """Returns the horoscope and zodiac sign for the given month and day. errors: invalid month or day, fortune unavailable """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') example from the grpc repository def UnUn(self, request, context): if _application_common.UNARY_UNARY_REQUEST == request: return _application_common.UNARY_UNARY_RESPONSE else: context.set_code(grpc.StatusCode.INVALID_ARGUMENT) context.set_details('Something is wrong with your request!') return services_pb2.Down() And in a Go client an error object is (one of) the result parameters: stream, err := client.RouteChat(ctx) if err != nil { log.Fatalf("%v.RouteChat(_) = _, %v", client, err) } It's unfortunate that the official documentation doesn't seem to explicitly cover error handling practices. A good 3rd party reference I found is at http://avi.im/grpc-errors/
{ "pile_set_name": "StackExchange" }
Q: Magento2 outdated issues I am creating a docker container for magento2. Made everything ready and now I am getting this error from the running container. Previously had an permission issue fixed by changing the permission for directory required, than I got his error. I tried this ./bin/magento setup:upgrade but didn't solve the problem. 1 exception(s): Exception #0 (Magento\Framework\Exception\LocalizedException): Please update your modules: Run "composer install" from the Magento root directory. The following modules are outdated: Magento_Directory db schema version: defined in codebase - 2.0.1, currently installed - 2.0.2 Magento_Directory db data version: defined in codebase - 2.0.1, currently installed - 2.0.2 Magento_Catalog db schema version: defined in codebase - 2.2.3, currently installed - 2.2.4 Magento_Catalog db data version: defined in codebase - 2.2.3, currently installed - 2.2.4 Magento_Sales db schema version: defined in codebase - 2.0.7, currently installed - 2.0.9 Magento_Sales db data version: defined in codebase - 2.0.7, currently installed - 2.0.9 Exception #0 (Magento\Framework\Exception\LocalizedException): Please update your modules: Run "composer install" from the Magento root directory. The following modules are outdated: Magento_Directory db schema version: defined in codebase - 2.0.1, currently installed - 2.0.2 Magento_Directory db data version: defined in codebase - 2.0.1, currently installed - 2.0.2 Magento_Catalog db schema version: defined in codebase - 2.2.3, currently installed - 2.2.4 Magento_Catalog db data version: defined in codebase - 2.2.3, currently installed - 2.2.4 Magento_Sales db schema version: defined in codebase - 2.0.7, currently installed - 2.0.9 Magento_Sales db data version: defined in codebase - 2.0.7, currently installed - 2.0.9 #0 /var/www/html/magento2/lib/internal/Magento/Framework/Interception/Interceptor.php(121): Magento\Framework\Module\Plugin\DbStatusValidator->beforeDispatch(Object(Magento\Framework\App\FrontController\Interceptor), Object(Magento\Framework\App\Request\Http)) #1 /var/www/html/magento2/app/code/Magento/PageCache/Model/App/FrontController/BuiltinPlugin.php(73): Magento\Framework\App\FrontController\Interceptor->Magento\Framework\Interception\{closure}(Object(Magento\Framework\App\Request\Http)) #2 /var/www/html/magento2/lib/internal/Magento/Framework/Interception/Interceptor.php(135): Magento\PageCache\Model\App\FrontController\BuiltinPlugin->aroundDispatch(Object(Magento\Framework\App\FrontController\Interceptor), Object(Closure), Object(Magento\Framework\App\Request\Http)) #3 /var/www/html/magento2/lib/internal/Magento/Framework/Interception/Interceptor.php(153): Magento\Framework\App\FrontController\Interceptor->Magento\Framework\Interception\{closure}(Object(Magento\Framework\App\Request\Http)) #4 /var/www/html/magento2/generated/code/Magento/Framework/App/FrontController/Interceptor.php(26): Magento\Framework\App\FrontController\Interceptor->___callPlugins('dispatch', Array, Array) #5 /var/www/html/magento2/lib/internal/Magento/Framework/App/Http.php(135): Magento\Framework\App\FrontController\Interceptor->dispatch(Object(Magento\Framework\App\Request\Http)) #6 /var/www/html/magento2/generated/code/Magento/Framework/App/Http/Interceptor.php(24): Magento\Framework\App\Http->launch() #7 /var/www/html/magento2/lib/internal/Magento/Framework/App/Bootstrap.php(256): Magento\Framework\App\Http\Interceptor->launch() #8 /var/www/html/magento2/pub/index.php(37): Magento\Framework\App\Bootstrap->run(Object(Magento\Framework\App\Http\Interceptor)) #9 {main} A: This is poor error messaging on the part of Magento The following modules are outdated: Magento_Directory db schema version: defined in codebase - 2.0.1, currently installed - 2.0.2 A better error message might have been "your system database is configured with modules ahead of those in your codebase. Somehow, the module.xml files on your system. #File: vendor/magento/module-directory/etc/module.xml <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="Magento_Directory" setup_version="2.0.1"> <sequence> <module name="Magento_Store"/> </sequence> </module> </config> have one version number, but the data in the setup table in MySQL (or cached values read from this table) mysql> SELECT * FROM setup_module WHERE module = 'Magento_Directory'; +-------------------+----------------+--------------+ | module | schema_version | data_version | +-------------------+----------------+--------------+ | Magento_Directory | 2.0.2 | 2.0.2 | +-------------------+----------------+--------------+ Somehow you've updated your system with one set of module files, but the system you're actually serving your files from is still an older one.
{ "pile_set_name": "StackExchange" }
Q: Using Stored Procedure variable in Like statement I can't seem to properly use the LIKE statement using a variable from a stored procedure. I want to find all the rows from a table that start with the variable passed. I am currently using the following query where @id is the value passed to the stored procedure as nvarchar(20). This works fine when the IDs completely match, but does not properly use the '%' appended. What is the proper way to complete this task? SELECT * FROM Table WHERE id LIKE @id + '%' A: This works for me: declare @id nvarchar(20) select @id = '1' SELECT * FROM tab WHERE id LIKE @id + '%' Sql Fiddle DEMO
{ "pile_set_name": "StackExchange" }
Q: How do I authorize access to ServiceStack resources using OAuth2 access tokens via DotNetOpenAuth? I've created an OAuth2 authorization server using DotNetOpenAuth, which is working fine - I'm using the resource owner password flow, and successfully exchanging user credentials for an access token. I now want to use that access token to retrieve data from secure endpoints in a ServiceStack API, and I can't work out how to do so. I've examined the Facebook, Google, etc. providers included with ServiceStack but it's not clear whether I should be following the same pattern or not. What I'm trying to achieve (I think!) is OAuth client (my app) asks resource owner ('Catherine Smith') for credentials Client submits request to authorization server, receives an access token Client requests a secure resource from the resource server (GET /users/csmith/photos) The access token is included in an HTTP header, e.g. Authorization: Bearer 1234abcd... The resource server decrypts the access token to verify the identity of the resource owner The resource server checks that the resource owner has access to the requested resource The resource server returns the resource to the client Steps 1 and 2 are working, but I can't work out how to integrate the DotNetOpenAuth resource server code with the ServiceStack authorization framework. Is there an example somewhere of how I would achieve this? I've found a similar StackOverflow post at How to build secured api using ServiceStack as resource server with OAuth2.0? but it isn't a complete solution and doesn't seem to use the ServiceStack authorization provider model. EDIT: A little more detail. There's two different web apps in play here. One is the authentication/authorisation server - this doesn't host any customer data (i.e. no data API), but exposes the /oauth/token method that will accept a username/password and return an OAuth2 access token and refresh token, and also provides token-refresh capability. This is built on ASP.NET MVC because it's almost identical to the AuthorizationServer sample included with DotNetOpenAuth. This might be replaced later, but for now it's ASP.NET MVC. For the actual data API, I'm using ServiceStack because I find it much better than WebAPI or MVC for exposing ReSTful data services. So in the following example: the Client is a desktop application running on a user's local machine, the Auth server is ASP.NET MVC + DotNetOpenAuth, and the Resource server is ServiceStack The particular snippet of DotNetOpenAuth code that's required is: // scopes is the specific OAuth2 scope associated with the current API call. var scopes = new string[] { "some_scope", "some_other_scope" } var analyzer = new StandardAccessTokenAnalyzer(authServerPublicKey, resourceServerPrivateKey); var resourceServer = new DotNetOpenAuth.OAuth2.ResourceServer(analyzer); var wrappedRequest = System.Web.HttpRequestWrapper(HttpContext.Current.Request); var principal = resourceServer.GetPrincipal(wrappedRequest, scopes); if (principal != null) { // We've verified that the OAuth2 access token grants this principal // access to the requested scope. } So, assuming I'm on the right track, what I need to do is to run that code somewhere in the ServiceStack request pipeline, to verify that the Authorization header in the API request represents a valid principal who has granted access to the requested scope. I'm starting to think the most logical place to implement this is in a custom attribute that I use to decorate my ServiceStack service implementations: using ServiceStack.ServiceInterface; using SpotAuth.Common.ServiceModel; namespace SpotAuth.ResourceServer.Services { [RequireScope("hello")] public class HelloService : Service { public object Any(Hello request) { return new HelloResponse { Result = "Hello, " + request.Name }; } } } This approach would also allow specifying the scope(s) required for each service method. However, that seems to run rather contrary to the 'pluggable' principle behind OAuth2, and to the extensibility hooks built in to ServiceStack's AuthProvider model. In other words - I'm worried I'm banging in a nail with a shoe because I can't find a hammer... A: OK, after a lot of stepping through the various libraries with a debugger, I think you do it like this: https://github.com/dylanbeattie/OAuthStack There's two key integration points. First, a custom filter attribute that's used on the server to decorate the resource endpoints that should be secured with OAuth2 authorization: /// <summary>Restrict this service to clients with a valid OAuth2 access /// token granting access to the specified scopes.</summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true)] public class RequireOAuth2ScopeAttribute : RequestFilterAttribute { private readonly string[] oauth2Scopes; public RequireOAuth2ScopeAttribute(params string[] oauth2Scopes) { this.oauth2Scopes = oauth2Scopes; } public override void Execute(IHttpRequest request, IHttpResponse response, object requestDto) { try { var authServerKeys = AppHostBase.Instance.Container.ResolveNamed<ICryptoKeyPair>("authServer"); var dataServerKeys = AppHostBase.Instance.Container.ResolveNamed<ICryptoKeyPair>("dataServer"); var tokenAnalyzer = new StandardAccessTokenAnalyzer(authServerKeys.PublicSigningKey, dataServerKeys.PrivateEncryptionKey); var oauth2ResourceServer = new DotNetOpenAuth.OAuth2.ResourceServer(tokenAnalyzer); var wrappedRequest = new HttpRequestWrapper((HttpRequest)request.OriginalRequest); HttpContext.Current.User = oauth2ResourceServer.GetPrincipal(wrappedRequest, oauth2Scopes); } catch (ProtocolFaultResponseException x) { // see the GitHub project for detailed error-handling code throw; } } } Second, this is how you hook into the ServiceStack HTTP client pipeline and use DotNetOpenAuth to add the OAuth2 Authorization: Bearer {key} token to the outgoing request: // Create the ServiceStack API client and the request DTO var apiClient = new JsonServiceClient("http://api.mysite.com/"); var apiRequestDto = new Shortlists { Name = "dylan" }; // Wire up the ServiceStack client filter so that DotNetOpenAuth can // add the authorization header before the request is sent // to the API server apiClient.LocalHttpWebRequestFilter = request => { // This is the magic line that makes all the client-side magic work :) ClientBase.AuthorizeRequest(request, accessTokenTextBox.Text); } // Send the API request and dump the response to our output TextBox var helloResponseDto = apiClient.Get(apiRequestDto); Console.WriteLine(helloResponseDto.Result); Authorized requests will succeed; requests with a missing token, expired token or insufficient scope will raise a WebServiceException This is still very much proof-of-concept stuff, but seems to work pretty well. I'd welcome feedback from anyone who knows ServiceStack or DotNetOpenAuth better than I do. A: Update On further reflection, your initial thought, to create a RequiredScope attribute would be a cleaner way to go. Adding it to the ServiceStack pipeline is as easy as adding the IHasRequestFilter interface, implementing a custom request filter, as documented here: https://github.com/ServiceStack/ServiceStack/wiki/Filter-attributes public class RequireScopeAttribute : Attribute, IHasRequestFilter { public void RequireScope(IHttpRequest req, IHttpResponse res, object requestDto) { //This code is executed before the service //Close the request if user lacks required scope } ... } Then decorate your DTO's or Services as you've outlined: using ServiceStack.ServiceInterface; using SpotAuth.Common.ServiceModel; namespace SpotAuth.ResourceServer.Services { [RequireScope("hello")] public class HelloService : Service { public object Any(Hello request) { return new HelloResponse { Result = "Hello, " + request.Name }; } } } Your RequireScope custom filter would be almost identical to ServiceStack's RequiredRoleAttribute implementation., so use it as a starting point to code from. Alternately, you could map scope to permission. Then decorate your DTO or service accordingly (see SS wiki for details) for example: [Authenticate] [RequiredPermission("Hello")] public class HelloService : Service { public object Any(Hello request) { return new HelloResponse { Result = "Hello, " + request.Name }; } } Normally ServiceStack calls the method bool HasPermission(string permission) in IAuthSession. This method checks if the list List Permissions in IAuthSession contains the required permission, so, in a custom IAuthSession you could override HasPermission and put your OAuth2 scopes checking there.
{ "pile_set_name": "StackExchange" }
Q: How to make Javascript "isPrototypeOf" function return true? I was trying this function to see if different objects have arelationship with each other, so I tried: var o={name:'abc'}; var o2=o; console.log(o.isPrototypeOf(o2)); console.log(o2.isPrototypeOf(o)); Well, it prints 2 falses. I felt weird that, "prototype" is a property/function of each function/object, so how does JS judge whether one object is the prototype of another? I also tried: var Person=function(){ name='abc', age=30 }; var o1=new Person(); var o2=new Person(); console.log(o1.isPrototypeOf(o2)); console.log(o2.isPrototypeOf(o1)); Again, it prints 2 falses, while I expect 2 trues. A: For an o to be a prototype of o2 the o2 object needs to be constructed from a constructor whose prototype is o. In other words, o2 needs to properly inherit o. It is not enough that a variable is assigned an object or two objects are similar. One object must inherit from another. So in the classic sense, this must happen: var o = {}; var OConstructor = function () {}; OConstructor.prototype = o; var o2 = new OConstructor(); o.isPrototypeOf(o2); // true In modern code you can also inherit using Object.create(): var o = {}; var o2 = Object.create(o); o.isPrototypeOf(o2); // true
{ "pile_set_name": "StackExchange" }
Q: Translating a function from R into Matlab I am trying to reproduce a function in R in Matlab. I do not have much experience with R so it is difficult for me to understand some of the code. Here is the R code: # Model Calculations # ================== # # Function to determine length of stay df. # # t = time since hospital admission in days # age = age at admision in years # type = type of stroke (1. Haemorhagic, 2. Cerebral Infarction, 3. TIA) # los.df <- Vectorize(function(t, age, type,dest){ par <- c(6.63570, -0.03652, -3.06931, 0.07153, -8.66118, 0.08801, 22.10156, 2.48820, 1.56162, 1.27849, 11.76860, 3.41989, 63.92514) alpha1 <- par[1] beta1 <- par[2] alpha2 <- par[3] beta2 <- par[4] theta0 <- par[5] theta1 <- par[6] mu1 <- par[7] mu2 <- par[8] mu3 <- par[9] mu4 <- 0 nu1 <- 0 nu2 <- 0 nu3 <- par[10] nu4 <- 0 rho1 <- 0 rho2 <- par[11] rho3 <- par[12] rho4 <- par[13] # p <- exp(-exp(theta0 + theta1*age)) temp.mat <- matrix(c(1,0,1,0,1-p,p),3,2,byrow=TRUE) initial.state.vec <- rep(0,7) initial.state.vec[c(type,type+1)] <- temp.mat[type,] # lambda1 <- exp(alpha1 + beta1*age) lambda2 <- exp(alpha2 + beta2*age) Q <- matrix(0,7,7) Q[1,] <- c(-(lambda1+mu1+nu1+rho1), lambda1, 0, 0, mu1, nu1, rho1) Q[2,] <- c(0, -(lambda2+mu2+nu2+rho2), lambda2, 0, mu2, nu2, rho2) Q[3,] <- c(0, 0, -(mu3+nu3+rho3), 0, mu3, nu3, rho3) Q[4,] <- c(0, 0, 0, -(mu4+nu4+rho4), mu4, nu4, rho4) Pt <- expm(t/365*Q) Ft <- sum(as.numeric(initial.state.vec %*% Pt)[dest:dest]) return(Ft) }) I am having difficulty in understanding the following lines of code and what they mean: temp.mat <- matrix(c(1,0,1,0,1-p,p),3,2,byrow=TRUE) initial.state.vec <- rep(0,7) initial.state.vec[c(type,type+1)] <- temp.mat[type,] Here is my Matlab code in which I have tried to reproduce the R code: function Ft = losdf(age, strokeType, dest) % function to determine length of stay in hospitaal of stroke patients % t = time since admission (days); % age = age of patient; % strokeType = 1. Haemorhagic, 2. Cerebral Infarction, 3. TIA; % dest = 5.Death 6.Nursing Home 7. Usual Residence; alpha1 = 6.63570; beta1 = -0.03652; alpha2 = -3.06931; beta2 = 0.07153; theta0 = -8.66118; theta1 = 0.08801; mu1 = 22.10156; mu2 = 2.48820; mu3 = 1.56162; mu4 = 0; nu1 = 0; nu2 = 0; nu3 = 1.27849; nu4 = 0; rho1 = 0; rho2 = 11.76860; rho3 = 3.41989; rho4 = 63.92514; Ft = zeros(365,1); for t = 1:1:365 p = (exp(-exp(theta0 + (theta1.*age)))); if strokeType == 1 initialstatevec = [1 0 0 0 0 0 0]; elseif strokeType == 2 initialstatevec = [0 1 0 0 0 0 0]; else initialstatevec = [0 0 (1-p) p 0 0 0]; end lambda1 = exp(alpha1 + (beta1.*age)); lambda2 = exp(alpha2 + (beta2.*age)); Q = [ -(lambda1+mu1+nu1+rho1) lambda1 0 0 mu1 nu1 rho1; 0 -(lambda2+mu2+nu2+rho2) lambda2 0 mu2 nu2 rho2; 0 0 -(mu3+nu3+rho3) 0 mu3 nu3 rho3; 0 0 0 -(mu4+nu4+rho4) mu4 nu4 rho4; 0 0 0 0 0 0 0; 0 0 0 0 0 0 0; 0 0 0 0 0 0 0]; Pt = expm(t./365.*Q); Pt = Pt(strokeType, dest); Ft(t) = sum(initialstatevec.*Pt); end When I plot the output, it is not giving me the same values in Matlab as it is in R. I cannot identify where I am going wrong; I know my values of Pt are correct. I think I may have made an error in setting up initialstatevec or in defining Ft(t)? If anyone can give me advice on where I have went wrong this would be much appreciated. A: This line temp.mat <- matrix(c(1,0,1,0,1-p,p),3,2,byrow=TRUE) creates a matrix of 3 rows and 2 columns and are putting the elements you give him by filling rows by rows. Let's say p = 0.5 and temp.mat is like this : [,1] [,2] [1,] 1.0 0.0 [2,] 1.0 0.0 [3,] 0.5 0.5 This line initial.state.vec <- rep(0,7) creates a vector of seven 0 : > initial.state.vec [1] 0 0 0 0 0 0 0 And this line initial.state.vec[c(type,type+1)] <- temp.mat[type,], according to the value of type : 1, 2 or 3, puts the row indexed by type of your matrix in specific indexes of vector which are also calculated according to the value of type. It means that : For type = 1, you take the 1st row of your matrix and you put in the 1st and 2nd index of your vector. For type = 2, you take the 2nd row of your matrix and you put it in the index 2 and 3 and for type = 3, you take the 3rd row and you put in the index 3 and 4. Example with type = 3 : temp.mat[type,] [1] 0.5 0.5 initial.state.vec [1] 0.0 0.0 0.5 0.5 0.0 0.0 0.0 Hope it will help for your translation.
{ "pile_set_name": "StackExchange" }
Q: Creating Internal Wizards using Java Swing I want to create an internal wizard in my Java GUI application such that the clicking of a menu item results in popping up of a wizard that guides the user through a series of steps. I have done lot of research and couldn't find anything with decent enough documentation. Can someone help me out please? Has someone worked on creating a wizard that pops up INSIDE a GUI application? Thanks in advance! A: You can use cjwizard. It can be embedded inside a JDialog as it is based in JPanel. And you can see how to use it in https://github.com/cjwizard/cjwizard/blob/master/docs/quickstart.md for example: // create the WizardContainer: final PageFactory pageFactory = /* create a PageFactory, see the link */; final WizardContainer wizard = new WizardContainer(pageFactory) // stick the WizardContainer into a dialog: final JDialog dialog = new JDialog(); dialog.getContentPane().add(wizard); dialog.pack(); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dialog.setVisible(true); Disclaimer: I'm part of the development team. A: If there are no third-party libraries to satisfy the requirements you have then you can just write your own approach. A set of panels, each one having Previous, Next buttons and some of them Finish. The current panel just needs to know which are the previous and the next panels.
{ "pile_set_name": "StackExchange" }
Q: Remove a line from a .txt line on grep match in Shell So I'm fairly new to Shell scripting and trying to build a function that deletes a line from a .txt file. To be clear I want to be able to run the following command $ ./script.sh searchTerm delete Which should find the line containing 'searchTerm' and remove it. I am passing the $1 (to capture the searchTerm) into the deletePassword function but can't seem to get it to work. Would love some advice :) #Delete a password if [[ $2 == "delete" ]]; then deletePassword $1 fi function deletePassword () { line=grep -Hrn $1 pwstore.txt sed -n $line pwstore.txt echo "Deleted that for you.." } When running the previous command I get the following error: sed: 1: "pwstore.txt": extra characters at the end of p command A: Your line variable isn't being set as you expect, as you need to use command substitution to capture the result of a command like that. eg: line=$(grep -Hrn $1 pwstore.txt) I would suggest just using sed instead: sed -i.bak "/$1/d" pwstore.txt This will delete any lines which match the string stored in $1 from pwstore.txt (and create a backup of the original file at pwstore.txt.bak)
{ "pile_set_name": "StackExchange" }
Q: jQuery UI Autocomplete code doesn't work w/ valid XML, any ideas why? Using jQuery UI's "XML data parsed once" autocomplete. I've checked the feed and it comes out as valid and I even logged it with error() and I get OK 200 for the status and 4 for the readystate (the XML file can be seen below). http://www.finalfantasyunion.com/includes/xml/games.xml My jQuery code is: <script> $(document).ready(function() { $.ajax({ dataType: 'xml', url: '/includes/xml/games.xml', success: function(xmlResponse) { var data = $('game', xmlResponse).map(function() { return { name: $('name', this).text(), parsed: $('parsed', this).text() }; }).get(); $("#category").autocomplete({ source: data, minLength: 2, select: function(event, ui) { alert(ui.item.name); } }); }, error: function(xmlResponse) { console.log(xmlResponse); } }) }); </script> If it makes any difference, this file the above code is loaded in is done via Ajax (basically, I have a page which has a div, which loads in a PHP, which include the above code at the top). But I doubt that has anything to do with this, since the xmlResponse seems to appear fine, just can't seem to figure out why success: isn't firing. A: Check the Overview section in the plugin documentation: The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. Notice, that you need to have either label or value property in your js object to have it displayed. So, try something like this: return { value: $('name', this).text(), name: $('name', this).text(), parsed: $('parsed', this).text() };
{ "pile_set_name": "StackExchange" }
Q: Form is posting nothing when trying to post formdata using ajax When posting my form using ajax I see all data is entirely empty. A result comes back from the php page I am posting to, so the ajax call works fine. This is my ajax code: $("#vacature-form").on('submit',(function(e){ e.preventDefault(); grecaptcha.ready(function() { // do request for recaptcha token // response is promise with passed token grecaptcha.execute('6LdtbqEUAAAAAMU9yt7aKM0H0xUqXpQOsNhn0nNA', {action: 'new_email'}).then(function(token) { // add token to form $('#vacature-form').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token + '">'); $.ajax({ url: "mail/mail_send.php", type: "POST", data: new FormData(this), contentType: false, cache: false, processData:false, success: function(data){ $(".error-container2").slideDown().html(data); }, error: function(){ console.log('oops'); } }); }); }); })); And this is my html form: <form id="vacature-form" action="mail/mail_send.php" enctype="multipart/form-data" method="post" class="contact_form row contact-form" role="form"> <p class="col-sm-12 kl-fancy-form"> <input type="text" name="name" class="form-control form-control-name" tabindex="1" maxlength="35" required=""> <label class="control-label">Naam</label> </p> <p class="col-sm-12 kl-fancy-form"> <select class="geslacht form-control geslacht-control" name="geslacht" required> <option value="" disabled selected>Kies uw geslacht</option> <option value="Man">Man</option> <option value="Vrouw">Vrouw</option> </select> </p> <p class="col-sm-12 kl-fancy-form"> <input type="text" name="place" class="form-control form-control-place"tabindex="1" maxlength="35" required=""> <label class="control-label">Woonplaats</label> </p> <p class="col-sm-12 kl-fancy-form"> <input type="text" name="phone" class="form-control form-control-phone" tabindex="1" maxlength="35" required=""> <label class="control-label">Telefoonnummer</label> </p> <p class="col-sm-12 kl-fancy-form"> <input type="file" name="files[]" class="file-control form-control form-control-file" tabindex="1" maxlength="35" multiple> <label class="control-label">Upload je CV</label> </p> <p class="col-sm-12 kl-fancy-form"> <input type="text" name="email" class="form-control form-control-email h5-email" tabindex="1" maxlength="35" required=""> <label class="control-label">Emailadres</label> </p> <p class="col-sm-12 kl-fancy-form"> <textarea name="message" class="form-control form-control-message" cols="30" rows="10" tabindex="4" required=""></textarea> <label class="control-label">Bericht</label> </p> <p class="col-sm-12"> <button class="btn btn-fullcolor sendbutton" type="submit">Verzenden</button> </p> <div class="col-sm-12"> <div class="error-container2 lean"></div> </div> </form> I've tried adding enctype="multipart/form-data" to my form but this changed nothing. Form Data in my network tab shows nothing, not even the names of the input fields in my form, it's just completely empty. How can I fix that? A: You are using this to get the form, inside the promise resolve callback, but you should do it like this $("#vacature-form").on('submit',(function(e){ e.preventDefault(); var form = e.target; grecaptcha.ready(function() { // do request for recaptcha token // response is promise with passed token grecaptcha.execute('6LdtbqEUAAAAAMU9yt7aKM0H0xUqXpQOsNhn0nNA', {action: 'new_email'}).then(function(token) { // add token to form $('#vacature-form').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token + '">'); $.ajax({ url: "mail/mail_send.php", type: "POST", data: new FormData(form), contentType: false, cache: false, processData:false, success: function(data){ $(".error-container2").slideDown().html(data); }, error: function(){ console.log('oops'); } }); }); }); }));
{ "pile_set_name": "StackExchange" }
Q: Get File Path using File name from a TextBox in C# I'm using input type = file and I'm using Chrome so I would not be allowed to get the file path of the file chosen. It only gives back the file name. This is my existing code: string path = Path.GetFullPath(appPerfLog.Value); I was expecting this result so that I could use the full Path in my app: C:\Users\myUsername\Desktop\someFolder\Proactive_Hiring_VW101582_Combo_200users_09210316.csv But this is what I get instead: C:\Program Files (x86)\IIS Express\Proactive_Hiring_VW101582_Combo_200users_09210316.csv How can I get the full path by searching the directories in my computer? I need to use it for StreamReader. Google Chrome only returns the file name due to security concerns so I need help on knowing a workaround/alternative. A: There is no such thing as a full path to an uploaded file, or at least, not one you ought to be using. When you upload a file to a web server, the web framework you use stores this file either in memory or on disk in a temporary directory, and from there, it is made accessible to your application as a stream to read it once, or with a method to save it to a directory of your choice. What you're trying to do is not going to fly once your application is deployed on a web server, because there is no guarantee that the file is even going to be present with the name it used to have on the client. For all you know, the file named D:\Temp\Foo.txt at the client is named C:\Windows\Temp\asdfg123.tmp on the server. You will need to use the appropriate APIs for the web application framework you're using. For an ASP.NET FileUpload control, you're going to have to use FileUpload.SaveAs(string filename) to let ASP.NET write the file to a path of your choosing. After that, you can use the filename to read the file from your code.
{ "pile_set_name": "StackExchange" }
Q: Can I install pg_dump without installing postgres on Alpine? I have tried to install pg_dump as part of installation of postgres-client, however it does not include pg_dump. Can pg_dump be installed without a full installation of postgres on Alpine Linux? A: No - to install pg_dump and associated utilities, you'll need to run apk add postgresql, which will install the full PostgreSQL suite. The installed size is currently 12.1mb (for v9.6.0-r1) vs just 451kb for postgresql-client, so it's definitely bigger. If you're using Alpine in Docker, that might not be a big deal. If you're using it in an embedded device where size matters, you could simply copy over pg_dump or whatever else you need.
{ "pile_set_name": "StackExchange" }
Q: PHP Why the imported csv file only insert the first row of csv to SQL Let's say I have 3 row in the .csv file with 3 column. In that case I need to import the exact same file for 3 times to get all my data in the .csv file to completely inserted into my SQL database. I thought !feof($file) should make sure the looping through the end of file? if (isset($_POST['submitI'])){ $filename = $_FILES["file"]["tmp_name"]; if ($_FILES["file"]["size"] > 0){ $file = fopen($filename, "r"); while (!feof($file)){ $getData = fgetcsv($file, '0'); $sql = "SELECT * FROM murid WHERE No_Sek_Murid = '".$getData[0]."'"; $result = mysqli_query($conn, $sql); if(empty($getData[0] || $getData[1] || $getData[2])){ $errorForm = "Sila isikan semua medan dalam fail!"; echo "<script type='text/javascript'>alert('$errorForm');</script>"; echo "<script> location.href='../main.php'; </script>"; exit(); } if(mysqli_num_rows($result) === 0){ $sqlMurid = "INSERT INTO murid (No_Sek_Murid, Nama_Murid, Kelas_Murid) VALUES ('".$getData[0]."', '".$getData[1]."', '".$getData[2]."')"; $sqlKelab = "INSERT INTO kelab (Kod_Kelab, No_Sek_Murid, ID_Pengguna) VALUES ('{$_SESSION['kodKelab']}', '".$getData[0]."', '{$_SESSION['username']}')"; mysqli_query($conn, $sqlMurid); mysqli_query($conn, $sqlKelab); $success = "Berjaya menambah rekod ke dalam pangkalan data!"; echo "<script type='text/javascript'>alert('$success');</script>"; echo "<script> location.href='../main.php'; </script>"; exit(); } } fclose($file); } else { $errorfile = "Operasi import gagal!"; echo "<script type='text/javascript'>alert('$errorfile');</script>"; echo "<script> location.href='../main.php'; </script>"; exit(); } } A: Don't use exit() unnecessarily. Also you passed multiple parameters to empty() function which seems incorrect. You can run your code without exit function as below: if (isset($_POST['submitI'])){ $filename = $_FILES["file"]["tmp_name"]; if ($_FILES["file"]["size"] > 0){ $file = fopen($filename, "r"); while (!feof($file)){ $getData = fgetcsv($file, '0'); $sql = "SELECT * FROM murid WHERE No_Sek_Murid = '".$getData[0]."'"; $result = mysqli_query($conn, $sql); if(empty($getData[0]) || empty($getData[1]) || empty($getData[2])){ $errorForm = "Sila isikan semua medan dalam fail!"; echo "<script type='text/javascript'>alert('$errorForm');</script>"; echo "<script> location.href='../main.php'; </script>"; } elseif(mysqli_num_rows($result) === 0){ $sqlMurid = "INSERT INTO murid (No_Sek_Murid, Nama_Murid, Kelas_Murid) VALUES ('".$getData[0]."', '".$getData[1]."', '".$getData[2]."')"; $sqlKelab = "INSERT INTO kelab (Kod_Kelab, No_Sek_Murid, ID_Pengguna) VALUES ('{$_SESSION['kodKelab']}', '".$getData[0]."', '{$_SESSION['username']}')"; mysqli_query($conn, $sqlMurid); mysqli_query($conn, $sqlKelab); $success = "Berjaya menambah rekod ke dalam pangkalan data!"; echo "<script type='text/javascript'>alert('$success');</script>"; echo "<script> location.href='../main.php'; </script>"; } } fclose($file); } else { $errorfile = "Operasi import gagal!"; echo "<script type='text/javascript'>alert('$errorfile');</script>"; echo "<script> location.href='../main.php'; </script>"; }
{ "pile_set_name": "StackExchange" }
Q: Enlace HTML no se abre Debido a que quiero que el enlace se abra en la misma pestaña, no he añadido ningún target, ya que se supone que "_self" es el que viene por defecto. No obstante, solo con este código, no abre ningún enlace: <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> </head> <body> <h1>Abre</h1> <a href="www.youtube.com" >YT</a> </body> </html> He probado a poner onclick="window.open(this.href)" después del enlace, pero ello no ha solucionado el problema. Sé que el problema no es del enlace en sí ya que, de poner target="_blank" sí se abre. El problema es que de esta manera se abre en otra pestaña y a mi me gustaría que lo hiciera en la misma. ¿Qué puedo hacer para que el link se abra y lo haga en la misma pestaña? A: Agrégale el protocolo http:// al enlace. <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> </head> <body> <h1>Abre</h1> <a href="https://www.youtube.com" >YT</a> </body> </html> Hay que agregarle el protocolo http o https porque sin él, la URL estaba funcionando como una URL relativa, adjuntando la cadena www.youtube.com a la URL que tenga el navegador, de tal modo que si estamos en http://localhost el resultado del click nos estaba redirigiendo a http://localhost/www.youtube.com Agregándole el protocolo si nos lleva directamente a http://www.youtube.com
{ "pile_set_name": "StackExchange" }
Q: Update Query With If Exists I am trying to write a query that will update my table #master12.cg when it is null. So here are my steps needed: 1) Check if #master12.uid exists in #check1.dasboot and if it does, then update #master12.cg with that value 2) Check if #master12.uid exists in #check.uid and if it does update #master12.cg with the value in #check2.redbluegreen 3) If #master12.uid does not exist in either table then just leave #master12.uid as null I have tried this query Update #master12 Set [cg] = case when exists (Select [dasboot] FROM [#check1] WHERE [#master]. [uid] = [#check1].[uid]) when not exists (Select [redbluegreen] FROM [#check2] WHERE [#master12].[uid] = [#check2].[uid] else [#master12].[cg] end WHERE [#master12].[cg] IS NULL However this query presents an error of: Msg 156, Level 15, State 1, Line 4 Incorrect syntax near the keyword 'when'. Msg 156, Level 15, State 1, Line 5 Incorrect syntax near the keyword 'else'. How should I write this update statement so that the checks listed above are performed and my table is updated accordingly? A: SQLServer case when statement doesn't work like that. You need a condition, and then a result. Your query only has a condition. You could rewrite your query like that : Update #master12 Set [cg] = [dasboot] from #master12 m join [#check1] c1 on m.[uid] = c1.[uid] WHERE m.[cg] IS NULL Update #master12 Set [cg] = [redbluegreen] from #master12 m join [#check2] c2 on m.[uid] = c2.[uid] WHERE m.[cg] IS NULL Or maybe in a single one like : Update #master12 Set [cg] = isnull([dasboot], [redbluegreen]) from #master12 m left join [#check1] c1 on m.[uid] = c1.[uid] left join [#check2] c2 on m.[uid] = c2.[uid] WHERE m.[cg] IS NULL But it will also depend on what you want when you have a uid value present in both tables #check1 and #check2 and which value you want to be used for the update.
{ "pile_set_name": "StackExchange" }
Q: not able to display footer using TOM and javascript in mozila How to diplay footer like this in mozilla? <html> <TABLE ID="oTable_1" BORDER="0" BGCOLOR="lightslategray" width=100% > <TBODY ID="oTBody0_1"></TBODY> <TBODY ID="oTBody0_2"></TBODY></TABLE> <SCRIPT LANGUAGE="JavaScript"> var oTHead = oTable_1.createTHead(); var oTFoot = oTable_1.createTFoot(); var oCaption = oTable_1.createCaption(); var oRow, oCell; //code to display table body //but when i am displayin footer its not displaying in mozila ..working in chrome and IE oRow = oTFoot.insertRow(); oCell = oRow.insertCell(); oCell.innerHTML = '<center> hi mozilla </center>' ; oCell.colSpan = "12"; </script> </html> A: Try oRow = oTFoot.insertRow(-1); oCell = oRow.insertCell(-1) The index argument is not optional for insertRow() and insertCell(): If index is -1 or equal to the number of rows, the row is appended as the last row. If index is omitted or greater than the number of rows, an error will result.
{ "pile_set_name": "StackExchange" }
Q: How to avoid downloading schema file from internet during spring initialization I have a web app running on a production server which does not allow public internet access. The initialization fails with error like 2010-02-18 15:21:33,150 **WARN** [SimpleSaxErrorHandler.java:47] Ignored XML validation warning org.xml.sax.SAXParseException: schema_reference.4: Failed to read schema document 'https://jax-ws.dev.java.net/spring/servlet.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>. at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195) ... 2010-02-18 15:21:33,154 **ERROR** [ContextLoader.java:215] Context initialization failed org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 9 in XML document from ServletContext resource [/WEB-INF/app.xml] is invalid; nested exception is org.xml.sax.SAXPar seException: cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'wss:binding'. at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:389) It seems the 1st WARN indicates the app failed to download the schema file, which caused the 2nd ERROR. My questions are: I feel it is reasonable that I should be able to run an app w/o having to have internet access. how can I ask the xml parser to use a local schema file instead of a copy downloaded from the internet. I know XML catalog has the capability. I am using tomcat and spring. Is there a way to configure XML catalog? Are there other mechanisms that can achieve the same purpose? If I cannot redirect the parser to use a local schema file. Can I disable the xml schema validation? Again, I would like to just configure the behavior without touching the code. A: Put the schemas you need in your classpath, and then use a resolver to use it.
{ "pile_set_name": "StackExchange" }
Q: Why isn't the Microsoft Public License compatible with the GPL? According to this GNU Project page, regarding Microsoft Public License (Ms-PL): This is a free software license; it has a copyleft that is not strong, but incompatible with the GNU GPL. They do not explain why it is incompatible. I cannot find any satisfactory answers nor explanations via Google. A: As far as I can see, the incompatibility between GPL and Ms-PL stems from the fact that the Ms-PL does not seem to allow sub-licensing or dual-licensing. As the GPL requires that all code in a GPL-licensed product is covered by the GPL and the Ms-PL seems to require code that is Ms-PL licensed to remain covered by the Ms-PL and only the Ms-PL, this makes it impossible to have code covered by these two licenses in one product, thus rendering the licenses incompatible. My understanding of the incompatibility comes from this quote from the Ms-PL license (emphasis mine): (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. [...] A: I am not a lawyer, and this is not legal advice. If you want a definitive answer, consult an attorney. I cannot find any potential incompatibility with the GPL v3 (as I understand it) except perhaps §3(D), which disallows relicensing under a license that does not impose compatible requirements. The GPL also disallows relicensing under a license that is less permissive, as the FSF defines it. You should email the FSF about this, to get their take, as I can't find their reasoning published on the GNU or FSF websites. A: In general, the GPL states that you can use non-GPL licensed code in your GPL-licensed product provided that the non-GPL license does not impose more restrictions than the GPL. In other words, you can freely use 3-clause-BSD-licensed code in your GPL project. This doesn't change the license of the BSD-licensed code - the GPL is viral only to code that uses GPL-licensed code, not to code that is used by GPL-licensed code (that would be unreasonable and in general impossible). On the other hand, the 4-clause-BSD license contains an additional clause about advertising, which doesn't exist in the GPL, and so is incompatible. I see two candidates for the offending clauses in the Ms-PL. One is 3c, which requires the preservation of not only copyright notices (that's pretty much universal across licenses), but also patent, trademark and attribution notices. The other is the second part of 3d, which imposes a restriction on the compiled form of the code that is not there in this form in the GPL. But IANAL, so I'm not sure about this. Note also that the Ms-PL contains a patent provision similar to that of the Apache License, which makes it incompatible with the GPLv2, but not the GPLv3 (which added similar wording of its own). See the description on GNU's website: http://www.gnu.org/licenses/license-list.html#apache2
{ "pile_set_name": "StackExchange" }
Q: Routing rules for MVC 2 in ASP.Net (c#) How can I add a routing rule that takes this URL http://localhost:57334/Blog/index.aspx?Id=23 and converts to this: http://localhost:57334/Blog/Id/23/blog A: Routing rules typically interprets the urls you give and maps them to resources meant to handle those requests. Your url suggests you are using webforms and not asp.net mvc. What i think you need is URL rewriting... you could check out this link Hope this helps
{ "pile_set_name": "StackExchange" }
Q: C++17 std::optional in G++? cppreference.com - std::optional identifies std::optional as being available "since C++17". C++ Standards Support in GCC - C++1z Language Features Lists c++17 features. I do not see std::optional in the list. Were is std::optional documented for G++? #include <string> #include <iostream> #include <optional> // optional can be used as the return type of a factory that may fail std::optional<std::string> create(bool b) { if(b) return "Godzilla"; else return {}; } int main() { std::cout << "create(false) returned " << create(false).value_or("empty") << '\n'; // optional-returning factory functions are usable as conditions of while and if if(auto str = create(true)) { std::cout << "create(true) returned " << *str << '\n'; } } A: You need to follow the "library implementation" link https://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html#status.iso.201z it is described under Library Fundamentals V1 TS Components (Table 1.5). That's because std::optional is a library feature, not a language feature, as mentioned in one of the comments.
{ "pile_set_name": "StackExchange" }
Q: Windows 10 BSOD due to HID Log Name: System Source: Microsoft-Windows-DriverFrameworks-UserMode Date: 28/11/2018 16:34:44 Event ID: 10111 Task Category: User-mode Driver problems. Level: Critical Keywords: User: SYSTEM Computer: DESKTOP-3JS743D Description: The device HID-compliant headset (location (unknown)) is offline due to a user-mode driver crash. Windows will attempt to restart the device 5 more times. Please contact the device manufacturer for more information about this problem. Event Xml: <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event"> <System> <Provider Name="Microsoft-Windows-DriverFrameworks-UserMode" Guid="{2e35aaeb-857f-4beb-a418-2e6c0e54d988}" /> <EventID>10111</EventID> <Version>1</Version> <Level>1</Level> <Task>64</Task> <Opcode>0</Opcode> <Keywords>0x2000000000000000</Keywords> <TimeCreated SystemTime="2018-11-28T16:34:44.466142000Z" /> <EventRecordID>1122</EventRecordID> <Correlation /> <Execution ProcessID="740" ThreadID="860" /> <Channel>System</Channel> <Computer>DESKTOP-3JS743D</Computer> <Security UserID="S-1-5-18" /> </System> <UserData> <UmdfDeviceOffline xmlns="http://www.microsoft.com/DriverFrameworks/UserMode/Event"> <LifetimeId>{714af0f3-18c1-4dd0-8385-17569f8faac6}</LifetimeId> <FriendlyName>HID-compliant headset</FriendlyName> <Location>(unknown)</Location> <InstanceId>HID\VID_0951&amp;PID_16A4&amp;MI_03&amp;COL02\7&amp;1C94FA2&amp;0&amp;0001</InstanceId> <RestartCount>5</RestartCount> </UmdfDeviceOffline> </UserData> </Event> Can anyone help me with this crash? I dont really understand how I can fix this. The driver files it refers to are c:\Windows\system32\DRIVERS\UMDF\HidTelephony.dll and C:\Windows\system32\drivers\WudfRD.sys All drivers are up to date. Headset is the HyperX Cloud. A: The issue was entirely unrelated to Drivers and ended up being bad CPU voltage settings.
{ "pile_set_name": "StackExchange" }
Q: How to add markers on OpenLayers 3 giving coordinates I need to add a marker on my map when I call the method addMarker(long, lat). The only example I have found is this one in the OpenLayers example list, but it adds only one marker in a specific place. I need to be able to call my method anytime I need and pass the coordinates (the general idea is to have a simple menu where the user can type the long and lat and click a submit button and the marker is drawn on the map). In the example, if I got it right, they created a feature and its style, then created a layer to draw the icon and initialized the map using that layer. var iconFeature = new ol.Feature({ geometry: new ol.geom.Point(ol.proj.transform([-72.0704, 46.678], 'EPSG:4326', 'EPSG:3857')), name: 'Null Island', population: 4000, rainfall: 500 }); var iconStyle = new ol.style.Style({ image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({ anchor: [0.5, 46], anchorXUnits: 'fraction', anchorYUnits: 'pixels', opacity: 0.75, src: 'data/icon.png' })) }); iconFeature.setStyle(iconStyle); var vectorSource = new ol.source.Vector({ features: [iconFeature] }); var vectorLayer = new ol.layer.Vector({ source: vectorSource }); var map = new ol.Map({ layers: [new ol.layer.Tile({ source: new ol.source.OSM() }), vectorLayer], target: document.getElementById('map'), view: new ol.View2D({ center: [0, 0], zoom: 3 }) }); I believe I can create an array of features, something like that(an example I saw here): var iconFeatures=[]; var iconFeature = new ol.Feature({ geometry: new ol.geom.Point(ol.proj.transform([-72.0704, 46.678], 'EPSG:4326', 'EPSG:3857')), name: 'Null Island', population: 4000, rainfall: 500 }); var iconFeature1 = new ol.Feature({ geometry: new ol.geom.Point(ol.proj.transform([-73.1234, 45.678], 'EPSG:4326', 'EPSG:3857')), name: 'Null Island Two', population: 4001, rainfall: 501 }); iconFeatures.push(iconFeature); iconFeatures.push(iconFeature1); Here is my method so far: class map{ private markerFeatures = []; //receive an array of coordinates public addMarkers(markers: Array<Marker>): void { for (var i in markers) { var markFeature = new ol.Feature({ geometry: new ol.geom.Point(ol.proj.transform([markers[i].long, markers[i].lat], 'EPSG:4326', 'EPSG:3857')), name: 'Null Island', population: 4000, rainfall: 500 }); this.markerFeatures.push(markFeature); } } } But nothing happened when I did that. Obs: I created the map, the layer and called the method. I'm using OL v3.7 A: Assuming you have a layer containing a vector source, you just need to add one more step to your addMarkers function: myVectorSource.addFeatures(markerFeatures);
{ "pile_set_name": "StackExchange" }
Q: Set windows form properties values from separated class I have a windows forms application i have too many forms, i want to set all of them same properties at once, any help please A: You can use PropertyBinding, and the value is save on Settings from application. I make one example: In Properties window, select Application Settings, PropertyBinding: And select whats property you want, if exists the setting select, or create new: After, you can change the value on Settings window, and all forms with setting, will be changed: Result: Values are save in the .config file: <applicationSettings> <WindowsFormsPropertiesBind.Properties.Settings> <setting name="BackColor" serializeAs="String"> <value>LightBlue</value> </setting> </WindowsFormsPropertiesBind.Properties.Settings> </applicationSettings>
{ "pile_set_name": "StackExchange" }
Q: What Android methods are called when battery dies? When the battery on my Android device dies what methods in the Activity and Fragment classes (if any) are called during the "Powering Off" stage of the device? Also, if a user is currently looking at a screen in my app and they hold the power button and choose switch off, do the events called/not called coincide with when the battery is depleted and shuts down automatically? OnPause? OnStop? OnDestroy? OnDetach? Bonus: Will I have enough time to save a small amount of data to a web server? To clarify "dies" when the device's battery is 'completely' dead, accepts no more input and a message box/loading screen pops up on the screen stating "Powering Off". Shortly there after the device switches off. I just need enough time to save a forms state before the phone switches off, I have a strategy to clean the saved data should the phone not switch off, but I want to get as close to the phone switching off as possible (any more than a minute is pointless really). A: onDestroy is called on everything when the battery reaches 0.5% EDIT: There is no specified time that you have to do anything in the shutdown process resulting from low/dead battery, that would be dependent on the specific phone battery and not the system, so you may have enough time to save data to a web server on some phones but not others. Experimentally, I have only been able to write a short line to a file I was already writing to before onDestroy was called and nothing more.
{ "pile_set_name": "StackExchange" }
Q: Query to group distinct values and show sum of array values in mongodb I wanted to group by cart.name and find the sum of cart.qty in mongodb. Below is sample document { "_id" : ObjectId("581323379ae5e607645cb485"), "cust" : { "name" : "Customer 1", "dob" : "09/04/1989", "mob" : 999999999, "loc" : "Karimangalam", "aadhar" : { } }, "cart" : [ { "name" : "Casual Shirt", "qty" : 1, "mrp" : 585, "discperc" : 10, "fit" : null, "size" : "L" }, { "name" : "Casual Shirt", "qty" : 1, "mrp" : 500, "discperc" : 0, "fit" : null, "size" : "L" }, { "name" : "Cotton Pant", "qty" : 1, "mrp" : 850, "discperc" : 0, "fit" : null, "size" : "34" }, { "name" : "Cotton Pant", "qty" : 1, "mrp" : 1051, "discperc" : 10, "fit" : null, "size" : "34" } ], "summary" : { "bill" : 2822.4, "qty" : 4, "mrp" : 2986, "received" : "2800", "balance" : -22.40000000000009 }, "createdAt" : ISODate("2016-10-28T10:06:47.367Z"), "updatedAt" : ISODate("2016-10-28T10:06:47.367Z") } There are many document like this. I want the output as below distinct product name (cart.name) and its total qty {Casual Shirt , 30}, {Cotton Pant , 10}, {T-Shirt , 15}, {Lower , 12} Here is my query trying to group by cart.name and sum qty db.order.aggregate( [ { $unwind: "$cart" }, { $group: { _id: "$cart.name", totalQTY: { $sum:"$cart.qty"}, count: { $sum: 1 } } } ] ) but it displays wrong totalQty values for each product name. I checked manually. Please give me the correct query. A: > db.collection.aggregate([ ... { $unwind: "$cart" }, ... { $group: { "_id": "$cart.name", totalQTY: { $sum: "$cart.qty" }, count: { $sum: 1 } } } ... ]) I get the following result: { "_id" : "Cotton Pant", "totalQTY" : 2, "count" : 2 } { "_id" : "Casual Shirt", "totalQTY" : 11, "count" : 2 } I'm not sure what you're looking for, it looks like your aggregation pipeline is correct. (Note I changed the Casual Shirt Quantity to be 10 and 1 respectively)
{ "pile_set_name": "StackExchange" }
Q: fusion-tables, help needed with getting latest data from a table and inserting it in maps code Hi all trying to find the code to pull the latest co-ordinates from a google fusion table and insert it into the code below as the origin. (var origin1) GOOGLE Fusion table setup; { "kind": "fusiontables#columnList", "totalItems": 15, "items": [ { "kind": "fusiontables#column", "columnId": 0, "name": "description", "type": "STRING" }, { "kind": "fusiontables#column", "columnId": 1, "name": "kind", "type": "STRING" }, { "kind": "fusiontables#column", "columnId": 2, "name": "name", "type": "STRING" }, { "kind": "fusiontables#column", "columnId": 3, "name": "placeId", "type": "STRING" }, { "kind": "fusiontables#column", "columnId": 4, "name": "info1", "type": "STRING" }, { "kind": "fusiontables#column", "columnId": 5, "name": "info2", "type": "STRING" }, { "kind": "fusiontables#column", "columnId": 6, "name": "info3", "type": "STRING" }, { "kind": "fusiontables#column", "columnId": 7, "name": "info4", "type": "STRING" }, { "kind": "fusiontables#column", "columnId": 8, "name": "accuracy", "type": "NUMBER" }, { "kind": "fusiontables#column", "columnId": 9, "name": "speed", "type": "NUMBER" }, { "kind": "fusiontables#column", "columnId": 10, "name": "heading", "type": "NUMBER" }, { "kind": "fusiontables#column", "columnId": 11, "name": "altitude", "type": "NUMBER" }, { "kind": "fusiontables#column", "columnId": 12, "name": "altitudeAccuracy", "type": "NUMBER" }, { "kind": "fusiontables#column", "columnId": 13, "name": "timestamp", "type": "NUMBER" }, { "kind": "fusiontables#column", "columnId": 14, "name": "geometry", "type": "LOCATION" } ] } and here is some of the data it keeps, i am trying to get the "LATEST" geometry coordinates and add that my map, to provide realtime updates. { "kind": "fusiontables#sqlresponse", "columns": [ "description", "kind", "name", "placeId", "info1", "info2", "info3", "info4", "accuracy", "speed", "heading", "altitude", "altitudeAccuracy", "timestamp", "geometry" ], "rows": [ [ "", "", "Location at Mon 14/05/2012 13:42:58", "", "resourceasstring", "", "", "", "65", NaN, NaN, NaN, NaN, 1.336966978085E12, { "geometry": { "type": "Point", "coordinates": [ 144.9339931215855, -37.83169408321385, 0.0 ] } } ], [ "", "", "Location at Mon 14/05/2012 19:20:11", "", "resourceasstring", "", "", "", "1414", NaN, NaN, NaN, NaN, 1.336987211753E12, { "geometry": { "type": "Point", "coordinates": [ 145.2516605102396, -37.92732182161065, 0.0 ] } } ], [ "", "", "Location at Mon 14/05/2012 19:40:12", "", "resourceasstring", "", "", "", "1414", NaN, NaN, NaN, NaN, 1.336988412041E12, { "geometry": { "type": "Point", "coordinates": [ 145.3447657261889, -37.91152087158031, 0.0 ] } } ], [ "", "", "Location at Tue 15/05/2012 09:41:57", "", "resourceasstring", "", "", "", "65", NaN, NaN, NaN, NaN, 1.337038917553E12, { "geometry": { "type": "Point", "coordinates": [ 144.9339498133275, -37.8317148043096, 0.0 ] } } ], This is the html/java code that display's the map; <!DOCTYPE html> <html> <head> <title>Google Maps API v3 Example: Distance Matrix</title> <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script> <style> body { margin: 20px; font-family: courier, sans-serif; font-size: 12px; } #map { height: 480px; width: 640px; border: solid thin #333; margin-top: 20px; } </style> <script> //Taken and adopted from https://developers.google.com/maps/documentation/javascript/distancematrix //Need to make the fusion table part work next!! var map; var geocoder; var bounds = new google.maps.LatLngBounds(); var markersArray = []; //var origin1 is where i want it to pull the data from the fusion table. var origin1 = new google.maps.LatLng(-37.83169408321385,144.9339931215855); var destinationA = 'glen iris, Australia'; var destinationIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000'; var originIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000'; function initialize() { var opts = { center: new google.maps.LatLng(-37.83,144.93), zoom: 20, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById('map'), opts); geocoder = new google.maps.Geocoder(); } function calculateDistances() { var service = new google.maps.DistanceMatrixService(); service.getDistanceMatrix( { origins: [origin1], destinations: [destinationA], travelMode: google.maps.TravelMode.DRIVING, unitSystem: google.maps.UnitSystem.METRIC, avoidHighways: false, avoidTolls: false }, callback); } function callback(response, status) { if (status != google.maps.DistanceMatrixStatus.OK) { alert('Error was: ' + status); } else { var origins = response.originAddresses; var destinations = response.destinationAddresses; var outputDiv = document.getElementById('outputDiv'); outputDiv.innerHTML = ''; deleteOverlays(); for (var i = 0; i < origins.length; i++) { var results = response.rows[i].elements; addMarker(origins[i], false); for (var j = 0; j < results.length; j++) { addMarker(destinations[j], true); outputDiv.innerHTML += origins[i] + ' to ' + destinations[j] + ': ' + results[j].distance.text + ' in ' + results[j].duration.text + '<br>'; } } } } function addMarker(location, isDestination) { var icon; if (isDestination) { icon = destinationIcon; } else { icon = originIcon; } geocoder.geocode({'address': location}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { bounds.extend(results[0].geometry.location); map.fitBounds(bounds); var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location, icon: icon }); markersArray.push(marker); } else { alert('Geocode was not successful for the following reason: ' + status); } }); } function deleteOverlays() { if (markersArray) { for (i in markersArray) { markersArray[i].setMap(null); } markersArray.length = 0; } } </script> </head> <META HTTP-EQUIV="refresh" CONTENT="60"> <body onload="initialize(), calculateDistances()"> <div id="inputs"> <pre class="prettyprint"> This will automatically calculate distances on load and then will re-load every minute. hahaha... Really need to work out how to pull data from a fusion table as well. </pre> <p><button type="button" onclick="calculateDistances();">Force Re-Calculate distances</button></p> </div> <div id="outputDiv"></div> <div id="map"></div> </body> </html> thx matt. A: Proof of concept: http://www.geocodezip.com/v3_GoogleEx_FusionTables_latestData.html Uses the FusionTables API v1.0 to query the table for the data; creates a native Google Maps API v3 marker for the "latest" location (the one with the greatest value in the timestamp column). Note that if you have lots of markers or only markers you may want to modify the approach.
{ "pile_set_name": "StackExchange" }
Q: GCC's extended version of asm I never thought I'd be posting an assembly question. :-) In GCC, there is an extended version of the asm function. This function can take four parameters: assembly-code, output-list, input-list and overwrite-list. My question is, are the registers in the overwrite-list zeroed out? What happens to the values that were previously in there (from other code executing). Update: In considering my answers thus far (thank you!), I want to add that though a register is listed in the clobber-list, it (in my instance) is being used in a pop (popl) command. There is no other reference. A: No, they are not zeroed out. The purpose of the overwrite list (more commonly called the clobber list) is to inform GCC that, as a result of the asm instructions the register(s) listed in the clobber list will be modified, and so the compiler should preserve any which are currently live. For example, on x86 the cpuid instruction returns information in four parts using four fixed registers: %eax, %ebx, %ecx and %edx, based on the input value of %eax. If we were only interested in the result in %eax and %ebx, then we might (naively) write: int input_res1 = 0; // also used for first part of result int res2; __asm__("cpuid" : "+a"(input_res1), "=b"(res2) ); This would get the first and second parts of the result in C variables input_res1 and res2; however if GCC was using %ecx and %edx to hold other data; they would be overwritten by the cpuid instruction without gcc knowing. To prevent this; we use the clobber list: int input_res1 = 0; // also used for first part of result int res2; __asm__("cpuid" : "+a"(input_res1), "=b"(res2) : : "%ecx", "%edx" ); As we have told GCC that %ecx and %edx will be overwritten by this asm call, it can handle the situation correctly - either by not using %ecx or %edx, or by saving their values to the stack before the asm function and restoring after. Update: With regards to your second question (why you are seeing a register listed in the clobber list for a popl instruction) - assuming your asm looks something like: __asm__("popl %eax" : : : "%eax" ); Then the code here is popping an item off the stack, however it doesn't care about the actual value - it's probably just keeping the stack balanced, or the value isn't needed in this code path. By writing this way, as opposed to: int trash // don't ever use this. __asm__("popl %0" : "=r"(trash)); You don't have to explicitly create a temporary variable to hold the unwanted value. Admittedly in this case there isn't a huge difference between the two, but the version with the clobber makes it clear that you don't care about the value from the stack. A: If by "zeroed out" you mean "the values in the registers are replaced with 0's to prevent me from knowing what some other function was doing" then no, the registers are not zeroed out before use. But it shouldn't matter because you're telling GCC you plan to store information there, not that you want to read information that's currently there. You give this information to GCC so that (reading the documentation) "you need not guess which registers or memory locations will contain the data you want to use" when you're finished with the assembly code (eg., you don't have to remember if the data will be in the stack register, or some other register). GCC needs a lot of help for assembly code because "The compiler ... does not parse the assembler instruction template and does not know what it means or even whether it is valid assembler input. The extended asm feature is most often used for machine instructions the compiler itself does not know exist." Update GCC is designed as a multi-pass compiler. Many of the passes are in fact entirely different programs. A set of programs forming "the compiler" translate your source from C, C++, Ada, Java, etc. into assembly code. Then a separate program (gas, for GNU Assembler) takes that assembly code and turns it into a binary (and then ld and collect2 do more things to the binary). Assembly blocks exist to pass text directly to gas, and the clobber-list (and input list) exist so that the compiler can do whatever set up is needed to pass information between the C, C++, Ada, Java, etc. side of things and the gas side of things, and to guarantee that any important information currently in registers can be protected from the assembly block by copying it to memory before the assembly block runs (and copying back from memory afterward). The alternative would be to save and restore every register for every assembly code block. On a RISC machine with a large number of registers that could get expensive (the Itanium has 128 general registers, another 128 floating point registers and 64 1-bit registers, for instance). It's been a while since I've written any assembly code. And I have much more experience using GCC's named registers feature than doing things with specific registers. So, looking at an example: #include <stdio.h> long foo(long l) { long result; asm ( "movl %[l], %[reg];" "incl %[reg];" : [reg] "=r" (result) : [l] "r" (l) ); return result; } int main(int argc, char** argv) { printf("%ld\n", foo(5L)); } I have asked for an output register, which I will call reg inside the assembly code, and that GCC will automatically copy to the result variable on completion. There is no need to give this variable different names in C code vs assembly code; I only did it to show that it is possible. Whichever physical register GCC decides to use -- whether it's %%eax, %%ebx, %%ecx, etc. -- GCC will take care of copying any important data from that register into memory when I enter the assembly block so that I have full use of that register until the end of the assembly block. I have also asked for an input register, which I will call l both in C and in assembly. GCC promises that whatever physical register it decides to give me will have the value currently in the C variable l when I enter the assembly block. GCC will also do any needed recordkeeping to protect any data that happens to be in that register before I enter the assembly block. What if I add a line to the assembly code? Say: "addl %[reg], %%ecx;" Since the compiler part of GCC doesn't check the assembly code it won't have protected the data in %%ecx. If I'm lucky, %%ecx may happen to be one of the registers GCC decided to use for %[reg] or %[l]. If I'm not lucky, I will have "mysteriously" changed a value in some other part of my program. A: I suspect the overwrite list is just to give GCC a hint not to store anything of value in these registers across the ASM call; since GCC doesn't analyze what ASM you're giving it, and certain instructions have side-effects that touch other registers not explicitly named in the code, this is the way to tell GCC about it.
{ "pile_set_name": "StackExchange" }
Q: What was the Democrats' counter to REDMAP? For the 2010 elections, Republicans created the Redistricting Majority Project (REDMAP) with the plan of flipping state legislative chambers to take control of the redistricting process. Did the Democrats have a similar organization, and if so what was it called? (Note: I don't consider the DSLC an equivalent group, as the Republicans also had the RSLC in 2010 but that never seems to get mentioned in analysis.) A: The DSLC has launched Advantage 2020, which seeks to be an answer to REDMAP, which will also be launching REDMAP 2020. More info: http://www.dlcc.org/advantage-2020
{ "pile_set_name": "StackExchange" }
Q: How to prevent pcre(C library) to continue matching when it failed in one string? If I have a string and a pattern: char src[]="\"http://www.aaa.cn\"</tab><tab>\"www.bbb.com\""; char pattern[] = "\"http:\/\/.*\.com\""; Then it returns "http://www.aaa.cn\"</tab><tab>\"www.bbb.com" to me (it failed but continue matching next characters). I just want some like "http://www.aaa.com", "http://www.bbb.com", not like that combined string. Can someone help me out? Should I change my pattern or add some arguments to pcre_compile() and pcre_exec() functions? A: Try this. char pattern[] = "\"http://[^\"]*\""; Better yet, don't parse HTML (or fragments thereof or XML) with regexen.
{ "pile_set_name": "StackExchange" }
Q: In graph's axis, can we say "somewhere between year1 and year2"? Here is a graph I get somewhere in the internet for illustration: Can I say Somewhere between 2006 and 2010, first three lines raise significantly ...? If we mention about lines, I think using somewhere is not wrong. But if we using the legends directly, can I use somewhere or I have to use some times? I find that we can use somewhere down the road and some times down the road at the same time. A: As you are referring to a graph, where the lines are physically drawn on a piece of paper (or on a computer screen or whatever), there is clearly a "where", the place on the graph where the lines begin going up. So "somewhere between 2006 and 2010" is perfectly acceptable and is literally accurate. There is a place on the graph between the place marked 2006 and the place marked 2010, etc. If you were just talking of this trend generally, without reference to a graph, it would be more correct to say "some time between". But people often do say "somewhere between" in that context. Perhaps they are thinking of a graph or perhaps their language is just getting a little sloppy. BTW "first three lines" requires an article. It should be "THE first three lines". And we don't say that a trend "raises", we say that it "rises". So the sentence should be, "Somewhere between 2006 and 2010, the first three lines rise significantly."
{ "pile_set_name": "StackExchange" }
Q: Why is “de” used in “il n'y a pas de bus direct”? I would need help in order not to mix up de and le or un (What article can I use to refer to a thing correctly?) I came across this sentence Il n'y a pas de bus direct? But I couldn't understand why le wasn't used (or for that matter un, if you don't want to refer to a particular bus). Y avoir doesn't seem to be in this list of verbs that are succeeded by «de» here http://french.about.com/od/grammar/a/preposition_de_3.htm A: There are some situations, and negative sentences are one of them, where de is used instead of des (which is in this context the plural of un, there may be several direct busses). Il y a des bus directs. Il n'y a pas de bus directs. (Note the plural for directs in both sentences).
{ "pile_set_name": "StackExchange" }
Q: How could i change the Text of an label by a function? I have a Label on my Windows Forms, and I want to change the Text of it by a Button2_Click, but only if an another Button clicked before. Example Code: bool var1 = false; //the Label Example label1.Text = "Noooh!"; private void Button2_Click(object sender, EventArgs e) { function1(label1.Text); } private void Button1_Click(object sender, EventArgs e) { var1 = true; } private void function1(string Text) { if (var1) { Text = "Yeaaah!"; } } It should work like this, you need to click on the button1 first, after this you should click button2 by this the function1 should be activated and change the label1 Text to "Yeaaah!". The Code is executed in Visual Studio but the label1 Text doesn't change, don't know why. A: Change function's (techically, we call it method, not function) design, pass Control (e.g. label1), not its Text: private void Button2_Click(object sender, EventArgs e) { // we modify control... function1(label1); } private void function1(Control ctrl) { if (var1) { // ... control's Text to be exact ctrl.Text = "Yeaaah!"; } }
{ "pile_set_name": "StackExchange" }
Q: How to write an if statement that's always true without using any variables and operators? How to write an if condition without using variables and operators? The condition should always be true. if(condition) { executable statements; } A: Just use any non-zero number to fill the condition in if statement Examples: if(1), if(2), .....so on similarly if(-1), if(-2), .....so on These would be held true for all cases except if(0) Reason: You can fill the condition with any value except 0. The reason for this is that generally in C, 0 is returned by a false condition and so if you enter a 0, C skips the if block terating the condition to be false. so your code would be: if(1) //I just considered 1 { executable statements; }
{ "pile_set_name": "StackExchange" }
Q: What ASP.NET MVC 3 CMS Provides Multi-language support? What Content Management Systems are built in ASP.NET MVC, are preferably open-source, and provide multi-language support? A: I asked a similar question around CMS choice some time ago: Edit in Place CMS Suggestions Having tried several I would say that Umbraco CMS is the way to go - Umbraco 5 (currently in pre-production) is written on MVC 3
{ "pile_set_name": "StackExchange" }
Q: Allow Tabbing in a contentEditable div with execCommand I am making an application where I need for a contentEditable div to be allowed to have tabs in it. I have already figured out that it is really not possible to have to work correctly. So is there a way that on keyDown it adds the HTML code for a tab, which is &#09; What I have so far is this document.getElementById('codeline').contentEditable='true'; document.getElementById('codeline').onkeydown=function(e){ if(e.keyCode==9){ e.preventDefault(); //document.getElementById('codeline').contentWindow.document.execCommand("InsertHTML",false,"&#09;"); //Thought this would work but it doesn't } } If anybody knows if there is a way to do this, or if that is the way and I am simply doing it wrong, please tell me! Thanks! A: The HTML spec specifies that a TAB char should be treated as a single white space except for when it's contained inside a <pre> element. The code that you posted above does work and it does insert a TAB char but it's just displayed by the browser as a white space. If you can put your entire editable content in a <pre> tag then your tabs will show up. If you only want to use the tabs to indent content, you can also look into execCommand('indent', false, null) A: For future readers, perhaps a simpler solution is to just use the 'pre' white-space style. original post here. white-space: pre;
{ "pile_set_name": "StackExchange" }
Q: Regular expression to transform 1.2.3 to 1.02.03 i'm really not good with regular expressions and i need one to transform "1.2.3" to "1.02.03" in a way that first part stays always as it was and second and third one will transform 2 to 02, 7 to 07 and so on but if there is 10, 15, 17 and so on it will leave it as it is. I want to use it in msbuild. samples: 2.5.7 -> 2.05.07 2.10.9 -> 2.10.09 1.7.18 -> 1.07.18 Thanks. A: /\.(\d)(?=\D|$)/g => .0$1 Works with any number of dots :) Edit: when look-ahead isn't supported but word boundaries are, you can use /\.(\d)\b/g => .0$1 ... or just because it's simpler :)
{ "pile_set_name": "StackExchange" }
Q: chmod 4755 (rwsr-xr-x) gives (rwxrwxrwx) I want to get the permissions of a program, call_shellcode (which calls shellcode), to be set to -rwsr-xr-x. When I run: sudo chmod 4755 call_shellcode the permissions for some reason is still set at -rwxrwxrwx I am trying to get the root shell, but when I execute the program I get a normal shell. I am using Ubuntu 16.04 (32-bit) in VirtualBox A: You are running gcc as root for some strange reason, but then you run the chmod as your regular user. You don't have [permission to change the rights of call_shellcode since you compiled it as root, and therefore the permissions remain unchanged. Don't compile as root! Don't do anything as root unless you have to.
{ "pile_set_name": "StackExchange" }
Q: Paper status changed from under review to Awaiting Decision I submitted my manuscript to a journal from 1 month ago in scholar one. The status changed to admin check to under review after one week. Now, it shows Awaiting Decision. Does this mean that the paper has passed the editorial check and the external reviewer completed? A: If it has been "under review" for some time, then yes - the external reviewers are done. If you didn't see "under review", then the editor is making a decision without consulting reviewers, which is usually a bad sign.
{ "pile_set_name": "StackExchange" }
Q: ORDER BY with IF...ELSE SQL Server 2008 r2 I've got a very basic problem that I'm trying to solve (basic to me, anyway), but I'm having trouble understanding why one bit of code works standalone, but when you wrap it in an IF statement, it doesn't. This works just fine: SELECT DISTINCT H.FB FROM I_HSE H WHERE H.AC IN (@AC) ORDER BY H.FB However, when I try to make use of it in an IF statement: IF @FILTERBY = '2' BEGIN (SELECT DISTINCT H.FB FROM I_HSE H WHERE H.AC IN (@AC) ORDER BY H.FB) END I get the error "Incorrect syntax near the keyword 'ORDER' I've done some searching, but I can't seem to figure out why this doesn't work. Is there another way to order the returned result set? A: Take the parenthesis off Like so: IF @FILTERBY = '2' BEGIN SELECT DISTINCT H.FB FROM I_HSE H WHERE H.AC IN (@AC) ORDER BY H.FB END
{ "pile_set_name": "StackExchange" }
Q: overwrite hdfs directory Sqoop import Is it possible to overwrite HDFS directory automatically instead of overwriting it every time manually while Sqoop import? (Do we have any option like "--overwrite" like we have for hive import "--hive-overwrite") A: Use --delete-target-dir ​It will delete <HDFS-target-dir> provided in command before writing data to this directory. A: Use this: --delete-target-dir This will work for overwriting the hdfs directory using sqoop syntax: $ sqoop import --connect jdbc:mysql://localhost/dbname --username username -P --table tablename --delete-target-dir --target-dir '/targetdirectorypath' -m 1 E.g: $ sqoop import --connect jdbc:mysql://localhost/abc --username root -P --table empsqooptargetdel --delete-target-dir --target-dir '/tmp/sqooptargetdirdelete' -m 1 This command will refresh the corresponding hdfs directory or hive table data with updated/fresh data, every time this command is run.
{ "pile_set_name": "StackExchange" }
Q: Assume $G$ is abelian. Prove that $p$ divides $|Z(G)|$. Let $G$ be a group and let $p$ be a positive prime number. Suppose $|G| = p^ n$. for some positive integer $n$. I know to be abelian you have to be commutative, where $ab=ba$ and $a,b \in$ a group. And we have that the center: $Z(G) = \{z ∈ G : ∀g \in G, zg = gz\}$. Its looks so easy to connect but I am not sure how to connect. A: Since $G$ is abelian, $G=Z(G)$, so it's obvious. But I want to tell you that even if $G$ is not abelian the theorem also holds. It follows from the Class Equation.
{ "pile_set_name": "StackExchange" }
Q: Why does the `describe` function display floats using scientific notation? Data in a .csv file looks like this: But when I am using function describe it shows me numbers in scientific notation? How can I format them within describe function? A: You can try following as mentioned in similar issue: pd.set_option('float_format',lambda x: "%.6f" % x) From the document: display.float_format : callable The callable should accept a floating point number and return a string with the desired format of the number. This is used in some places like SeriesFormatter. See formats.format.EngFormatter for an example. [default: None] [currently: None]
{ "pile_set_name": "StackExchange" }
Q: Running bazel build with an aspect on test targets does not yield test output jars running bazel build //... \ --aspects some-aspect.bzl%some_aspect \ --output_groups=some_new_output,default does not create test jars outputs. on the other hand running bazel test does create the test jar outputs: bazel test //... \ --aspects some-aspect.bzl%some_aspect \ --output_groups=some_new_output,default How come? This question was updated to reflect use of aspects: The original question: running bazel build //... does not add test code to output jar. on the other hand bazel test //... builds the test code but also runs it. Is there a way in bazel to build the test code without running the tests? A: I had a mistake in the values I gave the --output_groups flag. It should have been --output_groups=+some_new_output,+default The default can even be omitted: --output_groups=+some_new_output This flag is not documented at all. There is an open issue on this in bazel github repo.
{ "pile_set_name": "StackExchange" }
Q: Solving Boolean equations @Artes suggested this code to me to solve this system of equations: 'x[a_, b_] := Boole[a >= b] y[a_, c_] := Boole[a >= c] z[b_, c_] := Boole[b >= c] Solve[ a == x[a, b] + y[a, c] && b == x[a, b] + z[b, c] && c == y[a, c] + z[b, c], {a, b, c}]' What's the fastest way to get to the solution of x[a_, b_], which should be a parameter now. A problem which arised while coding the above was, that this code H[1, x_, y_] := 1 /; 10 - x - y >= p[B2] - y && 10 - x - y >= 0 H[1, x_, y_] := 1 /; 6 - x > p[B2] - y && 6 - x >= 0 H[1, x_, y_] := 0.5 /; 4 - x == p[B2] - y && 4 - x >= 0 H[1, x_, y_] := 0 /; others doesn't work for me. P[q_, w_] := 1 /; q > w P[q_, w_] := 0 /; others P[q_, w_] := 0.5 /; q == w This code on the other hand works fine. So i suppose that "others" in the case of multiple conditions doesn't work any longer. Is there a solution? A: Let's define the following functions: x[a_, b_] := Boole[a >= b] y[a_, c_] := Boole[a >= c] z[b_, c_] := Boole[b >= c] In fact we need only one function but for clarity of dealing with variables we have used three definitions, then we rewrite the given system Solve[ a == x[a, b] + y[a, c] && b == x[a, b] + z[b, c] && c == y[a, c] + z[b, c], {a, b, c}] {{a -> 0, b -> 1, c -> 1}, {a -> 2, b -> 2, c -> 2}} alternatively Reduce[ a == x[a, b] + y[a, c] && b == x[a, b] + z[b, c] && c == y[a, c] + z[b, c], {a, b, c}] (a == 0 && b == 1 && c == 1) || (a == 2 && b == 2 && c == 2)
{ "pile_set_name": "StackExchange" }
Q: "The fact of its being" Grammar "The fact of its being so rare a flower ought to have made it easier to trace the source of this particular specimen, but in practice it was an impossible task." I just found this sentence reading a book and it sounds weird to me. I understand the meaning, but I've never seen or studied this structure in English before. I did some research on the Internet but I could find nothing. Could anyone explain the grammar? Could you please provide more examples with the same structure? A: That sentence sounds fine to me as an English speaker. A verb ending in -ing can function as a noun (usually called a 'gerund'). Example: 'His being late inconvenienced us all' Not the most common way to express it, but grammatically valid nonetheless. 'His' (and 'its' in your example) are adjectives modifying the gerund. Adding 'the fact of' is a tad redundant but also grammatically okay. It's just a prepositional phrase with the object 'its being'. so rare a flower This is a construction in English that takes the form 'So [adjective] a [noun]'. The more colloquial way to express it would be 'such a [adjective] [noun]'. Neither of these constructions are very common in spoken English, or in plain writing.
{ "pile_set_name": "StackExchange" }
Q: Use a type generated at runtime I've several classes which I'd like to select and instantiate at run time. For example: public class MyClassA{ public int property1 {get; set;} public string property2 {get; set;} } public class MyClassB{ public int property1 {get; set;} public string property3 {get; set;} } Let's say, MyClassB was selected at runtime: Type t = Type.GetType("MyNamespace.MyClassB"); Object myType = Activator.CreateInstance(t); Now, i'd like to use myType as a type to pass to other classes/methods like this. myType myDeserializedObject = JsonConvert.DeserializeObject<myType>(MyJsonString); Code never compiles throwing "myType is a variable but is used like a type" error. Is there any way or workaround to convert the activated instance to a type? Let me know if there is any other approach I should look into. Thanks! A: You cant pass in a variable Type as a generic. Instead use var myDeserializedObject = JsonConvert.DeserializeObject(MyJsonString, t);
{ "pile_set_name": "StackExchange" }
Q: How to measure the performance of a domain adaptation /Transfer learning technique? Given that the performance you achieve depends on how far the target from the source domain is, how can you judge the performance of an algorithm? A: You can measure the divergence between the source and target domain using KL-Divergence (there are some ways to estimate k-l divergence e.g. depdended on k-nn algorithm). Then you can check if there is a correlation between the divergence and the accuracy of the models considering a few cases of source-target pairs of datasets. You can compare several algorithms of Transfer Learning/Domain Adaptation using the same source-target datasets.
{ "pile_set_name": "StackExchange" }
Q: Checkout maven project from SCM: disconnect and merge Whenever checking out Maven project from svn server in Eclipse, it creates a new folder like maven.xxxxxxxxxxxx under the target workspace. After specific time, it disconnected from SVN server. My question is when the new checkout process is started again:- Can the next checking-out process merge to one of the existing folder maven.xxxxxxxxxxxx? Any input would be appreciated!! A: No, not directly. This happens if something stops the import step. While I can not tell you wat exactly went wrong in your case, I can tell you how to solve it: Rename the maven.xxxxxfolder in your workspace to the real project name. The select File -> Import... -> Existing Maven Project and choose the project folder. The project will appear in your workspace as maven project. Depending on your eclipse configuration and plugins environment, you might also need to right-click on your new project and select Team -> Share... -> SVN (if there is a long list of options under Team, it is already correctly identifed as SVN project). Update If your maven.xxxx folder is empty, than you seem to have connection problems. Split the checkout and the import part: Switch to the "SVN Repository Exploring" perspective, create the repository (if not already there). Can you browse the repository? If not, you have a connection problem (proxy?). Right click your SVN project and select -> Checkout... Select Check out as project in the workspace This checks out the project as simple resource project now back in the java perspective you can either delete the project and do an "Import existing Maven Project" or convert the project to a maven project using right-click -> Configure -> Convert to Maven project (exact command may vary with your m2e version). If everything elese fails, try to checkout your project using TortoiseSVN (on Windows) or the commandline and doing "import -> existing maven project" afterwards.
{ "pile_set_name": "StackExchange" }
Q: how to call a module file in header file in opencart 2.0.1.1 I have a module of facebook login. But it could be add in content top or content bottom I want to add it in header for users. Could someone can tell me how to call a module named facebook_login.tpl as <?php $facebook_login ?> in header.tpl file in Opencart 2.0.1.1. A: You will call controller in header.php file. for eg. if you want to call controller of facebook_login.php file so you need to write code in header.php like : $data['facebook_login'] = $this->load->controller('common/facebook_login'); and in header.tpl file you need to write code like : <?php echo $facebook_login;?> maybe it will be helpful Thanks
{ "pile_set_name": "StackExchange" }
Q: Code generation for Java JVM / .NET CLR I am doing a compilers discipline at college and we must generate code for our invented language to any platform we want to. I think the simplest case is generating code for the Java JVM or .NET CLR. Any suggestion which one to choose, and which APIs out there can help me on this task? I already have all the semantic analysis done, just need to generate code for a given program. Thank you A: From what I know, on higher level, two VMs are actually quite similar: both are classic stack-based machines, with largely high-level operations (e.g. virtual method dispatch is an opcode). That said, CLR lets you get down to the metal if you want, as it has raw data pointers with arithmetic, raw function pointers, unions etc. It also has proper tailcalls. So, if the implementation of language needs any of the above (e.g. Scheme spec mandates tailcalls), or if it is significantly advantaged by having those features, then you would probably want to go the CLR way. The other advantage there is that you get a stock API to emit bytecode there - System.Reflection.Emit - even though it is somewhat limited for full-fledged compiler scenarios, it is still generally enough for a simple compiler. With JVM, two main advantages you get are better portability, and the fact that bytecode itself is arguably simpler (because of less features).
{ "pile_set_name": "StackExchange" }
Q: Unable to Reach a Value..... ReactJS I am currently having trouble accessing a value within a function. Here is my code: distanceBool = (event) => { console.dir(event); let address = ["Toronto, ON, CA"]; let destination = ["Vancouver"]; let location = this; let service = new window.google.maps.DistanceMatrixService(); new Promise((resolve)=>{ resolve( service.getDistanceMatrix({ origins: ["Waterloo ON"], destinations: destination, travelMode: 'DRIVING', avoidHighways: false, avoidTolls: false }, function(response, status){ if (status == 'OK') { var origins = response.originAddresses; var destinations = response.destinationAddresses; for (var i = 0; i < origins.length; i++) { var results = response.rows[i].elements; for (var j = 0; j < results.length; j++) { var element = results[j]; var distance = element.distance.text; var duration = element.duration.text; var from = origins[i]; var to = destinations[j]; location.distFinal = distance; location.setState({ dist: distance }) } } } }) ) }).then((res)=>{ // console.log(res) // console.dir(location); console.dir(location); console.dir(location.distFinal); // console.log("hello") }) } I am trying to access the distance so I did console.dir(location.distFinal) but it gave me an undefined value. However, when I did console.dir(location), it gave me the object with distFinal as a value.... This is what I mean: Line 132 is the console.dir(location) and line 133 is console.dir(location.distFinal) Please! I just want to be able to extract the distance! A: Your top-level promise resolves immediately - you probably want to resolve only once the asynchronous code inside finishes. new Promise((resolve)=>{ service.getDistanceMatrix({ origins: ["Waterloo ON"], destinations: destination, travelMode: 'DRIVING', avoidHighways: false, avoidTolls: false }, function(response, status){ if (status !== 'OK') return; var origins = response.originAddresses; var destinations = response.destinationAddresses; for (var i = 0; i < origins.length; i++) { var results = response.rows[i].elements; for (var j = 0; j < results.length; j++) { var element = results[j]; var distance = element.distance.text; var duration = element.duration.text; var from = origins[i]; var to = destinations[j]; location.distFinal = distance; location.setState({ dist: distance }) } } // all the looping is done: resolve(); }) }).then((res)=>{ // console.log(res) // console.dir(location); console.dir(location); console.dir(location.distFinal); // console.log("hello") })
{ "pile_set_name": "StackExchange" }
Q: Replacing a specified line in File I want to search for a item and then replace it's quantity. Is it possible to do it to a file? Example of text file: apples 10.2 banana 20.5 oranges 10 So when I input "banana" I want to be able to update the 20.5 to a different number. A: since you haven't posted what you have done so far I can only give you pointers ; # open the file -> check out python's open() function and the different modes , w+ opens the file for both writing ad reading .... file_handle = open("yourtextfile", "w+") # check out readlines() function , it gives you back a list of lines , in the order of from the first line to the last ..... the_lines = file_handle.readlines() # remove newline '\n' from every element in the list ..... new_list = [elem.strip() for elem in the_lines] # look for existence of 'banana' in the new_list and going by the structure of the file you just posted edit the value next to the banana i.e 20.5 .... for item in new_list: if item == "banana": index = new_list.index(item) + 1 new_list[index] = new_value #add the newlines back new_string = '\n'.join(new_list) file_handle.write(new_string) file_handle.close() break
{ "pile_set_name": "StackExchange" }
Q: No database selected, even though explictly stated I have a query running in a script, and when it's run in mysql workbench it works fine. However, running the script results in 'no database selected' error in powershell. I've followed the error prompts but you can see in my query I explicitly state the database for each table, i.e. (ambition.ambition_totals). Is there another constraint I should add to this? $stmt3 = mysqli_prepare($conn2, "UPDATE ambition.ambition_totals a INNER JOIN (SELECT c.user AS UserID, COUNT(*) AS dealers, ROUND((al.NumberOfDealers / al.NumberOfDealerContacts) * 100 ,2) AS percent FROM jfi_dealers.contact_events c JOIN jackson_id.users u ON c.user = u.id JOIN jfi_dealers.dealers d ON c.dealer_num = d.dealer_num LEFT JOIN ( SELECT user_id, COUNT(*) AS NumberOfDealerContacts, SUM(CASE WHEN ( d.next_call_date + INTERVAL 7 DAY) THEN 1 ELSE 0 END) AS NumberOfDealers FROM jackson_id.attr_list AS al JOIN jfi_dealers.dealers AS d ON d.csr = al.data WHERE al.attr_id = 14 GROUP BY user_id) AS al ON al.user_id = c.user GROUP BY UserID) as cu on cu.UserID = a.ext_id SET a.dealers_contacted = cu.dealers, a.percent_up_to_date = cu.percent; ") or die(mysqli_error($conn2)); A: Specify the database name as the fourth parameter to mysqli_connect() Here's an example that assumes you're connecting on localhost: $conn2 = mysqli_connect("localhost", "your_username", "your_password", "ambition"); or do mysqli_select_db("ambition") before your mysqli_prepare statement if ambition was not your default database.
{ "pile_set_name": "StackExchange" }
Q: What java based CMS can manage existing pages' content? We have an existing and running java web application, currently the pages' content is static but the pages are still jsp files, they have look and feel designed specifically. My customer now wants to use CMS to manage the update of content like news, events with the minimal changes to the jsp code, I tried opencms and haven't found yet it can do that. As much as I know pages are needed to create through opencms ade in opencms world. The layout,look and feel must follow the pattern of opencms , that being said many block contents on pages.Is there any kind of CMS which can match my requirements out of the world? A: OpenCms and Magnolia are leading open source java-based CMS. They can do it, but of course there is some effort to it, which depends on the architecture of your current website. If you're only, and really only, using JSPs in your current website, then you can just dump the JSPs into OpenCms, and that's it. Then you have the website within OpenCms, of course not yet editable, and then integrate the editable elements step by step, using structured content elements (XSDs). The process can't be described briefly in an answer here as it's quite complex, it definitely takes a bit of OpenCms experience to do it, as it's harder than building a OpenCms based website from scratch. If your current application uses a framework like Spring, then there are additional steps to it. We've integrated Spring with OpenCms before and it works. I assume most java CMS will allow what you need, but it will take a bit of effort in all of them. Additionally, if you're using jars in your current application, you need to check that there are no conflicts between those and those of the OpenCms version you're using. Alternatively, you can just create your own small CMS functionality by implementing FCKEditor / CKEditor, if your CMS requirements are very basic. Please provide some more details about your current technology stack / frameworks, etc. Then it's easier to answer in more detail. Update (2015): As of 2015, I meanwhile moved from OpenCms to Magnolia, and would recommend that very much. Documentation is great an they explicitly have a module for Spring integration named Blossom. https://documentation.magnolia-cms.com/display/DOCS/Blossom+module.
{ "pile_set_name": "StackExchange" }
Q: recreating whole SQL Server Database with relations i have used SQL server 2012 and made a huge database with many relations. today i realized using "NCHAR" instead on "NVARCHAR" adds space on end of strings which i don't like it. is there any way to recreate database with relations. I've tried "drop and create" for tables but needs to remove all relations and define them again which is very time consuming. A: It's possible to alter only the affected tables? like this: SELECT 'alter table '+s.name+'.'+t.name+ ' alter column '+c.name+' nvarchar('+convert(varchar(11),c.max_length/2)+') go' FROM sys.tables as T inner join sys.schemas as s on T.[schema_id]=s.[schema_id] inner join sys.columns as C on T.[object_id]=C.[object_id] and c.system_type_id=239--nchar type , and before that don't forget to use the same kind of mechanism to generate an update statement to remove extra spaces.
{ "pile_set_name": "StackExchange" }
Q: SyntaxError: illegal character when posting array to data attribute of highcharts I have a rails app that uses highcharts to display a line graph of 2 currencies. However when I run the app on my browser I keep getting the following error in firebug SyntaxError: illegal character data: #&lt;Forex::ActiveRecord_Relation:0xc743144&gt; I can't figure out what's wrong with my javascript code since it does not include the following after data attribute of highcharts #&lt Here is my code: <div id="forex"> <script type="text/javascript" charset="utf-8"> $(function() { new Highcharts.Chart({ chart: { renderTo: "forex" }, title: { text: "Forex" }, xAxis: { type: "datetime" }, yAxis: { title: { text: "Shillings" } }, tooltip: { formatter: function() { return Highcharts.dateFormat("%B %e, %Y", this.x) + ': ' + "$" + Highcharts.numberFormat(this.y, 2); } }, series: [ <% { "Dollar" => Forex.dollar, "British Pound" => Forex.british_pound }.each do |name, value| %> { name: "<%= name %>", pointInterval: <%= 1.day * 1000 %>, pointStart: <%= 3.weeks.ago.to_i * 1000 %>, data: <%= value %> }, <% end %> ] }); }); </script> </div> I'm populating my data from a scope defined on forex.rb which is as follows scope :dollar, -> { where(:us_dollar != 0) } scope :british_pound, -> { where(:british_pound != 0 ) } I've done according to Santosh's answer: <% { "Dollar" => Forex.dollar, "British Pound" => Forex.british_pound }.each do |name, value| %> <p><%= name == 'Dollar' ? a=value.pluck(:us_dollar) : b=value.pluck(:british_pound) %></p> <% end %> But this prints out 2 empty arrays while I have 2 values in my table attributes us_dollar: 88.27 and british_pound: 149.23 A: Your scope syntax is wrong Change the conditions to where(["us_dollar != ?", 0]) Change the data to data: <%= name == 'Dollar' ? value.pluck(:us_dollar) : value.pluck(:british_pound) %>
{ "pile_set_name": "StackExchange" }
Q: send dynamic table or div content as an email body content I have a page (somePage.aspx) and I need the content that has been generated as an Email body <div id="DV_TimeReportWraper" runat="server" style="display:block"> <table id="TBL_UsersinTblTime"> <tr id="TR_UsersinTblTime"> <td id="TD_H_Name" class="Dg"> name </td> <td id="TD_H_UserID" class="Dg"> ID </td> <td id="TD_H_Status" class="Dg"> initial Stage </td> <td id="TD_H_SignOutAutoExeState" class="Dg"> current Stage </td> </tr> <% if(edata != null) for (int idx=0;idx<edata.Count;idx++) { var row = edata[idx]; bool bgcl = (idx % 2) == 0; string BgCol = ""; if (bgcl) BgCol = "#70878F"; else BgCol = "#E6E6B8"; %> <tr style=" background-color:<%=BgCol%>"> <td id="TD_Name"> <% = row["name"] %> </td> <td id="TD_UserID"> <%= row["UserId"]%> </td> <td id="TD_Status"> <% int uidForSrc = Convert.ToInt32(row["UserId"]); string src = "images/SignedOutNoFrame.png"; if (UserDidnotSignOutTimeOut(uidForSrc)) src = "images/didnotSignOut.png"; %> <input type="image" src="<% =src %>" style="width:25px" /> </td> <td id="TD_SignOutAutoExeState" > <% string EexcSrc = ""; string inputType ="hidden"; //this updates if needed then returns true= needed update false = isn't need if (UpdatedTimeOutOKForUSER(uidForSrc)) { inputType = "image"; excSrc = "/images/SignedOutNoFrame.png"; } %> <input type="<%=inputType %>" src="<%=EexcSrc %>" style="width:25px" /> </td> </tr> <% if (idx == edata.Count - 1) sendLog(); } %> </table> </div> code for sendLog() public void sendLog() { mail.aReciver="[email protected]"; mail.bSubject="ttest"; mail.cBody = DV_UsersInTblTime.InnerHtml; mail.HentalSend(); } I can't get the value of content to assign mail.cBody with. It's saying something about the value not being a literal etc'. That is the method I'm using in an external class which works fine till this last attempt to add the functionality of page content as a body, how is it possible to achieve the result as needed here? public static class mail { public static string aReciver, bSubject, cBody; public static void HentalSend() { string SmtpServer = "smtp.gmail.com"; int port = 587; string sender = "[email protected]"; string ReCiver = aReciver; string Subject = bSubject; string Body = cBody; string account = "[email protected]"; string Pass = "123456"; Send(SmtpServer, port, account, Pass, sender, Receiver, Subject, Body); ... //send() is another relevant method to this question, it does rest of mail settings } } A: This code will get the generated HTML of your dynamic control in to a string variable. StringBuilder stringBuilder = new StringBuilder(); StringWriter writer = new StringWriter(stringBuilder); HtmlTextWriter htmlWriter = new HtmlTextWriter(writer); try { DV_TimeReportWraper.RenderControl(htmlWriter); } catch (HttpException generatedExceptionName) { } string DV_TimeReportWraper_innerHTML = stringBuilder.ToString(); Then just use DV_TimeReportWraper_innerHTML as the body of your email You might have to create a loop in case this control has children controls. More on that here: http://msdn.microsoft.com/en-us/library/htwek607.aspx#Y472
{ "pile_set_name": "StackExchange" }
Q: Is it correct to use citations as nouns for scientific papers, such as dissertations of articles? Which of these two is better accepted, or preferred, for scientific papers? THIS The model detaches the calculation of the vertical velocity from the equations system, and focuses on the longitudinal velocities instead, leaving the model as a 2D equations system. [Mintgen, 2018] provides a description for the properties, characteristics and limitations of SWE in a detailed manner, some of which will be further addressed an extended for a deeper analysis in Section 2.1. OR The model detaches the calculation of the vertical velocity from the equations system, and focuses on the longitudinal velocities instead, leaving the model as a 2D equations system. In his dissertation, Florian Mintgen [Mintgen, 2018] provides a description for the properties, characteristics and limitations of SWE in a detailed manner, some of which will be further addressed an extended for a deeper analysis in Section 2.1. Or if you have any other accepted way of doing it, please feel free. Thank you References [Mintgen, 2018] Mintgen, G. F. (2018). Coupling of Shallow and Non-Shallow Flow Solvers An Open Source Framework. Dissertation, Technische Universitaet Muenchen, Muenchen. A: There’s no unique answer to this as citation styles (in text or in bibliography) are somewhat personal or institutional. Some good ways of getting guidance include Get one or more previous theses on the same topic and follow those models, Look up established journals in the field and use their models (if they have a common one). I personally prefer your second alternative but would then use numbered referencing to avoid name repetition, v.g. “In his dissertation [1], Mintgen ...”
{ "pile_set_name": "StackExchange" }
Q: Why does HashMap's get() compare both the hash value and key in Java? I was looking at the implementation of HashMap in JDK8. In the get methods, I saw the below line which is used to find the Node that matches with the given key. if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) Why is there the need to compare the hash value along with key? Why is the line above not written as: if (((k = e.key) == key) || (key != null && key.equals(k))) Is there any explanation on why it is done this way? Thank you. A: What seems to be causing your confusion, are two things: 1. Comparing the hash values is (often very much) faster than comparing keys directly. 2. In a == operator, the second condition won't be checked if the first is false. So first the hash values are compared, which is fast: When they are not equal, you know the keys aren't equal as well, and you are done. When they are equal, you don't know if the keys are equal as well, so you must compare keys, which is (relatively) slow. Since most keys are not equal, most of the time you only compare hashes. Only when keys are equal (or when hashes are equal due to hash collisions) do you compare the keys, which is rare, and thus you have a performance benefit. A: This is an efficient way to check if two values can possibly be equal. The contract for hashcode mandates: JavaDocs of Object.hashCode If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. Therefore, if the hashes are distinct, there is not point in performing further checks. As HashMap requires the hashcodes for the keys anyway for choosing the buckets to put the entries in, the tradeoff is storing an additional int per entry vs. possibly having to compute it repeatedly and having to execute equals for the keys more often. HashMap is more optimized for fast retrieval and insertion, less so for memory efficiency. Side Note: HashMap relies on keys not being mutated in any way that would change their "identity" in terms of equals and hashcode - while this may seem obvious, it is not explicitly mentioned in the JavaDocs for HashMap and has led to questions in the past: Are mutable hashmap keys a dangerous practice? - this is covered by the more general Map contract: Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map.
{ "pile_set_name": "StackExchange" }
Q: Nginx location image Есть папка с картинками site.com/upload/image1.png и я не могу добавить правило если по запросу картинки из папки upload нет, то выдать картинку (по умолчанию noimage.png) без изменения url Пытался так №1: location /upload/ { try_files $uri /1_image_not_found.png; } Пытался так №2: location /upload/ { error_page 404 /1_image_not_found.png; } Толку ноль вижу страницу 404 UPD: Полностью конфиг UPD2: Изменил server { listen 443 ssl spdy; server_name site.com www.site.com; resolver 8.8.8.8; ssl on; ssl_certificate /etc/nginx/ssl/site.com.crt; ssl_certificate_key /etc/nginx/ssl/site.com.key; ssl_session_timeout 5m; ssl_session_cache shared:SSL:20m; ssl_stapling on; ssl_dhparam /etc/nginx/dhparam.pem; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers HIGH:!aNULL:!MD5:!kEDH; ssl_prefer_server_ciphers on; root /home/site.com/public_html; index index.php index.html index.htm; access_log /dev/null; error_log /home/site.com/logs/nginx.error.log; location = /favicon.ico { access_log off; log_not_found off; } location = /robots.txt { access_log off; log_not_found off; } location ~* ".+\.(?:ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|rss|css|swf|js|atom|jpe?g|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$" { access_log off; log_not_found off; expires max; } location / { try_files $uri $uri/ /index.php; } location ~ \.php$ { limit_req zone=one burst=5; try_files $uri $uri/ =404; fastcgi_pass unix:/tmp/site.com; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } location /upload/ { try_files $uri /upload/1_image_not_found.png; } location ~ /\. { deny all; access_log off; log_not_found off; return 404; }} A: location /upload/ { try_files $uri /upload/1_image_not_found.png; } UPD: После публикации полной конфигурации. Nginx обходит location в определенном порядке. Сначала он ищет совпадения среди location заданных строками, в вашем случае максимально близкий это / и /upload/, но дальше nginx ищет среди location заданных регулярными выражениями. В вашем случае это будет строка где вы указываете всю статику, чтобы выключить журналирование добавить кэширование. Именно по этой причине не срабатывает изображение по умолчанию. Один из вариантов решения сделать location /upload/ не строковой, а с помощью регулярных выражений. Например location ~ ^/upload/(.+). Более подробно можно прочитать в инструкции nginx: Как nginx обрабатывает запросы
{ "pile_set_name": "StackExchange" }
Q: Is this writing pattern called an attribution? I had posted this question under "academic-writing" and on there someone believes that it might be called "attribution". Can anyone confirm if this is correct or where I can find a reference? Original Question: I'm curious to know if this style of writing (pattern) has a name. They can sometimes take up almost a full paragraph giving background about a specific person or subject when introducing them into an article. "At the Saturday briefing, Dr. Stephen Hahn, commissioner of the Food and Drug Administration, co-author of the critically acclaimed book "XYZ", told us that..." A: It is indeed an example of attribution. This website lists 4 distinct styles of attribution, and your example is the first kind: On the record: All statements are directly quotable and attributable, by name and title, to the person making the statement. This is the most valuable type of attribution. Example: "The U.S. has no plans to invade Iran," said White House press secretary Jim Smith. Your statement is simply the reverse. Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: How to update column by a long char in Oracle12c I want to update an HTML format, but the HTML format is too long to update. Furthermore, there are functions in this HTML format. it seems that Oracle recognized the characters as the replace() function UPDATE DS_ADPRODSET_FREETAG SET html='<script type="text/javascript"> (function(){function c(g){return g.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function b(h,n){var j={};var l=h.split(n);if(l.length!=2){return j}var m=l[1].split("&");for(var k=0;k<m.length;k++){var g=m[k].split("=");if(g.length==1){j[g[0]]=""}else{j[g[0]]=c(window.decodeURIComponent(g[1]))}}return j}function e(g){var h=/^(http:\/\/i\.yimg\.jp|https:\/\/s\.yimg\.jp)\/images\/listing\/tool\/yads\/yads-iframe.*\.html/;return h.test(g)}var a=(function(){v ar k="14467902";var j;if(e(window.location.href)){j=window.location.href}else{try{if(e(window.parent.location.href)){j=window.parent.location.href}else{return k}}catch(i){return k}}var g=b(j,"?");if(typeof(g["sid"])!="undefined"&&g["sid"]!=""){return g["sid"]}var h=b(j,"#");if(typeof(h["sid"])!="undefined"&&h["sid"]!=""){return h["sid"]}return k})();var f=(location.protocol=="https:")?"https:":"http:";var d=f+"//yeas.yahoo.co.jp/a?f="+a+"&l=LREC2&p=jp&jcode=u&c=rp&domain=yimg.jp&rnd="+new Date() .getTime();document.write("<sc"+'ript type="text/javascript" src="'+d+'">');document.write("</sc"+"ript>")})(); </script>' WHERE adprodset_id=11111; the Oracle asked me to replace the '&gt', but I just want the contents in XXX are characters. A: What follows & is recognised a substitution variable in IDEs like SQL developer and SQL* Plus Add SET DEFINE OFF before running the query. Checkout this link to know more about substitution variable
{ "pile_set_name": "StackExchange" }
Q: MYSQL: Get result twice based on if statement i'm trying to get from each department from the dept table, the number of rich AND poor employees from the employee table. So far I was able to get one of each but can't seem to figure how to get both rich and poor written on two rows for each dept. SELECT Depts.Department, IF (Employees.Salary>100000, 'Rich', 'Poor'), COUNT(*) FROM `Employees`, `Depts` WHERE Depts.Dept = Employees.Dept GROUP BY Depts.Department thanks for any help A: including your IF logic in GROUP BY SELECT Depts.Department, IF (Employees.Salary>100000, 'Rich', 'Poor'), COUNT(*) FROM `Employees`, `Depts` WHERE Depts.Dept = Employees.Dept GROUP BY Depts.Department, IF (Employees.Salary>100000, 'Rich', 'Poor')
{ "pile_set_name": "StackExchange" }
Q: How to use the labeling function of Prolog (ECLIPSE program) within the SEND+MORE = MONEY program? So I managed to write the SEND + MORE = MONEY program for Prolog and I'm having trouble labeling the results. Any ideas on how to do that? I keep using the labeling function but it still wouldn't work. I'm lost here. :- lib(ic). puzzle(List) :- List = [S, E, N, D, M, O, R, Y], List :: 0..9, diff_list(List), 1000*S + 100*E + 10*N + D + 1000*M + 100*O + 10*R + E $= 10000*M + 1000*O + 100*N + 10*E + Y, S $\= 0, M $\= 0, shallow_backtrack(List). shallow_backtrack(List) :- ( foreach(Var, List) do once(indomain(Var)) ). diff_list(List) :- ( fromto(List, [X|Tail], Tail, []) do ( foreach(Y, Tail), param(X) do X $\= Y ) ). Results: ?- puzzle(X). X = [9, 5, 6, 7, 1, 0, 8, 2] Yes (0.00s cpu) Any help would be appreciated! Thanks! A: Here is a variant of your program that uses labeling: :- lib(ic). puzzle(List) :- List = [S, E, N, D, M, O, R, Y], List :: 0..9, alldifferent(List), 1000*S + 100*E + 10*N + D + 1000*M + 100*O + 10*R + E $= 10000*M + 1000*O + 100*N + 10*E + Y, S $\= 0, M $\= 0, labeling(List).
{ "pile_set_name": "StackExchange" }
Q: the fundamental differences of the way to overwrite getattr and setattr My hope is to make attributes case-insensitive. But overwriting __getattr__ and __setattr__ are somewhat different, as indicated by the following toy example: class A(object): x = 10 def __getattr__(self, attribute): return getattr(self, attribute.lower()) ## following alternatives don't work ## # def __getattr__(self, attribute): # return self.__getattr__(attribute.lower()) # def __getattr__(self, attribute): # return super().__getattr__(attribute.lower()) def __setattr__(self, attribute, value): return super().__setattr__(attribute.lower(), value) ## following alternative doesn't work ## # def __setattr__(self, attribute, value): # return setattr(self, attribute.lower(), value) a = A() print(a.x) ## output is 10 a.X = 2 print(a.X) ## output is 2 I am confused by two points. I assume getattr() is a syntactic sugar for __getattr__, but they behave differently. Why does __setattr__ need to call super(), while __getattr__ doesn't? A: I assume getattr() is a syntactic sugar for __getattr__, but they behave differently. That's because the assumption is incorrect. getattr() goes through the entire attribute lookup process, of which __getattr__ is only a part. Attribute lookup first invokes a different hook, namely the __getattribute__ method, which by default performs the familiar search through the instance dict and class hierarchy. __getattr__ will be called only if the attribute hasn't been found by __getattribute__. From the __getattr__ documentation: Called when the default attribute access fails with an AttributeError (either __getattribute__() raises an AttributeError because name is not an instance attribute or an attribute in the class tree for self; or __get__() of a name property raises AttributeError). In other words, __getattr__ is an extra hook to access attributes that don't exist, and would otherwise raise AttributeError. Also, functions like getattr() or len() are not syntactic sugar for a dunder method. They almost always do more work, with the dunder method a hook for that process to call. Sometimes there are multiple hooks involved, such as here, or when creating an instance of a class by calling the class. Sometimes the connection is fairly direct, such as in len(), but even in the simple cases there are additional checks being made that the hook itself is not responsible for. Why does __setattr__ need to call super(), while __getattr__ doesn't? __getattr__ is an optional hook. There is no default implementation, which is why super().__getattr__() doesn't work. __setattr__ is not optional, so object provides you with a default implementation. Note that by using getattr() you created an infinite loop! instance.non_existing will call __getattribute__('non_existing') and then __getattr__('non_existing'), at which point you use getattr(..., 'non_existing') which calls __getattribute__() and then __getattr__, etc. In this case, you should override __getattribute__ instead: class A(object): x = 10 def __getattribute__(self, attribute): return super().__getattribute__(attribute.lower()) def __setattr__(self, attribute, value): return super().__setattr__(attribute.lower(), value)
{ "pile_set_name": "StackExchange" }
Q: IIS 7 manager not opening but working I have windows 7 home premium. I have turned on IIS .Confirmed if its running by typing localhost on my address bar. It show IIS welcome message, showing its working. However when I try to open IIS manager, nothing happens. I want to deploy my asp.net mvc 3 application on it. How do I solve this issue? A: For me helped focusing on the window via Alt-Tab, then pressing Alt-Space and select Move in the drop-down menu. After that, either drag the mouse or move with keyboard buttons. By the way, works with all windows. Update for Win 10 There is another easier solution for such windows for Win 10. You can pull any available window to the left edge of the screen. Windows will expand the window to half of the screen and prompts you to choose any opened window to fill the second half. Choose the window you can't access and you're good.
{ "pile_set_name": "StackExchange" }
Q: How to make method in data access class for parameterized query? I have created one method in data Access class to select data from database with parameter. I just want to use parameterized query. Method Is : public DataTable executeSelectQuery(String _query, SqlParameter[] sqlParameter) { SqlCommand myCommand = new SqlCommand(); DataTable dataTable = new DataTable(); dataTable = null; DataSet ds = new DataSet(); try { myCommand.Connection = openConnection(); myCommand.CommandText = _query; myCommand.Parameters.AddRange(sqlParameter); myCommand.ExecuteNonQuery(); myAdapter.SelectCommand = myCommand; myAdapter.Fill(ds); dataTable = ds.Tables[0]; } catch (SqlException e) { return null; } finally { myCommand.Connection = CloseConnection(); } return dataTable; } but I can't understand how to use this method to fetch data and how to pass parameter? My query may be "select password from tblUsers where email=@email" How to pass @email at business layer? How to make method in data access class for getting Scalar value? public string getpasswrd(string unm) { con.Open(); string cpaswrd; cmd1 = new SqlCommand("select password from tbl_login where username='" + unm + "'", con); cpaswrd = (String)cmd1.ExecuteScalar(); con.Close(); return cpaswrd; } A: SqlParameter param; cmd1 = new SqlCommand("select password from tbl_login where username=@username, con); param = new SqlParameter("@username", SqlDbType.VarChar); param.Direction = ParameterDirection.Input; param.Value = unm; cmd1.Parameters.Add(param); cpaswrd = cmd1.ExecuteScalar().ToString();
{ "pile_set_name": "StackExchange" }
Q: Configure pylint for modules within eggs. (VS code) Project structure I have the following folder structure | |- src | |- mypackage | | |- __init__.py | | |- mymodule.py | |- utils.egg |- main.py in mymodule.py file I can import the egg adding it to the sys.path as import sys sys.path.append('src/utils.egg') import utils When calling main.py everything works fine (python -m main). Problem The problem comes from pylint. First, it shows the following message in mymodule.py file Unable to import 'utils' pylint(import-error) if I ask for suggestions (CRTL + Space) when importing I got utils.build .dist .utils .setup # |- suggestions And from utils.utils I can acces the actual classes / functions in utils module. Of course if I import utils.utils, when executing the main script, an importing error pops up. How can I configure my vscode setting in order fix pylint? should I install the egg instead of copy it to the working folder? Is my project's folder-structure ok, or it goes against recommended practices? Extra info In case you wonder the EGG-INFO/SOURCE.txt file looks like setup.py utils/__init__.py utils/functions.py utils.egg-info/PKG-INFO utils.egg-info/SOURCES.txt utils.egg-info/dependency_links.txt utils.egg-info/top_level.txt utils/internals/__init__.py utils/internals/somemodule.py utils/internals/someothermodule.py Also, there aren't build nor dist folder in the egg. A: This is an issue with Pylint itself and not the Python extension, so it will come down to however you need to configure Pylint. As for whether you should copy an egg around or install it, you should be installing it into your virtual environment, or at least copying over the appropriate .pth file to make the egg directory work appropriately.
{ "pile_set_name": "StackExchange" }
Q: How to get a dynamic elements height in console Stupid question I know but can't seem to get this working. Using Chrome console, I need to get the height of some elements (can do with inspector, but this has become personal) console.log$('#myDiv').height(); returns TypeError: Object # has no method 'log$' console.log $('#myDiv').height(); returns SyntaxError: Unexpected identifier I know this is simple, and Ive looked around but cant see the forrest for the trees at this point. A: console.log( $('#myDiv').height() ) console.log is a function so you need parentheses to call it, passing as argument(s) what you want to output in the console. If typing directly into the console directly, you can omit console.log: $('#myDiv').height() The console automatically returns the last return value to your screen so you don't have to console.log when using the console.
{ "pile_set_name": "StackExchange" }
Q: Incorporate string with list entries - alternating So SO, i am trying to "merge" a string (a) and a list of strings (b): a = '1234' b = ['+', '-', ''] to get the desired output (c): c = '1+2-34' The characters in the desired output string alternate in terms of origin between string and list. Also, the list will always contain one element less than characters in the string. I was wondering what the fastest way to do this is. what i have so far is the following: c = a[0] for i in range(len(b)): c += b[i] + a[1:][i] print(c) # prints -> 1+2-34 But i kind of feel like there is a better way to do this.. A: You can use itertools.zip_longest to zip the two sequences, then keep iterating even after the shorter sequence ran out of characters. If you run out of characters, you'll start getting None back, so just consume the rest of the numerical characters. >>> from itertools import chain >>> from itertools import zip_longest >>> ''.join(i+j if j else i for i,j in zip_longest(a, b)) '1+2-34' As @deceze suggested in the comments, you can also pass a fillvalue argument to zip_longest which will insert empty strings. I'd suggest his method since it's a bit more readable. >>> ''.join(i+j for i,j in zip_longest(a, b, fillvalue='')) '1+2-34' A further optimization suggested by @ShadowRanger is to remove the temporary string concatenations (i+j) and replace those with an itertools.chain.from_iterable call instead >>> ''.join(chain.from_iterable(zip_longest(a, b, fillvalue=''))) '1+2-34'
{ "pile_set_name": "StackExchange" }
Q: Vector graphics in LaTeX I need to add some vector graphics to my LaTeX files. I would like to end up with good looking wireframes, such as in Hatcher's book "Algebraic Topology" (for an example take a look here). Which tools would you recommend? Any help would be appreciated, thanks in advance. EDIT: The best thing would be to use an external tool, such as a 3d editor (just a simple one, which lets you easily model a 3d mesh from scratch) and then export the wireframe as a vector image. I don't know if something like this could exist. Tools like tikz or pstricks could do the job, but they are mainly suitable for flat drawings, and require more effort for 3d (drawing something like this could be very tedious). A: You can use tikz or pstricks to draw diagrams from within a LaTeX document. Diagram drawing software capable of creating eps or pdf files (e.g. xfig (free) or Adobe Illustrator) will also yield good results. For examples using TikZ (including 3D), see here. A: Ipe is another drawing program you may want to consider. It has very nice TeX integration. Inkscape is yet another option; see this.
{ "pile_set_name": "StackExchange" }
Q: Is there equivalent of WPF OriginalSource event property in Winform and ASP.NET? From: http://www.wpfwiki.com/WPF%20Q14.12.ashx The OriginalSource property of the object identifies the original object that received/initiated the event. Consider a custom control (called CustomControl1 in this example) that is composed of a TextBlock. When a MouseDown event is raised on the TextBlock, the OriginalSource property will be the TextBlock, but in CustomControl1's handler, the Source will be changed to the CustomControl1 object so that other elements along the event's route will know that CustomControl1 received a MouseDown. Is there equivalent of WPF OriginalSource event property in Winform and ASP.NET ? If not how to emulate this ? A: the "sender" argument which is sent to the event does not comfort your case, since you need another object to determine the container object which raised the event. I emulate this by manually firing events either on server-side or on client-side through javascript. Example: if a Span was inside a Div, on the, let's say, click event of the span, I call the click event on its container the div here. And then, in the event handler, the argument will be the div not the span. Hope that helps.
{ "pile_set_name": "StackExchange" }
Q: java.lang.IllegalArgumentException: Comparison method violates its general contract! java.util.Date java.lang.IllegalArgumentException: Comparison method violates its general contract! at java.util.TimSort.mergeLo(TimSort.java:747) at java.util.TimSort.mergeAt(TimSort.java:483) at java.util.TimSort.mergeCollapse(TimSort.java:410) at java.util.TimSort.sort(TimSort.java:214) at java.util.TimSort.sort(TimSort.java:173) at java.util.Arrays.sort(Arrays.java:659) at java.util.Collections.sort(Collections.java:217) I am sorting a collection based on the following comparator. public static Comparator<MyClass> CMP_TIME_DESC = new Comparator<MyClass>() { @Override public int compare(MyClass o1, MyClass o2) { return o2.getOrderSendTime().compareTo(o1.getOrderSendTime()); } }; The values are always non-null. And the getOrderSendTime() object is of the java.util.Date class. I understand that this is a transitivity inconsistency, and I would assume a class like this would not have such issues. I searched for open issues, but did not find any on the topic. Any ideas? A: Your issue is related to this one: Sort algorithm changes in Java 7 It happens because the default sort algorithm has changed from MergeSort to TimSort. One workaround is to add -Djava.util.Arrays.useLegacyMergeSort=true to the JVM environment. The best option is to conform to the comparison general contract but I think you didn't provide enough information in your question for this. A: I had this same exception, and it happened when I had java.util.Date and java.sql.Timestamp objects in the same list/array when being sorted, running on Java8. (This mix was due to some objects being loaded from database records with the Timestamp data type, and others being created manually, and the objects having only a Date object in them.) The exception also doesn't happen every time you sort the same data set, and it seems that there also have to be at least 32 of these mixed objects in the array for it to occur. If I use the legacy sort algorithm, this also doesn't occur (see how in Ortomala Lokni's answer). This also doesn't happen if you use only java.util.Date objects or only java.sql.Timestamp objects in the array. So, the issue seems to be TimSort combined with the compareTo methods in java.util.Date and java.sql.Timestamp. However, it didn't pay for me to research why this is happening since it is fixed in Java 9! As a workaround until Java9 is released and we can get our systems updated, we have manually implemented a Comparator that only uses getTime(). This seems to work fine. Here is code that can be used to reproduce the issue: import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import org.junit.Test; public class TimSortDateAndTimestampTest { // the same test data with all Dates, all Timestamps, all Strings or all Longs does NOT fail. // only fails with mixed Timestamp and Date objects @Test public void testSortWithTimestampsAndDatesFails() throws Exception { List<Date> dates = new ArrayList<>(); dates.add(new Timestamp(1498621254602L)); dates.add(new Timestamp(1498621254603L)); dates.add(new Timestamp(1498621254603L)); dates.add(new Timestamp(1498621254604L)); dates.add(new Timestamp(1498621254604L)); dates.add(new Timestamp(1498621254605L)); dates.add(new Timestamp(1498621254605L)); dates.add(new Timestamp(1498621254605L)); dates.add(new Timestamp(1498621254605L)); dates.add(new Timestamp(1498621254606L)); dates.add(new Timestamp(1498621254607L)); dates.add(new Date(1498621254605L)); dates.add(new Timestamp(1498621254607L)); dates.add(new Timestamp(1498621254609L)); dates.add(new Date(1498621254603L)); dates.add(new Date(1498621254604L)); dates.add(new Date(1498621254605L)); dates.add(new Date(1498621254605L)); dates.add(new Date(1498621254607L)); dates.add(new Timestamp(1498621254607L)); dates.add(new Date(1498621254608L)); dates.add(new Timestamp(1498621254608L)); dates.add(new Date(1498621254611L)); dates.add(new Timestamp(1498621254612L)); dates.add(new Timestamp(1498621254613L)); dates.add(new Date(1498621254607L)); dates.add(new Timestamp(1498621254607L)); dates.add(new Timestamp(1498621254608L)); dates.add(new Timestamp(1498621254609L)); dates.add(new Timestamp(1498621254611L)); dates.add(new Date(1498621254603L)); dates.add(new Date(1498621254606L)); for (int i = 0; i < 200; i++) { Collections.shuffle(dates); Collections.sort(dates); } } } Edit: I have removed the exception expectation so you can SEE it throwing when run.
{ "pile_set_name": "StackExchange" }
Q: Schnorr identification protocol security proof I read about security proof of Schnorr identification protocol against impersonation attack. For the sake of comprehensibility let me sum up the protocol: Given group $G$ with generator $g$. Verifier is initialized by prover's public key $g^a$, where the knowledge of secret counterpart is to be proven by prover. The protocol runs as following: Prover generates random $a_t\in G$ and sends $g^{a_t}$ to verifier Verifier responds by sending random $c$ to the prover. Prover responds by sending $a_z = a_t + c\,a$ Verifier checks whether $g^{a_z}\overset{?}{=}g^{a_t}\,(g^a)^c$ Now, the idea of the security proof was: Given adversary $\mathcal{A}$ being able to issue valid $a_z'$ against arbitrary public key $g^{a'}$, we can turn $\mathcal{A}$ into an efficient $\mathrm{DLog}\,_g(g^{a'})$ oracle. The proof assumed we can "rewind" the adversary so that it issues 2 different $a_z$'s with respect to a single $a_t$. I didn't understand this assumption. It seems somehow incomplete to me. What if I have non-cooperative adversary? This can't be turned into DLog oracle, since such adversary were indistinguishable from honest prover who knows secret key, thus breaking zero-knowledge protocol property. So is this a complete proof, which I merely didn't get or is the fact that malicious adversary might break the protocol without breaking DLog on $G$ essentially unprovable? A: It is important to understand that the simulator is a non-interactive machine; it does not interact with the prover (or with anybody else). What it can do is mimic (or simulate) a real interaction between the prover and the verifier, by playing the roles of both parties and internally "sending messages to itself". But it is not required to mimic the protocol exactly, only to produce an output that is close enough to the output of a real execution of the protocol. This is why it can internally repeat the protocol many times until it obtains a satisfactory output; there is no need for the prover to "cooperate", since again the simulator does not interact with the prover.
{ "pile_set_name": "StackExchange" }
Q: PHP/MySQL - Calculate Total for each Reservation I've got a Reservation application, and I'd like to calculate the total number of meals needed by reservations date span. My database has fields: $name - Person reserving $chkin - Check in date (DATE yyyy-mm-dd) $chkout - Check out date (DATE yyyy-mm-dd) $guests - Number of people in group $meal - Eating meals (Yes/No) So for each reservation I have: // Days of Stay $days = (strtotime($chkout) - strtotime($chkin)) / (60 * 60 * 24); What I'm not sure of is how to do the calculation for each reservation in the database. My calculation for each reservation would be something like: $days * $guests I would appreciate advice on this query... I'm trying to give a snapshot of how many meals will be need to be prepared for a given month, weeekend, etc. Thank you! A: You can use the MYSQL date diff to achieve a count of the days, then this can be multiplied by the number of guests. Finally you will need to select a date range for this search. Below are the basics or the MYSQL needed in order to get these values. This should put you on the right track to achieving what you want. SELECT DATEDIFF(a.chkout,a.chkin) * a.guests as meals FROM table as a WHERE a.chkin > '0000-00-00' AND a.chkout < '0000-00-00 I have tested this with a table of mine and it appears to be working correctly, however, without much data I can only test lightly. If you have any issues, leave a comment and I will try to help further. http://www.w3schools.com/sql/func_datediff.asp
{ "pile_set_name": "StackExchange" }
Q: Pandas Combining data in two excel I have two excel Excel 1 files language blank comment code 15 C++ 66 35 354 1 C/C++ Header 3 7 4 Excel 2 files language blank comment code 16 C++ 33 35 354 1 C/C++ Header 3 7 4 1 Python 1 1 1 Trying to get combined excel files language blank comment code 31 C++ 99 70 708 2 C/C++ Header 6 14 8 1 Python 1 1 1 Any tips in pandas A: Use concat with aggregate sum by groupby: df = pd.concat([df1, df2]).groupby('language', as_index=False).sum() print (df) language files blank comment code 0 C++ 31 99 70 708 1 C/C++ Header 2 6 14 8 2 Python 1 1 1 1 If order of columns is important add reindex: df=pd.concat([df1, df2]).groupby('language',as_index=False).sum().reindex(columns=df1.columns) print (df) files language blank comment code 0 31 C++ 99 70 708 1 2 C/C++ Header 6 14 8 2 1 Python 1 1 1
{ "pile_set_name": "StackExchange" }
Q: On click the template data needs to be rendered in the same page I am trying to render the data(from the template) like hide(when back button is clicked) and show(when the view button is clicked) on the same HTML page. My code is below: <h2>Saved Deals</h2> <p>This includes deals which are in draft</p> <p><a class="btn btn-black fjalla" id="viewsaveddeals" role="button">View »</a>{{> saveddeals}}</p> A: You could use Meteor Sessions, for example: if (Meteor.isClient) { Template.deals.helpers({ showSavedDeals: function () { return Session.equals('showSavedDeals', true); } }); Template.deals.events({ 'click #viewsaveddeals': function () { Session.set('showSavedDeals', true); } }); Template.deals.onDestroyed(function () { Session.set('showSavedDeals', null); }); } <template name="deals"> <h2>Deals<span>12</span></h2> <p>This includes deals which are in draft</p> <p><a class="btn btn-black fjalla" id="viewsaveddeals" role="button">View »</a>{{#if showSavedDeals}}{{> saveddeals}}{{/if}}</p> </template> <template name="saveddeals"> <h2>Saved deals</h2> </template>
{ "pile_set_name": "StackExchange" }
Q: Moving data.table columns to rows based on conditions I have a large data.table that is set up like this: ID Line.Rec Line.D.Amount Line.Desc Line1.Record Line1.D.Amount Line1.C.Amount Line2.Rec 1 1 100 test 2 500 200 3 2 1 200 testb 2 800 100 3 3 1 600 testc 2 900 500 NA Each event/row contains an ID and other static columns such as Eventdate. But, there is a varying amounts of lines (potentially anywhere from 1 to 99). Lines contains varying amounts of columns as well. The lines are not fixed, and some files will have different lines than this one. Therefore, I have to use column names rather than position. I would like the data.table to look like this: ID Record D.Amount C.Amount Description 1 1 100 0 test 1 2 500 200 1 3 0 0 2 1 200 testb 2 2 800 100 2 3 0 0 3 1 600 0 testc 3 2 900 500 The solution needs to be ensure that any column that matches first part of the name (line., line1., line2.,...line99.) are included in the correct row. The ID line (and EventDate) needs to be included as illustrated to make sure that I can trace which lines belong together. Any ideas? A: Not really a data.table question. You might want to consider changing the tag. Here is something that should get you started: library(data.table) dt <- fread("ID Line.Rec Line.D.Amount Line.Desc Line1.Record Line1.D.Amount Line1.C.Amount Line2.Rec 1 1 100 test 2 500 200 3 2 1 200 testb 2 800 100 3 3 1 600 testc 2 900 500 NA") #ensure that relevant columns share the same names setnames(dt, gsub("Rec$", "Record", names(dt))) #identify which columns forms a sub dataset otherCols <- setdiff(names(dt), "ID") groupCols <- split(otherCols, sapply(strsplit(otherCols, "\\."), `[`, 1)) newCols <- sapply(names(groupCols), function(x) gsub(paste0(x, "."), "", groupCols[[x]])) #take sub columns of original dataset by group subDataLs <- lapply(names(groupCols), function(x) setnames(dt[, c("ID", groupCols[[x]]), with=FALSE], c("ID", newCols[[x]])) ) #rbind sub datasets output <- rbindlist(subDataLs, use.names=TRUE, fill=TRUE) #format to desired output cols <- names(output)[sapply(output, is.numeric)] output[, (cols) := replace(.SD, is.na(.SD), 0), .SDcols=cols] cols <- names(output)[sapply(output, is.character)] output[, (cols) := replace(.SD, is.na(.SD), ""), .SDcols=cols] output: ID Record D.Amount Desc C.Amount 1: 1 1 100 test 0 2: 2 1 200 testb 0 3: 3 1 600 testc 0 4: 1 2 500 200 5: 2 2 800 100 6: 3 2 900 500 7: 1 3 0 0 8: 2 3 0 0 9: 3 0 0 0
{ "pile_set_name": "StackExchange" }
Q: Remove note about bash that appears when opening the terminal I tried instaling ROOT by CERN by following steps described by certain people. But although that was unsuccessful, I keep getting the following line when I open a new terminal. bash: /home/USER/bin/thisroot.sh: No such file or directory How can I remove that? EDIT- Please note, for those who have raised the doubts, that I have redacted my true username. And I wrote USER in that place. A: There's probably an alias on your .bashrc or .bash_profile calling that file, so it tries to load it everytime you get a new prompt. Try editing them with one of these commands: gedit $HOME/.bashrc gedit $HOME/.bash_profile gedit $HOME/.profile Look for any line loading 'thisroot.sh' and comment it (write a # character at the begining of those lines). If you see after saving and opening a terminal that all works well, you can go ahead and directly deleting those lines. Also, the way the script is being called sounds wrong, shouldn't it be /home/YOURUSERNAMEHERE/bin/thisroot.sh?
{ "pile_set_name": "StackExchange" }
Q: In programming, when does it make sense to have 2 references to the same object (name ambiguity) In programming, the standard practice is to give each object it's own unique name by assigning it's address to only one reference variable. If we assign one reference variable to another reference variable, it creates two different names for the same thing. I was asked when doing this would be useful. When would using ambiguous names be useful? The only reason I could see for doing this is if you need to make a copy of an object's value to prevent overwriting. A: What you describe is not ambiguity, it's aliasing (specifically pointer aliasing). You don't usually do it explicitly, but it can be very useful if you pass a reference/pointer to another method. Then at least two variables (the original one and the parameter) will reference the same object, but for different reasons. If you do it explicitly, then it's usually because two variables take two different roles. For example if you're writing code that traverses a tree, you usually start at the root. So the beginning of your code might look like this: TreeNode rootNode = getTreeRootFromSomewhere(); TreeNode currentNode = rootNode; while (currentNode != null) { ... In this case currentNode is obviously an alias for rootNode at this point. Later on we will certainly change what currentNode points to, but the first time you enter the loop they point to the same object.
{ "pile_set_name": "StackExchange" }
Q: Hive SQL Extract string of varying length between two non-alphanumeric characters I would like to extract strings of varying length located between two repeating underscores in Hive QL. Below I show a sampling of the pattern of the rows. Specifically, I would like to extract the string between the 3rd and 4th underscores. Thanks! 2016_sadfsa_IL_THIS_xsdaf_asd_eventbyevent_tsaC_NA_300x250 2017_thisshopper_MA_THIS_NAT_Leb_ReasonsWhy_HDIMC_NA_300x600 2017_FordShopper_IL_THESE_NAT_sov_winterEvent_HDIMC_NA_300x600 Just kept trying and I modified this from previous responses to non-Hive SQL. I am still interested in knowing better ways of doing this. Note that creative_str is the name of the column: select creative_str, ltrim(rtrim(substring(regexp_replace(cast(creative_str as varchar(1000)), '_', repeat(cast(' ' as varchar(1000)),10000)), 30001, 10000))) from impression_cr A: You should be able to do this with Hive's SPLIT() function. If you're trying to grab the value between the third and fourth underscores, this will do it: SELECT SPLIT("2016_sadfsa_IL_THIS_xsdaf_asd_eventbyevent_tsaC_NA_300x250", "[_]")[3], SPLIT("2017_thisshopper_MA_THIS_NAT_Leb_ReasonsWhy_HDIMC_NA_300x600", "[_]")[3], SPLIT("2017_FordShopper_IL_THESE_NAT_sov_winterEvent_HDIMC_NA_300x600", "[_]")[3]
{ "pile_set_name": "StackExchange" }
Q: How many 3 dB couplers are needed to construct a 16 way fiber optic splitter? Wikipedia says we need 31 couplers. Can't we do it with 8 couplers? A: Follow the math in the wiki article: (2^4)-1=15.
{ "pile_set_name": "StackExchange" }
Q: jQuery autocomplete - IE8 issue - this tab has been recovered I run into a problem with jQuery UI - Autocomplete and IE8. I'm using combobox method which you can find on jQuery UI website - here Basically, it is creating autocomplete input + select menu from select/option list. I'm using jQuery 1.6.4 and jQuery UI 1.8.16; both from google server. It is working perfectly on Chrome / FF / Opera, but does not work on IE8. On IE8 - once you select something (after typing), or use dropdown button IE will reload the page. Please not that IE will not crash till you use arrows or try to select something. res://ieframe.dll/acr_error.htm#, in the URL, in front of the actual path or a message this tab has been reloaded; a problem with the page causes IE to close and reopen the page Live example here Any idea what is causing IE to act like that? Any suggestion much appreciated. jQuery code: <script> (function( $ ) { $.widget( "ui.combobox", { _create: function() { var self = this, select = this.element.hide(), selected = select.children( ":selected" ), value = selected.val() ? selected.text() : ""; var input = this.input = $( "<input>" ) .insertAfter( select ) .val( value ) .autocomplete({ delay: 0, minLength: 0, source: function( request, response ) { var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" ); response( select.children( "option" ).map(function() { var text = $( this ).text(); if ( this.value && ( !request.term || matcher.test(text) ) ) return { label: text.replace( new RegExp( "(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(request.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi" ), "<strong>$1</strong>" ), value: text, option: this }; }) ); }, select: function( event, ui ) { ui.item.option.selected = true; self._trigger( "selected", event, { item: ui.item.option }); }, change: function( event, ui ) { if ( !ui.item ) { var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ), valid = false; select.children( "option" ).each(function() { if ( $( this ).text().match( matcher ) ) { this.selected = valid = true; return false; } }); if ( !valid ) { // remove invalid value, as it didn't match anything $( this ).val( "" ); select.val( "" ); input.data( "autocomplete" ).term = ""; return false; } } } }) .addClass( "ui-widget ui-widget-content ui-corner-left" ); input.data( "autocomplete" )._renderItem = function( ul, item ) { return $( "<li></li>" ) .data( "item.autocomplete", item ) .append( "<a>" + item.label + "</a>" ) .appendTo( ul ); }; this.button = $( "<button type='button'>&nbsp;</button>" ) .attr( "tabIndex", -1 ) .attr( "title", "Show All Items" ) .insertAfter( input ) .button({ text: false }) .removeClass( "ui-corner-all" ) .click(function() { // close if already visible if ( input.autocomplete( "widget" ).is( ":visible" ) ) { input.autocomplete( "close" ); return; } // work around a bug (likely same cause as #5265) $( this ).blur(); // pass empty string as value to search for, displaying all results input.autocomplete( "search", "" ); input.focus(); }); }, destroy: function() { this.input.remove(); this.button.remove(); this.element.show(); $.Widget.prototype.destroy.call( this ); } }); })( jQuery ); $(document).ready( function() { $("#combobox").combobox(); }); </script> A: I'm still trying to work out why IE8 is crashing but it does work for me when you add a jQueryUI theme to the page, for example: <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/cupertino/jquery-ui.css"> Edit: I think I know which line it is crashing on, but I still do not know why! In the jQueryUI code activate: function( event, item ) { is the following code which adds style and an attribute to the active item. this.active = item.eq(0) .children("a") .addClass("ui-state-hover") .attr("id", "ui-active-menuitem") .end(); For some reason, IE8 crashes here, although for me sometimes does not crash when I remove the .addClass and .attr lines. Edit 2: OK, for some reason IE is crashing with your .ui-autocomplete style. If you change overflow:scroll; to overflow:auto; then IE8 does not crash. Alternatively change max-height to just height, which also fixes it. Guess it's a bug in IE either with max-height (maybe IE8 overflow:auto with max-height) or overflow.
{ "pile_set_name": "StackExchange" }
Q: How to call instance variable form another class and file I have a question, I have 4 file app.py, face.py, camera.py and db.py Inside face.py file I have one variable call known_encoding_faces. If I put print code inside my face.py and run the app.py the result will display in my command prompt. My question is how can i use known_encoding_faces variable in my camera.py? My expected result is when i run my app.py and open my webcam the command prompt will show the printed known_encoding_faces output. I believe if this work means this known_encoding_faces variable successfully can be used by camera.py file. Here I attach my code. Hope someone can help me regarding on this matter. app.py from flask import Flask, Response, json, render_template from werkzeug.utils import secure_filename from flask import request from os import path, getcwd import time from face import Face from db import Database app = Flask(__name__) import cv2 from camera import VideoCamera app.config['file_allowed'] = ['image/png', 'image/jpeg'] app.config['train_img'] = path.join(getcwd(), 'train_img') app.db = Database() app.face = Face(app) def gen(camera): while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') @app.route('/video_feed') def video_feed(): return Response(gen(VideoCamera()), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route('/') def index(): return render_template('index.html') def success_handle(output, status=200, mimetype='application/json'): return Response(output, status=status, mimetype=mimetype) face.py import face_recognition from os import path import cv2 import face_recognition class Face: def __init__(self, app): self.train_img = app.config["train_img"] self.db = app.db self.faces = [] self.face_user_keys = {} self.known_encoding_faces = [] # faces data for recognition self.load_all() def load_user_by_index_key(self, index_key=0): key_str = str(index_key) if key_str in self.face_user_keys: return self.face_user_keys[key_str] return None def load_train_file_by_name(self,name): trained_train_img = path.join(self.train_img, 'trained') return path.join(trained_train_img, name) def load_unknown_file_by_name(self,name): unknown_img = path.join(self.train_img, 'unknown') return path.join(unknown_img, name) def load_all(self): results = self.db.select('SELECT faces.id, faces.user_id, faces.filename, faces.created FROM faces') for row in results: user_id = row[1] filename = row[2] face = { "id": row[0], "user_id": user_id, "filename": filename, "created": row[3] } self.faces.append(face) face_image = face_recognition.load_image_file(self.load_train_file_by_name(filename)) face_image_encoding = face_recognition.face_encodings(face_image)[0] index_key = len(self.known_encoding_faces) self.known_encoding_faces.append(face_image_encoding) index_key_string = str(index_key) self.face_user_keys['{0}'.format(index_key_string)] = user_id def recognize(self,unknown_filename): unknown_image = face_recognition.load_image_file(self.load_unknown_file_by_name(unknown_filename)) unknown_encoding_image = face_recognition.face_encodings(unknown_image)[0] results = face_recognition.compare_faces(self.known_encoding_faces, unknown_encoding_image); print("results", results) index_key = 0 for matched in results: if matched: # so we found this user with index key and find him user_id = self.load_user_by_index_key(index_key) return user_id index_key = index_key + 1 return None camera.py import face_recognition from os import path import cv2 from db import Database from face import Face class VideoCamera(object): def __init__(self): # Using OpenCV to capture from device 0. If you have trouble capturing # from a webcam, comment the line below out and use a video file # instead. self.video = cv2.VideoCapture(0) # If you decide to use video.mp4, you must have this file in the folder # as the main.py. # self.video = cv2.VideoCapture('video.mp4') def __del__(self): self.video.release() def get_frame(self): success, image = self.video.read() # We are using Motion JPEG, but OpenCV defaults to capture raw images, # so we must encode it into JPEG in order to correctly display the # video stream. ret, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() A: known_encoding_faces is a member of a Face object. That means it does not exist on its own - as evidence, note you only reference self.known_encoding_faces rather than just known_encoding_faces. You need to initialize some Face object, and than you can use it. Further more, it looks like you would need to call load_all on said object to properly initialize it. The minimal thing you need is some thing like: from face import Face aface = Face(app) #You would need an app here aface.load_all() known_encoding_faces = aface.known_encoding_faces If you are expecting this to exist irrespective of an objects creation, you need to rethink your design, and take it out of your class. If you are expecting this to be called from the main script, you can demand this variable to initialize your camera: VideoCamera(app.face.known_encoding_faces) #Called from main script and in camera.py: class VideoCamera(object): def __init__(self,known_face_encodings): self.known_encoding_faces = known_face_encodings self.video = cv2.VideoCapture(0) and in this class you can now use self.known_encoding_faces.
{ "pile_set_name": "StackExchange" }
Q: MatPlotLib dynamic time axis I've been researching for a bit and haven't found the solution I'm looking for. Is there a method to creating a dynamic x-axis with matplotlib? I have a graph with a data stream being plotted, and I would like to have the x-axis display elapsed time (currently is static 0-100, while the rest of the graph updating to my data stream). Each tick would ideally be .5 seconds apart, with the latest 10s displaying. The program will be running 24/7, so I could have it set to actual time instead of stopwatch time. I've only been finding static datetime axis in my research. I can provide code if necessary, but doesn't seem necessary for this question. A: Since I don't know what you are streaming, I wrote a generic example and it may help you solving your problem. from pylab import * import matplotlib.animation as animation class Monitor(object): """ This is supposed to be the class that will capture the data from whatever you are doing. """ def __init__(self,N): self._t = linspace(0,100,N) self._data = self._t*0 def captureNewDataPoint(self): """ The function that should be modified to capture the data according to your needs """ return 2.0*rand()-1.0 def updataData(self): while True: self._data[:] = roll(self._data,-1) self._data[-1] = self.captureNewDataPoint() yield self._data class StreamingDisplay(object): def __init__(self): self._fig = figure() self._ax = self._fig.add_subplot(111) def set_labels(self,xlabel,ylabel): self._ax.set_xlabel(xlabel) self._ax.set_ylabel(ylabel) def set_lims(self,xlim,ylim): self._ax.set_xlim(xlim) self._ax.set_ylim(ylim) def plot(self,monitor): self._line, = (self._ax.plot(monitor._t,monitor._data)) def update(self,data): self._line.set_ydata(data) return self._line # Main if __name__ == '__main__': m = Monitor(100) sd = StreamingDisplay() sd.plot(m) sd.set_lims((0,100),(-1,1)) ani = animation.FuncAnimation(sd._fig, sd.update, m.updataData, interval=500) # interval is in ms plt.show() Hope it helps
{ "pile_set_name": "StackExchange" }
Q: Find a variable from a variable value in C I am trying to make a game similar to chess. I want the user to type in what position of the piece they want to move is, then were they want to move it... ( on an 8x8 grid - A1 through to H8) I cant workout a simple way to find a variable from what the user has typed in. The code I currently have is: void main() { printf("Enter Piece to Move: "); scanf("%s",&move); printf("\n\nWhere would you like to move %s?:",move); scanf("%s",&to); [...] What i also have is a variable list of all the location of pieces. What I would like to happen is, if the user was to enter A1 for the piece to move. I want the value of variable named A1 to be used. This is so I can have the current position of the piece and also what is in the place... Hope this makes scene and someone can help :) A: Take a look at the concept of arrays. If you have a 2-dimensional array, you just need to convert the letter 'A' to a number and use it as in index in the array.
{ "pile_set_name": "StackExchange" }
Q: Confusion Matrix to get precsion,recall, f1score I have a dataframe df. I have performed decisionTree classification algorithm on the dataframe. The two columns are label and features when algorithm is performed. The model is called dtc. How can I create a confusion matrix in pyspark? dtc = DecisionTreeClassifier(featuresCol = 'features', labelCol = 'label') dtcModel = dtc.fit(train) predictions = dtcModel.transform(test) from pyspark.mllib.linalg import Vectors from pyspark.mllib.regression import LabeledPoint from pyspark.mllib.evaluation import MulticlassMetrics preds = df.select(['label', 'features']) \ .df.map(lambda line: (line[1], line[0])) metrics = MulticlassMetrics(preds) # Confusion Matrix print(metrics.confusionMatrix().toArray())``` A: You need to cast to an rdd and map to tuple before calling metrics.confusionMatrix().toArray(). From the official documentation, class pyspark.mllib.evaluation.MulticlassMetrics(predictionAndLabels)[source] Evaluator for multiclass classification. Parameters: predictionAndLabels – an RDD of (prediction, label) pairs. Here is an example to guide you. ML part import pyspark.sql.functions as F from pyspark.ml.feature import VectorAssembler from pyspark.ml.classification import DecisionTreeClassifier from pyspark.mllib.evaluation import MulticlassMetrics from pyspark.sql.types import FloatType #Note the differences between ml and mllib, they are two different libraries. #create a sample data frame data = [(1.54,3.45,2.56,0),(9.39,8.31,1.34,0),(1.25,3.31,9.87,1),(9.35,5.67,2.49,2),\ (1.23,4.67,8.91,1),(3.56,9.08,7.45,2),(6.43,2.23,1.19,1),(7.89,5.32,9.08,2)] cols = ('a','b','c','d') df = spark.createDataFrame(data, cols) assembler = VectorAssembler(inputCols=['a','b','c'], outputCol='features') df_features = assembler.transform(df) #df.show() train_data, test_data = df_features.randomSplit([0.6,0.4]) dtc = DecisionTreeClassifier(featuresCol='features',labelCol='d') dtcModel = dtc.fit(train_data) predictions = dtcModel.transform(test_data) Evaluation part #important: need to cast to float type, and order by prediction, else it won't work preds_and_labels = predictions.select(['predictions','d']).withColumn('label', F.col('d').cast(FloatType())).orderBy('prediction') #select only prediction and label columns preds_and_labels = preds_and_labels.select(['prediction','label']) metrics = MultiClassMetrics(preds_and_labels.rdd.map(tuple)) #print(metrics.ConfusionMatrix().toArray())
{ "pile_set_name": "StackExchange" }
Q: Jar file not running on mac I have made a runnable java file on eclipse on my windows 64 bit computer using jre and jdk 8. The runnable file opens on my windows computer and on my desktop windows computer. When i email the jar file over to my mac, the jar file does not work and it gives the error the java jar file "snoman3.jar" could not be launched. I ran it through the terminal and still gives the same error. I have jre 8 on my mac yet it is still not running. There are many duplicates of this question but i could not find a solution that worked for me, may somebody please tell me possible solutions for this? PS I am running OS X yosemite on my mac. The following is the error I am getting. PS I am using the libGDX graphics library. java -jar snoman3.jar Exception in thread "main" java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58) Caused by: java.lang.UnsatisfiedLinkError: Can't load library: /var/folders/88/wtc6dz2d5tvdr3qnzb3pq69w0000gn/T/libgdxasma/75260a42/liblwjgl.dylib at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1817) at java.lang.Runtime.load0(Runtime.java:809) at java.lang.System.load(System.java:1083) at org.lwjgl.Sys$1.run(Sys.java:70) at java.security.AccessController.doPrivileged(Native Method) at org.lwjgl.Sys.doLoadLibrary(Sys.java:66) at org.lwjgl.Sys.loadLibrary(Sys.java:95) at org.lwjgl.Sys.<clinit>(Sys.java:112) at org.lwjgl.openal.AL.<clinit>(AL.java:59) at com.badlogic.gdx.backends.openal.OpenALAudio.<init>(OpenALAudio.java:70) at com.badlogic.gdx.backends.lwjgl.LwjglApplication.<init>(LwjglApplication.java:81) at com.badlogic.gdx.backends.lwjgl.LwjglApplication.<init>(LwjglApplication.java:63) at com.rarster.snowman.Main.main(Main.java:15) ... 5 more A: Looks like you are getting a NullPointerException behind the scenes. InvocationTargetException is just a wrapper for an exception that's thrown within a dynamic invocation. If I saw your code, I could have helped you more.
{ "pile_set_name": "StackExchange" }
Q: Openshift RHC setup throws error After successfully installing rhc, when I try to rhc setup and I get the following console output: Anyone any idea why this happens? A: Okay so after further investigation how I fixed this was: rhc ssh *my_app_name* after which I ran tail_all This gave me a pretty extensive error log generated by the openshift server. Silly error - turned out it was just a missing dependency from the package.json file :)
{ "pile_set_name": "StackExchange" }
Q: jqplot and width I am having some trouble with the width of the ticks on the xaxis. It seems that they are auto adjusted to fill the width of the div - what if I want to override that? Regards, Jacob A: I had the same problem but could not find anything useful in the docs. I solved it by changing the width of the div dynamically, based on the data array size, before drawing the graph.
{ "pile_set_name": "StackExchange" }
Q: Swift - Is there a way to differentiate between a field not being present or a field being nil/null when decoding an optional Codable value The Necessary Functionality I'm in the process of modifying a system to save a queue of currently unsent API requests to UserDefaults to be re-sent when the user's connection allows. As some patch requests require the ability to send an actual NULL value to the API (and not just ignore out the field if its a nil optional), this means I need the ability to encode and decode nil/NULL values from defaults for certain fields. The Issue I have the encoding side down, and can happily encode requests to either send NULL fields to the server or encode them to Defaults. However, my issue is that when it comes to decoding saved unsent requests, I can't find a way to differentiate between an actual Nil value and the field just not being there. I am currently using decodeIfPresent to decode my fields (all of the fields for these requests are optional), which returns nil if the field is empty OR if the field is set to Nil/NULL. Obviously this doesn't work for my fields that can explicitly be set to Nil, as there is no way for me to differentiate between the two cases. Question Is there any decode methodology I could implement that would allow for differentiating between a field not being there and a field actually being set to nil? A: There is no way , but you can add another info to know that struct Root : Codable { let code : Int? let codeExists:Bool? init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) code = try values.decodeIfPresent(Int.self, forKey: .code) codeExists = values.contains(.code) } } According to docs decodeIfPresent This method returns nil if the container does not have a value associated with key, or if the value is null. The difference between these states can be distinguished with a contains(_:) call. So decoding let str = """ { "code" : 12 } """ gives Root(code: Optional(12), codeExists: Optional(true)) && This let str = """ { "code" : null } """ gives Root(code: nil, codeExists: Optional(true)) and this let str = """ { } """ gives Root(code: nil, codeExists: Optional(false))
{ "pile_set_name": "StackExchange" }
Q: mat-autocomplete: Need to Reset the List of Options After a Selection is Made I have a mat-autocomplete component with the options wired up to be populated from a service call as the user types (partial search): <mat-autocomplete #auto="matAutocomplete" (optionSelected)="areaSelected($event.option.value)"> <mat-option *ngFor="let option of options" [value]="option">{{ option }}</mat-option> </mat-autocomplete> In my TS code, I am setting the options array to be an empty array at the end of the processing I do when a user selects a value: resetFetchedOptions() { this.options = []; } This works in that the code is called, and that this.options is set to an empty array. The problem is that when the user tries to type another value in the field, the previous options are still there. If they type, the options get cleared out, and the new options based on the partial search are populated, so I think this is a rendering problem, but I'm a bit new to Angular Material, so I'm not sure if this is the wrong approach or I'm missing a step. Thanks! A: Are you using reactive forms? I made a similar thing like this (based on this article); html <mat-form-field class="width-filler"> <input type="text" matInput placeholder="Search" [matAutocomplete]="auto" [formControl]="formControl" autocomplete="off" autofocus> <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFunc"> <mat-option *ngIf="isSearching" class="is-loading"><mat-spinner diameter="20"></mat-spinner></mat-option> <mat-option *ngFor="let result of filteredResult" [value]="result"> {{result.description}} </mat-option> </mat-autocomplete> <mat-hint>{{searchHint()}}</mat-hint> </mat-form-field> Typescript ngOnInit() { this.formControl .valueChanges .pipe( debounceTime(300), tap(() => this.isSearching = true), switchMap(value => this.someService.searchStuff<ResultType[]>(this.getSearchString(value as any)) .pipe( finalize(() => this.isSearching = false), ) ) ) .subscribe(result => this.filteredResult = result); this.formControl.valueChanges.subscribe(value => this.setValue(value)); } // Need to handle both the search string and a selected full type private setValue(value: string | ResultType) : void { if (typeof value === "string") this.selectedValue = null; else this.selectedValue = value; } private getSearchString(value: string | ResultType) { if (typeof value === "string") return value; else return value.description; }
{ "pile_set_name": "StackExchange" }
Q: How do I install required gcc and libc6-dev files on 20.04? I am trying to build software from source (specifically, Asymptote 2.66). This worked fine on Ubuntu 18.04. But a number of the files the make file needs, such as: byteswap-16.h and libio.h in /usr/include/x86-64-linux-gnu/bits/ limits.h in /usr/lib/gcc/x86-64-linux-gnu/7/include-fixed are simply not present in Ubuntu 20.04. Well, not present in the expected locations. They can be found in /snap/gnome-3-34-1804. Every bit of help online says to install build-essentials, libc6-dev, and linux-libc-dev. But all of these are installed. Other than manually copying needed files one by one, is there a way to get all the necessary files to build from source? A: At first - the Asymptote 2.62 is contained in the official repository, so you can start getting its build-dependencies by enabling source code repositories in Software & Updates (software-properties-gtk) and by using the following command: sudo apt-get build-dep asymptote And then compile the source code: cd ~/Downloads wget https://github.com/vectorgraphics/asymptote/archive/2.66.tar.gz tar -xf 2.66.tar.gz cd asymptote-2.66 ./autogen.sh ./configure make sudo make install and then run the application with asy command.
{ "pile_set_name": "StackExchange" }
Q: How to share models between different MVC websites? I have 2 seperate areas for my ASP.NET MVC 3 website - Admin (Intranet website) and Client (Internet website). The Model (business and data access layer) will be used by both websites. The websites will be hosted on seperate servers. So, the folder will not be shared. So, I am planning to create the DLL of the Model and put the DLL in the Bin Folder of both website and use it. I hope this will keep my UI neat and less code as well. Now, my doubts are: Do I need to create a Class Library project to create the DLL of the Model or do I need to use and MVC web application project to create the DLL? Where should I put the web config? Hope I need in both Model and also in UI? A: Do I need to create a Class Library project to create the DLL of the Model Yes, a separate class library shared between the 2 web applications is the best approach. Do I need to use and MVC web application project to create the DLL (looking for the best approach)? No, the ASP.NET MVC could contain only the views. Do not reference and reuse a web application for common logic in other applications. Where should I put the web config? Each ASP.NET MVC web application should have its own web.config. A: Yes, your abstracted business logic should be in a separate class library project. You can then reference this project from web apps in the same solution or compile it and reference it as a DLL. Your web.config file(s) will still live in your web project(s). To add settings for your class library in your web project, use configuration sections: <configSections> <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <section name="My.Class.Library.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </sectionGroup> </configSections> <applicationSettings> <My.Class.Library.Properties.Settings> <setting name="SettingName" serializeAs="String"> <value>SettingValue</value> </setting> </My.Class.Library.Properties.Settings> </applicationSettings>
{ "pile_set_name": "StackExchange" }
Q: Regular Expression To Validate Email Address I'm trying to create a regular expression to check to see if a valid email address has been entered. There is something wrong with my regular expression. Here is the source code I'm using: if (!Pattern.matches("^[\\w-\\+]+(\\.[\\w]+)*@[\\w-]+(\\.[\\w]+)*(\\.[a-z]{2,})$", s)) { et.setError("Enter a valid Email Address"); } What am I doing wrong? A: This did the trick: ([\\w-+]+(?:\\.[\\w-+]+)*@(?:[\\w-]+\\.)+[a-zA-Z]{2,7})
{ "pile_set_name": "StackExchange" }
Q: component lookup exception with org.apache.maven.repository.RepositorySystem in Maven plugin testing I'm trying to use maven-plugin-testing-harness version 2.1 with the following test case: public class FooTest extends AbstractMojoTestCase { @Override protected void setUp() throws Exception { super.setUp(); } public void testSomething() throws Exception { // todo } } The test fails at the setUp() call: org.codehaus.plexus.component.repository.exception.ComponentLookupException: java.util.NoSuchElementException role: org.apache.maven.repository.RepositorySystem roleHint: at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:257) at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:245) at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:239) at org.codehaus.plexus.PlexusTestCase.lookup(PlexusTestCase.java:206) at org.apache.maven.plugin.testing.AbstractMojoTestCase.setUp(AbstractMojoTestCase.java:118) at foo.FooTest.setUp(FooTest.java:54) These dependencies I have in the pom.xml: <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-plugin-api</artifactId> <version>3.0.5</version> </dependency> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-model</artifactId> <version>3.0.5</version> </dependency> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-core</artifactId> <version>3.0.5</version> </dependency> <dependency> <groupId>org.apache.maven.plugin-testing</groupId> <artifactId>maven-plugin-testing-harness</artifactId> <version>2.1</version> <scope>test</scope> </dependency> Any ideas? A: Recently I faced the same exception. After a bit researching I found that maven-compat plugin solves the problem: <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-compat</artifactId> <version>3.0.5</version> <scope>test</scope> </dependency> A: Leaving this here for anyone who runs into this problem in the future: smoke's answer does work, but make sure the versions of the dependencies included in yegor256's in the original question match. Adding org.apache.maven:maven-compat did not work for me until I had changed those 4 dependencies to also have version 3.0.5.
{ "pile_set_name": "StackExchange" }
Q: Minecraft crashes after launching with buildcraft I just installed Minecraft 1.6.2 and then installed forge. The game launches Forge and the Timber mod but when I attempted to add the Buildcraft mod, the game just crashes. The Mojang screen appears and then the game closes. I don't know what is happening. There isn't and error report or anything, the game just closes. A: You've been tricked The latest BuildCraft (version 3.7.2) from the official download site is for Minecraft 1.5.2. It will not work for Minecraft 1.6.2. Either you downloaded it from a scam/malware site that lied about being compatible with 1.6.2 (scam mod sites are very common, since it's easy to prey on people hoping for mods compatible with the latest Minecraft version), or someone well-meaning simply didn't understand compatibility and was wrong when they told you it would work with 1.6.2. There is no fix. You'll have to either downgrade to Minecraft 1.5.2 and use that to play BuildCraft, or wait for BuildCraft to update to Minecraft 1.6.x. Always download mods from reputable sources you trust! Never find mods by Googling. Either find the mod on the author's site or from Minecraftforums.net pinned mod list thread. Anywhere else is either illegally redistributing the real mod or is offering a fake mod that might be malware. Even if it's the real mod, they often provide inaccurate or misleading compatibility information to boost downloads and their advertising income, leaving you with a mod that simply doesn't work while they get paid for your misfortune.
{ "pile_set_name": "StackExchange" }
Q: Unable to get the text field value in typescript using angular I have two type of Request that I need to fetch from the Angular UI page and pass it into app.component.ts file so that I can call my REST client through HTML page. Request 1: End Point: (GET call) http://localhost:8081/api/products?productId=7e1308ba2b9af I just created a text field in the app.component.html file as like below: <div> <input type="text" placeholder="Product ID" class="user_id_text"/> </div> <div> <input type="submit" value="submit"/> </div> Output: I have written the below code and ensured it works as expected by using the hard-coded value. app.component.ts: ngOnInit():void{ this.http.get('http://localhost:8081/api/products?productId=7e1308ba2b9af').subscribe(data =>{ console.log(data); }); } The above code return data array with proper response. But the above productId value is hard-coded (7e1308ba2b9af). And I just want to get that value from HTML text box when user click the submit button and pass it to query param and run the above request. Request 2: I have to get the below format json file from text box and pass it as JSON request body to the below end point URL. End Point: (PUT call) https://localhost:8081/api/updateRecord Request JSON: { "productId":234242882, "purchaseDate" : "2019-12-20", "status": "dispatched" } I just want to create a text field and get the above json file if user click submit button and invoke the above end point. I'm very new to the Angular and not sure how to implement this. I just googled but I didn't understand the way they resolved. It would be much appreciated if someone explain me the things and guide me to resolve this. A: Use [(ngModel)] to bind an input to a variable: <div> <input type="text" [(ngModel)]="productId" placeholder="Product ID" class="user_id_text"/> </div> Use (click) to bind a button to a function: <div> <input type="submit" (click)="getById(productId)" value="submit"/> </div> In the controller: ngOnInit():void { this.http.get('http://localhost:8081/api/products?productId=7e1308ba2b9af').subscribe(data =>{ console.log(data); }); } getById():void { const base:string = "http://localhost:8081/api/products"; const url:string = `${base}?productId=${this.productId}`; this.http.get(url).subscribe(data =>{ console.log(data); }); }
{ "pile_set_name": "StackExchange" }
Q: Review queues always empty I am not able to review any post although I have enough reputation (more than 1400) on my Stack Overflow account. However, the review queues always show zero contents. Up until now I've only reviewed one item. Is something broken? A: At your current reputation, you can only see the "Late Answers" and "First Posts" (I believe). These queues are often empty and, even when they're not, a large group of users constantly patrols the queues and will snatch up the opportunity to review. Once your reputation increases, you'll gain access to some queues that typically have a handful of items in them at any one point. Once you reach 3k, you can drown in all the close reviews you can handle... (Minimal reputation artfully added in red)
{ "pile_set_name": "StackExchange" }
Q: Can I calculate tension in a preloaded string by superposition when the string is deformed? I am trying to calculate the tension in a string with preloaded tension after a force is applied to the string as in the diagram below. The string would be under tension prior to the force $F$ being applied. The force should deform the string by an amount determined by Young's modulus and the other physical properties of the string. However, this does not account for all tension in the string. If we call the preloaded tension $T$, when the string is straight, can I simply add the tension caused by the deformation to the initial tension in the string? My attempt to solve for the tension (call it $T'$) after the force $F$ is applied begins by calculating the change in length of the string. The length before bending is $$\sqrt{L^2+h^2}$$ and the length after bending is $$x+\sqrt{(L-x)^2+h^2}$$ Therefore, the change in length is calculated as $$x+\sqrt{(L-x)^2+h^2}-\sqrt{L^2+h^2}$$ and the strain can be calculated as $$\epsilon=\frac{x+\sqrt{(L-x)^2+h^2}-\sqrt{L^2+h^2}}{\sqrt{L^2+h^2}}=\frac{x+\sqrt{(L-x)^2+h^2}}{\sqrt{L^2+h^2}}-1$$ Calling the tension induced by deformation $T_d$ and the cross-sectional area of the string $A$, stress is calculated as $$\sigma=T_d/A$$ Given that Young's modulus is $$Y=\frac{\sigma}{\epsilon} \therefore \sigma = Y\cdot \epsilon$$ we can substitute and rearrange to get $$T_d=Y\cdot A\cdot \left(\frac{x+\sqrt{(L-x)^2+h^2}}{\sqrt{L^2+h^2}}-1\right)$$ Firstly, is this a even valid calculation given the angle $\theta$? I'm not very confident about it, but it's the best I can come up with. Secondly, given the increase in tension due to the change in overall length, is it valid to simply add this amount to the preloaded tension in the string. I'm mostly concerned with the tension in the section of the string labeled $x$, but would be interested in knowing the tension in both sections if possible. A: Well, if I understood the system correctly, pushing the string down to the given configuration will make the tension on both the parts of the string equal. This follows from a choice of point without friction, as you can easily find examples of. Having established that, calculating the tension on an ideal string needs us to find the strain on the spring. Strain is $$\epsilon = \frac{\Delta{L}}{L_0}$$ where $L_0$ is the length of the unstrained spring (i.e. without force). This makes the calculations trivial: You first calculate $L_0$ from the first configuration with tension $T$, then use this length to find the final strain and tension $T'$.
{ "pile_set_name": "StackExchange" }